index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ExecutableDescriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.aot.generate; import java.lang.reflect.Constructor; import java.lang.reflect.Executable; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * A describer that describes the need for reflection on a {@link Executable}. */ public class ExecutableDescriber extends MemberDescriber { private final List<String> parameterTypes; private final ExecutableMode mode; public ExecutableDescriber(Constructor<?> constructor, ExecutableMode mode) { this( "<init>", Arrays.stream(constructor.getParameterTypes()) .map(Class::getName) .collect(Collectors.toList()), mode); } public ExecutableDescriber(String name, List<String> parameterTypes, ExecutableMode mode) { super(name); this.parameterTypes = parameterTypes; this.mode = mode; } public List<String> getParameterTypes() { return parameterTypes; } public ExecutableMode getMode() { return mode; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ExecutableDescriber that = (ExecutableDescriber) o; return Objects.equals(parameterTypes, that.parameterTypes) && mode == that.mode; } @Override public int hashCode() { return Objects.hash(parameterTypes, mode); } }
8,400
0
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectionConfigWriter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.aot.generate; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; /** * Write {@link ReflectConfigMetadataRepository} to the JSON output expected by the GraalVM * {@code native-image} compiler, typically named {@code reflect-config.json} * or {@code jni-config.json}. */ public class ReflectionConfigWriter { public static final ReflectionConfigWriter INSTANCE = new ReflectionConfigWriter(); public void write(BasicJsonWriter writer, ReflectConfigMetadataRepository repository) { writer.writeArray(repository.getTypes().stream().map(this::toAttributes).collect(Collectors.toList())); } private Map<String, Object> toAttributes(TypeDescriber describer) { Map<String, Object> attributes = new LinkedHashMap<>(); attributes.put("name", describer.getName()); handleCondition(attributes, describer); handleCategories(attributes, describer.getMemberCategories()); handleFields(attributes, describer.getFields()); handleExecutables(attributes, describer.getConstructors()); handleExecutables(attributes, describer.getMethods()); return attributes; } private void handleCondition(Map<String, Object> attributes, TypeDescriber describer) { if (describer.getReachableType() != null) { Map<String, Object> conditionAttributes = new LinkedHashMap<>(); conditionAttributes.put("typeReachable", describer.getReachableType()); attributes.put("condition", conditionAttributes); } } private void handleFields(Map<String, Object> attributes, Set<FieldDescriber> fieldDescribers) { addIfNotEmpty( attributes, "fields", fieldDescribers.stream().map(this::toAttributes).collect(Collectors.toList())); } private Map<String, Object> toAttributes(FieldDescriber describer) { Map<String, Object> attributes = new LinkedHashMap<>(); attributes.put("name", describer.getName()); return attributes; } private void handleExecutables(Map<String, Object> attributes, Set<ExecutableDescriber> executableDescribers) { addIfNotEmpty( attributes, "methods", executableDescribers.stream() .filter(h -> h.getMode().equals(ExecutableMode.INVOKE)) .map(this::toAttributes) .collect(Collectors.toList())); addIfNotEmpty( attributes, "queriedMethods", executableDescribers.stream() .filter(h -> h.getMode().equals(ExecutableMode.INTROSPECT)) .map(this::toAttributes) .collect(Collectors.toList())); } private Map<String, Object> toAttributes(ExecutableDescriber describer) { Map<String, Object> attributes = new LinkedHashMap<>(); attributes.put("name", describer.getName()); attributes.put("parameterTypes", describer.getParameterTypes()); return attributes; } private void handleCategories(Map<String, Object> attributes, Set<MemberCategory> categories) { categories.forEach(category -> { switch (category) { case PUBLIC_FIELDS: attributes.put("allPublicFields", true); break; case DECLARED_FIELDS: attributes.put("allDeclaredFields", true); break; case INTROSPECT_PUBLIC_CONSTRUCTORS: attributes.put("queryAllPublicConstructors", true); break; case INTROSPECT_DECLARED_CONSTRUCTORS: attributes.put("queryAllDeclaredConstructors", true); break; case INVOKE_PUBLIC_CONSTRUCTORS: attributes.put("allPublicConstructors", true); break; case INVOKE_DECLARED_CONSTRUCTORS: attributes.put("allDeclaredConstructors", true); break; case INTROSPECT_PUBLIC_METHODS: attributes.put("queryAllPublicMethods", true); break; case INTROSPECT_DECLARED_METHODS: attributes.put("queryAllDeclaredMethods", true); break; case INVOKE_PUBLIC_METHODS: attributes.put("allPublicMethods", true); break; case INVOKE_DECLARED_METHODS: attributes.put("allDeclaredMethods", true); break; case PUBLIC_CLASSES: attributes.put("allPublicClasses", true); break; case DECLARED_CLASSES: attributes.put("allDeclaredClasses", true); break; default: break; } }); } private void addIfNotEmpty(Map<String, Object> attributes, String name, Object value) { if ((value instanceof Collection<?> && ((Collection<?>) value).size() != 0)) { attributes.put(name, value); } } }
8,401
0
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ConditionalDescriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.aot.generate; /** * A describer that describes the conditions for the configuration to take effect. */ public interface ConditionalDescriber { String getReachableType(); }
8,402
0
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceBundleDescriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.aot.generate; import java.util.List; import java.util.Objects; import java.util.ResourceBundle; /** * A describer that describes the need to access a {@link ResourceBundle}. */ public class ResourceBundleDescriber implements ConditionalDescriber { private final String name; private final List<String> locales; private final String reachableType; public ResourceBundleDescriber(String name, List<String> locales, String reachableType) { this.name = name; this.locales = locales; this.reachableType = reachableType; } public String getName() { return name; } public List<String> getLocales() { return locales; } @Override public String getReachableType() { return reachableType; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ResourceBundleDescriber that = (ResourceBundleDescriber) o; return name.equals(that.name) && locales.equals(that.locales) && reachableType.equals(that.reachableType); } @Override public int hashCode() { return Objects.hash(name, locales, reachableType); } }
8,403
0
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourcePatternDescriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.aot.generate; import java.util.Arrays; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * A describer that describes resources that should be made available at runtime. */ public class ResourcePatternDescriber implements ConditionalDescriber { private final String pattern; private final String reachableType; public ResourcePatternDescriber(String pattern, String reachableType) { this.pattern = pattern; this.reachableType = reachableType; } public String getPattern() { return pattern; } @Override public String getReachableType() { return reachableType; } public Pattern toRegex() { String prefix = (this.pattern.startsWith("*") ? ".*" : ""); String suffix = (this.pattern.endsWith("*") ? ".*" : ""); String regex = Arrays.stream(this.pattern.split("\\*")) .filter(s -> !s.isEmpty()) .map(Pattern::quote) .collect(Collectors.joining(".*", prefix, suffix)); return Pattern.compile(regex); } }
8,404
0
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/FieldDescriber.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.aot.generate; import java.lang.reflect.Field; /** * A describer that describes the need for reflection on a {@link Field}. */ public class FieldDescriber extends MemberDescriber { protected FieldDescriber(String name) { super(name); } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { return super.equals(obj); } }
8,405
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package demo; public interface MultiClassLoaderService { Object call(MultiClassLoaderServiceRequest innerRequest); }
8,406
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package demo; import java.io.Serializable; public class MultiClassLoaderServiceRequest implements Serializable {}
8,407
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package demo; import java.util.concurrent.atomic.AtomicReference; public class MultiClassLoaderServiceImpl implements MultiClassLoaderService { private AtomicReference<MultiClassLoaderServiceRequest> innerRequestReference; private AtomicReference<MultiClassLoaderServiceResult> innerResultReference; public MultiClassLoaderServiceImpl( AtomicReference<MultiClassLoaderServiceRequest> innerRequestReference, AtomicReference<MultiClassLoaderServiceResult> innerResultReference) { this.innerRequestReference = innerRequestReference; this.innerResultReference = innerResultReference; } @Override public MultiClassLoaderServiceResult call(MultiClassLoaderServiceRequest innerRequest) { innerRequestReference.set(innerRequest); return innerResultReference.get(); } }
8,408
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/demo/MultiClassLoaderServiceResult.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package demo; import java.io.Serializable; public class MultiClassLoaderServiceResult implements Serializable {}
8,409
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/DubboShutdownHookTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static java.util.Arrays.asList; public class DubboShutdownHookTest { private DubboShutdownHook dubboShutdownHook; private ApplicationModel applicationModel; @BeforeEach public void init() { SysProps.setProperty(CommonConstants.IGNORE_LISTEN_SHUTDOWN_HOOK, "false"); FrameworkModel frameworkModel = new FrameworkModel(); applicationModel = frameworkModel.newApplication(); ModuleModel moduleModel = applicationModel.newModule(); dubboShutdownHook = new DubboShutdownHook(applicationModel); } @AfterEach public void clear() { SysProps.clear(); } @Test public void testDubboShutdownHook() { Assertions.assertNotNull(dubboShutdownHook); Assertions.assertLinesMatch(asList("DubboShutdownHook"), asList(dubboShutdownHook.getName())); Assertions.assertFalse(dubboShutdownHook.getRegistered()); } @Test public void testDestoryNoModuleManagedExternally() { boolean hasModuleManagedExternally = false; for (ModuleModel moduleModel : applicationModel.getModuleModels()) { if (moduleModel.isLifeCycleManagedExternally()) { hasModuleManagedExternally = true; break; } } Assertions.assertFalse(hasModuleManagedExternally); dubboShutdownHook.run(); Assertions.assertTrue(applicationModel.isDestroyed()); } @Test public void testDestoryWithModuleManagedExternally() throws InterruptedException { applicationModel.getModuleModels().get(0).setLifeCycleManagedExternally(true); new Thread(() -> { applicationModel.getModuleModels().get(0).destroy(); }) .start(); TimeUnit.MILLISECONDS.sleep(10); dubboShutdownHook.run(); Assertions.assertTrue(applicationModel.isDestroyed()); } }
8,410
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetadataReportConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.common.URL; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; class MetadataReportConfigTest { @Test void testFile() { MetadataReportConfig metadataReportConfig = new MetadataReportConfig(); metadataReportConfig.setFile("file"); assertThat(metadataReportConfig.getFile(), equalTo("file")); metadataReportConfig.setAddress("file://dir-to-file"); URL url = metadataReportConfig.toUrl(); assertThat(url.getParameter("file"), equalTo("file")); } }
8,411
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MetricsConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.common.URL; import org.apache.dubbo.config.nested.AggregationConfig; import org.apache.dubbo.config.nested.HistogramConfig; import org.apache.dubbo.config.nested.PrometheusConfig; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.MetricsConstants.PROTOCOL_PROMETHEUS; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; class MetricsConfigTest { @Test void testToUrl() { MetricsConfig metrics = new MetricsConfig(); metrics.setProtocol(PROTOCOL_PROMETHEUS); PrometheusConfig prometheus = new PrometheusConfig(); PrometheusConfig.Exporter exporter = new PrometheusConfig.Exporter(); PrometheusConfig.Pushgateway pushgateway = new PrometheusConfig.Pushgateway(); exporter.setEnabled(true); pushgateway.setEnabled(true); prometheus.setExporter(exporter); prometheus.setPushgateway(pushgateway); metrics.setPrometheus(prometheus); AggregationConfig aggregation = new AggregationConfig(); aggregation.setEnabled(true); metrics.setAggregation(aggregation); HistogramConfig histogram = new HistogramConfig(); histogram.setEnabled(true); metrics.setHistogram(histogram); URL url = metrics.toUrl(); assertThat(url.getProtocol(), equalTo(PROTOCOL_PROMETHEUS)); assertThat(url.getAddress(), equalTo("localhost:9090")); assertThat(url.getHost(), equalTo("localhost")); assertThat(url.getPort(), equalTo(9090)); assertThat(url.getParameter("prometheus.exporter.enabled"), equalTo("true")); assertThat(url.getParameter("prometheus.pushgateway.enabled"), equalTo("true")); assertThat(url.getParameter("aggregation.enabled"), equalTo("true")); assertThat(url.getParameter("histogram.enabled"), equalTo("true")); } @Test void testProtocol() { MetricsConfig metrics = new MetricsConfig(); metrics.setProtocol(PROTOCOL_PROMETHEUS); assertThat(metrics.getProtocol(), equalTo(PROTOCOL_PROMETHEUS)); } @Test void testPrometheus() { MetricsConfig metrics = new MetricsConfig(); PrometheusConfig prometheus = new PrometheusConfig(); PrometheusConfig.Exporter exporter = new PrometheusConfig.Exporter(); PrometheusConfig.Pushgateway pushgateway = new PrometheusConfig.Pushgateway(); exporter.setEnabled(true); exporter.setEnableHttpServiceDiscovery(true); exporter.setHttpServiceDiscoveryUrl("localhost:8080"); prometheus.setExporter(exporter); pushgateway.setEnabled(true); pushgateway.setBaseUrl("localhost:9091"); pushgateway.setUsername("username"); pushgateway.setPassword("password"); pushgateway.setJob("job"); pushgateway.setPushInterval(30); prometheus.setPushgateway(pushgateway); metrics.setPrometheus(prometheus); assertThat(metrics.getPrometheus().getExporter().getEnabled(), equalTo(true)); assertThat(metrics.getPrometheus().getExporter().getEnableHttpServiceDiscovery(), equalTo(true)); assertThat(metrics.getPrometheus().getExporter().getHttpServiceDiscoveryUrl(), equalTo("localhost:8080")); assertThat(metrics.getPrometheus().getPushgateway().getEnabled(), equalTo(true)); assertThat(metrics.getPrometheus().getPushgateway().getBaseUrl(), equalTo("localhost:9091")); assertThat(metrics.getPrometheus().getPushgateway().getUsername(), equalTo("username")); assertThat(metrics.getPrometheus().getPushgateway().getPassword(), equalTo("password")); assertThat(metrics.getPrometheus().getPushgateway().getJob(), equalTo("job")); assertThat(metrics.getPrometheus().getPushgateway().getPushInterval(), equalTo(30)); } @Test void testAggregation() { MetricsConfig metrics = new MetricsConfig(); AggregationConfig aggregation = new AggregationConfig(); aggregation.setEnabled(true); aggregation.setBucketNum(5); aggregation.setTimeWindowSeconds(120); metrics.setAggregation(aggregation); assertThat(metrics.getAggregation().getEnabled(), equalTo(true)); assertThat(metrics.getAggregation().getBucketNum(), equalTo(5)); assertThat(metrics.getAggregation().getTimeWindowSeconds(), equalTo(120)); } }
8,412
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractServiceConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.EXPORTER_LISTENER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SERVICE_FILTER_KEY; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.assertNull; class AbstractServiceConfigTest { @Test void testVersion() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setVersion("version"); assertThat(serviceConfig.getVersion(), equalTo("version")); } @Test void testGroup() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setGroup("group"); assertThat(serviceConfig.getGroup(), equalTo("group")); } @Test void testDelay() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setDelay(1000); assertThat(serviceConfig.getDelay(), equalTo(1000)); } @Test void testExport() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setExport(true); assertThat(serviceConfig.getExport(), is(true)); } @Test void testWeight() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setWeight(500); assertThat(serviceConfig.getWeight(), equalTo(500)); } @Test void testDocument() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setDocument("http://dubbo.apache.org"); assertThat(serviceConfig.getDocument(), equalTo("http://dubbo.apache.org")); Map<String, String> parameters = new HashMap<String, String>(); AbstractServiceConfig.appendParameters(parameters, serviceConfig); assertThat(parameters, hasEntry("document", "http%3A%2F%2Fdubbo.apache.org")); } @Test void testToken() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setToken("token"); assertThat(serviceConfig.getToken(), equalTo("token")); serviceConfig.setToken((Boolean) null); assertThat(serviceConfig.getToken(), nullValue()); serviceConfig.setToken(true); assertThat(serviceConfig.getToken(), is("true")); } @Test void testDeprecated() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setDeprecated(true); assertThat(serviceConfig.isDeprecated(), is(true)); } @Test void testDynamic() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setDynamic(true); assertThat(serviceConfig.isDynamic(), is(true)); } @Test void testProtocol() { ServiceConfig serviceConfig = new ServiceConfig(); assertThat(serviceConfig.getProtocol(), nullValue()); serviceConfig.setProtocol(new ProtocolConfig()); assertThat(serviceConfig.getProtocol(), notNullValue()); serviceConfig.setProtocols(new ArrayList<>(Collections.singletonList(new ProtocolConfig()))); assertThat(serviceConfig.getProtocols(), hasSize(1)); } @Test void testAccesslog() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setAccesslog("access.log"); assertThat(serviceConfig.getAccesslog(), equalTo("access.log")); serviceConfig.setAccesslog((Boolean) null); assertThat(serviceConfig.getAccesslog(), nullValue()); serviceConfig.setAccesslog(true); assertThat(serviceConfig.getAccesslog(), equalTo("true")); } @Test void testExecutes() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setExecutes(10); assertThat(serviceConfig.getExecutes(), equalTo(10)); } @Test void testFilter() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setFilter("mockfilter"); assertThat(serviceConfig.getFilter(), equalTo("mockfilter")); Map<String, String> parameters = new HashMap<String, String>(); parameters.put(SERVICE_FILTER_KEY, "prefilter"); AbstractServiceConfig.appendParameters(parameters, serviceConfig); assertThat(parameters, hasEntry(SERVICE_FILTER_KEY, "prefilter,mockfilter")); } @Test void testListener() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setListener("mockexporterlistener"); assertThat(serviceConfig.getListener(), equalTo("mockexporterlistener")); Map<String, String> parameters = new HashMap<String, String>(); parameters.put(EXPORTER_LISTENER_KEY, "prelistener"); AbstractServiceConfig.appendParameters(parameters, serviceConfig); assertThat(parameters, hasEntry(EXPORTER_LISTENER_KEY, "prelistener,mockexporterlistener")); } @Test void testRegister() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setRegister(true); assertThat(serviceConfig.isRegister(), is(true)); } @Test void testWarmup() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setWarmup(100); assertThat(serviceConfig.getWarmup(), equalTo(100)); } @Test void testSerialization() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setSerialization("serialization"); assertThat(serviceConfig.getSerialization(), equalTo("serialization")); } @Test void testPreferSerialization() { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setPreferSerialization("preferSerialization"); assertThat(serviceConfig.getPreferSerialization(), equalTo("preferSerialization")); } @Test void testPreferSerializationDefault1() { ServiceConfig serviceConfig = new ServiceConfig(); assertNull(serviceConfig.getPreferSerialization()); serviceConfig.checkDefault(); assertNull(serviceConfig.getPreferSerialization()); serviceConfig = new ServiceConfig(); serviceConfig.setSerialization("x-serialization"); assertNull(serviceConfig.getPreferSerialization()); serviceConfig.checkDefault(); assertThat(serviceConfig.getPreferSerialization(), equalTo("x-serialization")); } @Test void testPreferSerializationDefault2() { ServiceConfig serviceConfig = new ServiceConfig(); assertNull(serviceConfig.getPreferSerialization()); serviceConfig.refresh(); assertNull(serviceConfig.getPreferSerialization()); serviceConfig = new ServiceConfig(); serviceConfig.setSerialization("x-serialization"); assertNull(serviceConfig.getPreferSerialization()); serviceConfig.refresh(); assertThat(serviceConfig.getPreferSerialization(), equalTo("x-serialization")); } private static class ServiceConfig extends AbstractServiceConfig {} }
8,413
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.api.Greeting; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.context.ConfigMode; import org.apache.dubbo.config.support.Nested; import org.apache.dubbo.config.support.Parameter; import org.apache.dubbo.config.utils.ConfigValidationUtils; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ScopeModel; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; class AbstractConfigTest { @BeforeEach public void beforeEach() { DubboBootstrap.reset(); } @AfterEach public void afterEach() { SysProps.clear(); } @Test void testValidateProtocolConfig() { ProtocolConfig protocolConfig = new ProtocolConfig(); protocolConfig.setCodec("exchange"); protocolConfig.setName("test"); protocolConfig.setHost("host"); ConfigValidationUtils.validateProtocolConfig(protocolConfig); } @Test void testAppendParameters1() { Map<String, String> parameters = new HashMap<String, String>(); parameters.put("num", "ONE"); AbstractConfig.appendParameters(parameters, new ParameterConfig(1, "hello/world", 30, "password"), "prefix"); Assertions.assertEquals("one", parameters.get("prefix.key.1")); Assertions.assertEquals("two", parameters.get("prefix.key.2")); Assertions.assertEquals("ONE,1", parameters.get("prefix.num")); Assertions.assertEquals("hello%2Fworld", parameters.get("prefix.naming")); Assertions.assertEquals("30", parameters.get("prefix.age")); Assertions.assertFalse(parameters.containsKey("prefix.secret")); } @Test void testAppendParameters2() { Assertions.assertThrows(IllegalStateException.class, () -> { Map<String, String> parameters = new HashMap<String, String>(); AbstractConfig.appendParameters(parameters, new ParameterConfig()); }); } @Test void testAppendParameters3() { Map<String, String> parameters = new HashMap<String, String>(); AbstractConfig.appendParameters(parameters, null); assertTrue(parameters.isEmpty()); } @Test void testAppendParameters4() { Map<String, String> parameters = new HashMap<String, String>(); AbstractConfig.appendParameters(parameters, new ParameterConfig(1, "hello/world", 30, "password")); Assertions.assertEquals("one", parameters.get("key.1")); Assertions.assertEquals("two", parameters.get("key.2")); Assertions.assertEquals("1", parameters.get("num")); Assertions.assertEquals("hello%2Fworld", parameters.get("naming")); Assertions.assertEquals("30", parameters.get("age")); } @Test void testAppendAttributes1() { ParameterConfig config = new ParameterConfig(1, "hello/world", 30, "password", "BEIJING"); Map<String, String> parameters = new HashMap<>(); AbstractConfig.appendParameters(parameters, config); Map<String, String> attributes = new HashMap<>(); AbstractConfig.appendAttributes(attributes, config); Assertions.assertEquals(null, parameters.get("secret")); Assertions.assertEquals(null, parameters.get("parameters")); // secret is excluded for url parameters, but keep for attributes Assertions.assertEquals(config.getSecret(), attributes.get("secret")); Assertions.assertEquals(config.getName(), attributes.get("name")); Assertions.assertEquals(String.valueOf(config.getNumber()), attributes.get("number")); Assertions.assertEquals(String.valueOf(config.getAge()), attributes.get("age")); Assertions.assertEquals(StringUtils.encodeParameters(config.getParameters()), attributes.get("parameters")); Assertions.assertTrue(parameters.containsKey("detail.address")); // detailAddress -> detail.address Assertions.assertTrue(attributes.containsKey("detail-address")); // detailAddress -> detail-address } @Test void checkExtension() { Assertions.assertThrows( IllegalStateException.class, () -> ConfigValidationUtils.checkExtension( ApplicationModel.defaultModel(), Greeting.class, "hello", "world")); } @Test void checkMultiExtension1() { Assertions.assertThrows( IllegalStateException.class, () -> ConfigValidationUtils.checkMultiExtension( ApplicationModel.defaultModel(), Greeting.class, "hello", "default,world")); } @Test void checkMultiExtension2() { try { ConfigValidationUtils.checkMultiExtension( ApplicationModel.defaultModel(), Greeting.class, "hello", "default,-world"); } catch (Throwable t) { Assertions.fail(t); } } @Test void checkMultiExtension3() { Assertions.assertThrows( IllegalStateException.class, () -> ConfigValidationUtils.checkMultiExtension( ApplicationModel.defaultModel(), Greeting.class, "hello", "default , world")); } @Test void checkMultiExtension4() { try { ConfigValidationUtils.checkMultiExtension( ApplicationModel.defaultModel(), Greeting.class, "hello", "default , -world "); } catch (Throwable t) { Assertions.fail(t); } } @Test void checkLength() { Assertions.assertDoesNotThrow(() -> { StringBuilder builder = new StringBuilder(); for (int i = 0; i <= 200; i++) { builder.append('a'); } ConfigValidationUtils.checkLength("hello", builder.toString()); }); } @Test void checkPathLength() { Assertions.assertDoesNotThrow(() -> { StringBuilder builder = new StringBuilder(); for (int i = 0; i <= 200; i++) { builder.append('a'); } ConfigValidationUtils.checkPathLength("hello", builder.toString()); }); } @Test void checkName() { Assertions.assertDoesNotThrow(() -> ConfigValidationUtils.checkName("hello", "world%")); } @Test void checkNameHasSymbol() { try { ConfigValidationUtils.checkNameHasSymbol("hello", ":*,/ -0123\tabcdABCD"); ConfigValidationUtils.checkNameHasSymbol("mock", "force:return world"); } catch (Exception e) { fail("the value should be legal."); } } @Test void checkKey() { try { ConfigValidationUtils.checkKey("hello", "*,-0123abcdABCD"); } catch (Exception e) { fail("the value should be legal."); } } @Test void checkMultiName() { try { ConfigValidationUtils.checkMultiName("hello", ",-._0123abcdABCD"); } catch (Exception e) { fail("the value should be legal."); } } @Test void checkPathName() { try { ConfigValidationUtils.checkPathName("hello", "/-$._0123abcdABCD"); } catch (Exception e) { fail("the value should be legal."); } } @Test void checkMethodName() { try { ConfigValidationUtils.checkMethodName("hello", "abcdABCD0123abcd"); } catch (Exception e) { fail("the value should be legal."); } try { ConfigValidationUtils.checkMethodName("hello", "0a"); } catch (Exception e) { // ignore fail("the value should be legal."); } } @Test void checkParameterName() { Map<String, String> parameters = Collections.singletonMap("hello", ":*,/-._0123abcdABCD"); try { ConfigValidationUtils.checkParameterName(parameters); } catch (Exception e) { fail("the value should be legal."); } } @Test @Config( interfaceClass = Greeting.class, filter = {"f1, f2"}, listener = {"l1, l2"}, parameters = {"k1", "v1", "k2", "v2"}) public void appendAnnotation() throws Exception { Config config = getClass().getMethod("appendAnnotation").getAnnotation(Config.class); AnnotationConfig annotationConfig = new AnnotationConfig(); annotationConfig.appendAnnotation(Config.class, config); Assertions.assertSame(Greeting.class, annotationConfig.getInterface()); Assertions.assertEquals("f1, f2", annotationConfig.getFilter()); Assertions.assertEquals("l1, l2", annotationConfig.getListener()); Assertions.assertEquals(2, annotationConfig.getParameters().size()); Assertions.assertEquals("v1", annotationConfig.getParameters().get("k1")); Assertions.assertEquals("v2", annotationConfig.getParameters().get("k2")); assertThat(annotationConfig.toString(), Matchers.containsString("filter=\"f1, f2\" ")); assertThat(annotationConfig.toString(), Matchers.containsString("listener=\"l1, l2\" ")); } @Test void testRefreshAll() { try { OverrideConfig overrideConfig = new OverrideConfig(); overrideConfig.setAddress("override-config://127.0.0.1:2181"); overrideConfig.setProtocol("override-config"); overrideConfig.setEscape("override-config://"); overrideConfig.setExclude("override-config"); Map<String, String> external = new HashMap<>(); external.put("dubbo.override.address", "external://127.0.0.1:2181"); // @Parameter(exclude=true) external.put("dubbo.override.exclude", "external"); // @Parameter(key="key1", useKeyAsProperty=false) external.put("dubbo.override.key", "external"); // @Parameter(key="key2", useKeyAsProperty=true) external.put("dubbo.override.key2", "external"); ApplicationModel.defaultModel().modelEnvironment().initialize(); ApplicationModel.defaultModel().modelEnvironment().setExternalConfigMap(external); SysProps.setProperty("dubbo.override.address", "system://127.0.0.1:2181"); SysProps.setProperty("dubbo.override.protocol", "system"); // this will not override, use 'key' instead, @Parameter(key="key1", useKeyAsProperty=false) SysProps.setProperty("dubbo.override.key1", "system"); SysProps.setProperty("dubbo.override.key2", "system"); // Load configuration from system properties -> externalConfiguration -> RegistryConfig -> dubbo.properties overrideConfig.refresh(); Assertions.assertEquals("system://127.0.0.1:2181", overrideConfig.getAddress()); Assertions.assertEquals("system", overrideConfig.getProtocol()); Assertions.assertEquals("override-config://", overrideConfig.getEscape()); Assertions.assertEquals("external", overrideConfig.getKey()); Assertions.assertEquals("system", overrideConfig.getKey2()); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); } } @Test void testRefreshSystem() { try { OverrideConfig overrideConfig = new OverrideConfig(); overrideConfig.setAddress("override-config://127.0.0.1:2181"); overrideConfig.setProtocol("override-config"); overrideConfig.setEscape("override-config://"); overrideConfig.setExclude("override-config"); SysProps.setProperty("dubbo.override.address", "system://127.0.0.1:2181"); SysProps.setProperty("dubbo.override.protocol", "system"); SysProps.setProperty("dubbo.override.key", "system"); overrideConfig.refresh(); Assertions.assertEquals("system://127.0.0.1:2181", overrideConfig.getAddress()); Assertions.assertEquals("system", overrideConfig.getProtocol()); Assertions.assertEquals("override-config://", overrideConfig.getEscape()); Assertions.assertEquals("system", overrideConfig.getKey()); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); } } @Test void testRefreshProperties() throws Exception { try { ApplicationModel.defaultModel().modelEnvironment().setExternalConfigMap(new HashMap<>()); OverrideConfig overrideConfig = new OverrideConfig(); overrideConfig.setAddress("override-config://127.0.0.1:2181"); overrideConfig.setProtocol("override-config"); overrideConfig.setEscape("override-config://"); Properties properties = new Properties(); properties.load(this.getClass().getResourceAsStream("/dubbo.properties")); ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .setProperties(properties); overrideConfig.refresh(); Assertions.assertEquals("override-config://127.0.0.1:2181", overrideConfig.getAddress()); Assertions.assertEquals("override-config", overrideConfig.getProtocol()); Assertions.assertEquals("override-config://", overrideConfig.getEscape()); Assertions.assertEquals("properties", overrideConfig.getKey2()); // Assertions.assertEquals("properties", overrideConfig.getUseKeyAsProperty()); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); } } @Test void testRefreshExternal() { try { OverrideConfig overrideConfig = new OverrideConfig(); overrideConfig.setAddress("override-config://127.0.0.1:2181"); overrideConfig.setProtocol("override-config"); overrideConfig.setEscape("override-config://"); overrideConfig.setExclude("override-config"); Map<String, String> external = new HashMap<>(); external.put("dubbo.override.address", "external://127.0.0.1:2181"); external.put("dubbo.override.protocol", "external"); external.put("dubbo.override.escape", "external://"); // @Parameter(exclude=true) external.put("dubbo.override.exclude", "external"); // @Parameter(key="key1", useKeyAsProperty=false) external.put("dubbo.override.key", "external"); // @Parameter(key="key2", useKeyAsProperty=true) external.put("dubbo.override.key2", "external"); ApplicationModel.defaultModel().modelEnvironment().initialize(); ApplicationModel.defaultModel().modelEnvironment().setExternalConfigMap(external); overrideConfig.refresh(); Assertions.assertEquals("external://127.0.0.1:2181", overrideConfig.getAddress()); Assertions.assertEquals("external", overrideConfig.getProtocol()); Assertions.assertEquals("external://", overrideConfig.getEscape()); Assertions.assertEquals("external", overrideConfig.getExclude()); Assertions.assertEquals("external", overrideConfig.getKey()); Assertions.assertEquals("external", overrideConfig.getKey2()); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); } } @Test void testRefreshById() { try { OverrideConfig overrideConfig = new OverrideConfig(); overrideConfig.setId("override-id"); overrideConfig.setAddress("override-config://127.0.0.1:2181"); overrideConfig.setProtocol("override-config"); overrideConfig.setEscape("override-config://"); overrideConfig.setExclude("override-config"); Map<String, String> external = new HashMap<>(); external.put("dubbo.overrides.override-id.address", "external-override-id://127.0.0.1:2181"); external.put("dubbo.overrides.override-id.key", "external"); external.put("dubbo.overrides.override-id.key2", "external"); external.put("dubbo.override.address", "external://127.0.0.1:2181"); external.put("dubbo.override.exclude", "external"); ApplicationModel.defaultModel().modelEnvironment().initialize(); ApplicationModel.defaultModel().modelEnvironment().setExternalConfigMap(external); // refresh config overrideConfig.refresh(); Assertions.assertEquals("external-override-id://127.0.0.1:2181", overrideConfig.getAddress()); Assertions.assertEquals("override-config", overrideConfig.getProtocol()); Assertions.assertEquals("override-config://", overrideConfig.getEscape()); Assertions.assertEquals("external", overrideConfig.getKey()); Assertions.assertEquals("external", overrideConfig.getKey2()); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); } } @Test void testRefreshParameters() { try { Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "value1"); parameters.put("key2", "value2"); OverrideConfig overrideConfig = new OverrideConfig(); overrideConfig.setParameters(parameters); Map<String, String> external = new HashMap<>(); external.put("dubbo.override.parameters", "[{key3:value3},{key4:value4},{key2:value5}]"); ApplicationModel.defaultModel().modelEnvironment().initialize(); ApplicationModel.defaultModel().modelEnvironment().setExternalConfigMap(external); // refresh config overrideConfig.refresh(); Assertions.assertEquals("value1", overrideConfig.getParameters().get("key1")); Assertions.assertEquals("value5", overrideConfig.getParameters().get("key2")); Assertions.assertEquals("value3", overrideConfig.getParameters().get("key3")); Assertions.assertEquals("value4", overrideConfig.getParameters().get("key4")); SysProps.setProperty("dubbo.override.parameters", "[{key3:value6}]"); overrideConfig.refresh(); Assertions.assertEquals("value6", overrideConfig.getParameters().get("key3")); Assertions.assertEquals("value4", overrideConfig.getParameters().get("key4")); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); } } @Test void testRefreshParametersWithAttribute() { try { OverrideConfig overrideConfig = new OverrideConfig(); SysProps.setProperty("dubbo.override.parameters.key00", "value00"); overrideConfig.refresh(); assertEquals("value00", overrideConfig.getParameters().get("key00")); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); } } @Test void testRefreshParametersWithOverrideConfigMode() { FrameworkModel frameworkModel = new FrameworkModel(); try { // test OVERRIDE_ALL configMode { SysProps.setProperty(ConfigKeys.DUBBO_CONFIG_MODE, ConfigMode.OVERRIDE_ALL.name()); SysProps.setProperty("dubbo.override.address", "system://127.0.0.1:2181"); SysProps.setProperty("dubbo.override.protocol", "system"); SysProps.setProperty("dubbo.override.parameters", "[{key1:systemValue1},{key2:systemValue2}]"); ApplicationModel applicationModel1 = frameworkModel.newApplication(); OverrideConfig overrideConfig = new OverrideConfig(applicationModel1); overrideConfig.setAddress("override-config://127.0.0.1:2181"); overrideConfig.setProtocol("override-config"); Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "value1"); parameters.put("key3", "value3"); overrideConfig.setParameters(parameters); // overrideConfig's config is overridden by system config overrideConfig.refresh(); Assertions.assertEquals(overrideConfig.getAddress(), "system://127.0.0.1:2181"); Assertions.assertEquals(overrideConfig.getProtocol(), "system"); Assertions.assertEquals( overrideConfig.getParameters(), StringUtils.parseParameters("[{key1:systemValue1},{key2:systemValue2},{key3:value3}]")); } // test OVERRIDE_IF_ABSENT configMode { SysProps.setProperty(ConfigKeys.DUBBO_CONFIG_MODE, ConfigMode.OVERRIDE_IF_ABSENT.name()); SysProps.setProperty("dubbo.override.address", "system://127.0.0.1:2181"); SysProps.setProperty("dubbo.override.protocol", "system"); SysProps.setProperty("dubbo.override.parameters", "[{key1:systemValue1},{key2:systemValue2}]"); SysProps.setProperty("dubbo.override.key", "systemKey"); ApplicationModel applicationModel = frameworkModel.newApplication(); OverrideConfig overrideConfig = new OverrideConfig(applicationModel); overrideConfig.setAddress("override-config://127.0.0.1:2181"); overrideConfig.setProtocol("override-config"); Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "value1"); parameters.put("key3", "value3"); overrideConfig.setParameters(parameters); // overrideConfig's config is overridden/set by system config only when the overrideConfig's config is // absent/empty overrideConfig.refresh(); Assertions.assertEquals(overrideConfig.getAddress(), "override-config://127.0.0.1:2181"); Assertions.assertEquals(overrideConfig.getProtocol(), "override-config"); Assertions.assertEquals(overrideConfig.getKey(), "systemKey"); Assertions.assertEquals( overrideConfig.getParameters(), StringUtils.parseParameters("[{key1:value1},{key2:systemValue2},{key3:value3}]")); } } finally { frameworkModel.destroy(); } } @Test void testOnlyPrefixedKeyTakeEffect() { try { OverrideConfig overrideConfig = new OverrideConfig(); overrideConfig.setNotConflictKey("value-from-config"); Map<String, String> external = new HashMap<>(); external.put("notConflictKey", "value-from-external"); external.put("dubbo.override.notConflictKey2", "value-from-external"); ApplicationModel.defaultModel().modelEnvironment().setExternalConfigMap(external); overrideConfig.refresh(); Assertions.assertEquals("value-from-config", overrideConfig.getNotConflictKey()); Assertions.assertEquals("value-from-external", overrideConfig.getNotConflictKey2()); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); } } @Test void tetMetaData() { OverrideConfig overrideConfig = new OverrideConfig(); overrideConfig.setId("override-id"); overrideConfig.setAddress("override-config://127.0.0.1:2181"); overrideConfig.setProtocol("override-config"); overrideConfig.setEscape("override-config://"); overrideConfig.setExclude("override-config"); Map<String, String> metaData = overrideConfig.getMetaData(); Assertions.assertEquals("override-config://127.0.0.1:2181", metaData.get("address")); Assertions.assertEquals("override-config", metaData.get("protocol")); Assertions.assertEquals("override-config://", metaData.get("escape")); Assertions.assertEquals("override-config", metaData.get("exclude")); Assertions.assertNull(metaData.get("key")); Assertions.assertNull(metaData.get("key2")); // with prefix Map<String, String> prefixMetadata = overrideConfig.getMetaData(OverrideConfig.getTypePrefix(OverrideConfig.class)); Assertions.assertEquals("override-config://127.0.0.1:2181", prefixMetadata.get("dubbo.override.address")); Assertions.assertEquals("override-config", prefixMetadata.get("dubbo.override.protocol")); Assertions.assertEquals("override-config://", prefixMetadata.get("dubbo.override.escape")); Assertions.assertEquals("override-config", prefixMetadata.get("dubbo.override.exclude")); } @Test void testEquals() { ApplicationConfig application1 = new ApplicationConfig(); ApplicationConfig application2 = new ApplicationConfig(); application1.setName("app1"); application2.setName("app2"); Assertions.assertNotEquals(application1, application2); application1.setName("sameName"); application2.setName("sameName"); Assertions.assertEquals(application1, application2); ProtocolConfig protocol1 = new ProtocolConfig(); protocol1.setName("dubbo"); protocol1.setPort(1234); ProtocolConfig protocol2 = new ProtocolConfig(); protocol2.setName("dubbo"); protocol2.setPort(1235); Assertions.assertNotEquals(protocol1, protocol2); } @Test void testRegistryConfigEquals() { RegistryConfig hangzhou = new RegistryConfig(); hangzhou.setAddress("nacos://localhost:8848"); HashMap<String, String> parameters = new HashMap<>(); parameters.put("namespace", "hangzhou"); hangzhou.setParameters(parameters); RegistryConfig shanghai = new RegistryConfig(); shanghai.setAddress("nacos://localhost:8848"); parameters = new HashMap<>(); parameters.put("namespace", "shanghai"); shanghai.setParameters(parameters); Assertions.assertNotEquals(hangzhou, shanghai); } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.ANNOTATION_TYPE}) public @interface ConfigField { String value() default ""; } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.METHOD, ElementType.ANNOTATION_TYPE}) public @interface Config { Class<?> interfaceClass() default void.class; String interfaceName() default ""; String[] filter() default {}; String[] listener() default {}; String[] parameters() default {}; ConfigField[] configFields() default {}; ConfigField configField() default @ConfigField; } private static class OverrideConfig extends AbstractConfig { public String address; public String protocol; public String exclude; public String key; public String key2; public String escape; public String notConflictKey; public String notConflictKey2; protected Map<String, String> parameters; public OverrideConfig() {} public OverrideConfig(ScopeModel scopeModel) { super(scopeModel); } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } @Parameter(excluded = true) public String getExclude() { return exclude; } public void setExclude(String exclude) { this.exclude = exclude; } @Parameter(key = "key1") public String getKey() { return key; } public void setKey(String key) { this.key = key; } @Parameter(key = "mykey") public String getKey2() { return key2; } public void setKey2(String key2) { this.key2 = key2; } @Parameter(escaped = true) public String getEscape() { return escape; } public void setEscape(String escape) { this.escape = escape; } public String getNotConflictKey() { return notConflictKey; } public void setNotConflictKey(String notConflictKey) { this.notConflictKey = notConflictKey; } public String getNotConflictKey2() { return notConflictKey2; } public void setNotConflictKey2(String notConflictKey2) { this.notConflictKey2 = notConflictKey2; } public Map<String, String> getParameters() { return parameters; } public void setParameters(Map<String, String> parameters) { this.parameters = parameters; } } private static class ParameterConfig { private int number; private String name; private int age; private String secret; private String detailAddress; ParameterConfig() {} ParameterConfig(int number, String name, int age, String secret) { this(number, name, age, secret, ""); } ParameterConfig(int number, String name, int age, String secret, String detailAddress) { this.number = number; this.name = name; this.age = age; this.secret = secret; this.detailAddress = detailAddress; } public String getDetailAddress() { return detailAddress; } public void setDetailAddress(String detailAddress) { this.detailAddress = detailAddress; } @Parameter(key = "num", append = true) public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } @Parameter(key = "naming", append = true, escaped = true, required = true) public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Parameter(excluded = true) public String getSecret() { return secret; } public void setSecret(String secret) { this.secret = secret; } public Map getParameters() { Map<String, String> map = new HashMap<String, String>(); map.put("key.1", "one"); map.put("key.2", "two"); return map; } } private static class AnnotationConfig extends AbstractConfig { private Class interfaceClass; private String filter; private String listener; private Map<String, String> parameters; private String[] configFields; public Class getInterface() { return interfaceClass; } public void setInterface(Class interfaceName) { this.interfaceClass = interfaceName; } public String getFilter() { return filter; } public void setFilter(String filter) { this.filter = filter; } public String getListener() { return listener; } public void setListener(String listener) { this.listener = listener; } public Map<String, String> getParameters() { return parameters; } public void setParameters(Map<String, String> parameters) { this.parameters = parameters; } public String[] getConfigFields() { return configFields; } public void setConfigFields(String[] configFields) { this.configFields = configFields; } } @Test void testMetaData() throws Exception { // Expect empty metadata for new instance // Check and set default value of field in checkDefault() method List<Class<? extends AbstractConfig>> configClasses = Arrays.asList( ApplicationConfig.class, ConsumerConfig.class, ProviderConfig.class, ReferenceConfig.class, ServiceConfig.class, ProtocolConfig.class, RegistryConfig.class, ConfigCenterConfig.class, MetadataReportConfig.class, ModuleConfig.class, SslConfig.class, MetricsConfig.class, MonitorConfig.class, MethodConfig.class); for (Class<? extends AbstractConfig> configClass : configClasses) { AbstractConfig config = configClass.getDeclaredConstructor().newInstance(); Map<String, String> metaData = config.getMetaData(); Assertions.assertEquals( 0, metaData.size(), "Expect empty metadata for new instance but found: " + metaData + " of " + configClass.getSimpleName()); System.out.println(configClass.getSimpleName() + " metadata is checked."); } } @Test void testRefreshNested() { try { OuterConfig outerConfig = new OuterConfig(); Map<String, String> external = new HashMap<>(); external.put("dubbo.outer.a1", "1"); external.put("dubbo.outer.b.b1", "11"); external.put("dubbo.outer.b.b2", "12"); ApplicationModel.defaultModel().modelEnvironment().initialize(); ApplicationModel.defaultModel().modelEnvironment().setExternalConfigMap(external); // refresh config outerConfig.refresh(); Assertions.assertEquals(1, outerConfig.getA1()); Assertions.assertEquals(11, outerConfig.getB().getB1()); Assertions.assertEquals(12, outerConfig.getB().getB2()); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); } } @Test void testRefreshNestedWithId() { try { System.setProperty("dubbo.outers.test.a1", "1"); System.setProperty("dubbo.outers.test.b.b1", "11"); System.setProperty("dubbo.outers.test.b.b2", "12"); ApplicationModel.defaultModel().modelEnvironment().initialize(); OuterConfig outerConfig = new OuterConfig("test"); outerConfig.refresh(); Assertions.assertEquals(1, outerConfig.getA1()); Assertions.assertEquals(11, outerConfig.getB().getB1()); Assertions.assertEquals(12, outerConfig.getB().getB2()); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); System.clearProperty("dubbo.outers.test.a1"); System.clearProperty("dubbo.outers.test.b.b1"); System.clearProperty("dubbo.outers.test.b.b2"); } } @Test void testRefreshNestedBySystemProperties() { try { Properties p = System.getProperties(); p.put("dubbo.outer.a1", "1"); p.put("dubbo.outer.b.b1", "11"); p.put("dubbo.outer.b.b2", "12"); ApplicationModel.defaultModel().modelEnvironment().initialize(); OuterConfig outerConfig = new OuterConfig(); outerConfig.refresh(); Assertions.assertEquals(1, outerConfig.getA1()); Assertions.assertEquals(11, outerConfig.getB().getB1()); Assertions.assertEquals(12, outerConfig.getB().getB2()); } finally { ApplicationModel.defaultModel().modelEnvironment().destroy(); System.clearProperty("dubbo.outer.a1"); System.clearProperty("dubbo.outer.b.b1"); System.clearProperty("dubbo.outer.b.b2"); } } private static class OuterConfig extends AbstractConfig { private Integer a1; @Nested private InnerConfig b; OuterConfig() {} OuterConfig(String id) { this.setId(id); } public Integer getA1() { return a1; } public void setA1(Integer a1) { this.a1 = a1; } public InnerConfig getB() { return b; } public void setB(InnerConfig b) { this.b = b; } } public static class InnerConfig { private Integer b1; private Integer b2; public Integer getB1() { return b1; } public void setB1(Integer b1) { this.b1 = b1; } public Integer getB2() { return b2; } public void setB2(Integer b2) { this.b2 = b2; } } }
8,414
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigScopeModelInitializerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class ConfigScopeModelInitializerTest { private FrameworkModel frameworkModel; private ApplicationModel applicationModel; private ModuleModel moduleModel; @BeforeEach public void setUp() { frameworkModel = new FrameworkModel(); applicationModel = frameworkModel.newApplication(); moduleModel = applicationModel.newModule(); } @AfterEach public void reset() { frameworkModel.destroy(); } @Test void test() { Assertions.assertNotNull(applicationModel.getDeployer()); Assertions.assertNotNull(moduleModel.getDeployer()); } }
8,415
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ArgumentConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; class ArgumentConfigTest { @Test void testIndex() { ArgumentConfig argument = new ArgumentConfig(); argument.setIndex(1); assertThat(argument.getIndex(), is(1)); } @Test void testType() { ArgumentConfig argument = new ArgumentConfig(); argument.setType("int"); assertThat(argument.getType(), equalTo("int")); } @Test void testCallback() { ArgumentConfig argument = new ArgumentConfig(); argument.setCallback(true); assertThat(argument.isCallback(), is(true)); } @Test void testArguments() { ArgumentConfig argument = new ArgumentConfig(); argument.setIndex(1); argument.setType("int"); argument.setCallback(true); Map<String, String> parameters = new HashMap<String, String>(); AbstractServiceConfig.appendParameters(parameters, argument); assertThat(parameters, hasEntry("callback", "true")); assertThat(parameters.size(), is(1)); } }
8,416
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ApplicationConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_MANAGEMENT_MODE_ISOLATION; import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.sameInstance; import static org.hamcrest.collection.IsCollectionWithSize.hasSize; class ApplicationConfigTest { @BeforeEach public void beforeEach() { DubboBootstrap.reset(); } @AfterEach public void afterEach() { SysProps.clear(); } @Test void testName() { ApplicationConfig application = new ApplicationConfig(); application.setName("app"); assertThat(application.getName(), equalTo("app")); assertThat(application.getId(), equalTo(null)); application = new ApplicationConfig("app2"); assertThat(application.getName(), equalTo("app2")); assertThat(application.getId(), equalTo(null)); Map<String, String> parameters = new HashMap<String, String>(); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry(APPLICATION_KEY, "app2")); } @Test void testVersion() { ApplicationConfig application = new ApplicationConfig("app"); application.setVersion("1.0.0"); assertThat(application.getVersion(), equalTo("1.0.0")); Map<String, String> parameters = new HashMap<String, String>(); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry("application.version", "1.0.0")); } @Test void testOwner() { ApplicationConfig application = new ApplicationConfig("app"); application.setOwner("owner"); assertThat(application.getOwner(), equalTo("owner")); } @Test void testOrganization() { ApplicationConfig application = new ApplicationConfig("app"); application.setOrganization("org"); assertThat(application.getOrganization(), equalTo("org")); } @Test void testArchitecture() { ApplicationConfig application = new ApplicationConfig("app"); application.setArchitecture("arch"); assertThat(application.getArchitecture(), equalTo("arch")); } @Test void testEnvironment1() { ApplicationConfig application = new ApplicationConfig("app"); application.setEnvironment("develop"); assertThat(application.getEnvironment(), equalTo("develop")); application.setEnvironment("test"); assertThat(application.getEnvironment(), equalTo("test")); application.setEnvironment("product"); assertThat(application.getEnvironment(), equalTo("product")); } @Test void testEnvironment2() { Assertions.assertThrows(IllegalStateException.class, () -> { ApplicationConfig application = new ApplicationConfig("app"); application.setEnvironment("illegal-env"); }); } @Test void testRegistry() { ApplicationConfig application = new ApplicationConfig("app"); RegistryConfig registry = new RegistryConfig(); application.setRegistry(registry); assertThat(application.getRegistry(), sameInstance(registry)); application.setRegistries(Collections.singletonList(registry)); assertThat(application.getRegistries(), contains(registry)); assertThat(application.getRegistries(), hasSize(1)); } @Test void testMonitor() { ApplicationConfig application = new ApplicationConfig("app"); application.setMonitor(new MonitorConfig("monitor-addr")); assertThat(application.getMonitor().getAddress(), equalTo("monitor-addr")); application.setMonitor("monitor-addr"); assertThat(application.getMonitor().getAddress(), equalTo("monitor-addr")); } @Test void testLogger() { ApplicationConfig application = new ApplicationConfig("app"); application.setLogger("log4j"); assertThat(application.getLogger(), equalTo("log4j")); } @Test void testDefault() { ApplicationConfig application = new ApplicationConfig("app"); application.setDefault(true); assertThat(application.isDefault(), is(true)); } @Test void testDumpDirectory() { ApplicationConfig application = new ApplicationConfig("app"); application.setDumpDirectory("/dump"); assertThat(application.getDumpDirectory(), equalTo("/dump")); Map<String, String> parameters = new HashMap<String, String>(); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry(DUMP_DIRECTORY, "/dump")); } @Test void testQosEnable() { ApplicationConfig application = new ApplicationConfig("app"); application.setQosEnable(true); assertThat(application.getQosEnable(), is(true)); Map<String, String> parameters = new HashMap<String, String>(); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry(QOS_ENABLE, "true")); } @Test void testQosPort() { ApplicationConfig application = new ApplicationConfig("app"); application.setQosPort(8080); assertThat(application.getQosPort(), equalTo(8080)); } @Test void testQosAcceptForeignIp() { ApplicationConfig application = new ApplicationConfig("app"); application.setQosAcceptForeignIp(true); assertThat(application.getQosAcceptForeignIp(), is(true)); Map<String, String> parameters = new HashMap<String, String>(); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry(ACCEPT_FOREIGN_IP, "true")); } @Test void testParameters() throws Exception { ApplicationConfig application = new ApplicationConfig("app"); application.setQosAcceptForeignIp(true); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("k1", "v1"); ApplicationConfig.appendParameters(parameters, application); assertThat(parameters, hasEntry("k1", "v1")); assertThat(parameters, hasEntry(ACCEPT_FOREIGN_IP, "true")); } @Test void testAppendEnvironmentProperties() { ApplicationConfig application = new ApplicationConfig("app"); SysProps.setProperty("dubbo.labels", "tag1=value1;tag2=value2 ; tag3 = value3"); application.refresh(); Map<String, String> parameters = application.getParameters(); Assertions.assertEquals("value1", parameters.get("tag1")); Assertions.assertEquals("value2", parameters.get("tag2")); Assertions.assertEquals("value3", parameters.get("tag3")); ApplicationConfig application1 = new ApplicationConfig("app"); SysProps.setProperty("dubbo.env.keys", "tag1, tag2,tag3"); // mock environment variables SysProps.setProperty("tag1", "value1"); SysProps.setProperty("tag2", "value2"); SysProps.setProperty("tag3", "value3"); application1.refresh(); Map<String, String> parameters1 = application1.getParameters(); Assertions.assertEquals("value2", parameters1.get("tag2")); Assertions.assertEquals("value3", parameters1.get("tag3")); Map<String, String> urlParameters = new HashMap<>(); ApplicationConfig.appendParameters(urlParameters, application1); Assertions.assertEquals("value1", urlParameters.get("tag1")); Assertions.assertEquals("value2", urlParameters.get("tag2")); Assertions.assertEquals("value3", urlParameters.get("tag3")); } @Test void testMetaData() { ApplicationConfig config = new ApplicationConfig(); Map<String, String> metaData = config.getMetaData(); Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } @Test void testOverrideEmptyConfig() { String owner = "tom1"; SysProps.setProperty("dubbo.application.name", "demo-app"); SysProps.setProperty("dubbo.application.owner", owner); SysProps.setProperty("dubbo.application.version", "1.2.3"); ApplicationConfig applicationConfig = new ApplicationConfig(); DubboBootstrap.getInstance().application(applicationConfig).initialize(); Assertions.assertEquals(owner, applicationConfig.getOwner()); Assertions.assertEquals("1.2.3", applicationConfig.getVersion()); DubboBootstrap.getInstance().destroy(); } @Test void testOverrideConfigById() { String owner = "tom2"; SysProps.setProperty("dubbo.applications.demo-app.owner", owner); SysProps.setProperty("dubbo.applications.demo-app.version", "1.2.3"); SysProps.setProperty("dubbo.applications.demo-app.name", "demo-app"); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setId("demo-app"); DubboBootstrap.getInstance().application(applicationConfig).initialize(); Assertions.assertEquals("demo-app", applicationConfig.getId()); Assertions.assertEquals("demo-app", applicationConfig.getName()); Assertions.assertEquals(owner, applicationConfig.getOwner()); Assertions.assertEquals("1.2.3", applicationConfig.getVersion()); DubboBootstrap.getInstance().destroy(); } @Test void testOverrideConfigByName() { String owner = "tom3"; SysProps.setProperty("dubbo.applications.demo-app.owner", owner); SysProps.setProperty("dubbo.applications.demo-app.version", "1.2.3"); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("demo-app"); DubboBootstrap.getInstance().application(applicationConfig).initialize(); Assertions.assertEquals(owner, applicationConfig.getOwner()); Assertions.assertEquals("1.2.3", applicationConfig.getVersion()); DubboBootstrap.getInstance().destroy(); } @Test void testLoadConfig() { String owner = "tom4"; SysProps.setProperty("dubbo.applications.demo-app.owner", owner); SysProps.setProperty("dubbo.applications.demo-app.version", "1.2.3"); DubboBootstrap.getInstance().initialize(); ApplicationConfig applicationConfig = DubboBootstrap.getInstance().getApplication(); Assertions.assertEquals("demo-app", applicationConfig.getId()); Assertions.assertEquals("demo-app", applicationConfig.getName()); Assertions.assertEquals(owner, applicationConfig.getOwner()); Assertions.assertEquals("1.2.3", applicationConfig.getVersion()); DubboBootstrap.getInstance().destroy(); } @Test void testOverrideConfigConvertCase() { SysProps.setProperty("dubbo.application.NAME", "demo-app"); SysProps.setProperty("dubbo.application.qos-Enable", "false"); SysProps.setProperty("dubbo.application.qos_host", "127.0.0.1"); SysProps.setProperty("dubbo.application.qosPort", "2345"); DubboBootstrap.getInstance().initialize(); ApplicationConfig applicationConfig = DubboBootstrap.getInstance().getApplication(); Assertions.assertEquals(false, applicationConfig.getQosEnable()); Assertions.assertEquals("127.0.0.1", applicationConfig.getQosHost()); Assertions.assertEquals(2345, applicationConfig.getQosPort()); Assertions.assertEquals("demo-app", applicationConfig.getName()); DubboBootstrap.getInstance().destroy(); } @Test void testDefaultValue() { SysProps.setProperty("dubbo.application.NAME", "demo-app"); DubboBootstrap.getInstance().initialize(); ApplicationConfig applicationConfig = DubboBootstrap.getInstance().getApplication(); Assertions.assertEquals(DUBBO, applicationConfig.getProtocol()); Assertions.assertEquals(EXECUTOR_MANAGEMENT_MODE_ISOLATION, applicationConfig.getExecutorManagementMode()); Assertions.assertEquals(Boolean.TRUE, applicationConfig.getEnableFileCache()); DubboBootstrap.getInstance().destroy(); } }
8,417
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MonitorConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; class MonitorConfigTest { @Test void testAddress() throws Exception { MonitorConfig monitor = new MonitorConfig(); monitor.setAddress("monitor-addr"); assertThat(monitor.getAddress(), equalTo("monitor-addr")); Map<String, String> parameters = new HashMap<String, String>(); MonitorConfig.appendParameters(parameters, monitor); assertThat(parameters.isEmpty(), is(true)); } @Test void testProtocol() throws Exception { MonitorConfig monitor = new MonitorConfig(); monitor.setProtocol("protocol"); assertThat(monitor.getProtocol(), equalTo("protocol")); Map<String, String> parameters = new HashMap<String, String>(); MonitorConfig.appendParameters(parameters, monitor); assertThat(parameters.isEmpty(), is(true)); } @Test void testUsername() throws Exception { MonitorConfig monitor = new MonitorConfig(); monitor.setUsername("user"); assertThat(monitor.getUsername(), equalTo("user")); Map<String, String> parameters = new HashMap<String, String>(); MonitorConfig.appendParameters(parameters, monitor); assertThat(parameters.isEmpty(), is(true)); } @Test void testPassword() throws Exception { MonitorConfig monitor = new MonitorConfig(); monitor.setPassword("secret"); assertThat(monitor.getPassword(), equalTo("secret")); Map<String, String> parameters = new HashMap<String, String>(); MonitorConfig.appendParameters(parameters, monitor); assertThat(parameters.isEmpty(), is(true)); } @Test void testGroup() throws Exception { MonitorConfig monitor = new MonitorConfig(); monitor.setGroup("group"); assertThat(monitor.getGroup(), equalTo("group")); } @Test void testVersion() throws Exception { MonitorConfig monitor = new MonitorConfig(); monitor.setVersion("1.0.0"); assertThat(monitor.getVersion(), equalTo("1.0.0")); } @Test void testParameters() throws Exception { MonitorConfig monitor = new MonitorConfig(); Map<String, String> parameters = Collections.singletonMap("k1", "v1"); monitor.setParameters(parameters); assertThat(monitor.getParameters(), hasEntry("k1", "v1")); } @Test void testDefault() throws Exception { MonitorConfig monitor = new MonitorConfig(); monitor.setDefault(true); assertThat(monitor.isDefault(), is(true)); } @Test void testInterval() throws Exception { MonitorConfig monitor = new MonitorConfig(); monitor.setInterval("100"); assertThat(monitor.getInterval(), equalTo("100")); } @Test void testMetaData() { MonitorConfig config = new MonitorConfig(); Map<String, String> metaData = config.getMetaData(); Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } }
8,418
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ReferenceConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.Version; import org.apache.dubbo.common.compiler.support.CtClassBuilder; import org.apache.dubbo.common.compiler.support.JavassistCompiler; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.utils.ConfigUtils; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.annotation.Argument; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.context.ModuleConfigManager; import org.apache.dubbo.config.provider.impl.DemoServiceImpl; import org.apache.dubbo.registry.client.migration.MigrationInvoker; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.ProxyFactory; import org.apache.dubbo.rpc.cluster.filter.FilterChainBuilder; import org.apache.dubbo.rpc.cluster.support.registry.ZoneAwareClusterInvoker; import org.apache.dubbo.rpc.cluster.support.wrapper.MockClusterInvoker; import org.apache.dubbo.rpc.cluster.support.wrapper.ScopeClusterInvoker; import org.apache.dubbo.rpc.listener.ListenerInvokerWrapper; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ServiceMetadata; import org.apache.dubbo.rpc.protocol.ReferenceCountInvokerWrapper; import org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker; import org.apache.dubbo.rpc.protocol.injvm.InjvmProtocol; import org.apache.dubbo.rpc.service.GenericService; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.net.URLDecoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import javassist.CannotCompileException; import javassist.CtClass; import javassist.NotFoundException; import demo.MultiClassLoaderService; import demo.MultiClassLoaderServiceImpl; import demo.MultiClassLoaderServiceRequest; import demo.MultiClassLoaderServiceResult; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledForJreRange; import org.junit.jupiter.api.condition.JRE; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_VERSION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.DUMP_DIRECTORY; import static org.apache.dubbo.common.constants.CommonConstants.EXPORTER_LISTENER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.LIVENESS_PROBE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METADATA_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METADATA_SERVICE_PORT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METADATA_SERVICE_PROTOCOL_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PID_KEY; import static org.apache.dubbo.common.constants.CommonConstants.READINESS_PROBE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFER_ASYNC_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFER_BACKGROUND_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFER_THREAD_NUM_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED; import static org.apache.dubbo.common.constants.CommonConstants.RELEASE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REVISION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.STARTUP_PROBE; import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY; import static org.apache.dubbo.common.constants.CommonConstants.URL_MERGE_PROCESSOR_KEY; import static org.apache.dubbo.common.constants.QosConstants.ACCEPT_FOREIGN_IP; import static org.apache.dubbo.common.constants.QosConstants.QOS_ENABLE; import static org.apache.dubbo.common.constants.QosConstants.QOS_HOST; import static org.apache.dubbo.common.constants.QosConstants.QOS_PORT; import static org.apache.dubbo.registry.Constants.REGISTER_IP_KEY; import static org.apache.dubbo.rpc.Constants.DEFAULT_STUB_EVENT; import static org.apache.dubbo.rpc.Constants.LOCAL_KEY; import static org.apache.dubbo.rpc.Constants.LOCAL_PROTOCOL; import static org.apache.dubbo.rpc.Constants.SCOPE_REMOTE; import static org.apache.dubbo.rpc.cluster.Constants.PEER_KEY; class ReferenceConfigTest { private static String zkUrl1; private static String zkUrl2; private static String registryUrl1; @BeforeAll public static void beforeAll() { int zkServerPort1 = 2181; int zkServerPort2 = 2182; zkUrl1 = "zookeeper://localhost:" + zkServerPort1; zkUrl2 = "zookeeper://localhost:" + zkServerPort2; registryUrl1 = "registry://localhost:" + zkServerPort1 + "?registry=zookeeper"; } @BeforeEach public void setUp() throws Exception { DubboBootstrap.reset(); ApplicationModel.defaultModel().getApplicationConfigManager(); DubboBootstrap.getInstance(); } @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); Mockito.framework().clearInlineMocks(); } /** * Test whether the configuration required for the aggregation service reference meets expectations */ @Test void testAppendConfig() { ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("application1"); applicationConfig.setVersion("v1"); applicationConfig.setOwner("owner1"); applicationConfig.setOrganization("bu1"); applicationConfig.setArchitecture("architecture1"); applicationConfig.setEnvironment("test"); applicationConfig.setCompiler("javassist"); applicationConfig.setLogger("log4j"); applicationConfig.setDumpDirectory("/"); applicationConfig.setQosEnable(false); applicationConfig.setQosHost("127.0.0.1"); applicationConfig.setQosPort(77777); applicationConfig.setQosAcceptForeignIp(false); Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "value1"); parameters.put("key2", "value2"); applicationConfig.setParameters(parameters); applicationConfig.setShutwait("5"); applicationConfig.setMetadataType("local"); applicationConfig.setRegisterConsumer(false); applicationConfig.setRepository("repository1"); applicationConfig.setEnableFileCache(false); applicationConfig.setProtocol("dubbo"); applicationConfig.setMetadataServicePort(88888); applicationConfig.setMetadataServiceProtocol("tri"); applicationConfig.setLivenessProbe("livenessProbe"); applicationConfig.setReadinessProbe("readinessProb"); applicationConfig.setStartupProbe("startupProbe"); ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setClient("netty"); referenceConfig.setGeneric(Boolean.FALSE.toString()); referenceConfig.setProtocol("dubbo"); referenceConfig.setInit(true); referenceConfig.setLazy(false); referenceConfig.setInjvm(false); referenceConfig.setReconnect("reconnect"); referenceConfig.setSticky(false); referenceConfig.setStub(DEFAULT_STUB_EVENT); referenceConfig.setRouter("default"); referenceConfig.setReferAsync(true); MonitorConfig monitorConfig = new MonitorConfig(); applicationConfig.setMonitor(monitorConfig); ModuleConfig moduleConfig = new ModuleConfig(); moduleConfig.setMonitor("default"); moduleConfig.setName("module1"); moduleConfig.setOrganization("application1"); moduleConfig.setVersion("v1"); moduleConfig.setOwner("owner1"); ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setClient("netty"); consumerConfig.setThreadpool("fixed"); consumerConfig.setCorethreads(200); consumerConfig.setQueues(500); consumerConfig.setThreads(300); consumerConfig.setShareconnections(10); consumerConfig.setUrlMergeProcessor("default"); consumerConfig.setReferThreadNum(20); consumerConfig.setReferBackground(false); referenceConfig.setConsumer(consumerConfig); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); methodConfig.setStat(1); methodConfig.setRetries(0); methodConfig.setExecutes(10); methodConfig.setDeprecated(false); methodConfig.setSticky(false); methodConfig.setReturn(false); methodConfig.setService("service"); methodConfig.setServiceId(DemoService.class.getName()); methodConfig.setParentPrefix("demo"); referenceConfig.setMethods(Collections.singletonList(methodConfig)); referenceConfig.setInterface(DemoService.class); referenceConfig.getInterfaceClass(); referenceConfig.setCheck(false); RegistryConfig registry = new RegistryConfig(); registry.setAddress(zkUrl1); applicationConfig.setRegistries(Collections.singletonList(registry)); applicationConfig.setRegistryIds(registry.getId()); moduleConfig.setRegistries(Collections.singletonList(registry)); referenceConfig.setRegistry(registry); DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel()); dubboBootstrap .application(applicationConfig) .reference(referenceConfig) .registry(registry) .module(moduleConfig) .initialize(); referenceConfig.init(); ServiceMetadata serviceMetadata = referenceConfig.getServiceMetadata(); // verify additional side parameter Assertions.assertEquals(CONSUMER_SIDE, serviceMetadata.getAttachments().get(SIDE_KEY)); // verify additional interface parameter Assertions.assertEquals( DemoService.class.getName(), serviceMetadata.getAttachments().get(INTERFACE_KEY)); // verify additional metadata-type parameter Assertions.assertEquals( DEFAULT_METADATA_STORAGE_TYPE, serviceMetadata.getAttachments().get(METADATA_KEY)); // verify additional register.ip parameter Assertions.assertEquals( NetUtils.getLocalHost(), serviceMetadata.getAttachments().get(REGISTER_IP_KEY)); // verify additional runtime parameters Assertions.assertEquals( Version.getProtocolVersion(), serviceMetadata.getAttachments().get(DUBBO_VERSION_KEY)); Assertions.assertEquals( Version.getVersion(), serviceMetadata.getAttachments().get(RELEASE_KEY)); Assertions.assertTrue(serviceMetadata.getAttachments().containsKey(TIMESTAMP_KEY)); Assertions.assertEquals( String.valueOf(ConfigUtils.getPid()), serviceMetadata.getAttachments().get(PID_KEY)); // verify additional application config Assertions.assertEquals( applicationConfig.getName(), serviceMetadata.getAttachments().get(APPLICATION_KEY)); Assertions.assertEquals( applicationConfig.getOwner(), serviceMetadata.getAttachments().get("owner")); Assertions.assertEquals( applicationConfig.getVersion(), serviceMetadata.getAttachments().get(APPLICATION_VERSION_KEY)); Assertions.assertEquals( applicationConfig.getOrganization(), serviceMetadata.getAttachments().get("organization")); Assertions.assertEquals( applicationConfig.getArchitecture(), serviceMetadata.getAttachments().get("architecture")); Assertions.assertEquals( applicationConfig.getEnvironment(), serviceMetadata.getAttachments().get("environment")); Assertions.assertEquals( applicationConfig.getCompiler(), serviceMetadata.getAttachments().get("compiler")); Assertions.assertEquals( applicationConfig.getLogger(), serviceMetadata.getAttachments().get("logger")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registries")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registry.ids")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("monitor")); Assertions.assertEquals( applicationConfig.getDumpDirectory(), serviceMetadata.getAttachments().get(DUMP_DIRECTORY)); Assertions.assertEquals( applicationConfig.getQosEnable().toString(), serviceMetadata.getAttachments().get(QOS_ENABLE)); Assertions.assertEquals( applicationConfig.getQosHost(), serviceMetadata.getAttachments().get(QOS_HOST)); Assertions.assertEquals( applicationConfig.getQosPort().toString(), serviceMetadata.getAttachments().get(QOS_PORT)); Assertions.assertEquals( applicationConfig.getQosAcceptForeignIp().toString(), serviceMetadata.getAttachments().get(ACCEPT_FOREIGN_IP)); Assertions.assertEquals( applicationConfig.getParameters().get("key1"), serviceMetadata.getAttachments().get("key1")); Assertions.assertEquals( applicationConfig.getParameters().get("key2"), serviceMetadata.getAttachments().get("key2")); Assertions.assertEquals( applicationConfig.getShutwait(), serviceMetadata.getAttachments().get("shutwait")); Assertions.assertEquals( applicationConfig.getMetadataType(), serviceMetadata.getAttachments().get(METADATA_KEY)); Assertions.assertEquals( applicationConfig.getRegisterConsumer().toString(), serviceMetadata.getAttachments().get("register.consumer")); Assertions.assertEquals( applicationConfig.getRepository(), serviceMetadata.getAttachments().get("repository")); Assertions.assertEquals( applicationConfig.getEnableFileCache().toString(), serviceMetadata.getAttachments().get(REGISTRY_LOCAL_FILE_CACHE_ENABLED)); Assertions.assertEquals( applicationConfig.getMetadataServicePort().toString(), serviceMetadata.getAttachments().get(METADATA_SERVICE_PORT_KEY)); Assertions.assertEquals( applicationConfig.getMetadataServiceProtocol().toString(), serviceMetadata.getAttachments().get(METADATA_SERVICE_PROTOCOL_KEY)); Assertions.assertEquals( applicationConfig.getLivenessProbe(), serviceMetadata.getAttachments().get(LIVENESS_PROBE_KEY)); Assertions.assertEquals( applicationConfig.getReadinessProbe(), serviceMetadata.getAttachments().get(READINESS_PROBE_KEY)); Assertions.assertEquals( applicationConfig.getStartupProbe(), serviceMetadata.getAttachments().get(STARTUP_PROBE)); // verify additional module config Assertions.assertEquals( moduleConfig.getName(), serviceMetadata.getAttachments().get("module")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("monitor")); Assertions.assertEquals( moduleConfig.getOrganization(), serviceMetadata.getAttachments().get("module.organization")); Assertions.assertEquals( moduleConfig.getOwner(), serviceMetadata.getAttachments().get("module.owner")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("registries")); Assertions.assertEquals( moduleConfig.getVersion(), serviceMetadata.getAttachments().get("module.version")); // verify additional consumer config Assertions.assertEquals( consumerConfig.getClient(), serviceMetadata.getAttachments().get("client")); Assertions.assertEquals( consumerConfig.getThreadpool(), serviceMetadata.getAttachments().get("threadpool")); Assertions.assertEquals( consumerConfig.getCorethreads().toString(), serviceMetadata.getAttachments().get("corethreads")); Assertions.assertEquals( consumerConfig.getQueues().toString(), serviceMetadata.getAttachments().get("queues")); Assertions.assertEquals( consumerConfig.getThreads().toString(), serviceMetadata.getAttachments().get("threads")); Assertions.assertEquals( consumerConfig.getShareconnections().toString(), serviceMetadata.getAttachments().get("shareconnections")); Assertions.assertEquals( consumerConfig.getUrlMergeProcessor(), serviceMetadata.getAttachments().get(URL_MERGE_PROCESSOR_KEY)); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey(REFER_THREAD_NUM_KEY)); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey(REFER_BACKGROUND_KEY)); // verify additional reference config Assertions.assertEquals( referenceConfig.getClient(), serviceMetadata.getAttachments().get("client")); Assertions.assertEquals( referenceConfig.getGeneric(), serviceMetadata.getAttachments().get("generic")); Assertions.assertEquals( referenceConfig.getProtocol(), serviceMetadata.getAttachments().get("protocol")); Assertions.assertEquals( referenceConfig.isInit().toString(), serviceMetadata.getAttachments().get("init")); Assertions.assertEquals( referenceConfig.getLazy().toString(), serviceMetadata.getAttachments().get("lazy")); Assertions.assertEquals( referenceConfig.isInjvm().toString(), serviceMetadata.getAttachments().get("injvm")); Assertions.assertEquals( referenceConfig.getReconnect(), serviceMetadata.getAttachments().get("reconnect")); Assertions.assertEquals( referenceConfig.getSticky().toString(), serviceMetadata.getAttachments().get("sticky")); Assertions.assertEquals( referenceConfig.getStub(), serviceMetadata.getAttachments().get("stub")); Assertions.assertEquals( referenceConfig.getProvidedBy(), serviceMetadata.getAttachments().get("provided-by")); Assertions.assertEquals( referenceConfig.getRouter(), serviceMetadata.getAttachments().get("router")); Assertions.assertEquals( referenceConfig.getReferAsync().toString(), serviceMetadata.getAttachments().get(REFER_ASYNC_KEY)); // verify additional method config Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("name")); Assertions.assertEquals( methodConfig.getStat().toString(), serviceMetadata.getAttachments().get("sayName.stat")); Assertions.assertEquals( methodConfig.getRetries().toString(), serviceMetadata.getAttachments().get("sayName.retries")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.reliable")); Assertions.assertEquals( methodConfig.getExecutes().toString(), serviceMetadata.getAttachments().get("sayName.executes")); Assertions.assertEquals( methodConfig.getDeprecated().toString(), serviceMetadata.getAttachments().get("sayName.deprecated")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.stick")); Assertions.assertEquals( methodConfig.isReturn().toString(), serviceMetadata.getAttachments().get("sayName.return")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.service")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.service.id")); Assertions.assertFalse(serviceMetadata.getAttachments().containsKey("sayName.parent.prefix")); // verify additional revision and methods parameter Assertions.assertEquals( Version.getVersion(referenceConfig.getInterfaceClass(), referenceConfig.getVersion()), serviceMetadata.getAttachments().get(REVISION_KEY)); Assertions.assertTrue(serviceMetadata.getAttachments().containsKey(METHODS_KEY)); Assertions.assertEquals( DemoService.class.getMethods().length, StringUtils.split((String) serviceMetadata.getAttachments().get(METHODS_KEY), ',').length); dubboBootstrap.stop(); } @Test void testCreateInvokerForLocalRefer() { ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setScope(LOCAL_KEY); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("application1"); Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "value1"); parameters.put("key2", "value2"); applicationConfig.setParameters(parameters); referenceConfig.setInterface(DemoService.class); referenceConfig.getInterfaceClass(); referenceConfig.setCheck(false); DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel()); dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize(); referenceConfig.init(); Assertions.assertTrue(referenceConfig.getInvoker() instanceof ScopeClusterInvoker); ScopeClusterInvoker<?> scopeClusterInvoker = (ScopeClusterInvoker<?>) referenceConfig.getInvoker(); Invoker<?> mockInvoker = scopeClusterInvoker.getInvoker(); Assertions.assertTrue(mockInvoker instanceof MockClusterInvoker); Invoker<?> withCount = ((MockClusterInvoker<?>) mockInvoker) .getDirectory() .getAllInvokers() .get(0); Assertions.assertTrue(withCount instanceof ReferenceCountInvokerWrapper); Invoker<?> withFilter = ((ReferenceCountInvokerWrapper<?>) withCount).getInvoker(); Assertions.assertTrue(withFilter instanceof ListenerInvokerWrapper || withFilter instanceof FilterChainBuilder.CallbackRegistrationInvoker); if (withFilter instanceof ListenerInvokerWrapper) { Assertions.assertTrue( ((ListenerInvokerWrapper<?>) (((ReferenceCountInvokerWrapper<?>) withCount).getInvoker())) .getInvoker() instanceof InjvmInvoker); } if (withFilter instanceof FilterChainBuilder.CallbackRegistrationInvoker) { Invoker filterInvoker = ((FilterChainBuilder.CallbackRegistrationInvoker) withFilter).getFilterInvoker(); FilterChainBuilder.CopyOfFilterChainNode filterInvoker1 = (FilterChainBuilder.CopyOfFilterChainNode) filterInvoker; ListenerInvokerWrapper originalInvoker = (ListenerInvokerWrapper) filterInvoker1.getOriginalInvoker(); Invoker invoker = originalInvoker.getInvoker(); Assertions.assertTrue(invoker instanceof InjvmInvoker); } URL url = withFilter.getUrl(); Assertions.assertEquals("application1", url.getParameter("application")); Assertions.assertEquals("value1", url.getParameter("key1")); Assertions.assertEquals("value2", url.getParameter("key2")); dubboBootstrap.stop(); } /** * Verify the configuration of the registry protocol for remote reference */ @Test void testCreateInvokerForRemoteRefer() { ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setGeneric(Boolean.FALSE.toString()); referenceConfig.setProtocol("dubbo"); referenceConfig.setInit(true); referenceConfig.setLazy(false); referenceConfig.setInjvm(false); DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel()); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("application1"); Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "value1"); parameters.put("key2", "value2"); applicationConfig.setParameters(parameters); referenceConfig.refreshed.set(true); referenceConfig.setInterface(DemoService.class); referenceConfig.getInterfaceClass(); referenceConfig.setCheck(false); RegistryConfig registry = new RegistryConfig(); registry.setAddress(zkUrl1); applicationConfig.setRegistries(Collections.singletonList(registry)); applicationConfig.setRegistryIds(registry.getId()); referenceConfig.setRegistry(registry); dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize(); referenceConfig.init(); Assertions.assertTrue(referenceConfig.getInvoker() instanceof MigrationInvoker); dubboBootstrap.destroy(); } /** * Verify that the remote url is directly configured for remote reference */ @Test void testCreateInvokerWithRemoteUrlForRemoteRefer() { ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setGeneric(Boolean.FALSE.toString()); referenceConfig.setProtocol("dubbo"); referenceConfig.setInit(true); referenceConfig.setLazy(false); referenceConfig.setInjvm(false); DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel()); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("application1"); Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "value1"); parameters.put("key2", "value2"); applicationConfig.setParameters(parameters); referenceConfig.refreshed.set(true); referenceConfig.setInterface(DemoService.class); referenceConfig.getInterfaceClass(); referenceConfig.setCheck(false); referenceConfig.setUrl("dubbo://127.0.0.1:20880"); dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize(); referenceConfig.init(); Assertions.assertTrue(referenceConfig.getInvoker() instanceof ScopeClusterInvoker); Invoker scopeClusterInvoker = referenceConfig.getInvoker(); Assertions.assertTrue(((ScopeClusterInvoker) scopeClusterInvoker).getInvoker() instanceof MockClusterInvoker); Assertions.assertEquals( Boolean.TRUE, ((ScopeClusterInvoker) scopeClusterInvoker) .getInvoker() .getUrl() .getAttribute(PEER_KEY)); dubboBootstrap.destroy(); } /** * Verify that the registry url is directly configured for remote reference */ @Test void testCreateInvokerWithRegistryUrlForRemoteRefer() { ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setGeneric(Boolean.FALSE.toString()); referenceConfig.setProtocol("dubbo"); referenceConfig.setInit(true); referenceConfig.setLazy(false); referenceConfig.setInjvm(false); DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel()); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("application1"); Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "value1"); parameters.put("key2", "value2"); applicationConfig.setParameters(parameters); referenceConfig.refreshed.set(true); referenceConfig.setInterface(DemoService.class); referenceConfig.getInterfaceClass(); referenceConfig.setCheck(false); referenceConfig.setUrl(registryUrl1); dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize(); referenceConfig.init(); Assertions.assertTrue(referenceConfig.getInvoker() instanceof MigrationInvoker); dubboBootstrap.destroy(); } /** * Verify the service reference of multiple registries */ @Test void testMultipleRegistryForRemoteRefer() { ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setGeneric(Boolean.FALSE.toString()); referenceConfig.setProtocol("dubbo"); referenceConfig.setInit(true); referenceConfig.setLazy(false); referenceConfig.setInjvm(false); DubboBootstrap dubboBootstrap = DubboBootstrap.newInstance(FrameworkModel.defaultModel()); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("application1"); Map<String, String> parameters = new HashMap<>(); parameters.put("key1", "value1"); parameters.put("key2", "value2"); applicationConfig.setParameters(parameters); referenceConfig.refreshed.set(true); referenceConfig.setInterface(DemoService.class); referenceConfig.getInterfaceClass(); referenceConfig.setCheck(false); RegistryConfig registry1 = new RegistryConfig(); registry1.setAddress(zkUrl1); registry1.setId("zk1"); RegistryConfig registry2 = new RegistryConfig(); registry2.setAddress(zkUrl2); registry2.setId("zk2"); List<RegistryConfig> registryConfigs = new ArrayList<>(); registryConfigs.add(registry1); registryConfigs.add(registry2); applicationConfig.setRegistries(registryConfigs); applicationConfig.setRegistryIds("zk1,zk2"); referenceConfig.setRegistries(registryConfigs); dubboBootstrap.application(applicationConfig).reference(referenceConfig).initialize(); referenceConfig.init(); Assertions.assertTrue(referenceConfig.getInvoker() instanceof ZoneAwareClusterInvoker); dubboBootstrap.destroy(); } @Test @Disabled("Disabled due to Github Actions environment") public void testInjvm() throws Exception { ApplicationConfig application = new ApplicationConfig(); application.setName("test-protocol-random-port"); application.setEnableFileCache(false); ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(application); RegistryConfig registry = new RegistryConfig(); registry.setAddress(zkUrl1); ProtocolConfig protocol = new ProtocolConfig(); protocol.setName("dubbo"); ServiceConfig<DemoService> demoService; demoService = new ServiceConfig<>(); demoService.setInterface(DemoService.class); demoService.setRef(new DemoServiceImpl()); demoService.setRegistry(registry); demoService.setProtocol(protocol); ReferenceConfig<DemoService> rc = new ReferenceConfig<>(); rc.setRegistry(registry); rc.setInterface(DemoService.class.getName()); rc.setScope(SCOPE_REMOTE); try { System.setProperty("java.net.preferIPv4Stack", "true"); demoService.export(); rc.get(); Assertions.assertFalse( LOCAL_PROTOCOL.equalsIgnoreCase(rc.getInvoker().getUrl().getProtocol())); } finally { System.clearProperty("java.net.preferIPv4Stack"); rc.destroy(); demoService.unexport(); } // Manually trigger dubbo resource recycling. DubboBootstrap.getInstance().destroy(); } /** * unit test for dubbo-1765 */ @Test void test1ReferenceRetry() { ApplicationConfig application = new ApplicationConfig(); application.setName("test-reference-retry"); application.setEnableFileCache(false); ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(application); RegistryConfig registry = new RegistryConfig(); registry.setAddress(zkUrl1); ReferenceConfig<DemoService> rc = new ReferenceConfig<>(); rc.setRegistry(registry); rc.setInterface(DemoService.class.getName()); boolean success = false; DemoService demoService = null; try { demoService = rc.get(); success = true; } catch (Exception e) { // ignore } Assertions.assertFalse(success); Assertions.assertNull(demoService); try { System.setProperty("java.net.preferIPv4Stack", "true"); ProxyFactory proxy = ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension(); DemoService service = new DemoServiceImpl(); URL url = URL.valueOf("injvm://127.0.0.1/DemoService") .addParameter(INTERFACE_KEY, DemoService.class.getName()) .setScopeModel(ApplicationModel.defaultModel().getDefaultModule()); url = url.addParameter(EXPORTER_LISTENER_KEY, LOCAL_PROTOCOL); Protocol protocolSPI = ApplicationModel.defaultModel() .getExtensionLoader(Protocol.class) .getAdaptiveExtension(); protocolSPI.export(proxy.getInvoker(service, DemoService.class, url)); demoService = rc.get(); success = true; } catch (Exception e) { // ignore } finally { rc.destroy(); InjvmProtocol.getInjvmProtocol(FrameworkModel.defaultModel()).destroy(); System.clearProperty("java.net.preferIPv4Stack"); } Assertions.assertTrue(success); Assertions.assertNotNull(demoService); } @Test void test2ReferenceRetry() { ApplicationConfig application = new ApplicationConfig(); application.setName("test-reference-retry2"); application.setEnableFileCache(false); ApplicationModel.defaultModel().getApplicationConfigManager().setApplication(application); RegistryConfig registry = new RegistryConfig(); registry.setAddress(zkUrl1); ProtocolConfig protocol = new ProtocolConfig(); protocol.setName("mockprotocol"); ReferenceConfig<DemoService> rc = new ReferenceConfig<>(); rc.setRegistry(registry); rc.setInterface(DemoService.class.getName()); boolean success = false; DemoService demoService = null; try { demoService = rc.get(); success = true; } catch (Exception e) { // ignore } Assertions.assertFalse(success); Assertions.assertNull(demoService); ServiceConfig<DemoService> sc = new ServiceConfig<>(); sc.setInterface(DemoService.class.getName()); sc.setRef(new DemoServiceImpl()); sc.setRegistry(registry); sc.setProtocol(protocol); try { System.setProperty("java.net.preferIPv4Stack", "true"); sc.export(); demoService = rc.get(); success = true; } catch (Exception e) { // ignore } finally { rc.destroy(); sc.unexport(); System.clearProperty("java.net.preferIPv4Stack"); } Assertions.assertTrue(success); Assertions.assertNotNull(demoService); } @Test void testMetaData() { ReferenceConfig config = new ReferenceConfig(); Map<String, String> metaData = config.getMetaData(); Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); // test merged and override consumer attributes ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setAsync(true); consumerConfig.setActives(10); config.setConsumer(consumerConfig); config.setAsync(false); // override metaData = config.getMetaData(); Assertions.assertEquals(2, metaData.size()); Assertions.assertEquals(String.valueOf(consumerConfig.getActives()), metaData.get("actives")); Assertions.assertEquals(String.valueOf(config.isAsync()), metaData.get("async")); } @Test void testGetPrefixes() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setInterface(DemoService.class); List<String> prefixes = referenceConfig.getPrefixes(); Assertions.assertTrue(prefixes.contains("dubbo.reference." + referenceConfig.getInterface())); long start = System.currentTimeMillis(); for (int i = 0; i < 1000; i++) { referenceConfig.getPrefixes(); } long end = System.currentTimeMillis(); System.out.println("ReferenceConfig get prefixes cost: " + (end - start)); } @Test void testGenericAndInterfaceConflicts() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setInterface(DemoService.class); referenceConfig.setGeneric("true"); DubboBootstrap.getInstance() .application("demo app") .reference(referenceConfig) .initialize(); Assertions.assertEquals(GenericService.class, referenceConfig.getInterfaceClass()); } @Test void testLargeReferences() throws InterruptedException { int amount = 10000; ModuleConfigManager configManager = DubboBootstrap.getInstance() .getApplicationModel() .getDefaultModule() .getConfigManager(); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("test-app"); MetadataReportConfig metadataReportConfig = new MetadataReportConfig(); metadataReportConfig.setAddress("metadata://"); ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(); configCenterConfig.setAddress("diamond://"); testInitReferences(0, amount, applicationConfig, metadataReportConfig, configCenterConfig); configManager.clear(); testInitReferences(0, 1, applicationConfig, metadataReportConfig, configCenterConfig); configManager.clear(); long t1 = System.currentTimeMillis(); int nThreads = 8; ExecutorService executorService = Executors.newFixedThreadPool(nThreads); for (int i = 0; i < nThreads; i++) { int perCount = (int) (1.0 * amount / nThreads); int start = perCount * i; int end = start + perCount; if (i == nThreads - 1) { end = amount; } int finalEnd = end; System.out.println( String.format("start thread %s: range: %s - %s, count: %s", i, start, end, (end - start))); executorService.submit(() -> { testInitReferences(start, finalEnd, applicationConfig, metadataReportConfig, configCenterConfig); }); } executorService.shutdown(); executorService.awaitTermination(100, TimeUnit.SECONDS); long t2 = System.currentTimeMillis(); long cost = t2 - t1; System.out.println("Init large references cost: " + cost + "ms"); Assertions.assertEquals(amount, configManager.getReferences().size()); Assertions.assertTrue(cost < 1000, "Init large references too slowly: " + cost); // test equals testSearchReferences(); } private void testSearchReferences() { long t1 = System.currentTimeMillis(); Collection<ReferenceConfigBase<?>> references = DubboBootstrap.getInstance() .getApplicationModel() .getDefaultModule() .getConfigManager() .getReferences(); List<ReferenceConfigBase<?>> results = references.stream() .filter(rc -> rc.equals(references.iterator().next())) .collect(Collectors.toList()); long t2 = System.currentTimeMillis(); long cost = t2 - t1; System.out.println("Search large references cost: " + cost + "ms"); Assertions.assertEquals(1, results.size()); Assertions.assertTrue(cost < 1000, "Search large references too slowly: " + cost); } private long testInitReferences( int start, int end, ApplicationConfig applicationConfig, MetadataReportConfig metadataReportConfig, ConfigCenterConfig configCenterConfig) { // test add large number of references long t1 = System.currentTimeMillis(); try { for (int i = start; i < end; i++) { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setInterface("com.test.TestService" + i); referenceConfig.setApplication(applicationConfig); referenceConfig.setMetadataReportConfig(metadataReportConfig); referenceConfig.setConfigCenter(configCenterConfig); DubboBootstrap.getInstance().reference(referenceConfig); // ApplicationModel.defaultModel().getConfigManager().getConfigCenters(); } } catch (Throwable e) { e.printStackTrace(); } long t2 = System.currentTimeMillis(); return t2 - t1; } @Test void testConstructWithReferenceAnnotation() throws NoSuchFieldException { Reference reference = getClass().getDeclaredField("innerTest").getAnnotation(Reference.class); ReferenceConfig referenceConfig = new ReferenceConfig(reference); Assertions.assertEquals(1, referenceConfig.getMethods().size()); Assertions.assertEquals((referenceConfig.getMethods().get(0)).getName(), "sayHello"); Assertions.assertEquals(1300, (int) (referenceConfig.getMethods().get(0)).getTimeout()); Assertions.assertEquals(4, (int) (referenceConfig.getMethods().get(0)).getRetries()); Assertions.assertEquals((referenceConfig.getMethods().get(0)).getLoadbalance(), "random"); Assertions.assertEquals(3, (int) (referenceConfig.getMethods().get(0)).getActives()); Assertions.assertEquals(5, (int) (referenceConfig.getMethods().get(0)).getExecutes()); Assertions.assertTrue((referenceConfig.getMethods().get(0)).isAsync()); Assertions.assertEquals((referenceConfig.getMethods().get(0)).getOninvokeMethod(), "i"); Assertions.assertEquals((referenceConfig.getMethods().get(0)).getOnreturnMethod(), "r"); Assertions.assertEquals((referenceConfig.getMethods().get(0)).getOnthrowMethod(), "t"); Assertions.assertEquals((referenceConfig.getMethods().get(0)).getCache(), "c"); } @Test void testDifferentClassLoader() throws Exception { ApplicationConfig applicationConfig = new ApplicationConfig("TestApp"); ApplicationModel applicationModel = ApplicationModel.defaultModel(); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ModuleModel moduleModel = applicationModel.newModule(); DemoService demoService = new DemoServiceImpl(); ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(DemoService.class); serviceConfig.setRegistry(new RegistryConfig(zkUrl1)); serviceConfig.setScopeModel(moduleModel); serviceConfig.setRef(demoService); serviceConfig.export(); String basePath = DemoService.class .getProtectionDomain() .getCodeSource() .getLocation() .getFile(); basePath = URLDecoder.decode(basePath, "UTF-8"); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); TestClassLoader classLoader1 = new TestClassLoader(classLoader, basePath); TestClassLoader classLoader2 = new TestClassLoader(classLoader, basePath); Class<?> class1 = classLoader1.loadClass(DemoService.class.getName(), false); Class<?> class2 = classLoader2.loadClass(DemoService.class.getName(), false); Assertions.assertNotEquals(class1, class2); ReferenceConfig<DemoService> referenceConfig1 = new ReferenceConfig<>(); referenceConfig1.setInterface(class1); referenceConfig1.setRegistry(new RegistryConfig(zkUrl1)); referenceConfig1.setScopeModel(moduleModel); referenceConfig1.setScope("remote"); Object demoService1 = referenceConfig1.get(); for (Class<?> anInterface : demoService1.getClass().getInterfaces()) { Assertions.assertNotEquals(DemoService.class, anInterface); } Assertions.assertTrue(Arrays.stream(demoService1.getClass().getInterfaces()) .anyMatch((clazz) -> clazz.getClassLoader().equals(classLoader1))); java.lang.reflect.Method callBean1 = demoService1.getClass().getDeclaredMethod("callInnerClass"); callBean1.setAccessible(true); Object result1 = callBean1.invoke(demoService1); Assertions.assertNotEquals(result1.getClass(), DemoService.InnerClass.class); Assertions.assertEquals(classLoader1, result1.getClass().getClassLoader()); ReferenceConfig<DemoService> referenceConfig2 = new ReferenceConfig<>(); referenceConfig2.setInterface(class2); referenceConfig2.setRegistry(new RegistryConfig(zkUrl1)); referenceConfig2.setScopeModel(moduleModel); referenceConfig2.setScope("remote"); Object demoService2 = referenceConfig2.get(); for (Class<?> anInterface : demoService2.getClass().getInterfaces()) { Assertions.assertNotEquals(DemoService.class, anInterface); } Assertions.assertTrue(Arrays.stream(demoService2.getClass().getInterfaces()) .anyMatch((clazz) -> clazz.getClassLoader().equals(classLoader2))); java.lang.reflect.Method callBean2 = demoService2.getClass().getDeclaredMethod("callInnerClass"); callBean2.setAccessible(true); Object result2 = callBean2.invoke(demoService2); Assertions.assertNotEquals(callBean1, callBean2); Assertions.assertNotEquals(result2.getClass(), DemoService.InnerClass.class); Assertions.assertEquals(classLoader2, result2.getClass().getClassLoader()); Assertions.assertNotEquals(result1.getClass(), result2.getClass()); applicationModel.destroy(); DubboBootstrap.getInstance().destroy(); Thread.currentThread().setContextClassLoader(classLoader); Thread.currentThread().getContextClassLoader().loadClass(DemoService.class.getName()); } @Test @DisabledForJreRange(min = JRE.JAVA_16) public void testDifferentClassLoaderRequest() throws Exception { FrameworkModel frameworkModel = FrameworkModel.defaultModel(); String basePath = DemoService.class .getProtectionDomain() .getCodeSource() .getLocation() .getFile(); basePath = java.net.URLDecoder.decode(basePath, "UTF-8"); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); TestClassLoader1 classLoader1 = new TestClassLoader1(basePath); TestClassLoader1 classLoader2 = new TestClassLoader1(basePath); TestClassLoader2 classLoader3 = new TestClassLoader2(classLoader2, basePath); ApplicationConfig applicationConfig = new ApplicationConfig("TestApp"); ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel.getApplicationConfigManager().setApplication(applicationConfig); ModuleModel moduleModel = applicationModel.newModule(); Class<?> clazz1 = classLoader1.loadClass(MultiClassLoaderService.class.getName(), false); Class<?> clazz1impl = classLoader1.loadClass(MultiClassLoaderServiceImpl.class.getName(), false); Class<?> requestClazzCustom1 = compileCustomRequest(classLoader1); Class<?> resultClazzCustom1 = compileCustomResult(classLoader1); classLoader1.loadedClass.put(requestClazzCustom1.getName(), requestClazzCustom1); classLoader1.loadedClass.put(resultClazzCustom1.getName(), resultClazzCustom1); AtomicReference innerRequestReference = new AtomicReference(); AtomicReference innerResultReference = new AtomicReference(); innerResultReference.set(resultClazzCustom1.getDeclaredConstructor().newInstance()); Constructor<?> declaredConstructor = clazz1impl.getDeclaredConstructor(AtomicReference.class, AtomicReference.class); ServiceConfig serviceConfig = new ServiceConfig<>(); serviceConfig.setInterfaceClassLoader(classLoader1); serviceConfig.setInterface(clazz1); serviceConfig.setRegistry(new RegistryConfig(zkUrl1)); serviceConfig.setScopeModel(moduleModel); serviceConfig.setRef(declaredConstructor.newInstance(innerRequestReference, innerResultReference)); serviceConfig.export(); Class<?> clazz2 = classLoader2.loadClass(MultiClassLoaderService.class.getName(), false); Class<?> requestClazzOrigin = classLoader2.loadClass(MultiClassLoaderServiceRequest.class.getName(), false); Class<?> requestClazzCustom2 = compileCustomRequest(classLoader2); Class<?> resultClazzCustom3 = compileCustomResult(classLoader3); classLoader2.loadedClass.put(requestClazzCustom2.getName(), requestClazzCustom2); classLoader3.loadedClass.put(resultClazzCustom3.getName(), resultClazzCustom3); ReferenceConfig<DemoService> referenceConfig1 = new ReferenceConfig<>(); referenceConfig1.setInterface(clazz2); referenceConfig1.setInterfaceClassLoader(classLoader3); referenceConfig1.setRegistry(new RegistryConfig(zkUrl1)); referenceConfig1.setScopeModel(moduleModel); referenceConfig1.setScope("remote"); Object object1 = referenceConfig1.get(); java.lang.reflect.Method callBean1 = object1.getClass().getDeclaredMethod("call", requestClazzOrigin); callBean1.setAccessible(true); Object result1 = callBean1.invoke( object1, requestClazzCustom2.getDeclaredConstructor().newInstance()); Assertions.assertEquals(resultClazzCustom3, result1.getClass()); Assertions.assertNotEquals(classLoader2, result1.getClass().getClassLoader()); Assertions.assertEquals( classLoader1, innerRequestReference.get().getClass().getClassLoader()); Thread.currentThread().setContextClassLoader(classLoader1); callBean1.invoke(object1, requestClazzCustom2.getDeclaredConstructor().newInstance()); Assertions.assertEquals(classLoader1, Thread.currentThread().getContextClassLoader()); applicationModel.destroy(); DubboBootstrap.getInstance().destroy(); Thread.currentThread().setContextClassLoader(classLoader); Thread.currentThread().getContextClassLoader().loadClass(DemoService.class.getName()); } @Test void testClassLoader() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("Test")); ClassLoader originClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader classLoader = new ClassLoader(originClassLoader) {}; Thread.currentThread().setContextClassLoader(classLoader); ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(applicationModel.newModule()); serviceConfig.setInterface(DemoService.class); serviceConfig.setProtocol(new ProtocolConfig("dubbo", -1)); serviceConfig.setRegistry(new RegistryConfig("N/A")); serviceConfig.setRef(new DemoServiceImpl()); serviceConfig.export(); ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(applicationModel.newModule()); referenceConfig.setInterface(DemoService.class); referenceConfig.setRegistry(new RegistryConfig("N/A")); DemoService demoService = referenceConfig.get(); demoService.sayName("Dubbo"); Assertions.assertEquals(classLoader, Thread.currentThread().getContextClassLoader()); Thread.currentThread().setContextClassLoader(null); demoService.sayName("Dubbo"); Assertions.assertNull(Thread.currentThread().getContextClassLoader()); Thread.currentThread().setContextClassLoader(originClassLoader); frameworkModel.destroy(); } private Class<?> compileCustomRequest(ClassLoader classLoader) throws NotFoundException, CannotCompileException { CtClassBuilder builder = new CtClassBuilder(); builder.setClassName(MultiClassLoaderServiceRequest.class.getName() + "A"); builder.setSuperClassName(MultiClassLoaderServiceRequest.class.getName()); CtClass cls = builder.build(classLoader); // FIXME support JDK 17 return cls.toClass(classLoader, JavassistCompiler.class.getProtectionDomain()); } private Class<?> compileCustomResult(ClassLoader classLoader) throws NotFoundException, CannotCompileException { CtClassBuilder builder = new CtClassBuilder(); builder.setClassName(MultiClassLoaderServiceResult.class.getName() + "A"); builder.setSuperClassName(MultiClassLoaderServiceResult.class.getName()); CtClass cls = builder.build(classLoader); return cls.toClass(classLoader, JavassistCompiler.class.getProtectionDomain()); } @Reference( methods = { @Method( name = "sayHello", timeout = 1300, retries = 4, loadbalance = "random", async = true, actives = 3, executes = 5, deprecated = true, sticky = true, oninvoke = "instance.i", onthrow = "instance.t", onreturn = "instance.r", cache = "c", validation = "v", arguments = {@Argument(index = 24, callback = true, type = "sss")}) }) private InnerTest innerTest; private class InnerTest {} private static class TestClassLoader extends ClassLoader { private String basePath; public TestClassLoader(ClassLoader parent, String basePath) { super(parent); this.basePath = basePath; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { try { byte[] bytes = loadClassData(name); return defineClass(name, bytes, 0, bytes.length); } catch (Exception e) { throw new ClassNotFoundException(); } } @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { Class<?> loadedClass = this.findLoadedClass(name); if (loadedClass != null) { return loadedClass; } else { try { if (name.equals("org.apache.dubbo.config.api.DemoService") || name.equals("org.apache.dubbo.config.api.DemoService$InnerClass")) { Class<?> aClass = this.findClass(name); if (resolve) { this.resolveClass(aClass); } return aClass; } else { return super.loadClass(name, resolve); } } catch (Exception e) { return super.loadClass(name, resolve); } } } public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; FileInputStream fileInputStream; byte[] classBytes; fileInputStream = new FileInputStream(path); int length = fileInputStream.available(); classBytes = new byte[length]; fileInputStream.read(classBytes); fileInputStream.close(); return classBytes; } } private static class TestClassLoader1 extends ClassLoader { private String basePath; public TestClassLoader1(String basePath) { this.basePath = basePath; } Map<String, Class<?>> loadedClass = new ConcurrentHashMap<>(); @Override protected Class<?> findClass(String name) throws ClassNotFoundException { try { byte[] bytes = loadClassData(name); return defineClass(name, bytes, 0, bytes.length); } catch (Exception e) { throw new ClassNotFoundException(); } } @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (loadedClass.containsKey(name)) { return loadedClass.get(name); } if (name.startsWith("demo")) { Class<?> aClass = this.findClass(name); this.loadedClass.put(name, aClass); if (resolve) { this.resolveClass(aClass); } return aClass; } else { Class<?> loadedClass = this.findLoadedClass(name); if (loadedClass != null) { return loadedClass; } else { return super.loadClass(name, resolve); } } } public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; FileInputStream fileInputStream; byte[] classBytes; fileInputStream = new FileInputStream(path); int length = fileInputStream.available(); classBytes = new byte[length]; fileInputStream.read(classBytes); fileInputStream.close(); return classBytes; } } private static class TestClassLoader2 extends ClassLoader { private String basePath; private TestClassLoader1 testClassLoader; Map<String, Class<?>> loadedClass = new ConcurrentHashMap<>(); public TestClassLoader2(TestClassLoader1 testClassLoader, String basePath) { this.testClassLoader = testClassLoader; this.basePath = basePath; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { try { byte[] bytes = loadClassData(name); return defineClass(name, bytes, 0, bytes.length); } catch (Exception e) { throw new ClassNotFoundException(); } } @Override public Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (loadedClass.containsKey(name)) { return loadedClass.get(name); } if (name.startsWith("demo.MultiClassLoaderServiceRe")) { Class<?> aClass = this.findClass(name); this.loadedClass.put(name, aClass); if (resolve) { this.resolveClass(aClass); } return aClass; } else { return testClassLoader.loadClass(name, resolve); } } public byte[] loadClassData(String className) throws IOException { className = className.replaceAll("\\.", "/"); String path = basePath + File.separator + className + ".class"; FileInputStream fileInputStream; byte[] classBytes; fileInputStream = new FileInputStream(path); int length = fileInputStream.available(); classBytes = new byte[length]; fileInputStream.read(classBytes); fileInputStream.close(); return classBytes; } } }
8,419
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConsumerConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.common.utils.JsonUtils; import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.rpc.model.ApplicationModel; import java.util.Collection; import java.util.Collections; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; class ConsumerConfigTest { @BeforeEach public void setUp() { DubboBootstrap.reset(); } @AfterEach public void afterEach() { SysProps.clear(); } @Test void testTimeout() { System.clearProperty("sun.rmi.transport.tcp.responseTimeout"); ConsumerConfig consumer = new ConsumerConfig(); consumer.setTimeout(10); assertThat(consumer.getTimeout(), is(10)); assertThat(System.getProperty("sun.rmi.transport.tcp.responseTimeout"), equalTo("10")); } @Test void testDefault() throws Exception { ConsumerConfig consumer = new ConsumerConfig(); consumer.setDefault(true); assertThat(consumer.isDefault(), is(true)); } @Test void testClient() { ConsumerConfig consumer = new ConsumerConfig(); consumer.setClient("client"); assertThat(consumer.getClient(), equalTo("client")); } @Test void testThreadpool() { ConsumerConfig consumer = new ConsumerConfig(); consumer.setThreadpool("fixed"); assertThat(consumer.getThreadpool(), equalTo("fixed")); } @Test void testCorethreads() { ConsumerConfig consumer = new ConsumerConfig(); consumer.setCorethreads(10); assertThat(consumer.getCorethreads(), equalTo(10)); } @Test void testThreads() { ConsumerConfig consumer = new ConsumerConfig(); consumer.setThreads(20); assertThat(consumer.getThreads(), equalTo(20)); } @Test void testQueues() { ConsumerConfig consumer = new ConsumerConfig(); consumer.setQueues(5); assertThat(consumer.getQueues(), equalTo(5)); } @Test void testOverrideConfigSingle() { SysProps.setProperty("dubbo.consumer.check", "false"); SysProps.setProperty("dubbo.consumer.group", "demo"); SysProps.setProperty("dubbo.consumer.threads", "10"); ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setGroup("groupA"); consumerConfig.setThreads(20); consumerConfig.setCheck(true); DubboBootstrap.getInstance() .application("demo-app") .consumer(consumerConfig) .initialize(); Collection<ConsumerConfig> consumers = ApplicationModel.defaultModel() .getDefaultModule() .getConfigManager() .getConsumers(); Assertions.assertEquals(1, consumers.size()); Assertions.assertEquals(consumerConfig, consumers.iterator().next()); Assertions.assertEquals(false, consumerConfig.isCheck()); Assertions.assertEquals("demo", consumerConfig.getGroup()); Assertions.assertEquals(10, consumerConfig.getThreads()); DubboBootstrap.getInstance().destroy(); } @Test void testOverrideConfigByPluralityId() { SysProps.setProperty("dubbo.consumer.group", "demoA"); // ignore SysProps.setProperty("dubbo.consumers.consumerA.check", "false"); SysProps.setProperty("dubbo.consumers.consumerA.group", "demoB"); SysProps.setProperty("dubbo.consumers.consumerA.threads", "10"); ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setId("consumerA"); consumerConfig.setGroup("groupA"); consumerConfig.setThreads(20); consumerConfig.setCheck(true); DubboBootstrap.getInstance() .application("demo-app") .consumer(consumerConfig) .initialize(); Collection<ConsumerConfig> consumers = ApplicationModel.defaultModel() .getDefaultModule() .getConfigManager() .getConsumers(); Assertions.assertEquals(1, consumers.size()); Assertions.assertEquals(consumerConfig, consumers.iterator().next()); Assertions.assertEquals(false, consumerConfig.isCheck()); Assertions.assertEquals("demoB", consumerConfig.getGroup()); Assertions.assertEquals(10, consumerConfig.getThreads()); DubboBootstrap.getInstance().destroy(); } @Test void testOverrideConfigBySingularId() { // override success SysProps.setProperty("dubbo.consumer.group", "demoA"); SysProps.setProperty("dubbo.consumer.threads", "15"); // ignore singular format: dubbo.{tag-name}.{config-id}.{config-item}={config-value} SysProps.setProperty("dubbo.consumer.consumerA.check", "false"); SysProps.setProperty("dubbo.consumer.consumerA.group", "demoB"); SysProps.setProperty("dubbo.consumer.consumerA.threads", "10"); ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setId("consumerA"); consumerConfig.setGroup("groupA"); consumerConfig.setThreads(20); consumerConfig.setCheck(true); DubboBootstrap.getInstance() .application("demo-app") .consumer(consumerConfig) .initialize(); Collection<ConsumerConfig> consumers = ApplicationModel.defaultModel() .getDefaultModule() .getConfigManager() .getConsumers(); Assertions.assertEquals(1, consumers.size()); Assertions.assertEquals(consumerConfig, consumers.iterator().next()); Assertions.assertEquals(true, consumerConfig.isCheck()); Assertions.assertEquals("demoA", consumerConfig.getGroup()); Assertions.assertEquals(15, consumerConfig.getThreads()); DubboBootstrap.getInstance().destroy(); } @Test void testOverrideConfigByDubboProps() { ApplicationModel.defaultModel().getDefaultModule(); ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .setProperty("dubbo.consumers.consumerA.check", "false"); ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .setProperty("dubbo.consumers.consumerA.group", "demo"); ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .setProperty("dubbo.consumers.consumerA.threads", "10"); try { ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setId("consumerA"); consumerConfig.setGroup("groupA"); DubboBootstrap.getInstance() .application("demo-app") .consumer(consumerConfig) .initialize(); Collection<ConsumerConfig> consumers = ApplicationModel.defaultModel() .getDefaultModule() .getConfigManager() .getConsumers(); Assertions.assertEquals(1, consumers.size()); Assertions.assertEquals(consumerConfig, consumers.iterator().next()); Assertions.assertEquals(false, consumerConfig.isCheck()); Assertions.assertEquals("groupA", consumerConfig.getGroup()); Assertions.assertEquals(10, consumerConfig.getThreads()); } finally { ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .refresh(); DubboBootstrap.getInstance().destroy(); } } @Test void testReferenceAndConsumerConfigOverlay() { SysProps.setProperty("dubbo.consumer.group", "demo"); SysProps.setProperty("dubbo.consumer.threads", "12"); SysProps.setProperty("dubbo.consumer.timeout", "1234"); SysProps.setProperty("dubbo.consumer.init", "false"); SysProps.setProperty("dubbo.consumer.check", "false"); SysProps.setProperty("dubbo.registry.address", "N/A"); ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setInterface(DemoService.class); DubboBootstrap.getInstance() .application("demo-app") .reference(referenceConfig) .initialize(); Assertions.assertEquals("demo", referenceConfig.getGroup()); Assertions.assertEquals(1234, referenceConfig.getTimeout()); Assertions.assertEquals(false, referenceConfig.isInit()); Assertions.assertEquals(false, referenceConfig.isCheck()); DubboBootstrap.getInstance().destroy(); } @Test void testMetaData() { ConsumerConfig consumerConfig = new ConsumerConfig(); Map<String, String> metaData = consumerConfig.getMetaData(); Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } @Test void testSerialize() { ConsumerConfig consumerConfig = new ConsumerConfig(); consumerConfig.setCorethreads(1); consumerConfig.setQueues(1); consumerConfig.setThreads(1); consumerConfig.setThreadpool("Mock"); consumerConfig.setGroup("Test"); consumerConfig.setMeshEnable(false); consumerConfig.setReferThreadNum(2); consumerConfig.setShareconnections(2); consumerConfig.setTimeout(2); consumerConfig.setUrlMergeProcessor("test"); consumerConfig.setReferBackground(false); consumerConfig.setActives(1); consumerConfig.setAsync(false); consumerConfig.setCache("false"); consumerConfig.setCallbacks(1); consumerConfig.setConnections(1); consumerConfig.setInterfaceClassLoader(Thread.currentThread().getContextClassLoader()); consumerConfig.setApplication(new ApplicationConfig()); consumerConfig.setRegistries(Collections.singletonList(new RegistryConfig())); consumerConfig.setModule(new ModuleConfig()); consumerConfig.setMetadataReportConfig(new MetadataReportConfig()); consumerConfig.setMonitor(new MonitorConfig()); consumerConfig.setConfigCenter(new ConfigCenterConfig()); try { JsonUtils.toJson(consumerConfig); } catch (Throwable t) { Assertions.fail(t); } } }
8,420
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/RegistryConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.UrlUtils; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.PREFERRED_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.not; class RegistryConfigTest { @BeforeEach public void beforeEach() { DubboBootstrap.reset(); } @AfterEach public void afterEach() { SysProps.clear(); } @Test void testProtocol() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setProtocol("protocol"); assertThat(registry.getProtocol(), equalTo(registry.getProtocol())); } @Test void testAddress() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setAddress("zookeeper://mrh:123@localhost:9103/registry?backup=localhost:9104&k1=v1"); assertThat( registry.getAddress(), equalTo("zookeeper://mrh:123@localhost:9103/registry?backup=localhost:9104&k1=v1")); assertThat(registry.getProtocol(), equalTo("zookeeper")); assertThat(registry.getUsername(), equalTo("mrh")); assertThat(registry.getPassword(), equalTo("123")); assertThat(registry.getParameters().get("k1"), equalTo("v1")); Map<String, String> parameters = new HashMap<>(); RegistryConfig.appendParameters(parameters, registry); assertThat(parameters, not(hasKey("address"))); } @Test void testUsername() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setUsername("username"); assertThat(registry.getUsername(), equalTo("username")); } @Test void testPassword() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setPassword("password"); assertThat(registry.getPassword(), equalTo("password")); } @Test void testWait() throws Exception { try { RegistryConfig registry = new RegistryConfig(); registry.setWait(10); assertThat(registry.getWait(), is(10)); assertThat(System.getProperty(SHUTDOWN_WAIT_KEY), equalTo("10")); } finally { System.clearProperty(SHUTDOWN_TIMEOUT_KEY); } } @Test void testCheck() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setCheck(true); assertThat(registry.isCheck(), is(true)); } @Test void testFile() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setFile("file"); assertThat(registry.getFile(), equalTo("file")); } @Test void testTransporter() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setTransporter("transporter"); assertThat(registry.getTransporter(), equalTo("transporter")); } @Test void testClient() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setClient("client"); assertThat(registry.getClient(), equalTo("client")); } @Test void testTimeout() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setTimeout(10); assertThat(registry.getTimeout(), is(10)); } @Test void testSession() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setSession(10); assertThat(registry.getSession(), is(10)); } @Test void testDynamic() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setDynamic(true); assertThat(registry.isDynamic(), is(true)); } @Test void testRegister() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setRegister(true); assertThat(registry.isRegister(), is(true)); } @Test void testSubscribe() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setSubscribe(true); assertThat(registry.isSubscribe(), is(true)); } @Test void testCluster() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setCluster("cluster"); assertThat(registry.getCluster(), equalTo("cluster")); } @Test void testGroup() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setGroup("group"); assertThat(registry.getGroup(), equalTo("group")); } @Test void testVersion() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setVersion("1.0.0"); assertThat(registry.getVersion(), equalTo("1.0.0")); } @Test void testParameters() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setParameters(Collections.singletonMap("k1", "v1")); assertThat(registry.getParameters(), hasEntry("k1", "v1")); Map<String, String> parameters = new HashMap<String, String>(); RegistryConfig.appendParameters(parameters, registry); assertThat(parameters, hasEntry("k1", "v1")); } @Test void testDefault() throws Exception { RegistryConfig registry = new RegistryConfig(); registry.setDefault(true); assertThat(registry.isDefault(), is(true)); } @Test void testEquals() throws Exception { RegistryConfig registry1 = new RegistryConfig(); RegistryConfig registry2 = new RegistryConfig(); registry1.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress2()); registry2.setAddress("zookeeper://127.0.0.1:2183"); Assertions.assertNotEquals(registry1, registry2); } @Test void testMetaData() { RegistryConfig config = new RegistryConfig(); Map<String, String> metaData = config.getMetaData(); Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } @Test void testOverrideConfigBySystemProps() { SysProps.setProperty("dubbo.registry.address", "zookeeper://${zookeeper.address}:${zookeeper.port}"); SysProps.setProperty("dubbo.registry.useAsConfigCenter", "false"); SysProps.setProperty("dubbo.registry.useAsMetadataCenter", "false"); SysProps.setProperty("zookeeper.address", "localhost"); SysProps.setProperty("zookeeper.port", "2188"); DubboBootstrap.getInstance().application("demo-app").initialize(); Collection<RegistryConfig> registries = ApplicationModel.defaultModel().getApplicationConfigManager().getRegistries(); Assertions.assertEquals(1, registries.size()); RegistryConfig registryConfig = registries.iterator().next(); Assertions.assertEquals("zookeeper://localhost:2188", registryConfig.getAddress()); } public void testPreferredWithTrueValue() { RegistryConfig registry = new RegistryConfig(); registry.setPreferred(true); Map<String, String> map = new HashMap<>(); // process Parameter annotation AbstractConfig.appendParameters(map, registry); // Simulate the check that ZoneAwareClusterInvoker#doInvoke do URL url = UrlUtils.parseURL(ZookeeperRegistryCenterConfig.getConnectionAddress1(), map); Assertions.assertTrue(url.getParameter(PREFERRED_KEY, false)); } @Test void testPreferredWithFalseValue() { RegistryConfig registry = new RegistryConfig(); registry.setPreferred(false); Map<String, String> map = new HashMap<>(); // Process Parameter annotation AbstractConfig.appendParameters(map, registry); // Simulate the check that ZoneAwareClusterInvoker#doInvoke do URL url = UrlUtils.parseURL(ZookeeperRegistryCenterConfig.getConnectionAddress1(), map); Assertions.assertFalse(url.getParameter(PREFERRED_KEY, false)); } }
8,421
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ConfigCenterConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.remoting.Constants.CLIENT_KEY; class ConfigCenterConfigTest { @BeforeEach public void setUp() { DubboBootstrap.reset(); } @AfterEach public void afterEach() { SysProps.clear(); } @Test void testPrefix() { ConfigCenterConfig config = new ConfigCenterConfig(); Assertions.assertEquals(Arrays.asList("dubbo.config-center"), config.getPrefixes()); config.setId("configcenterA"); Assertions.assertEquals( Arrays.asList("dubbo.config-centers.configcenterA", "dubbo.config-center"), config.getPrefixes()); } @Test void testToUrl() { ConfigCenterConfig config = new ConfigCenterConfig(); config.setNamespace("namespace"); config.setGroup("group"); config.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress()); config.setHighestPriority(null); config.refresh(); Assertions.assertEquals( ZookeeperRegistryCenterConfig.getConnectionAddress() + "/" + ConfigCenterConfig.class.getName() + "?check=true&config-file=dubbo.properties&group=group&namespace=namespace&timeout=30000", config.toUrl().toFullString()); } @Test void testOverrideConfig() { String zkAddr = ZookeeperRegistryCenterConfig.getConnectionAddress(); // sysprops has no id SysProps.setProperty("dubbo.config-center.check", "false"); SysProps.setProperty("dubbo.config-center.address", zkAddr); // No id and no address ConfigCenterConfig configCenter = new ConfigCenterConfig(); configCenter.setAddress("N/A"); try { DubboBootstrap.getInstance() .application("demo-app") .configCenter(configCenter) .initialize(); } catch (Exception e) { // ignore e.printStackTrace(); } Collection<ConfigCenterConfig> configCenters = ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); Assertions.assertEquals(configCenter, configCenters.iterator().next()); Assertions.assertEquals(zkAddr, configCenter.getAddress()); Assertions.assertEquals(false, configCenter.isCheck()); DubboBootstrap.getInstance().stop(); } @Test void testOverrideConfig2() { String zkAddr = "nacos://127.0.0.1:8848"; // sysprops has no id SysProps.setProperty("dubbo.config-center.check", "false"); SysProps.setProperty("dubbo.config-center.address", zkAddr); // No id but has address ConfigCenterConfig configCenter = new ConfigCenterConfig(); configCenter.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress()); DubboBootstrap.getInstance() .application("demo-app") .configCenter(configCenter) .start(); Collection<ConfigCenterConfig> configCenters = ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); Assertions.assertEquals(configCenter, configCenters.iterator().next()); Assertions.assertEquals(zkAddr, configCenter.getAddress()); Assertions.assertEquals(false, configCenter.isCheck()); DubboBootstrap.getInstance().stop(); } @Test void testOverrideConfigBySystemProps() { // Config instance has Id, but sysprops without id SysProps.setProperty("dubbo.config-center.check", "false"); SysProps.setProperty("dubbo.config-center.timeout", "1234"); // Config instance has id ConfigCenterConfig configCenter = new ConfigCenterConfig(); configCenter.setTimeout(3000L); DubboBootstrap.getInstance() .application("demo-app") .configCenter(configCenter) .initialize(); Collection<ConfigCenterConfig> configCenters = ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); Assertions.assertEquals(configCenter, configCenters.iterator().next()); Assertions.assertEquals(1234, configCenter.getTimeout()); Assertions.assertEquals(false, configCenter.isCheck()); DubboBootstrap.getInstance().stop(); } @Test void testOverrideConfigByDubboProps() { ApplicationModel.defaultModel().getDefaultModule(); // Config instance has id, dubbo props has no id ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .setProperty("dubbo.config-center.check", "false"); ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .setProperty("dubbo.config-center.timeout", "1234"); try { // Config instance has id ConfigCenterConfig configCenter = new ConfigCenterConfig(); configCenter.setTimeout(3000L); DubboBootstrap.getInstance() .application("demo-app") .configCenter(configCenter) .initialize(); Collection<ConfigCenterConfig> configCenters = ApplicationModel.defaultModel() .getApplicationConfigManager() .getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); Assertions.assertEquals(configCenter, configCenters.iterator().next()); Assertions.assertEquals(3000L, configCenter.getTimeout()); Assertions.assertEquals(false, configCenter.isCheck()); } finally { ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .refresh(); DubboBootstrap.getInstance().stop(); } } @Test void testOverrideConfigBySystemPropsWithId() { // Both config instance and sysprops have id SysProps.setProperty("dubbo.config-centers.configcenterA.check", "false"); SysProps.setProperty("dubbo.config-centers.configcenterA.timeout", "1234"); // Config instance has id ConfigCenterConfig configCenter = new ConfigCenterConfig(); configCenter.setId("configcenterA"); configCenter.setTimeout(3000L); DubboBootstrap.getInstance() .application("demo-app") .configCenter(configCenter) .start(); Collection<ConfigCenterConfig> configCenters = ApplicationModel.defaultModel().getApplicationConfigManager().getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); Assertions.assertEquals(configCenter, configCenters.iterator().next()); Assertions.assertEquals(1234, configCenter.getTimeout()); Assertions.assertEquals(false, configCenter.isCheck()); DubboBootstrap.getInstance().stop(); } @Test void testOverrideConfigByDubboPropsWithId() { ApplicationModel.defaultModel().getDefaultModule(); // Config instance has id, dubbo props has id ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .setProperty("dubbo.config-centers.configcenterA.check", "false"); ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .setProperty("dubbo.config-centers.configcenterA.timeout", "1234"); try { // Config instance has id ConfigCenterConfig configCenter = new ConfigCenterConfig(); configCenter.setId("configcenterA"); configCenter.setTimeout(3000L); DubboBootstrap.getInstance() .application("demo-app") .configCenter(configCenter) .start(); Collection<ConfigCenterConfig> configCenters = ApplicationModel.defaultModel() .getApplicationConfigManager() .getConfigCenters(); Assertions.assertEquals(1, configCenters.size()); Assertions.assertEquals(configCenter, configCenters.iterator().next()); Assertions.assertEquals(3000L, configCenter.getTimeout()); Assertions.assertEquals(false, configCenter.isCheck()); } finally { ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .refresh(); DubboBootstrap.getInstance().stop(); } } @Test void testMetaData() { ConfigCenterConfig configCenter = new ConfigCenterConfig(); Map<String, String> metaData = configCenter.getMetaData(); Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } @Test void testParameters() { ConfigCenterConfig cc = new ConfigCenterConfig(); cc.setParameters(new LinkedHashMap<>()); cc.getParameters().put(CLIENT_KEY, null); Map<String, String> params = new LinkedHashMap<>(); ConfigCenterConfig.appendParameters(params, cc); Map<String, String> attributes = new LinkedHashMap<>(); ConfigCenterConfig.appendAttributes(attributes, cc); String encodedParametersStr = attributes.get("parameters"); Assertions.assertEquals("[]", encodedParametersStr); Assertions.assertEquals( 0, StringUtils.parseParameters(encodedParametersStr).size()); } @Test void testAttributes() { ConfigCenterConfig cc = new ConfigCenterConfig(); cc.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress()); Map<String, String> attributes = new LinkedHashMap<>(); ConfigCenterConfig.appendAttributes(attributes, cc); Assertions.assertEquals(cc.getAddress(), attributes.get("address")); Assertions.assertEquals(cc.getProtocol(), attributes.get("protocol")); Assertions.assertEquals("" + cc.getPort(), attributes.get("port")); Assertions.assertEquals(null, attributes.get("valid")); Assertions.assertEquals(null, attributes.get("refreshed")); } @Test void testSetAddress() { String address = ZookeeperRegistryCenterConfig.getConnectionAddress(); ConfigCenterConfig cc = new ConfigCenterConfig(); cc.setUsername("user123"); // set username first cc.setPassword("pass123"); cc.setAddress(address); // set address last, expect did not override username/password Assertions.assertEquals(address, cc.getAddress()); Assertions.assertEquals("zookeeper", cc.getProtocol()); Assertions.assertEquals(2181, cc.getPort()); Assertions.assertEquals("user123", cc.getUsername()); Assertions.assertEquals("pass123", cc.getPassword()); } }
8,422
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/SysProps.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import java.util.LinkedHashMap; import java.util.Map; /** * Use to set and clear System property */ public class SysProps { private static Map<String, String> map = new LinkedHashMap<String, String>(); public static void reset() { map.clear(); } public static void setProperty(String key, String value) { map.put(key, value); System.setProperty(key, value); } public static void clear() { for (String key : map.keySet()) { System.clearProperty(key); } reset(); } }
8,423
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/MethodConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.config.annotation.Argument; import org.apache.dubbo.config.annotation.Method; import org.apache.dubbo.config.annotation.Reference; import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.common.Person; import org.apache.dubbo.config.provider.impl.DemoServiceImpl; import org.apache.dubbo.rpc.model.AsyncMethodInfo; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.config.Constants.ON_INVOKE_INSTANCE_ATTRIBUTE_KEY; import static org.apache.dubbo.config.Constants.ON_INVOKE_METHOD_ATTRIBUTE_KEY; import static org.apache.dubbo.config.Constants.ON_RETURN_INSTANCE_ATTRIBUTE_KEY; import static org.apache.dubbo.config.Constants.ON_RETURN_METHOD_ATTRIBUTE_KEY; import static org.apache.dubbo.config.Constants.ON_THROW_INSTANCE_ATTRIBUTE_KEY; import static org.apache.dubbo.config.Constants.ON_THROW_METHOD_ATTRIBUTE_KEY; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.junit.jupiter.api.Assertions.assertEquals; class MethodConfigTest { private static final String METHOD_NAME = "sayHello"; private static final int TIMEOUT = 1300; private static final int RETRIES = 4; private static final String LOADBALANCE = "random"; private static final boolean ASYNC = true; private static final int ACTIVES = 3; private static final int EXECUTES = 5; private static final boolean DEPERECATED = true; private static final boolean STICKY = true; private static final String ONINVOKE = "invokeNotify"; private static final String ONINVOKE_METHOD = "onInvoke"; private static final String ONTHROW = "throwNotify"; private static final String ONTHROW_METHOD = "onThrow"; private static final String ONRETURN = "returnNotify"; private static final String ONRETURN_METHOD = "onReturn"; private static final String CACHE = "c"; private static final String VALIDATION = "v"; private static final int ARGUMENTS_INDEX = 24; private static final boolean ARGUMENTS_CALLBACK = true; private static final String ARGUMENTS_TYPE = "sss"; @Reference( methods = { @Method( name = METHOD_NAME, timeout = TIMEOUT, retries = RETRIES, loadbalance = LOADBALANCE, async = ASYNC, actives = ACTIVES, executes = EXECUTES, deprecated = DEPERECATED, sticky = STICKY, oninvoke = ONINVOKE + "." + ONINVOKE_METHOD, onthrow = ONTHROW + "." + ONTHROW_METHOD, onreturn = ONRETURN + "." + ONRETURN_METHOD, cache = CACHE, validation = VALIDATION, arguments = { @Argument(index = ARGUMENTS_INDEX, callback = ARGUMENTS_CALLBACK, type = ARGUMENTS_TYPE) }) }) private String testField; @BeforeEach public void beforeEach() { DubboBootstrap.reset(); } @AfterEach public void afterEach() { SysProps.clear(); } // TODO remove this test @Test void testStaticConstructor() throws NoSuchFieldException { Method[] methods = this.getClass() .getDeclaredField("testField") .getAnnotation(Reference.class) .methods(); List<MethodConfig> methodConfigs = MethodConfig.constructMethodConfig(methods); MethodConfig methodConfig = methodConfigs.get(0); assertThat(METHOD_NAME, equalTo(methodConfig.getName())); assertThat(TIMEOUT, equalTo(methodConfig.getTimeout())); assertThat(RETRIES, equalTo(methodConfig.getRetries())); assertThat(LOADBALANCE, equalTo(methodConfig.getLoadbalance())); assertThat(ASYNC, equalTo(methodConfig.isAsync())); assertThat(ACTIVES, equalTo(methodConfig.getActives())); assertThat(EXECUTES, equalTo(methodConfig.getExecutes())); assertThat(DEPERECATED, equalTo(methodConfig.getDeprecated())); assertThat(STICKY, equalTo(methodConfig.getSticky())); assertThat(ONINVOKE, equalTo(methodConfig.getOninvoke())); assertThat(ONINVOKE_METHOD, equalTo(methodConfig.getOninvokeMethod())); assertThat(ONTHROW, equalTo(methodConfig.getOnthrow())); assertThat(ONTHROW_METHOD, equalTo(methodConfig.getOnthrowMethod())); assertThat(ONRETURN, equalTo(methodConfig.getOnreturn())); assertThat(ONRETURN_METHOD, equalTo(methodConfig.getOnreturnMethod())); assertThat(CACHE, equalTo(methodConfig.getCache())); assertThat(VALIDATION, equalTo(methodConfig.getValidation())); assertThat(ARGUMENTS_INDEX, equalTo(methodConfig.getArguments().get(0).getIndex())); assertThat( ARGUMENTS_CALLBACK, equalTo(methodConfig.getArguments().get(0).isCallback())); assertThat(ARGUMENTS_TYPE, equalTo(methodConfig.getArguments().get(0).getType())); } @Test void testName() { MethodConfig method = new MethodConfig(); method.setName("hello"); assertThat(method.getName(), equalTo("hello")); Map<String, String> parameters = new HashMap<>(); MethodConfig.appendParameters(parameters, method); assertThat(parameters, not(hasKey("name"))); } @Test void testStat() { MethodConfig method = new MethodConfig(); method.setStat(10); assertThat(method.getStat(), equalTo(10)); } @Test void testRetry() { MethodConfig method = new MethodConfig(); method.setRetry(true); assertThat(method.isRetry(), is(true)); } @Test void testReliable() { MethodConfig method = new MethodConfig(); method.setReliable(true); assertThat(method.isReliable(), is(true)); } @Test void testExecutes() { MethodConfig method = new MethodConfig(); method.setExecutes(10); assertThat(method.getExecutes(), equalTo(10)); } @Test void testDeprecated() { MethodConfig method = new MethodConfig(); method.setDeprecated(true); assertThat(method.getDeprecated(), is(true)); } @Test void testArguments() { MethodConfig method = new MethodConfig(); ArgumentConfig argument = new ArgumentConfig(); method.setArguments(Collections.singletonList(argument)); assertThat(method.getArguments(), contains(argument)); assertThat(method.getArguments(), Matchers.<ArgumentConfig>hasSize(1)); } @Test void testSticky() { MethodConfig method = new MethodConfig(); method.setSticky(true); assertThat(method.getSticky(), is(true)); } @Test void testConvertMethodConfig2AsyncInfo() throws Exception { MethodConfig methodConfig = new MethodConfig(); String methodName = "setName"; methodConfig.setOninvokeMethod(methodName); methodConfig.setOnthrowMethod(methodName); methodConfig.setOnreturnMethod(methodName); methodConfig.setOninvoke(new Person()); methodConfig.setOnthrow(new Person()); methodConfig.setOnreturn(new Person()); AsyncMethodInfo methodInfo = methodConfig.convertMethodConfig2AsyncInfo(); assertEquals(methodInfo.getOninvokeMethod(), Person.class.getMethod(methodName, String.class)); assertEquals(methodInfo.getOnthrowMethod(), Person.class.getMethod(methodName, String.class)); assertEquals(methodInfo.getOnreturnMethod(), Person.class.getMethod(methodName, String.class)); } // @Test void testOnReturn() { MethodConfig method = new MethodConfig(); method.setOnreturn("on-return-object"); assertThat(method.getOnreturn(), equalTo("on-return-object")); Map<String, String> attributes = new HashMap<>(); MethodConfig.appendAttributes(attributes, method); assertThat(attributes, hasEntry(ON_RETURN_INSTANCE_ATTRIBUTE_KEY, "on-return-object")); Map<String, String> parameters = new HashMap<String, String>(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); } @Test void testOnReturnMethod() { MethodConfig method = new MethodConfig(); method.setOnreturnMethod("on-return-method"); assertThat(method.getOnreturnMethod(), equalTo("on-return-method")); Map<String, String> attributes = new HashMap<>(); MethodConfig.appendAttributes(attributes, method); assertThat(attributes, hasEntry(ON_RETURN_METHOD_ATTRIBUTE_KEY, "on-return-method")); Map<String, String> parameters = new HashMap<String, String>(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); } // @Test void testOnThrow() { MethodConfig method = new MethodConfig(); method.setOnthrow("on-throw-object"); assertThat(method.getOnthrow(), equalTo("on-throw-object")); Map<String, String> attributes = new HashMap<>(); MethodConfig.appendAttributes(attributes, method); assertThat(attributes, hasEntry(ON_THROW_INSTANCE_ATTRIBUTE_KEY, "on-throw-object")); Map<String, String> parameters = new HashMap<String, String>(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); } @Test void testOnThrowMethod() { MethodConfig method = new MethodConfig(); method.setOnthrowMethod("on-throw-method"); assertThat(method.getOnthrowMethod(), equalTo("on-throw-method")); Map<String, String> attributes = new HashMap<>(); MethodConfig.appendAttributes(attributes, method); assertThat(attributes, hasEntry(ON_THROW_METHOD_ATTRIBUTE_KEY, "on-throw-method")); Map<String, String> parameters = new HashMap<String, String>(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); } // @Test void testOnInvoke() { MethodConfig method = new MethodConfig(); method.setOninvoke("on-invoke-object"); assertThat(method.getOninvoke(), equalTo("on-invoke-object")); Map<String, String> attributes = new HashMap<>(); MethodConfig.appendAttributes(attributes, method); assertThat(attributes, hasEntry(ON_INVOKE_INSTANCE_ATTRIBUTE_KEY, "on-invoke-object")); Map<String, String> parameters = new HashMap<String, String>(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); } @Test void testOnInvokeMethod() { MethodConfig method = new MethodConfig(); method.setOninvokeMethod("on-invoke-method"); assertThat(method.getOninvokeMethod(), equalTo("on-invoke-method")); Map<String, String> attributes = new HashMap<>(); MethodConfig.appendAttributes(attributes, method); assertThat(attributes, hasEntry(ON_INVOKE_METHOD_ATTRIBUTE_KEY, "on-invoke-method")); Map<String, String> parameters = new HashMap<String, String>(); MethodConfig.appendParameters(parameters, method); assertThat(parameters.size(), is(0)); } @Test void testReturn() { MethodConfig method = new MethodConfig(); method.setReturn(true); assertThat(method.isReturn(), is(true)); } @Test void testOverrideMethodConfigOfReference() { String interfaceName = DemoService.class.getName(); SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.timeout", "1234"); SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.sticky", "true"); SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.parameters", "[{a:1},{b:2}]"); SysProps.setProperty("dubbo.reference." + interfaceName + ".init", "false"); ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(interfaceName); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); methodConfig.setTimeout(1000); referenceConfig.setMethods(Arrays.asList(methodConfig)); DubboBootstrap.getInstance() .application("demo-app") .reference(referenceConfig) .initialize(); Map<String, String> params = new LinkedHashMap<>(); params.put("a", "1"); params.put("b", "2"); Assertions.assertEquals(1234, methodConfig.getTimeout()); Assertions.assertEquals(true, methodConfig.getSticky()); Assertions.assertEquals(params, methodConfig.getParameters()); Assertions.assertEquals(false, referenceConfig.isInit()); } @Test void testAddMethodConfigOfReference() { String interfaceName = DemoService.class.getName(); SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.timeout", "1234"); SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.sticky", "true"); SysProps.setProperty("dubbo.reference." + interfaceName + ".sayName.parameters", "[{a:1},{b:2}]"); SysProps.setProperty("dubbo.reference." + interfaceName + ".init", "false"); ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(interfaceName); DubboBootstrap.getInstance() .application("demo-app") .reference(referenceConfig) .initialize(); List<MethodConfig> methodConfigs = referenceConfig.getMethods(); Assertions.assertEquals(1, methodConfigs.size()); MethodConfig methodConfig = methodConfigs.get(0); Map<String, String> params = new LinkedHashMap<>(); params.put("a", "1"); params.put("b", "2"); Assertions.assertEquals(1234, methodConfig.getTimeout()); Assertions.assertEquals(true, methodConfig.getSticky()); Assertions.assertEquals(params, methodConfig.getParameters()); Assertions.assertEquals(false, referenceConfig.isInit()); DubboBootstrap.getInstance().destroy(); } @Test void testOverrideMethodConfigOfService() { String interfaceName = DemoService.class.getName(); SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.timeout", "1234"); SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.sticky", "true"); SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.parameters", "[{a:1},{b:2}]"); SysProps.setProperty("dubbo.service." + interfaceName + ".group", "demo"); SysProps.setProperty("dubbo.registry.address", "N/A"); ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(interfaceName); serviceConfig.setRef(new DemoServiceImpl()); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); methodConfig.setTimeout(1000); serviceConfig.setMethods(Collections.singletonList(methodConfig)); DubboBootstrap.getInstance() .application("demo-app") .service(serviceConfig) .initialize(); Map<String, String> params = new LinkedHashMap<>(); params.put("a", "1"); params.put("b", "2"); Assertions.assertEquals(1234, methodConfig.getTimeout()); Assertions.assertEquals(true, methodConfig.getSticky()); Assertions.assertEquals(params, methodConfig.getParameters()); Assertions.assertEquals("demo", serviceConfig.getGroup()); DubboBootstrap.getInstance().destroy(); } @Test void testAddMethodConfigOfService() { String interfaceName = DemoService.class.getName(); SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.timeout", "1234"); SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.sticky", "true"); SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.parameters", "[{a:1},{b:2}]"); SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.0.callback", "true"); SysProps.setProperty("dubbo.service." + interfaceName + ".group", "demo"); SysProps.setProperty("dubbo.service." + interfaceName + ".echo", "non-method-config"); SysProps.setProperty("dubbo.registry.address", "N/A"); ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(interfaceName); serviceConfig.setRef(new DemoServiceImpl()); Assertions.assertNull(serviceConfig.getMethods()); DubboBootstrap.getInstance() .application("demo-app") .service(serviceConfig) .initialize(); List<MethodConfig> methodConfigs = serviceConfig.getMethods(); Assertions.assertEquals(1, methodConfigs.size()); MethodConfig methodConfig = methodConfigs.get(0); List<ArgumentConfig> arguments = methodConfig.getArguments(); Assertions.assertEquals(1, arguments.size()); ArgumentConfig argumentConfig = arguments.get(0); Map<String, String> params = new LinkedHashMap<>(); params.put("a", "1"); params.put("b", "2"); Assertions.assertEquals("demo", serviceConfig.getGroup()); Assertions.assertEquals(params, methodConfig.getParameters()); Assertions.assertEquals(1234, methodConfig.getTimeout()); Assertions.assertEquals(true, methodConfig.getSticky()); Assertions.assertEquals(0, argumentConfig.getIndex()); Assertions.assertEquals(true, argumentConfig.isCallback()); DubboBootstrap.getInstance().destroy(); } @Test void testVerifyMethodConfigOfService() { String interfaceName = DemoService.class.getName(); SysProps.setProperty("dubbo.service." + interfaceName + ".sayHello.timeout", "1234"); SysProps.setProperty("dubbo.service." + interfaceName + ".group", "demo"); SysProps.setProperty("dubbo.registry.address", "N/A"); ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(interfaceName); serviceConfig.setRef(new DemoServiceImpl()); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayHello"); methodConfig.setTimeout(1000); serviceConfig.setMethods(Collections.singletonList(methodConfig)); try { DubboBootstrap.getInstance() .application("demo-app") .service(serviceConfig) .initialize(); Assertions.fail("Method config verification should failed"); } catch (Exception e) { // ignore Throwable cause = e.getCause(); Assertions.assertEquals(IllegalStateException.class, cause.getClass()); Assertions.assertTrue(cause.getMessage().contains("not found method"), cause.toString()); } finally { DubboBootstrap.getInstance().destroy(); } } @Test void testIgnoreInvalidMethodConfigOfService() { String interfaceName = DemoService.class.getName(); SysProps.setProperty("dubbo.service." + interfaceName + ".sayHello.timeout", "1234"); SysProps.setProperty("dubbo.service." + interfaceName + ".sayName.timeout", "1234"); SysProps.setProperty("dubbo.registry.address", "N/A"); SysProps.setProperty(ConfigKeys.DUBBO_CONFIG_IGNORE_INVALID_METHOD_CONFIG, "true"); ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(interfaceName); serviceConfig.setRef(new DemoServiceImpl()); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayHello"); methodConfig.setTimeout(1000); serviceConfig.setMethods(Collections.singletonList(methodConfig)); DubboBootstrap.getInstance() .application("demo-app") .service(serviceConfig) .initialize(); // expect sayHello method config will be ignored, and sayName method config will be created. Assertions.assertEquals(1, serviceConfig.getMethods().size()); Assertions.assertEquals("sayName", serviceConfig.getMethods().get(0).getName()); DubboBootstrap.getInstance().destroy(); } @Test void testMetaData() { MethodConfig methodConfig = new MethodConfig(); Map<String, String> metaData = methodConfig.getMetaData(); Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } }
8,424
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractReferenceConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.remoting.Constants; import org.apache.dubbo.rpc.cluster.router.condition.ConditionStateRouterFactory; import org.apache.dubbo.rpc.cluster.router.condition.config.AppStateRouterFactory; import org.apache.dubbo.rpc.cluster.router.state.StateRouterFactory; import org.apache.dubbo.rpc.cluster.router.tag.TagStateRouterFactory; import org.apache.dubbo.rpc.model.FrameworkModel; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.apache.dubbo.common.constants.CommonConstants.INVOKER_LISTENER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY; import static org.apache.dubbo.common.constants.CommonConstants.STUB_EVENT_KEY; import static org.apache.dubbo.rpc.cluster.Constants.CLUSTER_STICKY_KEY; import static org.apache.dubbo.rpc.cluster.Constants.ROUTER_KEY; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.hasValue; import static org.hamcrest.Matchers.is; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class AbstractReferenceConfigTest { @AfterAll public static void afterAll() throws Exception { FrameworkModel.destroyAll(); } @Test void testCheck() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setCheck(true); assertThat(referenceConfig.isCheck(), is(true)); } @Test void testInit() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setInit(true); assertThat(referenceConfig.isInit(), is(true)); } @Test void testGeneric() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setGeneric(true); assertThat(referenceConfig.isGeneric(), is(true)); Map<String, String> parameters = new HashMap<String, String>(); AbstractInterfaceConfig.appendParameters(parameters, referenceConfig); // FIXME: not sure why AbstractReferenceConfig has both isGeneric and getGeneric assertThat(parameters, hasKey("generic")); } @Test void testInjvm() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setInjvm(true); assertThat(referenceConfig.isInjvm(), is(true)); } @Test void testFilter() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setFilter("mockfilter"); assertThat(referenceConfig.getFilter(), equalTo("mockfilter")); Map<String, String> parameters = new HashMap<String, String>(); parameters.put(REFERENCE_FILTER_KEY, "prefilter"); AbstractInterfaceConfig.appendParameters(parameters, referenceConfig); assertThat(parameters, hasValue("prefilter,mockfilter")); } @Test void testRouter() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setRouter("condition"); assertThat(referenceConfig.getRouter(), equalTo("condition")); Map<String, String> parameters = new HashMap<String, String>(); parameters.put(ROUTER_KEY, "tag"); AbstractInterfaceConfig.appendParameters(parameters, referenceConfig); assertThat(parameters, hasValue("tag,condition")); URL url = mock(URL.class); when(url.getParameter(ROUTER_KEY)).thenReturn("condition"); List<StateRouterFactory> routerFactories = ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getActivateExtension(url, ROUTER_KEY); assertThat( routerFactories.stream() .anyMatch(routerFactory -> routerFactory.getClass().equals(ConditionStateRouterFactory.class)), is(true)); when(url.getParameter(ROUTER_KEY)).thenReturn("-tag,-app"); routerFactories = ExtensionLoader.getExtensionLoader(StateRouterFactory.class).getActivateExtension(url, ROUTER_KEY); assertThat( routerFactories.stream() .allMatch(routerFactory -> !routerFactory.getClass().equals(TagStateRouterFactory.class) && !routerFactory.getClass().equals(AppStateRouterFactory.class)), is(true)); } @Test void testListener() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setListener("mockinvokerlistener"); assertThat(referenceConfig.getListener(), equalTo("mockinvokerlistener")); Map<String, String> parameters = new HashMap<String, String>(); parameters.put(INVOKER_LISTENER_KEY, "prelistener"); AbstractInterfaceConfig.appendParameters(parameters, referenceConfig); assertThat(parameters, hasValue("prelistener,mockinvokerlistener")); } @Test void testLazy() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setLazy(true); assertThat(referenceConfig.getLazy(), is(true)); } @Test void testOnconnect() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setOnconnect("onConnect"); assertThat(referenceConfig.getOnconnect(), equalTo("onConnect")); assertThat(referenceConfig.getStubevent(), is(true)); } @Test void testOndisconnect() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setOndisconnect("onDisconnect"); assertThat(referenceConfig.getOndisconnect(), equalTo("onDisconnect")); assertThat(referenceConfig.getStubevent(), is(true)); } @Test void testStubevent() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setOnconnect("onConnect"); Map<String, String> parameters = new HashMap<String, String>(); AbstractInterfaceConfig.appendParameters(parameters, referenceConfig); assertThat(parameters, hasKey(STUB_EVENT_KEY)); } @Test void testReconnect() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setReconnect("reconnect"); Map<String, String> parameters = new HashMap<String, String>(); AbstractInterfaceConfig.appendParameters(parameters, referenceConfig); assertThat(referenceConfig.getReconnect(), equalTo("reconnect")); assertThat(parameters, hasKey(Constants.RECONNECT_KEY)); } @Test void testSticky() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setSticky(true); Map<String, String> parameters = new HashMap<String, String>(); AbstractInterfaceConfig.appendParameters(parameters, referenceConfig); assertThat(referenceConfig.getSticky(), is(true)); assertThat(parameters, hasKey(CLUSTER_STICKY_KEY)); } @Test void testVersion() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setVersion("version"); assertThat(referenceConfig.getVersion(), equalTo("version")); } @Test void testGroup() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setGroup("group"); assertThat(referenceConfig.getGroup(), equalTo("group")); } @Test void testGenericOverride() { ReferenceConfig referenceConfig = new ReferenceConfig(); referenceConfig.setGeneric("false"); referenceConfig.refresh(); Assertions.assertFalse(referenceConfig.isGeneric()); Assertions.assertEquals("false", referenceConfig.getGeneric()); ReferenceConfig referenceConfig1 = new ReferenceConfig(); referenceConfig1.setGeneric(GENERIC_SERIALIZATION_NATIVE_JAVA); referenceConfig1.refresh(); Assertions.assertEquals(GENERIC_SERIALIZATION_NATIVE_JAVA, referenceConfig1.getGeneric()); Assertions.assertTrue(referenceConfig1.isGeneric()); ReferenceConfig referenceConfig2 = new ReferenceConfig(); referenceConfig2.refresh(); Assertions.assertNull(referenceConfig2.getGeneric()); } private static class ReferenceConfig extends AbstractReferenceConfig {} }
8,425
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProtocolConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.context.ConfigManager; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.ProviderConstants.DEFAULT_PREFER_SERIALIZATION; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.junit.jupiter.api.Assertions.assertNull; class ProtocolConfigTest { @BeforeEach public void setUp() { DubboBootstrap.reset(); } @AfterEach public void afterEach() { SysProps.clear(); } @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Test void testName() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); String protocolName = "xprotocol"; protocol.setName(protocolName); Map<String, String> parameters = new HashMap<String, String>(); ProtocolConfig.appendParameters(parameters, protocol); assertThat(protocol.getName(), equalTo(protocolName)); assertThat(protocol.getId(), equalTo(null)); assertThat(parameters.isEmpty(), is(true)); } @Test void testHost() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setHost("host"); Map<String, String> parameters = new HashMap<String, String>(); ProtocolConfig.appendParameters(parameters, protocol); assertThat(protocol.getHost(), equalTo("host")); assertThat(parameters.isEmpty(), is(true)); } @Test void testPort() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); int port = NetUtils.getAvailablePort(); protocol.setPort(port); Map<String, String> parameters = new HashMap<String, String>(); ProtocolConfig.appendParameters(parameters, protocol); assertThat(protocol.getPort(), equalTo(port)); assertThat(parameters.isEmpty(), is(true)); } @Test void testPath() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setContextpath("context-path"); Map<String, String> parameters = new HashMap<String, String>(); ProtocolConfig.appendParameters(parameters, protocol); assertThat(protocol.getPath(), equalTo("context-path")); assertThat(protocol.getContextpath(), equalTo("context-path")); assertThat(parameters.isEmpty(), is(true)); protocol.setPath("path"); assertThat(protocol.getPath(), equalTo("path")); assertThat(protocol.getContextpath(), equalTo("path")); } @Test void testCorethreads() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setCorethreads(10); assertThat(protocol.getCorethreads(), is(10)); } @Test void testThreads() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setThreads(10); assertThat(protocol.getThreads(), is(10)); } @Test void testIothreads() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setIothreads(10); assertThat(protocol.getIothreads(), is(10)); } @Test void testQueues() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setQueues(10); assertThat(protocol.getQueues(), is(10)); } @Test void testAccepts() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setAccepts(10); assertThat(protocol.getAccepts(), is(10)); } @Test void testCodec() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setName("dubbo"); protocol.setCodec("mockcodec"); assertThat(protocol.getCodec(), equalTo("mockcodec")); } @Test void testAccesslog() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setAccesslog("access.log"); assertThat(protocol.getAccesslog(), equalTo("access.log")); } @Test void testTelnet() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setTelnet("mocktelnethandler"); assertThat(protocol.getTelnet(), equalTo("mocktelnethandler")); } @Test void testRegister() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setRegister(true); assertThat(protocol.isRegister(), is(true)); } @Test void testTransporter() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setTransporter("mocktransporter"); assertThat(protocol.getTransporter(), equalTo("mocktransporter")); } @Test void testExchanger() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setExchanger("mockexchanger"); assertThat(protocol.getExchanger(), equalTo("mockexchanger")); } @Test void testDispatcher() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setDispatcher("mockdispatcher"); assertThat(protocol.getDispatcher(), equalTo("mockdispatcher")); } @Test void testNetworker() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setNetworker("networker"); assertThat(protocol.getNetworker(), equalTo("networker")); } @Test void testParameters() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setParameters(Collections.singletonMap("k1", "v1")); assertThat(protocol.getParameters(), hasEntry("k1", "v1")); } @Test void testDefault() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setDefault(true); assertThat(protocol.isDefault(), is(true)); } @Test void testKeepAlive() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setKeepAlive(true); assertThat(protocol.getKeepAlive(), is(true)); } @Test void testOptimizer() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setOptimizer("optimizer"); assertThat(protocol.getOptimizer(), equalTo("optimizer")); } @Test void testExtension() throws Exception { ProtocolConfig protocol = new ProtocolConfig(); protocol.setExtension("extension"); assertThat(protocol.getExtension(), equalTo("extension")); } @Test void testMetaData() { ProtocolConfig config = new ProtocolConfig(); Map<String, String> metaData = config.getMetaData(); Assertions.assertEquals(0, metaData.size(), "actual: " + metaData); } @Test void testOverrideEmptyConfig() { int port = NetUtils.getAvailablePort(); // dubbo.protocol.name=rest // dubbo.protocol.port=port SysProps.setProperty("dubbo.protocol.name", "rest"); SysProps.setProperty("dubbo.protocol.port", String.valueOf(port)); try { ProtocolConfig protocolConfig = new ProtocolConfig(); DubboBootstrap.getInstance() .application("test-app") .protocol(protocolConfig) .initialize(); Assertions.assertEquals("rest", protocolConfig.getName()); Assertions.assertEquals(port, protocolConfig.getPort()); } finally { DubboBootstrap.getInstance().stop(); } } @Test void testOverrideConfigByName() { int port = NetUtils.getAvailablePort(); SysProps.setProperty("dubbo.protocols.rest.port", String.valueOf(port)); try { ProtocolConfig protocolConfig = new ProtocolConfig(); protocolConfig.setName("rest"); DubboBootstrap.getInstance() .application("test-app") .protocol(protocolConfig) .initialize(); Assertions.assertEquals("rest", protocolConfig.getName()); Assertions.assertEquals(port, protocolConfig.getPort()); } finally { DubboBootstrap.getInstance().stop(); } } @Test void testOverrideConfigById() { int port = NetUtils.getAvailablePort(); SysProps.setProperty("dubbo.protocols.rest1.name", "rest"); SysProps.setProperty("dubbo.protocols.rest1.port", String.valueOf(port)); try { ProtocolConfig protocolConfig = new ProtocolConfig(); protocolConfig.setName("xxx"); protocolConfig.setId("rest1"); DubboBootstrap.getInstance() .application("test-app") .protocol(protocolConfig) .initialize(); Assertions.assertEquals("rest", protocolConfig.getName()); Assertions.assertEquals(port, protocolConfig.getPort()); } finally { DubboBootstrap.getInstance().stop(); } } @Test void testCreateConfigFromPropsWithId() { int port1 = NetUtils.getAvailablePort(); int port2 = NetUtils.getAvailablePort(); SysProps.setProperty("dubbo.protocols.rest1.name", "rest"); SysProps.setProperty("dubbo.protocols.rest1.port", String.valueOf(port1)); SysProps.setProperty("dubbo.protocol.name", "dubbo"); // ignore SysProps.setProperty("dubbo.protocol.port", String.valueOf(port2)); try { DubboBootstrap bootstrap = DubboBootstrap.getInstance(); bootstrap.application("test-app").initialize(); ConfigManager configManager = bootstrap.getConfigManager(); Collection<ProtocolConfig> protocols = configManager.getProtocols(); Assertions.assertEquals(1, protocols.size()); ProtocolConfig protocol = configManager.getProtocol("rest1").get(); Assertions.assertEquals("rest", protocol.getName()); Assertions.assertEquals(port1, protocol.getPort()); } finally { DubboBootstrap.getInstance().stop(); } } @Test void testCreateConfigFromPropsWithName() { int port1 = NetUtils.getAvailablePort(); int port2 = NetUtils.getAvailablePort(); SysProps.setProperty("dubbo.protocols.rest.port", String.valueOf(port1)); SysProps.setProperty("dubbo.protocol.name", "dubbo"); // ignore SysProps.setProperty("dubbo.protocol.port", String.valueOf(port2)); try { DubboBootstrap bootstrap = DubboBootstrap.getInstance(); bootstrap.application("test-app").initialize(); ConfigManager configManager = bootstrap.getConfigManager(); Collection<ProtocolConfig> protocols = configManager.getProtocols(); Assertions.assertEquals(1, protocols.size()); ProtocolConfig protocol = configManager.getProtocol("rest").get(); Assertions.assertEquals("rest", protocol.getName()); Assertions.assertEquals(port1, protocol.getPort()); } finally { DubboBootstrap.getInstance().stop(); } } @Test void testCreateDefaultConfigFromProps() { int port = NetUtils.getAvailablePort(); SysProps.setProperty("dubbo.protocol.name", "rest"); SysProps.setProperty("dubbo.protocol.port", String.valueOf(port)); String protocolId = "rest-protocol"; SysProps.setProperty("dubbo.protocol.id", protocolId); // Allow override config id from props try { DubboBootstrap bootstrap = DubboBootstrap.getInstance(); bootstrap.application("test-app").initialize(); ConfigManager configManager = bootstrap.getConfigManager(); Collection<ProtocolConfig> protocols = configManager.getProtocols(); Assertions.assertEquals(1, protocols.size()); ProtocolConfig protocol = configManager.getProtocol("rest").get(); Assertions.assertEquals("rest", protocol.getName()); Assertions.assertEquals(port, protocol.getPort()); Assertions.assertEquals(protocolId, protocol.getId()); } finally { DubboBootstrap.getInstance().stop(); } } @Test void testPreferSerializationDefault1() throws Exception { ProtocolConfig protocolConfig = new ProtocolConfig(); assertNull(protocolConfig.getPreferSerialization()); protocolConfig.checkDefault(); assertThat(protocolConfig.getPreferSerialization(), equalTo(DEFAULT_PREFER_SERIALIZATION)); protocolConfig = new ProtocolConfig(); protocolConfig.setSerialization("x-serialization"); assertNull(protocolConfig.getPreferSerialization()); protocolConfig.checkDefault(); assertThat(protocolConfig.getPreferSerialization(), equalTo("x-serialization")); } @Test void testPreferSerializationDefault2() throws Exception { ProtocolConfig protocolConfig = new ProtocolConfig(); assertNull(protocolConfig.getPreferSerialization()); protocolConfig.refresh(); assertThat(protocolConfig.getPreferSerialization(), equalTo(DEFAULT_PREFER_SERIALIZATION)); protocolConfig = new ProtocolConfig(); protocolConfig.setSerialization("x-serialization"); assertNull(protocolConfig.getPreferSerialization()); protocolConfig.refresh(); assertThat(protocolConfig.getPreferSerialization(), equalTo("x-serialization")); } }
8,426
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ModuleConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.hamcrest.Matchers; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.sameInstance; class ModuleConfigTest { @Test void testName2() throws Exception { ModuleConfig module = new ModuleConfig(); module.setName("module-name"); assertThat(module.getName(), equalTo("module-name")); assertThat(module.getId(), equalTo(null)); Map<String, String> parameters = new HashMap<String, String>(); ModuleConfig.appendParameters(parameters, module); assertThat(parameters, hasEntry("module", "module-name")); } @Test void testVersion() throws Exception { ModuleConfig module = new ModuleConfig(); module.setName("module-name"); module.setVersion("1.0.0"); assertThat(module.getVersion(), equalTo("1.0.0")); Map<String, String> parameters = new HashMap<String, String>(); ModuleConfig.appendParameters(parameters, module); assertThat(parameters, hasEntry("module.version", "1.0.0")); } @Test void testOwner() throws Exception { ModuleConfig module = new ModuleConfig(); module.setOwner("owner"); assertThat(module.getOwner(), equalTo("owner")); } @Test void testOrganization() throws Exception { ModuleConfig module = new ModuleConfig(); module.setOrganization("org"); assertThat(module.getOrganization(), equalTo("org")); } @Test void testRegistry() throws Exception { ModuleConfig module = new ModuleConfig(); RegistryConfig registry = new RegistryConfig(); module.setRegistry(registry); assertThat(module.getRegistry(), sameInstance(registry)); } @Test void testRegistries() throws Exception { ModuleConfig module = new ModuleConfig(); RegistryConfig registry = new RegistryConfig(); module.setRegistries(Collections.singletonList(registry)); assertThat(module.getRegistries(), Matchers.<RegistryConfig>hasSize(1)); assertThat(module.getRegistries(), contains(registry)); } @Test void testMonitor() throws Exception { ModuleConfig module = new ModuleConfig(); module.setMonitor("monitor-addr1"); assertThat(module.getMonitor().getAddress(), equalTo("monitor-addr1")); module.setMonitor(new MonitorConfig("monitor-addr2")); assertThat(module.getMonitor().getAddress(), equalTo("monitor-addr2")); } @Test void testDefault() throws Exception { ModuleConfig module = new ModuleConfig(); module.setDefault(true); assertThat(module.isDefault(), is(true)); } @Test void testMetaData() { MonitorConfig config = new MonitorConfig(); Map<String, String> metaData = config.getMetaData(); Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } }
8,427
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ServiceConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.api.Greeting; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.mock.MockProtocol2; import org.apache.dubbo.config.mock.MockRegistryFactory2; import org.apache.dubbo.config.mock.MockServiceListener; import org.apache.dubbo.config.mock.TestProxyFactory; import org.apache.dubbo.config.provider.impl.DemoServiceImpl; import org.apache.dubbo.metadata.MappingListener; import org.apache.dubbo.metadata.ServiceNameMapping; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Protocol; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.service.GenericService; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.collect.Lists; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_KEY; import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_DEFAULT; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY; import static org.apache.dubbo.common.constants.CommonConstants.METHODS_KEY; import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY; import static org.apache.dubbo.config.Constants.SHUTDOWN_TIMEOUT_KEY; import static org.apache.dubbo.remoting.Constants.BIND_IP_KEY; import static org.apache.dubbo.remoting.Constants.BIND_PORT_KEY; import static org.apache.dubbo.rpc.Constants.GENERIC_KEY; import static org.apache.dubbo.rpc.cluster.Constants.EXPORT_KEY; import static org.awaitility.Awaitility.await; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.hasSize; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.withSettings; class ServiceConfigTest { private Protocol protocolDelegate = Mockito.mock(Protocol.class); private Registry registryDelegate = Mockito.mock(Registry.class); private Exporter exporter = Mockito.mock(Exporter.class); private ServiceConfig<DemoServiceImpl> service; private ServiceConfig<DemoServiceImpl> service2; private ServiceConfig<DemoServiceImpl> serviceWithoutRegistryConfig; private ServiceConfig<DemoServiceImpl> delayService; @BeforeEach public void setUp() throws Exception { DubboBootstrap.reset(); service = new ServiceConfig<>(); service2 = new ServiceConfig<>(); serviceWithoutRegistryConfig = new ServiceConfig<>(); delayService = new ServiceConfig<>(); MockProtocol2.delegate = protocolDelegate; MockRegistryFactory2.registry = registryDelegate; Mockito.when(protocolDelegate.export(Mockito.any(Invoker.class))).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.class); service.setRef(new DemoServiceImpl()); service.setMethods(Collections.singletonList(method)); service.setGroup("demo1"); service2.setProvider(provider); service2.setApplication(app); service2.setRegistry(registry); service2.setInterface(DemoService.class); service2.setRef(new DemoServiceImpl()); service2.setMethods(Collections.singletonList(method)); service2.setProxy("testproxyfactory"); service2.setGroup("demo2"); delayService.setProvider(provider); delayService.setApplication(app); delayService.setRegistry(registry); delayService.setInterface(DemoService.class); delayService.setRef(new DemoServiceImpl()); delayService.setMethods(Collections.singletonList(method)); delayService.setDelay(100); delayService.setGroup("demo3"); serviceWithoutRegistryConfig.setProvider(provider); serviceWithoutRegistryConfig.setApplication(app); serviceWithoutRegistryConfig.setInterface(DemoService.class); serviceWithoutRegistryConfig.setRef(new DemoServiceImpl()); serviceWithoutRegistryConfig.setMethods(Collections.singletonList(method)); serviceWithoutRegistryConfig.setGroup("demo4"); } @AfterEach public void tearDown() {} @Test void testExport() throws Exception { service.export(); assertThat(service.getExportedUrls(), hasSize(1)); URL url = service.toUrl(); assertThat(url.getProtocol(), equalTo("mockprotocol2")); assertThat(url.getPath(), equalTo(DemoService.class.getName())); assertThat(url.getParameters(), hasEntry(ANYHOST_KEY, "true")); assertThat(url.getParameters(), hasEntry(APPLICATION_KEY, "app")); assertThat(url.getParameters(), hasKey(BIND_IP_KEY)); assertThat(url.getParameters(), hasKey(BIND_PORT_KEY)); assertThat(url.getParameters(), hasEntry(EXPORT_KEY, "true")); assertThat(url.getParameters(), hasEntry("echo.0.callback", "false")); assertThat(url.getParameters(), hasEntry(GENERIC_KEY, "false")); assertThat(url.getParameters(), hasEntry(INTERFACE_KEY, DemoService.class.getName())); assertThat(url.getParameters(), hasKey(METHODS_KEY)); assertThat(url.getParameters().get(METHODS_KEY), containsString("echo")); assertThat(url.getParameters(), hasEntry(SIDE_KEY, PROVIDER)); // export MetadataService and DemoService in "mockprotocol2" protocol. Mockito.verify(protocolDelegate, times(2)).export(Mockito.any(Invoker.class)); } @Test void testVersionAndGroupConfigFromProvider() { // Service no configuration version , the Provider configured. service.getProvider().setVersion("1.0.0"); service.getProvider().setGroup("groupA"); service.export(); String serviceVersion = service.getVersion(); String serviceVersion2 = service.toUrl().getVersion(); String group = service.getGroup(); String group2 = service.toUrl().getGroup(); assertEquals(serviceVersion2, serviceVersion); assertEquals(group, group2); } @Test void testProxy() throws Exception { service2.export(); assertThat(service2.getExportedUrls(), hasSize(1)); assertEquals(2, TestProxyFactory.count); // local injvm and registry protocol, so expected is 2 TestProxyFactory.count = 0; } @Test void testDelayExport() throws Exception { CountDownLatch latch = new CountDownLatch(1); delayService.addServiceListener(new ServiceListener() { @Override public void exported(ServiceConfig sc) { assertEquals(delayService, sc); assertThat(delayService.getExportedUrls(), hasSize(1)); latch.countDown(); } @Override public void unexported(ServiceConfig sc) {} }); delayService.export(); assertTrue(delayService.getExportedUrls().isEmpty()); latch.await(); } @Test 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 void testInterfaceClass() throws Exception { ServiceConfig<Greeting> service = new ServiceConfig<>(); service.setInterface(Greeting.class.getName()); service.setRef(Mockito.mock(Greeting.class)); assertThat(service.getInterfaceClass() == Greeting.class, is(true)); service = new ServiceConfig<>(); service.setRef(Mockito.mock(Greeting.class, withSettings().extraInterfaces(GenericService.class))); assertThat(service.getInterfaceClass() == GenericService.class, is(true)); } @Test void testInterface1() throws Exception { Assertions.assertThrows(IllegalStateException.class, () -> { ServiceConfig<DemoService> service = new ServiceConfig<>(); service.setInterface(DemoServiceImpl.class); }); } @Test void testInterface2() throws Exception { ServiceConfig<DemoService> service = new ServiceConfig<>(); service.setInterface(DemoService.class); assertThat(service.getInterface(), equalTo(DemoService.class.getName())); } @Test void testProvider() throws Exception { ServiceConfig service = new ServiceConfig(); ProviderConfig provider = new ProviderConfig(); service.setProvider(provider); assertThat(service.getProvider(), is(provider)); } @Test void testGeneric1() throws Exception { ServiceConfig service = new ServiceConfig(); service.setGeneric(GENERIC_SERIALIZATION_DEFAULT); assertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_DEFAULT)); service.setGeneric(GENERIC_SERIALIZATION_NATIVE_JAVA); assertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_NATIVE_JAVA)); service.setGeneric(GENERIC_SERIALIZATION_BEAN); assertThat(service.getGeneric(), equalTo(GENERIC_SERIALIZATION_BEAN)); } @Test void testGeneric2() throws Exception { Assertions.assertThrows(IllegalArgumentException.class, () -> { ServiceConfig service = new ServiceConfig(); service.setGeneric("illegal"); }); } @Test void testApplicationInUrl() { service.export(); assertNotNull(service.toUrl().getApplication()); Assertions.assertEquals("app", service.toUrl().getApplication()); } @Test void testMetaData() { // test new instance ServiceConfig config = new ServiceConfig(); Map<String, String> metaData = config.getMetaData(); Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); // test merged and override provider attributes ProviderConfig providerConfig = new ProviderConfig(); providerConfig.setAsync(true); providerConfig.setActives(10); config.setProvider(providerConfig); config.setAsync(false); // override metaData = config.getMetaData(); Assertions.assertEquals(2, metaData.size()); Assertions.assertEquals("" + providerConfig.getActives(), metaData.get("actives")); Assertions.assertEquals("" + config.isAsync(), metaData.get("async")); } @Test void testExportWithoutRegistryConfig() { serviceWithoutRegistryConfig.export(); assertThat(serviceWithoutRegistryConfig.getExportedUrls(), hasSize(1)); URL url = serviceWithoutRegistryConfig.toUrl(); assertThat(url.getProtocol(), equalTo("mockprotocol2")); assertThat(url.getPath(), equalTo(DemoService.class.getName())); assertThat(url.getParameters(), hasEntry(ANYHOST_KEY, "true")); assertThat(url.getParameters(), hasEntry(APPLICATION_KEY, "app")); assertThat(url.getParameters(), hasKey(BIND_IP_KEY)); assertThat(url.getParameters(), hasKey(BIND_PORT_KEY)); assertThat(url.getParameters(), hasEntry(EXPORT_KEY, "true")); assertThat(url.getParameters(), hasEntry("echo.0.callback", "false")); assertThat(url.getParameters(), hasEntry(GENERIC_KEY, "false")); assertThat(url.getParameters(), hasEntry(INTERFACE_KEY, DemoService.class.getName())); assertThat(url.getParameters(), hasKey(METHODS_KEY)); assertThat(url.getParameters().get(METHODS_KEY), containsString("echo")); assertThat(url.getParameters(), hasEntry(SIDE_KEY, PROVIDER)); // export MetadataService and DemoService in "mockprotocol2" protocol. Mockito.verify(protocolDelegate, times(2)).export(Mockito.any(Invoker.class)); } @Test void testServiceListener() { ExtensionLoader<ServiceListener> extensionLoader = ExtensionLoader.getExtensionLoader(ServiceListener.class); MockServiceListener mockServiceListener = (MockServiceListener) extensionLoader.getExtension("mock"); assertNotNull(mockServiceListener); mockServiceListener.clearExportedServices(); service.export(); Map<String, ServiceConfig> exportedServices = mockServiceListener.getExportedServices(); assertEquals(1, exportedServices.size()); ServiceConfig serviceConfig = exportedServices.get(service.getUniqueServiceName()); assertSame(service, serviceConfig); } @Test void testMethodConfigWithInvalidArgumentConfig() { Assertions.assertThrows(IllegalArgumentException.class, () -> { ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); service.setProtocol(new ProtocolConfig() { { setName("dubbo"); } }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { { // unset config. } })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); }); } @Test void testMethodConfigWithConfiguredArgumentTypeAndIndex() { ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); service.setProtocol(new ProtocolConfig() { { setName("dubbo"); } }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { { setType(String.class.getName()); setIndex(0); setCallback(false); } })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); assertFalse(service.getExportedUrls().isEmpty()); assertEquals("false", service.getExportedUrls().get(0).getParameters().get("sayName.0.callback")); } @Test void testMethodConfigWithConfiguredArgumentIndex() { ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); service.setProtocol(new ProtocolConfig() { { setName("dubbo"); } }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { { setIndex(0); setCallback(false); } })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); assertFalse(service.getExportedUrls().isEmpty()); assertEquals("false", service.getExportedUrls().get(0).getParameters().get("sayName.0.callback")); } @Test void testMethodConfigWithConfiguredArgumentType() { ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); service.setProtocol(new ProtocolConfig() { { setName("dubbo"); } }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { { setType(String.class.getName()); setCallback(false); } })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); assertFalse(service.getExportedUrls().isEmpty()); assertEquals("false", service.getExportedUrls().get(0).getParameters().get("sayName.0.callback")); } @Test void testMethodConfigWithUnknownArgumentType() { Assertions.assertThrows(IllegalArgumentException.class, () -> { ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); service.setProtocol(new ProtocolConfig() { { setName("dubbo"); } }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { { setType(Integer.class.getName()); setCallback(false); } })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); }); } @Test void testMethodConfigWithUnmatchedArgument() { Assertions.assertThrows(IllegalArgumentException.class, () -> { ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); service.setProtocol(new ProtocolConfig() { { setName("dubbo"); } }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { { setType(Integer.class.getName()); setIndex(0); } })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); }); } @Test void testMethodConfigWithInvalidArgumentIndex() { Assertions.assertThrows(IllegalArgumentException.class, () -> { ServiceConfig<DemoServiceImpl> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); service.setProtocol(new ProtocolConfig() { { setName("dubbo"); } }); MethodConfig methodConfig = new MethodConfig(); methodConfig.setName("sayName"); // invalid argument index. methodConfig.setArguments(Lists.newArrayList(new ArgumentConfig() { { setType(String.class.getName()); setIndex(1); } })); service.setMethods(Lists.newArrayList(methodConfig)); service.export(); }); } @Test void testOverride() { System.setProperty("dubbo.service.version", "TEST"); ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(DemoService.class); serviceConfig.setRef(new DemoServiceImpl()); serviceConfig.setVersion("1.0.0"); serviceConfig.refresh(); Assertions.assertEquals("1.0.0", serviceConfig.getVersion()); System.clearProperty("dubbo.service.version"); } @Test void testMappingRetry() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(applicationModel.newModule()); serviceConfig.exported(); ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); AtomicInteger count = new AtomicInteger(0); ServiceNameMapping serviceNameMapping = new ServiceNameMapping() { @Override public boolean map(URL url) { if (count.incrementAndGet() < 5) { throw new RuntimeException(); } return count.get() > 10; } @Override public boolean hasValidMetadataCenter() { return true; } @Override public Set<String> getMapping(URL consumerURL) { return null; } @Override public Set<String> getAndListen(URL registryURL, URL subscribedURL, MappingListener listener) { return null; } @Override public MappingListener stopListen(URL subscribeURL, MappingListener listener) { return null; } @Override public void putCachedMapping(String serviceKey, Set<String> apps) {} @Override public Set<String> getRemoteMapping(URL consumerURL) { return null; } @Override public Set<String> removeCachedMapping(String serviceKey) { return null; } @Override public void $destroy() {} }; ApplicationConfig applicationConfig = new ApplicationConfig("app"); applicationConfig.setMappingRetryInterval(10); serviceConfig.setApplication(applicationConfig); serviceConfig.mapServiceName(URL.valueOf(""), serviceNameMapping, scheduledExecutorService); await().until(() -> count.get() > 10); scheduledExecutorService.shutdown(); } @Test void testMappingNoRetry() { FrameworkModel frameworkModel = new FrameworkModel(); ApplicationModel applicationModel = frameworkModel.newApplication(); ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(applicationModel.newModule()); serviceConfig.exported(); ScheduledExecutorService scheduledExecutorService = Mockito.spy(Executors.newScheduledThreadPool(1)); AtomicInteger count = new AtomicInteger(0); ServiceNameMapping serviceNameMapping = new ServiceNameMapping() { @Override public boolean map(URL url) { return false; } @Override public boolean hasValidMetadataCenter() { return false; } @Override public Set<String> getAndListen(URL registryURL, URL subscribedURL, MappingListener listener) { return null; } @Override public MappingListener stopListen(URL subscribeURL, MappingListener listener) { return null; } @Override public void putCachedMapping(String serviceKey, Set<String> apps) {} @Override public Set<String> getMapping(URL consumerURL) { return null; } @Override public Set<String> getRemoteMapping(URL consumerURL) { return null; } @Override public Set<String> removeCachedMapping(String serviceKey) { return null; } @Override public void $destroy() {} }; ApplicationConfig applicationConfig = new ApplicationConfig("app"); applicationConfig.setMappingRetryInterval(10); serviceConfig.setApplication(applicationConfig); serviceConfig.mapServiceName(URL.valueOf(""), serviceNameMapping, scheduledExecutorService); verify(scheduledExecutorService, times(0)).schedule((Runnable) any(), anyLong(), any()); scheduledExecutorService.shutdown(); } @Test void testToString() { ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(); service.setRef(new DemoServiceImpl() { @Override public String toString() { throw new IllegalStateException(); } }); try { serviceConfig.toString(); } catch (Throwable t) { Assertions.fail(t); } } }
8,428
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/ProviderConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; class ProviderConfigTest { @Test void testProtocol() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setProtocol("protocol"); assertThat(provider.getProtocol().getName(), equalTo("protocol")); } @Test void testDefault() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setDefault(true); Map<String, String> parameters = new HashMap<String, String>(); ProviderConfig.appendParameters(parameters, provider); assertThat(provider.isDefault(), is(true)); assertThat(parameters, not(hasKey("default"))); } @Test void testHost() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setHost("demo-host"); Map<String, String> parameters = new HashMap<String, String>(); ProviderConfig.appendParameters(parameters, provider); assertThat(provider.getHost(), equalTo("demo-host")); assertThat(parameters, not(hasKey("host"))); } @Test void testPort() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setPort(8080); Map<String, String> parameters = new HashMap<String, String>(); ProviderConfig.appendParameters(parameters, provider); assertThat(provider.getPort(), is(8080)); assertThat(parameters, not(hasKey("port"))); } @Test void testPath() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setPath("/path"); Map<String, String> parameters = new HashMap<String, String>(); ProviderConfig.appendParameters(parameters, provider); assertThat(provider.getPath(), equalTo("/path")); assertThat(provider.getContextpath(), equalTo("/path")); assertThat(parameters, not(hasKey("path"))); } @Test void testContextPath() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setContextpath("/context-path"); Map<String, String> parameters = new HashMap<String, String>(); ProviderConfig.appendParameters(parameters, provider); assertThat(provider.getContextpath(), equalTo("/context-path")); assertThat(parameters, not(hasKey("/context-path"))); } @Test void testThreadpool() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setThreadpool("mockthreadpool"); assertThat(provider.getThreadpool(), equalTo("mockthreadpool")); } @Test void testThreads() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setThreads(10); assertThat(provider.getThreads(), is(10)); } @Test void testIothreads() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setIothreads(10); assertThat(provider.getIothreads(), is(10)); } @Test void testQueues() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setQueues(10); assertThat(provider.getQueues(), is(10)); } @Test void testAccepts() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setAccepts(10); assertThat(provider.getAccepts(), is(10)); } @Test void testCharset() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setCharset("utf-8"); assertThat(provider.getCharset(), equalTo("utf-8")); } @Test void testPayload() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setPayload(10); assertThat(provider.getPayload(), is(10)); } @Test void testBuffer() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setBuffer(10); assertThat(provider.getBuffer(), is(10)); } @Test void testServer() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setServer("demo-server"); assertThat(provider.getServer(), equalTo("demo-server")); } @Test void testClient() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setClient("client"); assertThat(provider.getClient(), equalTo("client")); } @Test void testTelnet() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setTelnet("mocktelnethandler"); assertThat(provider.getTelnet(), equalTo("mocktelnethandler")); } @Test void testPrompt() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setPrompt("#"); Map<String, String> parameters = new HashMap<String, String>(); ProviderConfig.appendParameters(parameters, provider); assertThat(provider.getPrompt(), equalTo("#")); assertThat(parameters, hasEntry("prompt", "%23")); } @Test void testStatus() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setStatus("mockstatuschecker"); assertThat(provider.getStatus(), equalTo("mockstatuschecker")); } @Test void testTransporter() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setTransporter("mocktransporter"); assertThat(provider.getTransporter(), equalTo("mocktransporter")); } @Test void testExchanger() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setExchanger("mockexchanger"); assertThat(provider.getExchanger(), equalTo("mockexchanger")); } @Test void testDispatcher() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setDispatcher("mockdispatcher"); assertThat(provider.getDispatcher(), equalTo("mockdispatcher")); } @Test void testNetworker() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setNetworker("networker"); assertThat(provider.getNetworker(), equalTo("networker")); } @Test void testWait() throws Exception { ProviderConfig provider = new ProviderConfig(); provider.setWait(10); assertThat(provider.getWait(), equalTo(10)); } @Test void testMetaData() { ProviderConfig config = new ProviderConfig(); Map<String, String> metaData = config.getMetaData(); Assertions.assertEquals(0, metaData.size(), "Expect empty metadata but found: " + metaData); } }
8,429
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/AbstractMethodConfigTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.isEmptyOrNullString; import static org.hamcrest.Matchers.sameInstance; class AbstractMethodConfigTest { @AfterAll public static void afterAll() { DubboBootstrap.reset(); } @Test void testTimeout() { MethodConfig methodConfig = new MethodConfig(); methodConfig.setTimeout(10); assertThat(methodConfig.getTimeout(), equalTo(10)); } @Test void testForks() { MethodConfig methodConfig = new MethodConfig(); methodConfig.setForks(10); assertThat(methodConfig.getForks(), equalTo(10)); } @Test void testRetries() { MethodConfig methodConfig = new MethodConfig(); methodConfig.setRetries(3); assertThat(methodConfig.getRetries(), equalTo(3)); } @Test void testLoadbalance() { MethodConfig methodConfig = new MethodConfig(); methodConfig.setLoadbalance("mockloadbalance"); assertThat(methodConfig.getLoadbalance(), equalTo("mockloadbalance")); } @Test void testAsync() { MethodConfig methodConfig = new MethodConfig(); methodConfig.setAsync(true); assertThat(methodConfig.isAsync(), is(true)); } @Test void testActives() { MethodConfig methodConfig = new MethodConfig(); methodConfig.setActives(10); assertThat(methodConfig.getActives(), equalTo(10)); } @Test void testSent() { MethodConfig methodConfig = new MethodConfig(); methodConfig.setSent(true); assertThat(methodConfig.getSent(), is(true)); } @Test void testMock() { MethodConfig methodConfig = new MethodConfig(); methodConfig.setMock((Boolean) null); assertThat(methodConfig.getMock(), isEmptyOrNullString()); methodConfig.setMock(true); assertThat(methodConfig.getMock(), equalTo("true")); methodConfig.setMock("return null"); assertThat(methodConfig.getMock(), equalTo("return null")); methodConfig.setMock("mock"); assertThat(methodConfig.getMock(), equalTo("mock")); } @Test void testMerger() { MethodConfig methodConfig = new MethodConfig(); methodConfig.setMerger("merger"); assertThat(methodConfig.getMerger(), equalTo("merger")); } @Test void testCache() { MethodConfig methodConfig = new MethodConfig(); methodConfig.setCache("cache"); assertThat(methodConfig.getCache(), equalTo("cache")); } @Test void testValidation() { MethodConfig methodConfig = new MethodConfig(); methodConfig.setValidation("validation"); assertThat(methodConfig.getValidation(), equalTo("validation")); } @Test void testParameters() throws Exception { MethodConfig methodConfig = new MethodConfig(); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("key", "value"); methodConfig.setParameters(parameters); assertThat(methodConfig.getParameters(), sameInstance(parameters)); } private static class MethodConfig extends AbstractMethodConfig {} }
8,430
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceConsumerBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.bootstrap.rest.UserService; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; /** * Dubbo Provider Bootstrap * * @since 2.7.5 */ public class DubboServiceConsumerBootstrap { public static void main(String[] args) throws Exception { DubboBootstrap bootstrap = DubboBootstrap.getInstance() .application("dubbo-consumer-demo") .protocol(builder -> builder.port(20887).name("dubbo")) // Eureka // .registry(builder -> // builder.address("eureka://127.0.0.1:8761?registry-type=service&subscribed-services=dubbo-provider-demo")) // Zookeeper .registry( "zookeeper", builder -> builder.address(ZookeeperRegistryCenterConfig.getConnectionAddress() + "?registry-type=service&subscribed-services=dubbo-provider-demo")) .metadataReport(new MetadataReportConfig(ZookeeperRegistryCenterConfig.getConnectionAddress())) // Nacos // .registry("nacos", builder -> // builder.address("nacos://127.0.0.1:8848?registry.type=service&subscribed.services=dubbo-provider-demo")) // Consul // .registry("consul", builder -> // builder.address("consul://127.0.0.1:8500?registry.type=service&subscribed.services=dubbo-provider-demo").group("namespace1")) .reference("echo", builder -> builder.interfaceClass(EchoService.class) .protocol("dubbo")) .reference("user", builder -> builder.interfaceClass(UserService.class) .protocol("rest")) .start(); EchoService echoService = bootstrap.getCache().get(EchoService.class); for (int i = 0; i < 500; i++) { Thread.sleep(2000L); System.out.println(echoService.echo("Hello,World")); } } }
8,431
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboBootstrapTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.deploy.ApplicationDeployListener; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.ReflectUtils; import org.apache.dubbo.config.AbstractInterfaceConfig; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.SysProps; import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.deploy.DefaultApplicationDeployer; import org.apache.dubbo.config.metadata.ConfigurableMetadataServiceExporter; import org.apache.dubbo.config.metadata.ExporterDeployListener; import org.apache.dubbo.config.provider.impl.DemoServiceImpl; import org.apache.dubbo.config.utils.ConfigValidationUtils; import org.apache.dubbo.metadata.MetadataService; import org.apache.dubbo.monitor.MonitorService; import org.apache.dubbo.registry.RegistryService; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.file.Path; import java.util.List; import java.util.Map; import java.util.Properties; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_MONITOR_ADDRESS; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_KEY; import static org.apache.dubbo.common.constants.CommonConstants.SHUTDOWN_WAIT_SECONDS_KEY; import static org.hamcrest.CoreMatchers.anything; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.is; /** * {@link DubboBootstrap} Test * * @since 2.7.5 */ class DubboBootstrapTest { private static File dubboProperties; private static String zkServerAddress; @BeforeAll public static void setUp(@TempDir Path folder) { DubboBootstrap.reset(); zkServerAddress = System.getProperty("zookeeper.connection.address.1"); dubboProperties = folder.resolve(CommonConstants.DUBBO_PROPERTIES_KEY).toFile(); System.setProperty(CommonConstants.DUBBO_PROPERTIES_KEY, dubboProperties.getAbsolutePath()); } @AfterAll public static void tearDown() { System.clearProperty(CommonConstants.DUBBO_PROPERTIES_KEY); } @AfterEach public void afterEach() throws IOException { DubboBootstrap.reset(); ApplicationModel.reset(); SysProps.clear(); } @Test void checkApplication() { SysProps.setProperty("dubbo.application.name", "demo"); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.refresh(); Assertions.assertEquals("demo", applicationConfig.getName()); } @Test void compatibleApplicationShutdown() { try { System.clearProperty(SHUTDOWN_WAIT_KEY); System.clearProperty(SHUTDOWN_WAIT_SECONDS_KEY); writeDubboProperties(SHUTDOWN_WAIT_KEY, "100"); ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .refresh(); ConfigValidationUtils.validateApplicationConfig(new ApplicationConfig("demo")); Assertions.assertEquals("100", System.getProperty(SHUTDOWN_WAIT_KEY)); System.clearProperty(SHUTDOWN_WAIT_KEY); writeDubboProperties(SHUTDOWN_WAIT_SECONDS_KEY, "1000"); ApplicationModel.defaultModel() .modelEnvironment() .getPropertiesConfiguration() .refresh(); ConfigValidationUtils.validateApplicationConfig(new ApplicationConfig("demo")); Assertions.assertEquals("1000", System.getProperty(SHUTDOWN_WAIT_SECONDS_KEY)); } finally { System.clearProperty("dubbo.application.name"); System.clearProperty(SHUTDOWN_WAIT_KEY); System.clearProperty(SHUTDOWN_WAIT_SECONDS_KEY); } } @Test void testLoadRegistries() { SysProps.setProperty("dubbo.registry.address", "addr1"); ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setInterface(DemoService.class); serviceConfig.setRef(new DemoServiceImpl()); serviceConfig.setApplication(new ApplicationConfig("testLoadRegistries")); // load configs from props DubboBootstrap.getInstance().initialize(); serviceConfig.refresh(); // ApplicationModel.defaultModel().getEnvironment().setDynamicConfiguration(new // CompositeDynamicConfiguration()); List<URL> urls = ConfigValidationUtils.loadRegistries(serviceConfig, true); Assertions.assertEquals(2, urls.size()); for (URL url : urls) { Assertions.assertTrue(url.getProtocol().contains("registry")); Assertions.assertEquals("addr1:9090", url.getAddress()); Assertions.assertEquals(RegistryService.class.getName(), url.getPath()); Assertions.assertTrue(url.getParameters().containsKey("timestamp")); Assertions.assertTrue(url.getParameters().containsKey("pid")); Assertions.assertTrue(url.getParameters().containsKey("registry")); Assertions.assertTrue(url.getParameters().containsKey("dubbo")); } } @Test void testLoadUserMonitor_address_only() { // -Ddubbo.monitor.address=monitor-addr:12080 SysProps.setProperty(DUBBO_MONITOR_ADDRESS, "monitor-addr:12080"); URL url = ConfigValidationUtils.loadMonitor( getTestInterfaceConfig(new MonitorConfig()), new ServiceConfigURL("dubbo", "addr1", 9090)); Assertions.assertEquals("monitor-addr:12080", url.getAddress()); Assertions.assertEquals(MonitorService.class.getName(), url.getParameter("interface")); Assertions.assertNotNull(url.getParameter("dubbo")); Assertions.assertNotNull(url.getParameter("pid")); Assertions.assertNotNull(url.getParameter("timestamp")); } @Test void testLoadUserMonitor_registry() { // dubbo.monitor.protocol=registry MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setProtocol("registry"); URL url = ConfigValidationUtils.loadMonitor( getTestInterfaceConfig(monitorConfig), URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); Assertions.assertEquals("dubbo", url.getProtocol()); Assertions.assertEquals("registry", url.getParameter("protocol")); } @Test void testLoadUserMonitor_service_discovery() { // dubbo.monitor.protocol=service-discovery-registry MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setProtocol("service-discovery-registry"); URL url = ConfigValidationUtils.loadMonitor( getTestInterfaceConfig(monitorConfig), URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); Assertions.assertEquals("dubbo", url.getProtocol()); Assertions.assertEquals("service-discovery-registry", url.getParameter("protocol")); } @Test void testLoadUserMonitor_no_monitor() { URL url = ConfigValidationUtils.loadMonitor( getTestInterfaceConfig(null), URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); Assertions.assertNull(url); } @Test void testLoadUserMonitor_user() { // dubbo.monitor.protocol=user MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setProtocol("user"); URL url = ConfigValidationUtils.loadMonitor( getTestInterfaceConfig(monitorConfig), URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); Assertions.assertEquals("user", url.getProtocol()); } @Test void testLoadUserMonitor_user_address() { // dubbo.monitor.address=user://1.2.3.4:5678?k=v MonitorConfig monitorConfig = new MonitorConfig(); monitorConfig.setAddress("user://1.2.3.4:5678?param1=value1"); URL url = ConfigValidationUtils.loadMonitor( getTestInterfaceConfig(monitorConfig), URL.valueOf(ZookeeperRegistryCenterConfig.getConnectionAddress())); Assertions.assertEquals("user", url.getProtocol()); Assertions.assertEquals("1.2.3.4:5678", url.getAddress()); Assertions.assertEquals("value1", url.getParameter("param1")); } private InterfaceConfig getTestInterfaceConfig(MonitorConfig monitorConfig) { InterfaceConfig interfaceConfig = new InterfaceConfig(); interfaceConfig.setApplication(new ApplicationConfig("testLoadMonitor")); if (monitorConfig != null) { interfaceConfig.setMonitor(monitorConfig); } return interfaceConfig; } @Test void testBootstrapStart() { ServiceConfig<DemoService> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); bootstrap .application(new ApplicationConfig("bootstrap-test")) .registry(new RegistryConfig(zkServerAddress)) .protocol(new ProtocolConfig(CommonConstants.DUBBO_PROTOCOL, -1)) .service(service) .start(); Assertions.assertTrue(bootstrap.isInitialized()); Assertions.assertTrue(bootstrap.isStarted()); Assertions.assertFalse(bootstrap.isStopped()); ApplicationModel applicationModel = bootstrap.getApplicationModel(); DefaultApplicationDeployer applicationDeployer = getApplicationDeployer(applicationModel); Assertions.assertNotNull(ReflectUtils.getFieldValue(applicationDeployer, "asyncMetadataFuture")); Assertions.assertTrue(applicationModel .getDefaultModule() .getServiceRepository() .getExportedServices() .size() > 0); } private DefaultApplicationDeployer getApplicationDeployer(ApplicationModel applicationModel) { return (DefaultApplicationDeployer) DefaultApplicationDeployer.get(applicationModel); } @Test void testLocalMetadataServiceExporter() { ServiceConfig<DemoService> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); int availablePort = NetUtils.getAvailablePort(); ApplicationConfig applicationConfig = new ApplicationConfig("bootstrap-test"); applicationConfig.setMetadataServicePort(availablePort); DubboBootstrap bootstrap = DubboBootstrap.getInstance(); bootstrap .application(applicationConfig) .registry(new RegistryConfig(zkServerAddress)) .protocol(new ProtocolConfig(CommonConstants.DUBBO_PROTOCOL, -1)) .service(service) .start(); assertMetadataService(bootstrap, availablePort, true); } @Test void testRemoteMetadataServiceExporter() { ServiceConfig<DemoService> service = new ServiceConfig<>(); service.setInterface(DemoService.class); service.setRef(new DemoServiceImpl()); int availablePort = NetUtils.getAvailablePort(); ApplicationConfig applicationConfig = new ApplicationConfig("bootstrap-test"); applicationConfig.setMetadataServicePort(availablePort); applicationConfig.setMetadataType(REMOTE_METADATA_STORAGE_TYPE); RegistryConfig registryConfig = new RegistryConfig(zkServerAddress); registryConfig.setUseAsMetadataCenter(false); registryConfig.setUseAsConfigCenter(false); Exception exception = null; try { DubboBootstrap.getInstance() .application(applicationConfig) .registry(registryConfig) .protocol(new ProtocolConfig(CommonConstants.DUBBO_PROTOCOL, -1)) .service(service) .start(); } catch (Exception e) { exception = e; DubboBootstrap.reset(); } Assertions.assertNotNull(exception); DubboBootstrap.getInstance() .application(applicationConfig) .registry(registryConfig) .protocol(new ProtocolConfig(CommonConstants.DUBBO_PROTOCOL, -1)) .service(service) .metadataReport(new MetadataReportConfig(zkServerAddress)) .start(); assertMetadataService(DubboBootstrap.getInstance(), availablePort, false); } private ExporterDeployListener getListener(ApplicationModel model) { return (ExporterDeployListener) model.getExtensionLoader(ApplicationDeployListener.class).getExtension("exporter"); } private void assertMetadataService(DubboBootstrap bootstrap, int availablePort, boolean metadataExported) { ExporterDeployListener listener = getListener(bootstrap.getApplicationModel()); ConfigurableMetadataServiceExporter metadataServiceExporter = listener.getMetadataServiceExporter(); Assertions.assertEquals(metadataExported, metadataServiceExporter.isExported()); DubboProtocol protocol = DubboProtocol.getDubboProtocol(bootstrap.getApplicationModel()); Map<String, Exporter<?>> exporters = protocol.getExporterMap(); if (metadataExported) { Assertions.assertEquals(2, exporters.size()); ServiceConfig<MetadataService> serviceConfig = new ServiceConfig<>(); serviceConfig.setRegistry(new RegistryConfig("N/A")); serviceConfig.setInterface(MetadataService.class); serviceConfig.setGroup( ApplicationModel.defaultModel().getCurrentConfig().getName()); serviceConfig.setVersion(MetadataService.VERSION); assertThat(exporters, hasEntry(is(serviceConfig.getUniqueServiceName() + ":" + availablePort), anything())); } else { Assertions.assertEquals(1, exporters.size()); } } private void writeDubboProperties(String key, String value) { OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(dubboProperties)); Properties properties = new Properties(); properties.put(key, value); properties.store(os, ""); os.close(); } catch (IOException e) { if (os != null) { try { os.close(); } catch (IOException ioe) { // ignore } } } } public static class InterfaceConfig extends AbstractInterfaceConfig {} }
8,432
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/MultiInstanceTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.common.deploy.ApplicationDeployer; import org.apache.dubbo.common.deploy.DeployListener; import org.apache.dubbo.common.deploy.DeployState; import org.apache.dubbo.common.deploy.ModuleDeployer; import org.apache.dubbo.common.logger.ErrorTypeAwareLogger; import org.apache.dubbo.common.logger.LoggerFactory; import org.apache.dubbo.common.utils.NetUtils; import org.apache.dubbo.common.utils.StringUtils; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.SysProps; import org.apache.dubbo.config.api.DemoService; import org.apache.dubbo.config.api.Greeting; import org.apache.dubbo.config.mock.GreetingLocal2; import org.apache.dubbo.config.provider.impl.DemoServiceImpl; import org.apache.dubbo.registry.client.migration.MigrationInvoker; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.rpc.model.FrameworkModel; import org.apache.dubbo.rpc.model.FrameworkServiceRepository; import org.apache.dubbo.rpc.model.ModuleModel; import org.apache.dubbo.rpc.model.ServiceDescriptor; import org.apache.dubbo.test.check.DubboTestChecker; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; import java.io.IOException; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import static org.apache.dubbo.remoting.Constants.EVENT_LOOP_BOSS_POOL_NAME; @Disabled class MultiInstanceTest { private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MultiInstanceTest.class); private RegistryConfig registryConfig; private static DubboTestChecker testChecker; private static String testClassName; @BeforeEach public void beforeAll() { FrameworkModel.destroyAll(); registryConfig = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1()); // pre-check threads // precheckUnclosedThreads(); } @AfterEach public void afterAll() throws Exception { FrameworkModel.destroyAll(); // check threads // checkUnclosedThreads(); } private static Map<Thread, StackTraceElement[]> precheckUnclosedThreads() throws IOException { // create a special DubboTestChecker if (testChecker == null) { testChecker = new DubboTestChecker(); testChecker.init(null); testClassName = MultiInstanceTest.class.getName(); } return testChecker.checkUnclosedThreads(testClassName, 0); } private static void checkUnclosedThreads() { Map<Thread, StackTraceElement[]> unclosedThreadMap = testChecker.checkUnclosedThreads(testClassName, 3000); if (unclosedThreadMap.size() > 0) { String str = getStackTraceString(unclosedThreadMap); Assertions.fail("Found unclosed threads: " + unclosedThreadMap.size() + "\n" + str); } } private static String getStackTraceString(Map<Thread, StackTraceElement[]> unclosedThreadMap) { StringBuilder sb = new StringBuilder(); for (Thread thread : unclosedThreadMap.keySet()) { sb.append(DubboTestChecker.getFullStacktrace(thread, unclosedThreadMap.get(thread))); sb.append("\n"); } return sb.toString(); } @BeforeEach public void setup() { FrameworkModel.destroyAll(); } @AfterEach public void afterEach() { SysProps.clear(); DubboBootstrap.reset(); } @Test void testIsolatedApplications() { DubboBootstrap dubboBootstrap1 = DubboBootstrap.newInstance(new FrameworkModel()); DubboBootstrap dubboBootstrap2 = DubboBootstrap.newInstance(new FrameworkModel()); try { ApplicationModel applicationModel1 = dubboBootstrap1.getApplicationModel(); ApplicationModel applicationModel2 = dubboBootstrap2.getApplicationModel(); Assertions.assertNotSame(applicationModel1, applicationModel2); Assertions.assertNotSame(applicationModel1.getFrameworkModel(), applicationModel2.getFrameworkModel()); Assertions.assertNotSame(dubboBootstrap1.getConfigManager(), dubboBootstrap2.getConfigManager()); // bootstrap1: provider app configProviderApp(dubboBootstrap1).start(); // bootstrap2: consumer app configConsumerApp(dubboBootstrap2).start(); testConsumer(dubboBootstrap2); DemoService demoServiceFromProvider = dubboBootstrap1.getCache().get(DemoService.class); Assertions.assertNull(demoServiceFromProvider); } finally { dubboBootstrap2.destroy(); dubboBootstrap1.destroy(); } } @Test void testDefaultProviderApplication() { DubboBootstrap dubboBootstrap = DubboBootstrap.getInstance(); try { configProviderApp(dubboBootstrap).start(); } finally { dubboBootstrap.destroy(); DubboBootstrap.reset(); } } @Test void testDefaultConsumerApplication() { SysProps.setProperty("dubbo.consumer.check", "false"); DubboBootstrap dubboBootstrap = DubboBootstrap.getInstance(); try { configConsumerApp(dubboBootstrap).start(); testConsumer(dubboBootstrap); } catch (Exception e) { Assertions.assertTrue(e.toString().contains("No provider available"), StringUtils.toString(e)); } finally { dubboBootstrap.destroy(); DubboBootstrap.reset(); SysProps.clear(); } } @Test void testDefaultMixedApplication() { DubboBootstrap dubboBootstrap = DubboBootstrap.getInstance(); try { dubboBootstrap.application("mixed-app"); configProviderApp(dubboBootstrap); configConsumerApp(dubboBootstrap); dubboBootstrap.start(); testConsumer(dubboBootstrap); } finally { dubboBootstrap.destroy(); DubboBootstrap.reset(); } } @Test void testSharedApplications() { FrameworkModel frameworkModel = new FrameworkModel(); DubboBootstrap dubboBootstrap1 = DubboBootstrap.newInstance(frameworkModel); DubboBootstrap dubboBootstrap2 = DubboBootstrap.newInstance(frameworkModel); try { ApplicationModel applicationModel1 = dubboBootstrap1.getApplicationModel(); ApplicationModel applicationModel2 = dubboBootstrap2.getApplicationModel(); Assertions.assertNotSame(applicationModel1, applicationModel2); Assertions.assertSame(applicationModel1.getFrameworkModel(), applicationModel2.getFrameworkModel()); Assertions.assertNotSame(dubboBootstrap1.getConfigManager(), dubboBootstrap2.getConfigManager()); configProviderApp(dubboBootstrap1).start(); configConsumerApp(dubboBootstrap2).start(); testConsumer(dubboBootstrap2); } finally { dubboBootstrap1.destroy(); dubboBootstrap2.destroy(); } } @Test void testMultiModuleApplication() throws InterruptedException { // SysProps.setProperty(METADATA_PUBLISH_DELAY_KEY, "100"); String version1 = "1.0"; String version2 = "2.0"; String version3 = "3.0"; DubboBootstrap providerBootstrap = null; DubboBootstrap consumerBootstrap = null; try { // provider app providerBootstrap = DubboBootstrap.newInstance(); ServiceConfig serviceConfig1 = new ServiceConfig(); serviceConfig1.setInterface(DemoService.class); serviceConfig1.setRef(new DemoServiceImpl()); serviceConfig1.setVersion(version1); ServiceConfig serviceConfig2 = new ServiceConfig(); serviceConfig2.setInterface(DemoService.class); serviceConfig2.setRef(new DemoServiceImpl()); serviceConfig2.setVersion(version2); ServiceConfig serviceConfig3 = new ServiceConfig(); serviceConfig3.setInterface(DemoService.class); serviceConfig3.setRef(new DemoServiceImpl()); serviceConfig3.setVersion(version3); providerBootstrap .application("provider-app") .registry(registryConfig) .protocol(new ProtocolConfig("dubbo", -1)) .service(serviceConfig1) .newModule() .service(serviceConfig2) .endModule() .newModule() .service(serviceConfig3) .endModule(); ApplicationModel applicationModel = providerBootstrap.getApplicationModel(); List<ModuleModel> moduleModels = applicationModel.getModuleModels(); Assertions.assertEquals(4, moduleModels.size()); Assertions.assertSame(moduleModels.get(0), applicationModel.getInternalModule()); Assertions.assertSame(moduleModels.get(1), applicationModel.getDefaultModule()); Assertions.assertSame(applicationModel.getDefaultModule(), serviceConfig1.getScopeModel()); Assertions.assertSame(moduleModels.get(2), serviceConfig2.getScopeModel()); Assertions.assertSame(moduleModels.get(3), serviceConfig3.getScopeModel()); Assertions.assertNotSame(applicationModel.getDefaultModule(), applicationModel.getInternalModule()); providerBootstrap.start(); // Thread.sleep(200); // consumer app consumerBootstrap = DubboBootstrap.newInstance(); consumerBootstrap .application("consumer-app") .registry(registryConfig) .reference(builder -> builder.interfaceClass(DemoService.class) .version(version1) .injvm(false)) .newModule() .reference(builder -> builder.interfaceClass(DemoService.class) .version(version2) .injvm(false)) .endModule(); consumerBootstrap.start(); DemoService referProxy1 = consumerBootstrap.getCache().get(DemoService.class.getName() + ":" + version1); Assertions.assertEquals("say:dubbo", referProxy1.sayName("dubbo")); DemoService referProxy2 = consumerBootstrap.getCache().get(DemoService.class.getName() + ":" + version2); Assertions.assertEquals("say:dubbo", referProxy2.sayName("dubbo")); Assertions.assertNotEquals(referProxy1, referProxy2); } finally { if (providerBootstrap != null) { providerBootstrap.destroy(); } if (consumerBootstrap != null) { consumerBootstrap.destroy(); } } } @Test void testMultiProviderApplicationsStopOneByOne() { FrameworkModel.destroyAll(); String version1 = "1.0"; String version2 = "2.0"; DubboBootstrap providerBootstrap1 = null; DubboBootstrap providerBootstrap2 = null; try { // save threads before provider app 1 Map<Thread, StackTraceElement[]> stackTraces0 = Thread.getAllStackTraces(); // start provider app 1 ServiceConfig serviceConfig1 = new ServiceConfig(); serviceConfig1.setInterface(DemoService.class); serviceConfig1.setRef(new DemoServiceImpl()); serviceConfig1.setVersion(version1); ProtocolConfig protocolConfig1 = new ProtocolConfig("dubbo", NetUtils.getAvailablePort()); providerBootstrap1 = DubboBootstrap.getInstance(); providerBootstrap1 .application("provider1") .registry(new RegistryConfig(registryConfig.getAddress())) .service(serviceConfig1) .protocol(protocolConfig1) .start(); // save threads of provider app 1 Map<Thread, StackTraceElement[]> lastAllThreadStackTraces = Thread.getAllStackTraces(); Map<Thread, StackTraceElement[]> stackTraces1 = findNewThreads(lastAllThreadStackTraces, stackTraces0); Assertions.assertTrue(stackTraces1.size() > 0, "Get threads of provider app 1 failed"); // start zk server 2 RegistryConfig registryConfig2 = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2()); // start provider app 2 use a difference zk server 2 ServiceConfig serviceConfig2 = new ServiceConfig(); serviceConfig2.setInterface(DemoService.class); serviceConfig2.setRef(new DemoServiceImpl()); serviceConfig2.setVersion(version2); ProtocolConfig protocolConfig2 = new ProtocolConfig("dubbo", NetUtils.getAvailablePort()); providerBootstrap2 = DubboBootstrap.newInstance(); providerBootstrap2 .application("provider2") .registry(registryConfig2) .service(serviceConfig2) .protocol(protocolConfig2) .start(); // save threads of provider app 2 Map<Thread, StackTraceElement[]> stackTraces2 = findNewThreads(Thread.getAllStackTraces(), stackTraces0); Assertions.assertTrue(stackTraces2.size() > 0, "Get threads of provider app 2 failed"); // stop provider app 1 and check threads providerBootstrap1.stop(); // TODO Remove ignore thread prefix of NettyServerBoss if supporting close protocol server only used by one // application // see org.apache.dubbo.config.deploy.DefaultApplicationDeployer.postDestroy // NettyServer will close when all applications are shutdown, but not close if any application of the // framework is alive, just ignore it currently checkUnclosedThreadsOfApp(stackTraces1, "Found unclosed threads of app 1: ", new String[] { EVENT_LOOP_BOSS_POOL_NAME, "Dubbo-global-shared-handler", "Dubbo-framework" }); // stop provider app 2 and check threads providerBootstrap2.stop(); // shutdown register center after dubbo application to avoid unregister services blocking checkUnclosedThreadsOfApp(stackTraces2, "Found unclosed threads of app 2: ", null); } finally { if (providerBootstrap1 != null) { providerBootstrap1.stop(); } if (providerBootstrap2 != null) { providerBootstrap2.stop(); } } } private Map<Thread, StackTraceElement[]> findNewThreads( Map<Thread, StackTraceElement[]> newAllThreadMap, Map<Thread, StackTraceElement[]> prevThreadMap) { Map<Thread, StackTraceElement[]> deltaThreadMap = new HashMap<>(newAllThreadMap); deltaThreadMap.keySet().removeAll(prevThreadMap.keySet()); // expect deltaThreadMap not contains any elements of prevThreadMap Assertions.assertFalse(deltaThreadMap.keySet().stream() .filter(thread -> prevThreadMap.containsKey(thread)) .findAny() .isPresent()); return deltaThreadMap; } private void checkUnclosedThreadsOfApp( Map<Thread, StackTraceElement[]> stackTraces1, String msg, String[] ignoredThreadPrefixes) { int waitTimeMs = 5000; System.out.println("Wait " + waitTimeMs + "ms to check threads of app ..."); try { Thread.sleep(waitTimeMs); } catch (InterruptedException e) { } HashMap<Thread, StackTraceElement[]> unclosedThreadMap1 = new HashMap<>(stackTraces1); unclosedThreadMap1.keySet().removeIf(thread -> !thread.isAlive()); if (ignoredThreadPrefixes != null && ignoredThreadPrefixes.length > 0) { unclosedThreadMap1.keySet().removeIf(thread -> isIgnoredThread(thread.getName(), ignoredThreadPrefixes)); } if (unclosedThreadMap1.size() > 0) { String str = getStackTraceString(unclosedThreadMap1); Assertions.fail(msg + unclosedThreadMap1.size() + "\n" + str); } } private boolean isIgnoredThread(String name, String[] ignoredThreadPrefixes) { if (ignoredThreadPrefixes != null && ignoredThreadPrefixes.length > 0) { for (String prefix : ignoredThreadPrefixes) { if (name.startsWith(prefix)) { return true; } } } return false; } @Test void testMultiModuleDeployAndReload() throws Exception { String version1 = "1.0"; String version2 = "2.0"; String version3 = "3.0"; String serviceKey1 = DemoService.class.getName() + ":" + version1; String serviceKey2 = DemoService.class.getName() + ":" + version2; String serviceKey3 = DemoService.class.getName() + ":" + version3; DubboBootstrap providerBootstrap = null; DubboBootstrap consumerBootstrap = null; try { // provider app providerBootstrap = DubboBootstrap.newInstance(); ServiceConfig serviceConfig1 = new ServiceConfig(); serviceConfig1.setInterface(DemoService.class); serviceConfig1.setRef(new DemoServiceImpl()); serviceConfig1.setVersion(version1); // provider module 1 providerBootstrap .application("provider-app") .registry(registryConfig) .protocol(new ProtocolConfig("dubbo", -1)) .service(builder -> builder.interfaceClass(Greeting.class).ref(new GreetingLocal2())) .newModule() .service(serviceConfig1) .endModule(); ApplicationModel applicationModel = providerBootstrap.getApplicationModel(); List<ModuleModel> moduleModels = applicationModel.getModuleModels(); Assertions.assertEquals(3, moduleModels.size()); Assertions.assertSame(moduleModels.get(0), applicationModel.getInternalModule()); Assertions.assertSame(moduleModels.get(1), applicationModel.getDefaultModule()); Assertions.assertSame(moduleModels.get(2), serviceConfig1.getScopeModel()); ModuleDeployer moduleDeployer1 = serviceConfig1.getScopeModel().getDeployer(); moduleDeployer1.start().get(); Assertions.assertTrue(moduleDeployer1.isStarted()); ModuleDeployer internalModuleDeployer = applicationModel.getInternalModule().getDeployer(); Assertions.assertTrue(internalModuleDeployer.isStarted()); FrameworkServiceRepository frameworkServiceRepository = applicationModel.getFrameworkModel().getServiceRepository(); Assertions.assertNotNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey1)); Assertions.assertNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey2)); Assertions.assertNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey3)); // consumer module 1 consumerBootstrap = DubboBootstrap.newInstance(); consumerBootstrap .application("consumer-app") .registry(registryConfig) .reference(builder -> builder.interfaceClass(DemoService.class) .version(version1) .injvm(false)); consumerBootstrap.start(); DemoService referProxy1 = consumerBootstrap.getCache().get(serviceKey1); String result1 = referProxy1.sayName("dubbo"); Assertions.assertEquals("say:dubbo", result1); // destroy provider module 1 serviceConfig1.getScopeModel().destroy(); // provider module 2 ServiceConfig serviceConfig2 = new ServiceConfig(); serviceConfig2.setInterface(DemoService.class); serviceConfig2.setRef(new DemoServiceImpl()); serviceConfig2.setVersion(version2); providerBootstrap.newModule().service(serviceConfig2).endModule(); // start provider module 2 and wait serviceConfig2.getScopeModel().getDeployer().start().get(); Assertions.assertNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey1)); Assertions.assertNotNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey2)); Assertions.assertNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey3)); // consumer module2 ModuleModel consumerModule2 = consumerBootstrap .newModule() .reference(builder -> builder.interfaceClass(DemoService.class) .version(version2) .injvm(false)) .getModuleModel(); ModuleDeployer moduleDeployer2 = consumerModule2.getDeployer(); moduleDeployer2.start().get(); DemoService referProxy2 = moduleDeployer2.getReferenceCache().get(serviceKey2); String result2 = referProxy2.sayName("dubbo2"); Assertions.assertEquals("say:dubbo2", result2); // destroy provider module 2 serviceConfig2.getScopeModel().destroy(); // provider module 3 ServiceConfig serviceConfig3 = new ServiceConfig(); serviceConfig3.setInterface(DemoService.class); serviceConfig3.setRef(new DemoServiceImpl()); serviceConfig3.setVersion(version3); providerBootstrap.newModule().service(serviceConfig3).endModule(); serviceConfig3.getScopeModel().getDeployer().start().get(); Assertions.assertNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey1)); Assertions.assertNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey2)); Assertions.assertNotNull(frameworkServiceRepository.lookupExportedServiceWithoutGroup(serviceKey3)); // consumer module3 ModuleModel consumerModule3 = consumerBootstrap .newModule() .reference(builder -> builder.interfaceClass(DemoService.class) .version(version3) .injvm(false)) .getModuleModel(); consumerBootstrap.start(); DemoService referProxy3 = consumerModule3.getDeployer().getReferenceCache().get(serviceKey3); String result3 = referProxy3.sayName("dubbo3"); Assertions.assertEquals("say:dubbo3", result3); } finally { if (providerBootstrap != null) { providerBootstrap.destroy(); } if (consumerBootstrap != null) { consumerBootstrap.destroy(); } } } @Test void testBothStartByModuleAndByApplication() throws Exception { String version1 = "1.0"; String version2 = "2.0"; String version3 = "3.0"; String serviceKey1 = DemoService.class.getName() + ":" + version1; String serviceKey2 = DemoService.class.getName() + ":" + version2; String serviceKey3 = DemoService.class.getName() + ":" + version3; // provider app DubboBootstrap providerBootstrap = null; try { providerBootstrap = DubboBootstrap.newInstance(); ServiceConfig serviceConfig1 = new ServiceConfig(); serviceConfig1.setInterface(DemoService.class); serviceConfig1.setRef(new DemoServiceImpl()); serviceConfig1.setVersion(version1); // provider module 1 providerBootstrap .application("provider-app") .registry(registryConfig) .protocol(new ProtocolConfig("dubbo", -1)) .service(builder -> builder.interfaceClass(Greeting.class).ref(new GreetingLocal2())) .newModule() .service(serviceConfig1) .endModule(); // 1. start module1 and wait ModuleDeployer moduleDeployer1 = serviceConfig1.getScopeModel().getDeployer(); moduleDeployer1.start().get(); Assertions.assertEquals(DeployState.STARTED, moduleDeployer1.getState()); ApplicationModel applicationModel = providerBootstrap.getApplicationModel(); ApplicationDeployer applicationDeployer = applicationModel.getDeployer(); Assertions.assertEquals(DeployState.STARTING, applicationDeployer.getState()); ModuleModel defaultModule = applicationModel.getDefaultModule(); Assertions.assertEquals( DeployState.PENDING, defaultModule.getDeployer().getState()); // 2. start application after module1 is started providerBootstrap.start(); Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState()); Assertions.assertEquals( DeployState.STARTED, defaultModule.getDeployer().getState()); // 3. add module2 and re-start application ServiceConfig serviceConfig2 = new ServiceConfig(); serviceConfig2.setInterface(DemoService.class); serviceConfig2.setRef(new DemoServiceImpl()); serviceConfig2.setVersion(version2); ModuleModel moduleModel2 = providerBootstrap.newModule().service(serviceConfig2).getModuleModel(); providerBootstrap.start(); Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState()); Assertions.assertEquals( DeployState.STARTED, moduleModel2.getDeployer().getState()); // 4. add module3 and start module3 ServiceConfig serviceConfig3 = new ServiceConfig(); serviceConfig3.setInterface(DemoService.class); serviceConfig3.setRef(new DemoServiceImpl()); serviceConfig3.setVersion(version3); ModuleModel moduleModel3 = providerBootstrap.newModule().service(serviceConfig3).getModuleModel(); moduleModel3.getDeployer().start().get(); Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState()); Assertions.assertEquals( DeployState.STARTED, moduleModel3.getDeployer().getState()); } finally { if (providerBootstrap != null) { providerBootstrap.stop(); } } } @Test void testBothStartModuleAndApplicationNoWait() throws Exception { String version1 = "1.0"; String version2 = "2.0"; String version3 = "3.0"; String serviceKey1 = DemoService.class.getName() + ":" + version1; String serviceKey2 = DemoService.class.getName() + ":" + version2; String serviceKey3 = DemoService.class.getName() + ":" + version3; // provider app DubboBootstrap providerBootstrap = null; try { providerBootstrap = DubboBootstrap.newInstance(); ServiceConfig serviceConfig1 = new ServiceConfig(); serviceConfig1.setInterface(DemoService.class); serviceConfig1.setRef(new DemoServiceImpl()); serviceConfig1.setVersion(version1); // provider module 1 providerBootstrap .application("provider-app") .registry(registryConfig) .protocol(new ProtocolConfig("dubbo", -1)) .service(builder -> builder.interfaceClass(Greeting.class).ref(new GreetingLocal2())) .newModule() .service(serviceConfig1) .endModule(); ApplicationModel applicationModel = providerBootstrap.getApplicationModel(); // 1. start module1 but no wait ModuleDeployer moduleDeployer1 = serviceConfig1.getScopeModel().getDeployer(); moduleDeployer1.start(); Assertions.assertTrue(moduleDeployer1.isRunning()); ApplicationDeployer applicationDeployer = applicationModel.getDeployer(); Assertions.assertEquals(DeployState.STARTING, applicationDeployer.getState()); ModuleModel defaultModule = applicationModel.getDefaultModule(); Assertions.assertEquals( DeployState.PENDING, defaultModule.getDeployer().getState()); // 2. start application after module1 is starting providerBootstrap.start(); Assertions.assertEquals(DeployState.STARTED, applicationDeployer.getState()); Assertions.assertEquals(DeployState.STARTED, moduleDeployer1.getState()); Assertions.assertEquals( DeployState.STARTED, defaultModule.getDeployer().getState()); } finally { if (providerBootstrap != null) { providerBootstrap.stop(); } } } @Test void testOldApiDeploy() throws Exception { try { // provider app ApplicationModel providerApplicationModel = ApplicationModel.defaultModel(); ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(); serviceConfig.setScopeModel(providerApplicationModel.getDefaultModule()); serviceConfig.setRef(new DemoServiceImpl()); serviceConfig.setInterface(DemoService.class); serviceConfig.setApplication(new ApplicationConfig("provider-app")); serviceConfig.setRegistry(new RegistryConfig(registryConfig.getAddress())); // add service // serviceConfig.getScopeModel().getConfigManager().addService(serviceConfig); // detect deploy events DeployEventHandler serviceDeployEventHandler = new DeployEventHandler(serviceConfig.getScopeModel()); serviceConfig.getScopeModel().getDeployer().addDeployListener(serviceDeployEventHandler); // before starting Map<DeployState, Long> serviceDeployEventMap = serviceDeployEventHandler.deployEventMap; Assertions.assertFalse(serviceDeployEventMap.containsKey(DeployState.STARTING)); Assertions.assertFalse(serviceDeployEventMap.containsKey(DeployState.STARTED)); // export service and start module serviceConfig.export(); // expect internal module is started Assertions.assertTrue( providerApplicationModel.getInternalModule().getDeployer().isStarted()); // expect service module is starting Assertions.assertTrue(serviceDeployEventMap.containsKey(DeployState.STARTING)); // wait for service module started serviceConfig.getScopeModel().getDeployer().getStartFuture().get(); Assertions.assertTrue(serviceDeployEventMap.containsKey(DeployState.STARTED)); // consumer app ApplicationModel consumerApplicationModel = ApplicationModel.defaultModel(); ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setScopeModel(consumerApplicationModel.getDefaultModule()); referenceConfig.setApplication(new ApplicationConfig("consumer-app")); referenceConfig.setInterface(DemoService.class); referenceConfig.setRegistry(new RegistryConfig(registryConfig.getAddress())); referenceConfig.setScope("remote"); // detect deploy events DeployEventHandler referDeployEventHandler = new DeployEventHandler(referenceConfig.getScopeModel()); referenceConfig.getScopeModel().getDeployer().addDeployListener(referDeployEventHandler); // before starting Map<DeployState, Long> deployEventMap = referDeployEventHandler.deployEventMap; Assertions.assertFalse(deployEventMap.containsKey(DeployState.STARTING)); Assertions.assertFalse(deployEventMap.containsKey(DeployState.STARTED)); // get ref proxy and start module DemoService demoService = referenceConfig.get(); // expect internal module is started Assertions.assertTrue( consumerApplicationModel.getInternalModule().getDeployer().isStarted()); Assertions.assertTrue(deployEventMap.containsKey(DeployState.STARTING)); // wait for reference module started referenceConfig.getScopeModel().getDeployer().getStartFuture().get(); Assertions.assertTrue(deployEventMap.containsKey(DeployState.STARTED)); // stop consumer app consumerApplicationModel.destroy(); Assertions.assertTrue(deployEventMap.containsKey(DeployState.STOPPING)); Assertions.assertTrue(deployEventMap.containsKey(DeployState.STOPPED)); // stop provider app providerApplicationModel.destroy(); Assertions.assertTrue(serviceDeployEventMap.containsKey(DeployState.STOPPING)); Assertions.assertTrue(serviceDeployEventMap.containsKey(DeployState.STOPPED)); } finally { FrameworkModel.destroyAll(); } } @Test void testAsyncExportAndReferServices() throws ExecutionException, InterruptedException { DubboBootstrap providerBootstrap = DubboBootstrap.newInstance(); DubboBootstrap consumerBootstrap = DubboBootstrap.newInstance(); try { ServiceConfig serviceConfig = new ServiceConfig(); serviceConfig.setInterface(Greeting.class); serviceConfig.setRef(new GreetingLocal2()); serviceConfig.setExportAsync(true); ReferenceConfig<Greeting> referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(Greeting.class); referenceConfig.setInjvm(false); referenceConfig.setReferAsync(true); referenceConfig.setCheck(false); // provider app Future providerFuture = providerBootstrap .application("provider-app") .registry(registryConfig) .protocol(new ProtocolConfig("dubbo", -1)) .service(serviceConfig) .asyncStart(); logger.info("provider app has start async"); // it might be started if running on fast machine. // Assertions.assertFalse(serviceConfig.getScopeModel().getDeployer().isStarted(), "Async export seems // something wrong"); // consumer app Future consumerFuture = consumerBootstrap .application("consumer-app") .registry(registryConfig) .reference(referenceConfig) .asyncStart(); logger.info("consumer app has start async"); // it might be started if running on fast machine. // Assertions.assertFalse(referenceConfig.getScopeModel().getDeployer().isStarted(), "Async refer seems // something wrong"); // wait for provider app startup providerFuture.get(); logger.info("provider app is startup"); Assertions.assertEquals(true, serviceConfig.isExported()); ServiceDescriptor serviceDescriptor = serviceConfig.getScopeModel().getServiceRepository().lookupService(Greeting.class.getName()); Assertions.assertNotNull(serviceDescriptor); // wait for consumer app startup consumerFuture.get(); logger.info("consumer app is startup"); Object target = referenceConfig.getServiceMetadata().getTarget(); Assertions.assertNotNull(target); // wait for invokers notified from registry MigrationInvoker migrationInvoker = (MigrationInvoker) referenceConfig.getInvoker(); for (int i = 0; i < 10; i++) { if (((List<Invoker>) migrationInvoker.getDirectory().getAllInvokers()) .stream().anyMatch(invoker -> invoker.getInterface() == Greeting.class)) { break; } Thread.sleep(100); } Greeting greetingService = (Greeting) target; String result = greetingService.hello(); Assertions.assertEquals("local", result); } finally { providerBootstrap.stop(); consumerBootstrap.stop(); } } private DubboBootstrap configConsumerApp(DubboBootstrap dubboBootstrap) { ReferenceConfig<DemoService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(DemoService.class); referenceConfig.setInjvm(false); if (!dubboBootstrap.getConfigManager().getApplication().isPresent()) { dubboBootstrap.application("consumer-app"); } dubboBootstrap.registry(registryConfig).reference(referenceConfig); return dubboBootstrap; } private void testConsumer(DubboBootstrap dubboBootstrap) { DemoService demoService = dubboBootstrap.getCache().get(DemoService.class); String result = demoService.sayName("dubbo"); System.out.println("result: " + result); Assertions.assertEquals("say:dubbo", result); } private DubboBootstrap configProviderApp(DubboBootstrap dubboBootstrap) { ProtocolConfig protocol1 = new ProtocolConfig(); protocol1.setName("dubbo"); protocol1.setPort(2001); ServiceConfig<DemoService> serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(DemoService.class); serviceConfig.setRef(new DemoServiceImpl()); if (!dubboBootstrap.getConfigManager().getApplication().isPresent()) { dubboBootstrap.application("provider-app"); } dubboBootstrap.registry(registryConfig).protocol(protocol1).service(serviceConfig); return dubboBootstrap; } private static class DeployEventHandler implements DeployListener<ModuleModel> { Map<DeployState, Long> deployEventMap = new LinkedHashMap<>(); ModuleModel moduleModel; public DeployEventHandler(ModuleModel moduleModel) { this.moduleModel = moduleModel; } @Override public void onInitialize(ModuleModel scopeModel) { Assertions.assertEquals(moduleModel, scopeModel); } @Override public void onStarting(ModuleModel scopeModel) { Assertions.assertEquals(moduleModel, scopeModel); deployEventMap.put(DeployState.STARTING, System.currentTimeMillis()); } @Override public void onStarted(ModuleModel scopeModel) { Assertions.assertEquals(moduleModel, scopeModel); deployEventMap.put(DeployState.STARTED, System.currentTimeMillis()); } @Override public void onStopping(ModuleModel scopeModel) { Assertions.assertEquals(moduleModel, scopeModel); deployEventMap.put(DeployState.STOPPING, System.currentTimeMillis()); } @Override public void onStopped(ModuleModel scopeModel) { Assertions.assertEquals(moduleModel, scopeModel); deployEventMap.put(DeployState.STOPPED, System.currentTimeMillis()); } @Override public void onFailure(ModuleModel scopeModel, Throwable cause) { Assertions.assertEquals(moduleModel, scopeModel); deployEventMap.put(DeployState.FAILED, System.currentTimeMillis()); } } }
8,433
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ConsulDubboServiceProviderBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.config.bootstrap.rest.UserService; import org.apache.dubbo.config.bootstrap.rest.UserServiceImpl; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE; /** * TODO */ public class ConsulDubboServiceProviderBootstrap { public static void main(String[] args) { DubboBootstrap.getInstance() .application("consul-dubbo-provider", app -> app.metadata(DEFAULT_METADATA_STORAGE_TYPE)) .registry(builder -> builder.address("consul://127.0.0.1:8500?registry-type=service") .useAsConfigCenter(true) .useAsMetadataCenter(true)) .protocol("dubbo", builder -> builder.port(-1).name("dubbo")) .protocol("rest", builder -> builder.port(8081).name("rest")) .service("echo", builder -> builder.interfaceClass(EchoService.class) .ref(new EchoServiceImpl()) .protocolIds("dubbo")) .service("user", builder -> builder.interfaceClass(UserService.class) .ref(new UserServiceImpl()) .protocolIds("rest")) .start() .await(); } }
8,434
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceProviderBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.config.bootstrap.rest.UserService; import org.apache.dubbo.config.bootstrap.rest.UserServiceImpl; import static org.apache.dubbo.common.constants.CommonConstants.COMPOSITE_METADATA_STORAGE_TYPE; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE; /** * TODO */ public class ZookeeperDubboServiceProviderBootstrap { public static void main(String[] args) { DubboBootstrap.getInstance() .application("zookeeper-dubbo-provider", app -> app.metadata(COMPOSITE_METADATA_STORAGE_TYPE)) .registry(builder -> builder.address("127.0.0.1:2181") .protocol("zookeeper") .parameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)) .protocol("dubbo", builder -> builder.port(-1).name("dubbo")) .protocol("rest", builder -> builder.port(8081).name("rest")) .service("echo", builder -> builder.interfaceClass(EchoService.class) .ref(new EchoServiceImpl()) .protocolIds("dubbo")) .service("user", builder -> builder.interfaceClass(UserService.class) .ref(new UserServiceImpl()) .protocolIds("rest")) .start() .await(); } }
8,435
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/EtcdDubboServiceConsumerBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.bootstrap.rest.UserService; /** * Dubbo Provider Bootstrap * * @since 2.7.5 */ public class EtcdDubboServiceConsumerBootstrap { public static void main(String[] args) throws Exception { DubboBootstrap bootstrap = DubboBootstrap.getInstance() .application("dubbo-consumer-demo") // Zookeeper .protocol(builder -> builder.port(20887).name("dubbo")) .registry( "etcd3", builder -> builder.address( "etcd3://127.0.0.1:2379?registry-type=service&subscribed-services=dubbo-provider-demo")) .metadataReport(new MetadataReportConfig("etcd://127.0.0.1:2379")) // Nacos // .registry("consul", builder -> // builder.address("consul://127.0.0.1:8500?registry.type=service&subscribed.services=dubbo-provider-demo").group("namespace1")) .reference("echo", builder -> builder.interfaceClass(EchoService.class) .protocol("dubbo")) .reference("user", builder -> builder.interfaceClass(UserService.class) .protocol("rest")) .start(); EchoService echoService = bootstrap.getCache().get(EchoService.class); for (int i = 0; i < 500; i++) { Thread.sleep(2000L); System.out.println(echoService.echo("Hello,World")); } } }
8,436
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceProviderBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.bootstrap.rest.UserService; import org.apache.dubbo.config.bootstrap.rest.UserServiceImpl; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE; /** * Dubbo Provider Bootstrap * * @since 2.7.5 */ public class NacosDubboServiceProviderBootstrap { public static void main(String[] args) { ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-nacos-provider-demo"); applicationConfig.setMetadataType(REMOTE_METADATA_STORAGE_TYPE); DubboBootstrap.getInstance() .application(applicationConfig) // Nacos in service registry type .registry("nacos", builder -> builder.address("nacos://127.0.0.1:8848?username=nacos&password=nacos") .parameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)) // Nacos in traditional registry type // .registry("nacos-traditional", builder -> builder.address("nacos://127.0.0.1:8848")) .protocol("dubbo", builder -> builder.port(20885).name("dubbo")) .protocol("rest", builder -> builder.port(9090).name("rest")) .service(builder -> builder.id("echo") .interfaceClass(EchoService.class) .ref(new EchoServiceImpl()) .protocolIds("dubbo")) .service(builder -> builder.id("user") .interfaceClass(UserService.class) .ref(new UserServiceImpl()) .protocolIds("rest")) .start() .await(); } }
8,437
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderMinimumBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.config.bootstrap.rest.UserService; import org.apache.dubbo.config.bootstrap.rest.UserServiceImpl; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; /** * TODO */ public class DubboServiceProviderMinimumBootstrap { public static void main(String[] args) { DubboBootstrap.getInstance() .application("dubbo-provider-demo") .registry(builder -> builder.address( ZookeeperRegistryCenterConfig.getConnectionAddress() + "?registry-type=service")) // .registry(builder -> builder.address("eureka://127.0.0.1:8761?registry-type=service")) .protocol(builder -> builder.port(-1).name("dubbo")) .service("echo", builder -> builder.interfaceClass(EchoService.class) .ref(new EchoServiceImpl())) .service("user", builder -> builder.interfaceClass(UserService.class) .ref(new UserServiceImpl())) .start() .await(); } }
8,438
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/EchoServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.rpc.RpcContext; import static java.lang.String.format; /** * The implementation of {@link EchoService} * * @see EchoService * @since 2.7.5 */ public class EchoServiceImpl implements EchoService { @Override public String echo(String message) { RpcContext rpcContext = RpcContext.getServiceContext(); return format("[%s:%s] ECHO - %s", rpcContext.getLocalHost(), rpcContext.getLocalPort(), message); } }
8,439
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/DubboServiceProviderBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.bootstrap.rest.UserService; import org.apache.dubbo.config.bootstrap.rest.UserServiceImpl; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; import java.util.Arrays; /** * Dubbo Provider Bootstrap * * @since 2.7.5 */ public class DubboServiceProviderBootstrap { public static void main(String[] args) { multipleRegistries(); } private static void multipleRegistries() { ProtocolConfig restProtocol = new ProtocolConfig(); restProtocol.setName("rest"); restProtocol.setId("rest"); restProtocol.setPort(-1); RegistryConfig interfaceRegistry = new RegistryConfig(); interfaceRegistry.setId("interfaceRegistry"); interfaceRegistry.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress()); RegistryConfig serviceRegistry = new RegistryConfig(); serviceRegistry.setId("serviceRegistry"); serviceRegistry.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress() + "?registry-type=service"); ServiceConfig<EchoService> echoService = new ServiceConfig<>(); echoService.setInterface(EchoService.class.getName()); echoService.setRef(new EchoServiceImpl()); // echoService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry)); ServiceConfig<UserService> userService = new ServiceConfig<>(); userService.setInterface(UserService.class.getName()); userService.setRef(new UserServiceImpl()); userService.setProtocol(restProtocol); // userService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry)); ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-provider-demo"); applicationConfig.setMetadataType("remote"); DubboBootstrap.getInstance() .application(applicationConfig) // Zookeeper in service registry type // .registry("zookeeper", builder -> // builder.address("zookeeper://127.0.0.1:2181?registry.type=service")) // Nacos // .registry("zookeeper", builder -> // builder.address("nacos://127.0.0.1:8848?registry.type=service")) .registries(Arrays.asList(interfaceRegistry, serviceRegistry)) // // .registry(RegistryBuilder.newBuilder().address("consul://127.0.0.1:8500?registry.type=service").build()) .protocol(builder -> builder.port(-1).name("dubbo")) .metadataReport(new MetadataReportConfig(ZookeeperRegistryCenterConfig.getConnectionAddress())) .service(echoService) .service(userService) .start() .await(); } private static void testSCCallDubbo() {} private static void testDubboCallSC() {} private static void testDubboTansormation() {} }
8,440
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ConsulDubboServiceConsumerBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.config.bootstrap.rest.UserService; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE; /** * Dubbo Provider Bootstrap * * @since 2.7.5 */ public class ConsulDubboServiceConsumerBootstrap { public static void main(String[] args) throws Exception { DubboBootstrap bootstrap = DubboBootstrap.getInstance() .application("consul-dubbo-consumer", app -> app.metadata(DEFAULT_METADATA_STORAGE_TYPE)) .registry("zookeeper", builder -> builder.address( "consul://127.0.0.1:8500?registry-type=service&subscribed-services=consul-dubbo-provider") .useAsConfigCenter(true) .useAsMetadataCenter(true)) .reference("echo", builder -> builder.interfaceClass(EchoService.class) .protocol("dubbo")) .reference("user", builder -> builder.interfaceClass(UserService.class) .protocol("rest")) .start(); EchoService echoService = bootstrap.getCache().get(EchoService.class); UserService userService = bootstrap.getCache().get(UserService.class); for (int i = 0; i < 5; i++) { Thread.sleep(2000L); System.out.println(echoService.echo("Hello,World")); System.out.println(userService.getUser(i * 1L)); } bootstrap.stop(); } }
8,441
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/ZookeeperDubboServiceConsumerBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.config.bootstrap.rest.UserService; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; import static org.apache.dubbo.common.constants.CommonConstants.COMPOSITE_METADATA_STORAGE_TYPE; import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY; import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE; /** * Dubbo Provider Bootstrap * * @since 2.7.5 */ public class ZookeeperDubboServiceConsumerBootstrap { public static void main(String[] args) throws Exception { DubboBootstrap bootstrap = DubboBootstrap.getInstance() .application("zookeeper-dubbo-consumer", app -> app.metadata(COMPOSITE_METADATA_STORAGE_TYPE)) .registry("zookeeper", builder -> builder.address(ZookeeperRegistryCenterConfig.getConnectionAddress()) .parameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE) .useAsConfigCenter(true) .useAsMetadataCenter(true)) .reference("echo", builder -> builder.interfaceClass(EchoService.class) .protocol("dubbo") .services("zookeeper-dubbo-provider")) .reference("user", builder -> builder.interfaceClass(UserService.class) .protocol("rest")) .start(); EchoService echoService = bootstrap.getCache().get(EchoService.class); UserService userService = bootstrap.getCache().get(UserService.class); for (int i = 0; i < 5; i++) { Thread.sleep(2000L); System.out.println(echoService.echo("Hello,World")); System.out.println(userService.getUser(i * 1L)); } bootstrap.stop(); } }
8,442
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/EtcdDubboServiceProviderBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.bootstrap.rest.UserService; import org.apache.dubbo.config.bootstrap.rest.UserServiceImpl; import java.util.Arrays; /** * Dubbo Provider Bootstrap * * @since 2.7.5 */ public class EtcdDubboServiceProviderBootstrap { public static void main(String[] args) { multipleRegistries(); } private static void multipleRegistries() { ProtocolConfig restProtocol = new ProtocolConfig(); restProtocol.setName("rest"); restProtocol.setId("rest"); restProtocol.setPort(-1); RegistryConfig interfaceRegistry = new RegistryConfig(); interfaceRegistry.setId("interfaceRegistry"); interfaceRegistry.setAddress("etcd3://127.0.0.1:2379"); RegistryConfig serviceRegistry = new RegistryConfig(); serviceRegistry.setId("serviceRegistry"); serviceRegistry.setAddress("etcd3://127.0.0.1:2379?registry-type=service"); ServiceConfig<EchoService> echoService = new ServiceConfig<>(); echoService.setInterface(EchoService.class.getName()); echoService.setRef(new EchoServiceImpl()); // echoService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry)); ServiceConfig<UserService> userService = new ServiceConfig<>(); userService.setInterface(UserService.class.getName()); userService.setRef(new UserServiceImpl()); userService.setProtocol(restProtocol); // userService.setRegistries(Arrays.asList(interfaceRegistry, serviceRegistry)); ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-provider-demo"); // applicationConfig.setMetadataType("remote"); DubboBootstrap.getInstance() .application(applicationConfig) // Zookeeper in service registry type // .registry("zookeeper", builder -> // builder.address("zookeeper://127.0.0.1:2181?registry.type=service")) // Nacos // .registry("zookeeper", builder -> // builder.address("nacos://127.0.0.1:8848?registry.type=service")) .registries(Arrays.asList(interfaceRegistry, serviceRegistry)) // // .registry(RegistryBuilder.newBuilder().address("consul://127.0.0.1:8500?registry.type=service").build()) .protocol(builder -> builder.port(-1).name("dubbo")) // .metadataReport(new MetadataReportConfig("etcd://127.0.0.1:2379")) .service(echoService) .service(userService) .start() .await(); } private static void testSCCallDubbo() {} private static void testDubboCallSC() {} private static void testDubboTansormation() {} }
8,443
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/EchoService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; /** * Echo Service * * @since 2.7.5 */ public interface EchoService { String GROUP = "DEFAULT"; String VERSION = "1.0.0"; String echo(String message); }
8,444
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/NacosDubboServiceConsumerBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.bootstrap.rest.UserService; import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE; /** * Dubbo Provider Bootstrap * * @since 2.7.5 */ public class NacosDubboServiceConsumerBootstrap { public static void main(String[] args) throws Exception { ApplicationConfig applicationConfig = new ApplicationConfig("dubbo-nacos-consumer-demo"); applicationConfig.setMetadataType(REMOTE_METADATA_STORAGE_TYPE); DubboBootstrap bootstrap = DubboBootstrap.getInstance() .application(applicationConfig) // Nacos in service registry type .registry("nacos", builder -> builder.address("nacos://127.0.0.1:8848?registry-type=service") .useAsConfigCenter(true) .useAsMetadataCenter(true)) // Nacos in traditional registry type // .registry("nacos-traditional", builder -> builder.address("nacos://127.0.0.1:8848")) .reference("echo", builder -> builder.interfaceClass(EchoService.class) .protocol("dubbo")) .reference("user", builder -> builder.interfaceClass(UserService.class) .protocol("rest")) .start(); EchoService echoService = bootstrap.getCache().get(EchoService.class); UserService userService = bootstrap.getCache().get(UserService.class); for (int i = 0; i < 5; i++) { Thread.sleep(2000L); System.out.println(echoService.echo("Hello,World")); System.out.println(userService.getUser(i * 1L)); } } }
8,445
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/compatible/DubboInterfaceConsumerBootstrap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.compatible; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.bootstrap.EchoService; import org.apache.dubbo.config.bootstrap.rest.UserService; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; /** * Dubbo Provider Bootstrap * * @since 2.7.5 */ public class DubboInterfaceConsumerBootstrap { public static void main(String[] args) throws Exception { RegistryConfig interfaceRegistry = new RegistryConfig(); interfaceRegistry.setId("interfaceRegistry"); interfaceRegistry.setAddress(ZookeeperRegistryCenterConfig.getConnectionAddress()); DubboBootstrap bootstrap = DubboBootstrap.getInstance() .application("dubbo-consumer-demo") // Zookeeper .registry(interfaceRegistry) // Nacos // .registry("consul", builder -> // builder.address("consul://127.0.0.1:8500?registry.type=service&subscribed.services=dubbo-provider-demo")) .reference("echo", builder -> builder.interfaceClass(EchoService.class) .protocol("dubbo")) .reference("user", builder -> builder.interfaceClass(UserService.class) .protocol("rest")) .start() .await(); EchoService echoService = bootstrap.getCache().get(EchoService.class); UserService userService = bootstrap.getCache().get(UserService.class); for (int i = 0; i < 500; i++) { Thread.sleep(2000L); System.out.println(echoService.echo("Hello,World")); System.out.println(userService.getUser(1L)); } } }
8,446
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ConsumerBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.ConsumerConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ConsumerBuilderTest { @Test void isDefault() { ConsumerBuilder builder = new ConsumerBuilder(); builder.isDefault(false); Assertions.assertFalse(builder.build().isDefault()); } @Test void client() { ConsumerBuilder builder = new ConsumerBuilder(); builder.client("client"); Assertions.assertEquals("client", builder.build().getClient()); } @Test void threadPool() { ConsumerBuilder builder = new ConsumerBuilder(); builder.threadPool("threadPool"); Assertions.assertEquals("threadPool", builder.build().getThreadpool()); } @Test void coreThreads() { ConsumerBuilder builder = new ConsumerBuilder(); builder.coreThreads(10); Assertions.assertEquals(10, builder.build().getCorethreads()); } @Test void threads() { ConsumerBuilder builder = new ConsumerBuilder(); builder.threads(100); Assertions.assertEquals(100, builder.build().getThreads()); } @Test void queues() { ConsumerBuilder builder = new ConsumerBuilder(); builder.queues(200); Assertions.assertEquals(200, builder.build().getQueues()); } @Test void shareConnections() { ConsumerBuilder builder = new ConsumerBuilder(); builder.shareConnections(300); Assertions.assertEquals(300, builder.build().getShareconnections()); } @Test void build() { ConsumerBuilder builder = new ConsumerBuilder(); builder.isDefault(true) .client("client") .threadPool("threadPool") .coreThreads(10) .threads(100) .queues(200) .shareConnections(300) .id("id"); ConsumerConfig config = builder.build(); ConsumerConfig config2 = builder.build(); Assertions.assertTrue(config.isDefault()); Assertions.assertEquals("client", config.getClient()); Assertions.assertEquals("threadPool", config.getThreadpool()); Assertions.assertEquals("id", config.getId()); Assertions.assertEquals(10, config.getCorethreads()); Assertions.assertEquals(100, config.getThreads()); Assertions.assertEquals(200, config.getQueues()); Assertions.assertEquals(300, config.getShareconnections()); Assertions.assertNotSame(config, config2); } }
8,447
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/RegistryBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.RegistryConfig; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class RegistryBuilderTest { @Test void address() { RegistryBuilder builder = new RegistryBuilder(); builder.address("address"); Assertions.assertEquals("address", builder.build().getAddress()); } @Test void username() { RegistryBuilder builder = new RegistryBuilder(); builder.username("username"); Assertions.assertEquals("username", builder.build().getUsername()); } @Test void password() { RegistryBuilder builder = new RegistryBuilder(); builder.password("password"); Assertions.assertEquals("password", builder.build().getPassword()); } @Test void port() { RegistryBuilder builder = new RegistryBuilder(); builder.port(8080); Assertions.assertEquals(8080, builder.build().getPort()); } @Test void protocol() { RegistryBuilder builder = new RegistryBuilder(); builder.protocol("protocol"); Assertions.assertEquals("protocol", builder.build().getProtocol()); } @Test void transporter() { RegistryBuilder builder = new RegistryBuilder(); builder.transporter("transporter"); Assertions.assertEquals("transporter", builder.build().getTransporter()); } @Test void transport() { RegistryBuilder builder = new RegistryBuilder(); builder.transport("transport"); Assertions.assertEquals("transport", builder.build().getTransport()); } @Test void server() { RegistryBuilder builder = new RegistryBuilder(); builder.server("server"); Assertions.assertEquals("server", builder.build().getServer()); } @Test void client() { RegistryBuilder builder = new RegistryBuilder(); builder.client("client"); Assertions.assertEquals("client", builder.build().getClient()); } @Test void cluster() { RegistryBuilder builder = new RegistryBuilder(); builder.cluster("cluster"); Assertions.assertEquals("cluster", builder.build().getCluster()); } @Test void group() { RegistryBuilder builder = new RegistryBuilder(); builder.group("group"); Assertions.assertEquals("group", builder.build().getGroup()); } @Test void version() { RegistryBuilder builder = new RegistryBuilder(); builder.version("version"); Assertions.assertEquals("version", builder.build().getVersion()); } @Test void timeout() { RegistryBuilder builder = new RegistryBuilder(); builder.timeout(1000); Assertions.assertEquals(1000, builder.build().getTimeout()); } @Test void session() { RegistryBuilder builder = new RegistryBuilder(); builder.session(2000); Assertions.assertEquals(2000, builder.build().getSession()); } @Test void file() { RegistryBuilder builder = new RegistryBuilder(); builder.file("file"); Assertions.assertEquals("file", builder.build().getFile()); } @Test void testWait() { RegistryBuilder builder = new RegistryBuilder(); builder.wait(Integer.valueOf(1000)); Assertions.assertEquals(1000, builder.build().getWait()); } @Test void isCheck() { RegistryBuilder builder = new RegistryBuilder(); builder.isCheck(true); Assertions.assertTrue(builder.build().isCheck()); } @Test void isDynamic() { RegistryBuilder builder = new RegistryBuilder(); builder.isDynamic(true); Assertions.assertTrue(builder.build().isDynamic()); } @Test void register() { RegistryBuilder builder = new RegistryBuilder(); builder.register(true); Assertions.assertTrue(builder.build().isRegister()); } @Test void subscribe() { RegistryBuilder builder = new RegistryBuilder(); builder.subscribe(true); Assertions.assertTrue(builder.build().isSubscribe()); } @Test void appendParameter() { RegistryBuilder builder = new RegistryBuilder(); builder.appendParameter("default.num", "one").appendParameter("num", "ONE"); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void appendParameters() { Map<String, String> source = new HashMap<>(); source.put("default.num", "one"); source.put("num", "ONE"); RegistryBuilder builder = new RegistryBuilder(); builder.appendParameters(source); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void isDefault() { RegistryBuilder builder = new RegistryBuilder(); builder.isDefault(true); Assertions.assertTrue(builder.build().isDefault()); } @Test void simplified() { RegistryBuilder builder = new RegistryBuilder(); builder.simplified(true); Assertions.assertTrue(builder.build().getSimplified()); } @Test void extraKeys() { RegistryBuilder builder = new RegistryBuilder(); builder.extraKeys("extraKeys"); Assertions.assertEquals("extraKeys", builder.build().getExtraKeys()); } @Test void build() { RegistryBuilder builder = new RegistryBuilder(); builder.address("address") .username("username") .password("password") .port(8080) .protocol("protocol") .transporter("transporter") .server("server") .client("client") .cluster("cluster") .group("group") .version("version") .timeout(1000) .session(2000) .file("file") .wait(Integer.valueOf(10)) .isCheck(true) .isDynamic(false) .register(true) .subscribe(false) .isDefault(true) .simplified(false) .extraKeys("A") .parameter("default.num", "one") .id("id"); RegistryConfig config = builder.build(); RegistryConfig config2 = builder.build(); Assertions.assertEquals(8080, config.getPort()); Assertions.assertEquals(1000, config.getTimeout()); Assertions.assertEquals(2000, config.getSession()); Assertions.assertEquals(10, config.getWait()); Assertions.assertTrue(config.isCheck()); Assertions.assertFalse(config.isDynamic()); Assertions.assertTrue(config.isRegister()); Assertions.assertFalse(config.isSubscribe()); Assertions.assertTrue(config.isDefault()); Assertions.assertFalse(config.getSimplified()); Assertions.assertEquals("address", config.getAddress()); Assertions.assertEquals("username", config.getUsername()); Assertions.assertEquals("password", config.getPassword()); Assertions.assertEquals("protocol", config.getProtocol()); Assertions.assertEquals("transporter", config.getTransporter()); Assertions.assertEquals("server", config.getServer()); Assertions.assertEquals("client", config.getClient()); Assertions.assertEquals("cluster", config.getCluster()); Assertions.assertEquals("group", config.getGroup()); Assertions.assertEquals("version", config.getVersion()); Assertions.assertEquals("file", config.getFile()); Assertions.assertEquals("A", config.getExtraKeys()); Assertions.assertTrue(config.getParameters().containsKey("default.num")); Assertions.assertEquals("one", config.getParameters().get("default.num")); Assertions.assertEquals("id", config.getId()); Assertions.assertNotSame(config, config2); } }
8,448
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ProviderBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.ProviderConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ProviderBuilderTest { @Test void setHost() { ProviderBuilder builder = new ProviderBuilder(); builder.host("host"); Assertions.assertEquals("host", builder.build().getHost()); } @Test void port() { ProviderBuilder builder = new ProviderBuilder(); builder.port(8080); Assertions.assertEquals(8080, builder.build().getPort()); } @Test void contextPath() { ProviderBuilder builder = new ProviderBuilder(); builder.contextPath("contextpath"); Assertions.assertEquals("contextpath", builder.build().getContextpath()); } @Test void threadPool() { ProviderBuilder builder = new ProviderBuilder(); builder.threadPool("mockthreadpool"); Assertions.assertEquals("mockthreadpool", builder.build().getThreadpool()); } @Test void threads() { ProviderBuilder builder = new ProviderBuilder(); builder.threads(20); Assertions.assertEquals(20, builder.build().getThreads()); } @Test void ioThreads() { ProviderBuilder builder = new ProviderBuilder(); builder.ioThreads(25); Assertions.assertEquals(25, builder.build().getIothreads()); } @Test void queues() { ProviderBuilder builder = new ProviderBuilder(); builder.queues(30); Assertions.assertEquals(30, builder.build().getQueues()); } @Test void accepts() { ProviderBuilder builder = new ProviderBuilder(); builder.accepts(35); Assertions.assertEquals(35, builder.build().getAccepts()); } @Test void codec() { ProviderBuilder builder = new ProviderBuilder(); builder.codec("mockcodec"); Assertions.assertEquals("mockcodec", builder.build().getCodec()); } @Test void charset() { ProviderBuilder builder = new ProviderBuilder(); builder.charset("utf-8"); Assertions.assertEquals("utf-8", builder.build().getCharset()); } @Test void payload() { ProviderBuilder builder = new ProviderBuilder(); builder.payload(40); Assertions.assertEquals(40, builder.build().getPayload()); } @Test void buffer() { ProviderBuilder builder = new ProviderBuilder(); builder.buffer(1024); Assertions.assertEquals(1024, builder.build().getBuffer()); } @Test void transporter() { ProviderBuilder builder = new ProviderBuilder(); builder.transporter("mocktransporter"); Assertions.assertEquals("mocktransporter", builder.build().getTransporter()); } @Test void exchanger() { ProviderBuilder builder = new ProviderBuilder(); builder.exchanger("mockexchanger"); Assertions.assertEquals("mockexchanger", builder.build().getExchanger()); } @Test void dispatcher() { ProviderBuilder builder = new ProviderBuilder(); builder.dispatcher("mockdispatcher"); Assertions.assertEquals("mockdispatcher", builder.build().getDispatcher()); } @Test void networker() { ProviderBuilder builder = new ProviderBuilder(); builder.networker("networker"); Assertions.assertEquals("networker", builder.build().getNetworker()); } @Test void server() { ProviderBuilder builder = new ProviderBuilder(); builder.server("server"); Assertions.assertEquals("server", builder.build().getServer()); } @Test void client() { ProviderBuilder builder = new ProviderBuilder(); builder.client("client"); Assertions.assertEquals("client", builder.build().getClient()); } @Test void telnet() { ProviderBuilder builder = new ProviderBuilder(); builder.telnet("mocktelnethandler"); Assertions.assertEquals("mocktelnethandler", builder.build().getTelnet()); } @Test void prompt() { ProviderBuilder builder = new ProviderBuilder(); builder.prompt("prompt"); Assertions.assertEquals("prompt", builder.build().getPrompt()); } @Test void status() { ProviderBuilder builder = new ProviderBuilder(); builder.status("mockstatuschecker"); Assertions.assertEquals("mockstatuschecker", builder.build().getStatus()); } @Test void Wait() { ProviderBuilder builder = new ProviderBuilder(); builder.wait(Integer.valueOf(1000)); Assertions.assertEquals(1000, builder.build().getWait()); } @Test void isDefault() { ProviderBuilder builder = new ProviderBuilder(); builder.isDefault(true); Assertions.assertTrue(builder.build().isDefault()); } @Test void build() { ProviderBuilder builder = new ProviderBuilder(); builder.host("host") .port(8080) .contextPath("contextpath") .threadPool("mockthreadpool") .threads(2) .ioThreads(3) .queues(4) .accepts(5) .codec("mockcodec") .charset("utf-8") .payload(6) .buffer(1024) .transporter("mocktransporter") .exchanger("mockexchanger") .dispatcher("mockdispatcher") .networker("networker") .server("server") .client("client") .telnet("mocktelnethandler") .prompt("prompt") .status("mockstatuschecker") .wait(Integer.valueOf(1000)) .isDefault(true) .id("id"); ProviderConfig config = builder.build(); ProviderConfig config2 = builder.build(); Assertions.assertEquals(8080, config.getPort()); Assertions.assertEquals(2, config.getThreads()); Assertions.assertEquals(3, config.getIothreads()); Assertions.assertEquals(4, config.getQueues()); Assertions.assertEquals(5, config.getAccepts()); Assertions.assertEquals(6, config.getPayload()); Assertions.assertEquals(1024, config.getBuffer()); Assertions.assertEquals(1000, config.getWait()); Assertions.assertEquals("host", config.getHost()); Assertions.assertEquals("contextpath", config.getContextpath()); Assertions.assertEquals("mockthreadpool", config.getThreadpool()); Assertions.assertEquals("mockcodec", config.getCodec()); Assertions.assertEquals("utf-8", config.getCharset()); Assertions.assertEquals("mocktransporter", config.getTransporter()); Assertions.assertEquals("mockexchanger", config.getExchanger()); Assertions.assertEquals("mockdispatcher", config.getDispatcher()); Assertions.assertEquals("networker", config.getNetworker()); Assertions.assertEquals("server", config.getServer()); Assertions.assertEquals("client", config.getClient()); Assertions.assertEquals("mocktelnethandler", config.getTelnet()); Assertions.assertEquals("prompt", config.getPrompt()); Assertions.assertEquals("mockstatuschecker", config.getStatus()); Assertions.assertTrue(config.isDefault()); Assertions.assertEquals("id", config.getId()); Assertions.assertNotSame(config, config2); } }
8,449
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractMethodBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.AbstractMethodConfig; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class AbstractMethodBuilderTest { @Test void timeout() { MethodBuilder builder = new MethodBuilder(); builder.timeout(10); Assertions.assertEquals(10, builder.build().getTimeout()); } @Test void retries() { MethodBuilder builder = new MethodBuilder(); builder.retries(3); Assertions.assertEquals(3, builder.build().getRetries()); } @Test void actives() { MethodBuilder builder = new MethodBuilder(); builder.actives(3); Assertions.assertEquals(3, builder.build().getActives()); } @Test void loadbalance() { MethodBuilder builder = new MethodBuilder(); builder.loadbalance("mockloadbalance"); Assertions.assertEquals("mockloadbalance", builder.build().getLoadbalance()); } @Test void async() { MethodBuilder builder = new MethodBuilder(); builder.async(true); Assertions.assertTrue(builder.build().isAsync()); } @Test void sent() { MethodBuilder builder = new MethodBuilder(); builder.sent(true); Assertions.assertTrue(builder.build().getSent()); } @Test void mock() { MethodBuilder builder = new MethodBuilder(); builder.mock("mock"); Assertions.assertEquals("mock", builder.build().getMock()); builder.mock("return null"); Assertions.assertEquals("return null", builder.build().getMock()); } @Test void mock1() { MethodBuilder builder = new MethodBuilder(); builder.mock(true); Assertions.assertEquals("true", builder.build().getMock()); builder.mock(false); Assertions.assertEquals("false", builder.build().getMock()); } @Test void merger() { MethodBuilder builder = new MethodBuilder(); builder.merger("merger"); Assertions.assertEquals("merger", builder.build().getMerger()); } @Test void cache() { MethodBuilder builder = new MethodBuilder(); builder.cache("cache"); Assertions.assertEquals("cache", builder.build().getCache()); } @Test void validation() { MethodBuilder builder = new MethodBuilder(); builder.validation("validation"); Assertions.assertEquals("validation", builder.build().getValidation()); } @Test void appendParameter() { MethodBuilder builder = new MethodBuilder(); builder.appendParameter("default.num", "one").appendParameter("num", "ONE"); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void appendParameters() { Map<String, String> source = new HashMap<>(); source.put("default.num", "one"); source.put("num", "ONE"); MethodBuilder builder = new MethodBuilder(); builder.appendParameters(source); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void forks() { MethodBuilder builder = new MethodBuilder(); builder.forks(5); Assertions.assertEquals(5, builder.build().getForks()); } @Test void build() { MethodBuilder builder = new MethodBuilder(); builder.id("id") .timeout(1) .retries(2) .actives(3) .loadbalance("mockloadbalance") .async(true) .sent(false) .mock("mock") .merger("merger") .cache("cache") .validation("validation") .appendParameter("default.num", "one"); MethodConfig config = builder.build(); MethodConfig config2 = builder.build(); Assertions.assertEquals("id", config.getId()); Assertions.assertEquals(1, config.getTimeout()); Assertions.assertEquals(2, config.getRetries()); Assertions.assertEquals(3, config.getActives()); Assertions.assertEquals("mockloadbalance", config.getLoadbalance()); Assertions.assertTrue(config.isAsync()); Assertions.assertFalse(config.getSent()); Assertions.assertEquals("mock", config.getMock()); Assertions.assertEquals("merger", config.getMerger()); Assertions.assertEquals("cache", config.getCache()); Assertions.assertEquals("validation", config.getValidation()); Assertions.assertTrue(config.getParameters().containsKey("default.num")); Assertions.assertEquals("one", config.getParameters().get("default.num")); Assertions.assertNotSame(config, config2); } private static class MethodBuilder extends AbstractMethodBuilder<MethodConfig, MethodBuilder> { public MethodConfig build() { MethodConfig parameterConfig = new MethodConfig(); super.build(parameterConfig); return parameterConfig; } @Override protected MethodBuilder getThis() { return this; } } private static class MethodConfig extends AbstractMethodConfig {} }
8,450
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractInterfaceBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.AbstractInterfaceConfig; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ConfigCenterConfig; import org.apache.dubbo.config.MetadataReportConfig; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import java.util.Collections; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class AbstractInterfaceBuilderTest { @BeforeEach void beforeEach() { DubboBootstrap.reset(); } @Test void local() { InterfaceBuilder builder = new InterfaceBuilder(); builder.local("GreetingMock"); Assertions.assertEquals("GreetingMock", builder.build().getLocal()); } @Test void local1() { InterfaceBuilder builder = new InterfaceBuilder(); builder.local((Boolean) null); Assertions.assertNull(builder.build().getLocal()); builder.local(false); Assertions.assertEquals("false", builder.build().getLocal()); builder.local(true); Assertions.assertEquals("true", builder.build().getLocal()); } @Test void stub() { InterfaceBuilder builder = new InterfaceBuilder(); builder.stub("GreetingMock"); Assertions.assertEquals("GreetingMock", builder.build().getStub()); } @Test void stub1() { InterfaceBuilder builder = new InterfaceBuilder(); builder.stub((Boolean) null); Assertions.assertNull(builder.build().getLocal()); builder.stub(false); Assertions.assertEquals("false", builder.build().getStub()); builder.stub(true); Assertions.assertEquals("true", builder.build().getStub()); } @Test void monitor() { InterfaceBuilder builder = new InterfaceBuilder(); builder.monitor("123"); MonitorConfig monitorConfig = new MonitorConfig("123"); Assertions.assertEquals(monitorConfig, builder.build().getMonitor()); } @Test void monitor1() { MonitorConfig monitorConfig = new MonitorConfig("123"); InterfaceBuilder builder = new InterfaceBuilder(); builder.monitor(monitorConfig); Assertions.assertEquals(monitorConfig, builder.build().getMonitor()); } @Test void proxy() { InterfaceBuilder builder = new InterfaceBuilder(); builder.proxy("mockproxyfactory"); Assertions.assertEquals("mockproxyfactory", builder.build().getProxy()); } @Test void cluster() { InterfaceBuilder builder = new InterfaceBuilder(); builder.cluster("mockcluster"); Assertions.assertEquals("mockcluster", builder.build().getCluster()); } @Test void filter() { InterfaceBuilder builder = new InterfaceBuilder(); builder.filter("mockfilter"); Assertions.assertEquals("mockfilter", builder.build().getFilter()); } @Test void listener() { InterfaceBuilder builder = new InterfaceBuilder(); builder.listener("mockinvokerlistener"); Assertions.assertEquals("mockinvokerlistener", builder.build().getListener()); } @Test void owner() { InterfaceBuilder builder = new InterfaceBuilder(); builder.owner("owner"); Assertions.assertEquals("owner", builder.build().getOwner()); } @Test void connections() { InterfaceBuilder builder = new InterfaceBuilder(); builder.connections(1); Assertions.assertEquals(1, builder.build().getConnections().intValue()); } @Test void layer() { InterfaceBuilder builder = new InterfaceBuilder(); builder.layer("layer"); Assertions.assertEquals("layer", builder.build().getLayer()); } @Test void application() { ApplicationConfig applicationConfig = new ApplicationConfig("AbtractInterfaceBuilderTest"); InterfaceBuilder builder = new InterfaceBuilder(); builder.application(applicationConfig); Assertions.assertEquals(applicationConfig, builder.build().getApplication()); } @Test void module() { ModuleConfig moduleConfig = new ModuleConfig(); InterfaceBuilder builder = new InterfaceBuilder(); builder.module(moduleConfig); Assertions.assertEquals(moduleConfig, builder.build().getModule()); } @Test void addRegistries() { RegistryConfig registryConfig = new RegistryConfig(); InterfaceBuilder builder = new InterfaceBuilder(); builder.addRegistries(Collections.singletonList(registryConfig)); Assertions.assertEquals(1, builder.build().getRegistries().size()); Assertions.assertSame(registryConfig, builder.build().getRegistries().get(0)); Assertions.assertSame(registryConfig, builder.build().getRegistry()); } @Test void addRegistry() { RegistryConfig registryConfig = new RegistryConfig(); InterfaceBuilder builder = new InterfaceBuilder(); builder.addRegistry(registryConfig); Assertions.assertEquals(1, builder.build().getRegistries().size()); Assertions.assertSame(registryConfig, builder.build().getRegistries().get(0)); Assertions.assertSame(registryConfig, builder.build().getRegistry()); } @Test void registryIds() { InterfaceBuilder builder = new InterfaceBuilder(); builder.registryIds("registryIds"); Assertions.assertEquals("registryIds", builder.build().getRegistryIds()); } @Test void onconnect() { InterfaceBuilder builder = new InterfaceBuilder(); builder.onconnect("onconnect"); Assertions.assertEquals("onconnect", builder.build().getOnconnect()); } @Test void ondisconnect() { InterfaceBuilder builder = new InterfaceBuilder(); builder.ondisconnect("ondisconnect"); Assertions.assertEquals("ondisconnect", builder.build().getOndisconnect()); } @Test void metadataReportConfig() { MetadataReportConfig metadataReportConfig = new MetadataReportConfig(); InterfaceBuilder builder = new InterfaceBuilder(); builder.metadataReportConfig(metadataReportConfig); Assertions.assertEquals(metadataReportConfig, builder.build().getMetadataReportConfig()); } @Test void configCenter() { ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(); InterfaceBuilder builder = new InterfaceBuilder(); builder.configCenter(configCenterConfig); Assertions.assertEquals(configCenterConfig, builder.build().getConfigCenter()); } @Test void callbacks() { InterfaceBuilder builder = new InterfaceBuilder(); builder.callbacks(2); Assertions.assertEquals(2, builder.build().getCallbacks().intValue()); } @Test void scope() { InterfaceBuilder builder = new InterfaceBuilder(); builder.scope("scope"); Assertions.assertEquals("scope", builder.build().getScope()); } @Test void build() { MonitorConfig monitorConfig = new MonitorConfig("123"); ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("appName"); ModuleConfig moduleConfig = new ModuleConfig(); RegistryConfig registryConfig = new RegistryConfig(); MetadataReportConfig metadataReportConfig = new MetadataReportConfig(); ConfigCenterConfig configCenterConfig = new ConfigCenterConfig(); InterfaceBuilder builder = new InterfaceBuilder(); builder.id("id") .local(true) .stub(false) .monitor("123") .proxy("mockproxyfactory") .cluster("mockcluster") .filter("mockfilter") .listener("mockinvokerlistener") .owner("owner") .connections(1) .layer("layer") .application(applicationConfig) .module(moduleConfig) .addRegistry(registryConfig) .registryIds("registryIds") .onconnect("onconnet") .ondisconnect("ondisconnect") .metadataReportConfig(metadataReportConfig) .configCenter(configCenterConfig) .callbacks(2) .scope("scope"); InterfaceConfig config = builder.build(); InterfaceConfig config2 = builder.build(); Assertions.assertEquals("id", config.getId()); Assertions.assertEquals("true", config.getLocal()); Assertions.assertEquals("false", config.getStub()); Assertions.assertEquals(monitorConfig, config.getMonitor()); Assertions.assertEquals("mockproxyfactory", config.getProxy()); Assertions.assertEquals("mockcluster", config.getCluster()); Assertions.assertEquals("mockfilter", config.getFilter()); Assertions.assertEquals("mockinvokerlistener", config.getListener()); Assertions.assertEquals("owner", config.getOwner()); Assertions.assertEquals(1, config.getConnections().intValue()); Assertions.assertEquals("layer", config.getLayer()); Assertions.assertEquals(applicationConfig, config.getApplication()); Assertions.assertEquals(moduleConfig, config.getModule()); Assertions.assertEquals(registryConfig, config.getRegistry()); Assertions.assertEquals("registryIds", config.getRegistryIds()); Assertions.assertEquals("onconnet", config.getOnconnect()); Assertions.assertEquals("ondisconnect", config.getOndisconnect()); Assertions.assertEquals(metadataReportConfig, config.getMetadataReportConfig()); Assertions.assertEquals(configCenterConfig, config.getConfigCenter()); Assertions.assertEquals(2, config.getCallbacks().intValue()); Assertions.assertEquals("scope", config.getScope()); Assertions.assertNotSame(config, config2); } private static class InterfaceBuilder extends AbstractInterfaceBuilder<InterfaceConfig, InterfaceBuilder> { public InterfaceConfig build() { InterfaceConfig config = new InterfaceConfig(); super.build(config); return config; } @Override protected InterfaceBuilder getThis() { return this; } } private static class InterfaceConfig extends AbstractInterfaceConfig {} }
8,451
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ServiceBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.MethodConfig; import org.apache.dubbo.config.ProviderConfig; import org.apache.dubbo.config.ServiceConfig; import java.util.Collections; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_DEFAULT; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_NATIVE_JAVA; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; class ServiceBuilderTest { @Test void path() { ServiceBuilder builder = new ServiceBuilder(); builder.path("path"); Assertions.assertEquals("path", builder.build().getPath()); } @Test void addMethod() { MethodConfig method = new MethodConfig(); ServiceBuilder builder = new ServiceBuilder(); builder.addMethod(method); Assertions.assertTrue(builder.build().getMethods().contains(method)); Assertions.assertEquals(1, builder.build().getMethods().size()); } @Test void addMethods() { MethodConfig method = new MethodConfig(); ServiceBuilder builder = new ServiceBuilder(); builder.addMethods(Collections.singletonList(method)); Assertions.assertTrue(builder.build().getMethods().contains(method)); Assertions.assertEquals(1, builder.build().getMethods().size()); } @Test void provider() { ProviderConfig provider = new ProviderConfig(); ServiceBuilder builder = new ServiceBuilder(); builder.provider(provider); Assertions.assertSame(provider, builder.build().getProvider()); } @Test void providerIds() { ServiceBuilder builder = new ServiceBuilder(); builder.providerIds("providerIds"); Assertions.assertEquals("providerIds", builder.build().getProviderIds()); } @Test void generic() throws Exception { ServiceBuilder builder = new ServiceBuilder(); builder.generic(GENERIC_SERIALIZATION_DEFAULT); assertThat(builder.build().getGeneric(), equalTo(GENERIC_SERIALIZATION_DEFAULT)); builder.generic(GENERIC_SERIALIZATION_NATIVE_JAVA); assertThat(builder.build().getGeneric(), equalTo(GENERIC_SERIALIZATION_NATIVE_JAVA)); builder.generic(GENERIC_SERIALIZATION_BEAN); assertThat(builder.build().getGeneric(), equalTo(GENERIC_SERIALIZATION_BEAN)); } @Test void generic1() throws Exception { Assertions.assertThrows(IllegalArgumentException.class, () -> { ServiceBuilder builder = new ServiceBuilder(); builder.generic("illegal").build(); }); } // // @Test // public void Mock() throws Exception { // Assertions.assertThrows(IllegalArgumentException.class, () -> { // ServiceBuilder builder = new ServiceBuilder(); // builder.mock("true"); // }); // } // // @Test // public void Mock1() throws Exception { // Assertions.assertThrows(IllegalArgumentException.class, () -> { // ServiceBuilder builder = new ServiceBuilder(); // builder.mock(true); // }); // } @Test void build() { MethodConfig method = new MethodConfig(); ProviderConfig provider = new ProviderConfig(); ServiceBuilder builder = new ServiceBuilder(); builder.path("path") .addMethod(method) .provider(provider) .providerIds("providerIds") .generic(GENERIC_SERIALIZATION_DEFAULT); ServiceConfig config = builder.build(); ServiceConfig config2 = builder.build(); assertThat(config.getGeneric(), equalTo(GENERIC_SERIALIZATION_DEFAULT)); Assertions.assertEquals("path", config.getPath()); Assertions.assertEquals("providerIds", config.getProviderIds()); Assertions.assertSame(provider, config.getProvider()); Assertions.assertTrue(config.getMethods().contains(method)); Assertions.assertEquals(1, config.getMethods().size()); Assertions.assertNotSame(config, config2); } }
8,452
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MetadataReportBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.MetadataReportConfig; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class MetadataReportBuilderTest { @Test void address() { MetadataReportBuilder builder = new MetadataReportBuilder(); builder.address("address"); Assertions.assertEquals("address", builder.build().getAddress()); } @Test void username() { MetadataReportBuilder builder = new MetadataReportBuilder(); builder.username("username"); Assertions.assertEquals("username", builder.build().getUsername()); } @Test void password() { MetadataReportBuilder builder = new MetadataReportBuilder(); builder.password("password"); Assertions.assertEquals("password", builder.build().getPassword()); } @Test void timeout() { MetadataReportBuilder builder = new MetadataReportBuilder(); builder.timeout(1000); Assertions.assertEquals(1000, builder.build().getTimeout()); } @Test void group() { MetadataReportBuilder builder = new MetadataReportBuilder(); builder.group("group"); Assertions.assertEquals("group", builder.build().getGroup()); } @Test void appendParameter() { MetadataReportBuilder builder = new MetadataReportBuilder(); builder.appendParameter("default.num", "one").appendParameter("num", "ONE"); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void appendParameters() { Map<String, String> source = new HashMap<>(); source.put("default.num", "one"); source.put("num", "ONE"); MetadataReportBuilder builder = new MetadataReportBuilder(); builder.appendParameters(source); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void retryTimes() { MetadataReportBuilder builder = new MetadataReportBuilder(); builder.retryTimes(1); Assertions.assertEquals(1, builder.build().getRetryTimes()); } @Test void retryPeriod() { MetadataReportBuilder builder = new MetadataReportBuilder(); builder.retryPeriod(2); Assertions.assertEquals(2, builder.build().getRetryPeriod()); } @Test void cycleReport() { MetadataReportBuilder builder = new MetadataReportBuilder(); builder.cycleReport(true); Assertions.assertTrue(builder.build().getCycleReport()); builder.cycleReport(false); Assertions.assertFalse(builder.build().getCycleReport()); builder.cycleReport(null); Assertions.assertNull(builder.build().getCycleReport()); } @Test void syncReport() { MetadataReportBuilder builder = new MetadataReportBuilder(); builder.syncReport(true); Assertions.assertTrue(builder.build().getSyncReport()); builder.syncReport(false); Assertions.assertFalse(builder.build().getSyncReport()); builder.syncReport(null); Assertions.assertNull(builder.build().getSyncReport()); } @Test void build() { MetadataReportBuilder builder = new MetadataReportBuilder(); builder.address("address") .username("username") .password("password") .timeout(1000) .group("group") .retryTimes(1) .retryPeriod(2) .cycleReport(true) .syncReport(false) .appendParameter("default.num", "one") .id("id"); MetadataReportConfig config = builder.build(); MetadataReportConfig config2 = builder.build(); Assertions.assertTrue(config.getCycleReport()); Assertions.assertFalse(config.getSyncReport()); Assertions.assertEquals(1000, config.getTimeout()); Assertions.assertEquals(1, config.getRetryTimes()); Assertions.assertEquals(2, config.getRetryPeriod()); Assertions.assertEquals("address", config.getAddress()); Assertions.assertEquals("username", config.getUsername()); Assertions.assertEquals("password", config.getPassword()); Assertions.assertEquals("group", config.getGroup()); Assertions.assertTrue(config.getParameters().containsKey("default.num")); Assertions.assertEquals("one", config.getParameters().get("default.num")); Assertions.assertEquals("id", config.getId()); Assertions.assertNotSame(config, config2); } }
8,453
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ConfigCenterBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.ConfigCenterConfig; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ConfigCenterBuilderTest { @Test void protocol() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.protocol("protocol"); Assertions.assertEquals("protocol", builder.build().getProtocol()); } @Test void address() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.address("address"); Assertions.assertEquals("address", builder.build().getAddress()); } @Test void cluster() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.cluster("cluster"); Assertions.assertEquals("cluster", builder.build().getCluster()); } @Test void namespace() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.namespace("namespace"); Assertions.assertEquals("namespace", builder.build().getNamespace()); } @Test void group() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.group("group"); Assertions.assertEquals("group", builder.build().getGroup()); } @Test void username() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.username("username"); Assertions.assertEquals("username", builder.build().getUsername()); } @Test void password() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.password("password"); Assertions.assertEquals("password", builder.build().getPassword()); } @Test void timeout() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.timeout(1000L); Assertions.assertEquals(1000L, builder.build().getTimeout()); } @Test void highestPriority() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.highestPriority(true); Assertions.assertTrue(builder.build().isHighestPriority()); } @Test void check() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.check(true); Assertions.assertTrue(builder.build().isCheck()); } @Test void configFile() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.configFile("configFile"); Assertions.assertEquals("configFile", builder.build().getConfigFile()); } @Test void appConfigFile() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.appConfigFile("appConfigFile"); Assertions.assertEquals("appConfigFile", builder.build().getAppConfigFile()); } @Test void appendParameter() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.appendParameter("default.num", "one").appendParameter("num", "ONE"); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void appendParameters() { Map<String, String> source = new HashMap<>(); source.put("default.num", "one"); source.put("num", "ONE"); ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.appendParameters(source); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void build() { ConfigCenterBuilder builder = new ConfigCenterBuilder(); builder.check(true) .protocol("protocol") .address("address") .appConfigFile("appConfigFile") .cluster("cluster") .configFile("configFile") .group("group") .highestPriority(false) .namespace("namespace") .password("password") .timeout(1000L) .username("usernama") .appendParameter("default.num", "one") .id("id"); ConfigCenterConfig config = builder.build(); ConfigCenterConfig config2 = builder.build(); Assertions.assertTrue(config.isCheck()); Assertions.assertFalse(config.isHighestPriority()); Assertions.assertEquals(1000L, config.getTimeout()); Assertions.assertEquals("protocol", config.getProtocol()); Assertions.assertEquals("address", config.getAddress()); Assertions.assertEquals("appConfigFile", config.getAppConfigFile()); Assertions.assertEquals("cluster", config.getCluster()); Assertions.assertEquals("configFile", config.getConfigFile()); Assertions.assertEquals("group", config.getGroup()); Assertions.assertEquals("namespace", config.getNamespace()); Assertions.assertEquals("password", config.getPassword()); Assertions.assertEquals("usernama", config.getUsername()); Assertions.assertTrue(config.getParameters().containsKey("default.num")); Assertions.assertEquals("one", config.getParameters().get("default.num")); Assertions.assertEquals("id", config.getId()); Assertions.assertNotSame(config, config2); } }
8,454
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ReferenceBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.ConsumerConfig; import org.apache.dubbo.config.MethodConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.api.DemoService; import java.util.Collections; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.utils.CollectionUtils.ofSet; class ReferenceBuilderTest { @Test void interfaceName() { ReferenceBuilder builder = new ReferenceBuilder(); builder.interfaceName(DemoService.class.getName()); Assertions.assertEquals( "org.apache.dubbo.config.api.DemoService", builder.build().getInterface()); } @Test void interfaceClass() { ReferenceBuilder builder = new ReferenceBuilder(); builder.interfaceClass(DemoService.class); Assertions.assertEquals(DemoService.class, builder.build().getInterfaceClass()); } @Test void client() { ReferenceBuilder builder = new ReferenceBuilder(); builder.client("client"); Assertions.assertEquals("client", builder.build().getClient()); } @Test void url() { ReferenceBuilder builder = new ReferenceBuilder(); builder.url("url"); Assertions.assertEquals("url", builder.build().getUrl()); } @Test void addMethods() { MethodConfig method = new MethodConfig(); ReferenceBuilder builder = new ReferenceBuilder(); builder.addMethods(Collections.singletonList(method)); Assertions.assertTrue(builder.build().getMethods().contains(method)); Assertions.assertEquals(1, builder.build().getMethods().size()); } @Test void addMethod() { MethodConfig method = new MethodConfig(); ReferenceBuilder builder = new ReferenceBuilder(); builder.addMethod(method); Assertions.assertTrue(builder.build().getMethods().contains(method)); Assertions.assertEquals(1, builder.build().getMethods().size()); } @Test void consumer() { ConsumerConfig consumer = new ConsumerConfig(); ReferenceBuilder builder = new ReferenceBuilder(); builder.consumer(consumer); Assertions.assertSame(consumer, builder.build().getConsumer()); } @Test void protocol() { ReferenceBuilder builder = new ReferenceBuilder(); builder.protocol("protocol"); Assertions.assertEquals("protocol", builder.build().getProtocol()); } @Test void build() { ConsumerConfig consumer = new ConsumerConfig(); MethodConfig method = new MethodConfig(); ReferenceBuilder<DemoService> builder = new ReferenceBuilder<>(); builder.id("id") .interfaceClass(DemoService.class) .protocol("protocol") .client("client") .url("url") .consumer(consumer) .addMethod(method) // introduced since 2.7.8 .services("test-service", "test-service2"); ReferenceConfig config = builder.build(); ReferenceConfig config2 = builder.build(); Assertions.assertEquals("org.apache.dubbo.config.api.DemoService", config.getInterface()); Assertions.assertEquals(DemoService.class, config.getInterfaceClass()); Assertions.assertEquals("protocol", config.getProtocol()); Assertions.assertEquals("client", config.getClient()); Assertions.assertEquals("url", config.getUrl()); Assertions.assertEquals(consumer, config.getConsumer()); Assertions.assertEquals("test-service,test-service2", config.getServices()); Assertions.assertEquals(ofSet("test-service", "test-service2"), config.getSubscribedServices()); Assertions.assertTrue(config.getMethods().contains(method)); Assertions.assertEquals(1, config.getMethods().size()); Assertions.assertNotSame(config, config2); } }
8,455
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ArgumentBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.ArgumentConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ArgumentBuilderTest { @Test void index() { ArgumentBuilder builder = new ArgumentBuilder(); builder.index(1); Assertions.assertEquals(1, builder.build().getIndex()); } @Test void type() { ArgumentBuilder builder = new ArgumentBuilder(); builder.type("int"); Assertions.assertEquals("int", builder.build().getType()); } @Test void callback() { ArgumentBuilder builder = new ArgumentBuilder(); builder.callback(true); Assertions.assertTrue(builder.build().isCallback()); builder.callback(false); Assertions.assertFalse(builder.build().isCallback()); } @Test void build() { ArgumentBuilder builder = new ArgumentBuilder(); builder.index(1).type("int").callback(true); ArgumentConfig argument1 = builder.build(); ArgumentConfig argument2 = builder.build(); Assertions.assertTrue(argument1.isCallback()); Assertions.assertEquals("int", argument1.getType()); Assertions.assertEquals(1, argument1.getIndex()); Assertions.assertNotSame(argument1, argument2); } }
8,456
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ModuleBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.ModuleConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.RegistryConfig; import java.util.Collections; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ModuleBuilderTest { @Test void name() { ModuleBuilder builder = new ModuleBuilder(); builder.name("name"); Assertions.assertEquals("name", builder.build().getName()); } @Test void version() { ModuleBuilder builder = new ModuleBuilder(); builder.version("version"); Assertions.assertEquals("version", builder.build().getVersion()); } @Test void owner() { ModuleBuilder builder = new ModuleBuilder(); builder.owner("owner"); Assertions.assertEquals("owner", builder.build().getOwner()); } @Test void organization() { ModuleBuilder builder = new ModuleBuilder(); builder.organization("organization"); Assertions.assertEquals("organization", builder.build().getOrganization()); } @Test void addRegistries() { RegistryConfig registry = new RegistryConfig(); ModuleBuilder builder = new ModuleBuilder(); builder.addRegistries(Collections.singletonList(registry)); Assertions.assertTrue(builder.build().getRegistries().contains(registry)); Assertions.assertEquals(1, builder.build().getRegistries().size()); } @Test void addRegistry() { RegistryConfig registry = new RegistryConfig(); ModuleBuilder builder = new ModuleBuilder(); builder.addRegistry(registry); Assertions.assertTrue(builder.build().getRegistries().contains(registry)); Assertions.assertEquals(1, builder.build().getRegistries().size()); } @Test void monitor() { MonitorConfig monitor = new MonitorConfig(); ModuleBuilder builder = new ModuleBuilder(); builder.monitor(monitor); Assertions.assertSame(monitor, builder.build().getMonitor()); } @Test void isDefault() { ModuleBuilder builder = new ModuleBuilder(); builder.isDefault(true); Assertions.assertTrue(builder.build().isDefault()); } @Test void build() { RegistryConfig registry = new RegistryConfig(); MonitorConfig monitor = new MonitorConfig(); ModuleBuilder builder = new ModuleBuilder(); builder.name("name") .version("version") .owner("owner") .organization("organization") .addRegistry(registry) .monitor(monitor) .isDefault(false); ModuleConfig config = builder.build(); ModuleConfig config2 = builder.build(); Assertions.assertEquals("name", config.getName()); Assertions.assertEquals("version", config.getVersion()); Assertions.assertEquals("owner", config.getOwner()); Assertions.assertEquals("organization", config.getOrganization()); Assertions.assertTrue(builder.build().getRegistries().contains(registry)); Assertions.assertSame(monitor, builder.build().getMonitor()); Assertions.assertFalse(config.isDefault()); Assertions.assertNotSame(config, config2); } }
8,457
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractServiceBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.AbstractServiceConfig; import org.apache.dubbo.config.ProtocolConfig; import java.util.Collections; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class AbstractServiceBuilderTest { @Test void version() { ServiceBuilder builder = new ServiceBuilder(); builder.version("version"); Assertions.assertEquals("version", builder.build().getVersion()); } @Test void group() { ServiceBuilder builder = new ServiceBuilder(); builder.group("group"); Assertions.assertEquals("group", builder.build().getGroup()); } @Test void deprecated() { ServiceBuilder builder = new ServiceBuilder(); builder.deprecated(true); Assertions.assertTrue(builder.build().isDeprecated()); builder.deprecated(false); Assertions.assertFalse(builder.build().isDeprecated()); } @Test void delay() { ServiceBuilder builder = new ServiceBuilder(); builder.delay(1000); Assertions.assertEquals(1000, builder.build().getDelay()); } @Test void export() { ServiceBuilder builder = new ServiceBuilder(); builder.export(true); Assertions.assertTrue(builder.build().getExport()); builder.export(false); Assertions.assertFalse(builder.build().getExport()); } @Test void weight() { ServiceBuilder builder = new ServiceBuilder(); builder.weight(500); Assertions.assertEquals(500, builder.build().getWeight()); } @Test void document() { ServiceBuilder builder = new ServiceBuilder(); builder.document("http://dubbo.apache.org"); Assertions.assertEquals("http://dubbo.apache.org", builder.build().getDocument()); } @Test void dynamic() { ServiceBuilder builder = new ServiceBuilder(); builder.dynamic(true); Assertions.assertTrue(builder.build().isDynamic()); builder.dynamic(false); Assertions.assertFalse(builder.build().isDynamic()); } @Test void token() { ServiceBuilder builder = new ServiceBuilder(); builder.token("token"); Assertions.assertEquals("token", builder.build().getToken()); } @Test void token1() { ServiceBuilder builder = new ServiceBuilder(); builder.token(true); Assertions.assertEquals("true", builder.build().getToken()); builder.token(false); Assertions.assertEquals("false", builder.build().getToken()); builder.token((Boolean) null); Assertions.assertNull(builder.build().getToken()); } @Test void accesslog() { ServiceBuilder builder = new ServiceBuilder(); builder.accesslog("accesslog"); Assertions.assertEquals("accesslog", builder.build().getAccesslog()); } @Test void accesslog1() { ServiceBuilder builder = new ServiceBuilder(); builder.accesslog(true); Assertions.assertEquals("true", builder.build().getAccesslog()); builder.accesslog(false); Assertions.assertEquals("false", builder.build().getAccesslog()); builder.accesslog((Boolean) null); Assertions.assertNull(builder.build().getAccesslog()); } @Test void addProtocols() { ProtocolConfig protocol = new ProtocolConfig(); ServiceBuilder builder = new ServiceBuilder(); Assertions.assertNull(builder.build().getProtocols()); builder.addProtocols(Collections.singletonList(protocol)); Assertions.assertNotNull(builder.build().getProtocols()); Assertions.assertEquals(1, builder.build().getProtocols().size()); } @Test void addProtocol() { ProtocolConfig protocol = new ProtocolConfig(); ServiceBuilder builder = new ServiceBuilder(); Assertions.assertNull(builder.build().getProtocols()); builder.addProtocol(protocol); Assertions.assertNotNull(builder.build().getProtocols()); Assertions.assertEquals(1, builder.build().getProtocols().size()); Assertions.assertEquals(protocol, builder.build().getProtocol()); } @Test void protocolIds() { ServiceBuilder builder = new ServiceBuilder(); builder.protocolIds("protocolIds"); Assertions.assertEquals("protocolIds", builder.build().getProtocolIds()); } @Test void tag() { ServiceBuilder builder = new ServiceBuilder(); builder.tag("tag"); Assertions.assertEquals("tag", builder.build().getTag()); } @Test void executes() { ServiceBuilder builder = new ServiceBuilder(); builder.executes(10); Assertions.assertEquals(10, builder.build().getExecutes()); } @Test void register() { ServiceBuilder builder = new ServiceBuilder(); builder.register(true); Assertions.assertTrue(builder.build().isRegister()); builder.register(false); Assertions.assertFalse(builder.build().isRegister()); } @Test void warmup() { ServiceBuilder builder = new ServiceBuilder(); builder.warmup(100); Assertions.assertEquals(100, builder.build().getWarmup()); } @Test void serialization() { ServiceBuilder builder = new ServiceBuilder(); builder.serialization("serialization"); Assertions.assertEquals("serialization", builder.build().getSerialization()); } @Test void build() { ProtocolConfig protocol = new ProtocolConfig(); ServiceBuilder builder = new ServiceBuilder(); builder.version("version") .group("group") .deprecated(true) .delay(1000) .export(false) .weight(1) .document("document") .dynamic(true) .token("token") .accesslog("accesslog") .addProtocol(protocol) .protocolIds("protocolIds") .tag("tag") .executes(100) .register(false) .warmup(200) .serialization("serialization") .id("id"); ServiceConfig config = builder.build(); ServiceConfig config2 = builder.build(); Assertions.assertEquals("id", config.getId()); Assertions.assertEquals("version", config.getVersion()); Assertions.assertEquals("group", config.getGroup()); Assertions.assertEquals("document", config.getDocument()); Assertions.assertEquals("token", config.getToken()); Assertions.assertEquals("accesslog", config.getAccesslog()); Assertions.assertEquals("protocolIds", config.getProtocolIds()); Assertions.assertEquals("tag", config.getTag()); Assertions.assertEquals("serialization", config.getSerialization()); Assertions.assertTrue(config.isDeprecated()); Assertions.assertFalse(config.getExport()); Assertions.assertTrue(config.isDynamic()); Assertions.assertFalse(config.isRegister()); Assertions.assertEquals(1000, config.getDelay()); Assertions.assertEquals(1, config.getWeight()); Assertions.assertEquals(100, config.getExecutes()); Assertions.assertEquals(200, config.getWarmup()); Assertions.assertNotSame(config, config2); } private static class ServiceBuilder extends AbstractServiceBuilder<ServiceConfig, ServiceBuilder> { public ServiceConfig build() { ServiceConfig parameterConfig = new ServiceConfig(); super.build(parameterConfig); return parameterConfig; } @Override protected ServiceBuilder getThis() { return this; } } private static class ServiceConfig extends AbstractServiceConfig {} }
8,458
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MethodBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.ArgumentConfig; import org.apache.dubbo.config.MethodConfig; import java.util.Collections; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class MethodBuilderTest { @Test void name() { MethodBuilder builder = new MethodBuilder(); builder.name("name"); Assertions.assertEquals("name", builder.build().getName()); } @Test void stat() { MethodBuilder builder = new MethodBuilder(); builder.stat(1); Assertions.assertEquals(1, builder.build().getStat()); } @Test void retry() { MethodBuilder builder = new MethodBuilder(); builder.retry(true); Assertions.assertTrue(builder.build().isRetry()); } @Test void reliable() { MethodBuilder builder = new MethodBuilder(); builder.reliable(true); Assertions.assertTrue(builder.build().isReliable()); } @Test void executes() { MethodBuilder builder = new MethodBuilder(); builder.executes(1); Assertions.assertEquals(1, builder.build().getExecutes()); } @Test void deprecated() { MethodBuilder builder = new MethodBuilder(); builder.deprecated(true); Assertions.assertTrue(builder.build().getDeprecated()); } @Test void sticky() { MethodBuilder builder = new MethodBuilder(); builder.sticky(true); Assertions.assertTrue(builder.build().getSticky()); } @Test void isReturn() { MethodBuilder builder = new MethodBuilder(); builder.isReturn(true); Assertions.assertTrue(builder.build().isReturn()); } @Test void oninvoke() { MethodBuilder builder = new MethodBuilder(); builder.oninvoke("on-invoke-object"); Assertions.assertEquals("on-invoke-object", builder.build().getOninvoke()); } @Test void oninvokeMethod() { MethodBuilder builder = new MethodBuilder(); builder.oninvokeMethod("on-invoke-method"); Assertions.assertEquals("on-invoke-method", builder.build().getOninvokeMethod()); } @Test void onreturn() { MethodBuilder builder = new MethodBuilder(); builder.onreturn("on-return-object"); Assertions.assertEquals("on-return-object", builder.build().getOnreturn()); } @Test void onreturnMethod() { MethodBuilder builder = new MethodBuilder(); builder.onreturnMethod("on-return-method"); Assertions.assertEquals("on-return-method", builder.build().getOnreturnMethod()); } @Test void onthrow() { MethodBuilder builder = new MethodBuilder(); builder.onthrow("on-throw-object"); Assertions.assertEquals("on-throw-object", builder.build().getOnthrow()); } @Test void onthrowMethod() { MethodBuilder builder = new MethodBuilder(); builder.onthrowMethod("on-throw-method"); Assertions.assertEquals("on-throw-method", builder.build().getOnthrowMethod()); } @Test void addArguments() { ArgumentConfig argument = new ArgumentConfig(); MethodBuilder builder = new MethodBuilder(); builder.addArguments(Collections.singletonList(argument)); Assertions.assertTrue(builder.build().getArguments().contains(argument)); Assertions.assertEquals(1, builder.build().getArguments().size()); } @Test void addArgument() { ArgumentConfig argument = new ArgumentConfig(); MethodBuilder builder = new MethodBuilder(); builder.addArgument(argument); Assertions.assertTrue(builder.build().getArguments().contains(argument)); Assertions.assertEquals(1, builder.build().getArguments().size()); } @Test void service() { MethodBuilder builder = new MethodBuilder(); builder.service("service"); Assertions.assertEquals("service", builder.build().getService()); } @Test void serviceId() { MethodBuilder builder = new MethodBuilder(); builder.serviceId("serviceId"); Assertions.assertEquals("serviceId", builder.build().getServiceId()); } @Test void build() { ArgumentConfig argument = new ArgumentConfig(); MethodBuilder builder = new MethodBuilder(); builder.name("name") .stat(1) .retry(true) .reliable(false) .executes(2) .deprecated(true) .sticky(false) .isReturn(true) .oninvoke("on-invoke-object") .oninvokeMethod("on-invoke-method") .service("service") .onreturn("on-return-object") .onreturnMethod("on-return-method") .serviceId("serviceId") .onthrow("on-throw-object") .onthrowMethod("on-throw-method") .addArgument(argument); MethodConfig config = builder.build(); MethodConfig config2 = builder.build(); Assertions.assertTrue(config.isRetry()); Assertions.assertFalse(config.isReliable()); Assertions.assertTrue(config.getDeprecated()); Assertions.assertFalse(config.getSticky()); Assertions.assertTrue(config.isReturn()); Assertions.assertEquals(1, config.getStat()); Assertions.assertEquals(2, config.getExecutes()); Assertions.assertEquals("on-invoke-object", config.getOninvoke()); Assertions.assertEquals("on-invoke-method", config.getOninvokeMethod()); Assertions.assertEquals("on-return-object", config.getOnreturn()); Assertions.assertEquals("on-return-method", config.getOnreturnMethod()); Assertions.assertEquals("on-throw-object", config.getOnthrow()); Assertions.assertEquals("on-throw-method", config.getOnthrowMethod()); Assertions.assertEquals("name", config.getName()); Assertions.assertEquals("service", config.getService()); Assertions.assertEquals("serviceId", config.getServiceId()); Assertions.assertNotSame(config, config2); } }
8,459
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractReferenceBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.AbstractReferenceConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import static org.apache.dubbo.common.constants.CommonConstants.GENERIC_SERIALIZATION_BEAN; class AbstractReferenceBuilderTest { @Test void check() { ReferenceBuilder builder = new ReferenceBuilder(); builder.check(true); Assertions.assertTrue(builder.build().isCheck()); builder.check(false); Assertions.assertFalse(builder.build().isCheck()); } @Test void init() { ReferenceBuilder builder = new ReferenceBuilder(); builder.init(true); Assertions.assertTrue(builder.build().isInit()); builder.init(false); Assertions.assertFalse(builder.build().isInit()); } @Test void generic() { ReferenceBuilder builder = new ReferenceBuilder(); builder.generic(true); Assertions.assertTrue(builder.build().isGeneric()); builder.generic(false); Assertions.assertFalse(builder.build().isGeneric()); } @Test void generic1() { ReferenceBuilder builder = new ReferenceBuilder(); builder.generic(GENERIC_SERIALIZATION_BEAN); Assertions.assertEquals(GENERIC_SERIALIZATION_BEAN, builder.build().getGeneric()); } @Test void injvm() { ReferenceBuilder builder = new ReferenceBuilder(); builder.injvm(true); Assertions.assertTrue(builder.build().isInjvm()); builder.injvm(false); Assertions.assertFalse(builder.build().isInjvm()); } @Test void lazy() { ReferenceBuilder builder = new ReferenceBuilder(); builder.lazy(true); Assertions.assertTrue(builder.build().getLazy()); builder.lazy(false); Assertions.assertFalse(builder.build().getLazy()); } @Test void reconnect() { ReferenceBuilder builder = new ReferenceBuilder(); builder.reconnect("reconnect"); Assertions.assertEquals("reconnect", builder.build().getReconnect()); } @Test void sticky() { ReferenceBuilder builder = new ReferenceBuilder(); builder.sticky(true); Assertions.assertTrue(builder.build().getSticky()); builder.sticky(false); Assertions.assertFalse(builder.build().getSticky()); } @Test void version() { ReferenceBuilder builder = new ReferenceBuilder(); builder.version("version"); Assertions.assertEquals("version", builder.build().getVersion()); } @Test void group() { ReferenceBuilder builder = new ReferenceBuilder(); builder.group("group"); Assertions.assertEquals("group", builder.build().getGroup()); } @Test void build() { ReferenceBuilder builder = new ReferenceBuilder(); builder.check(true) .init(false) .generic(true) .injvm(false) .lazy(true) .reconnect("reconnect") .sticky(false) .version("version") .group("group") .id("id"); ReferenceConfig config = builder.build(); ReferenceConfig config2 = builder.build(); Assertions.assertEquals("id", config.getId()); Assertions.assertTrue(config.isCheck()); Assertions.assertFalse(config.isInit()); Assertions.assertTrue(config.isGeneric()); Assertions.assertFalse(config.isInjvm()); Assertions.assertTrue(config.getLazy()); Assertions.assertFalse(config.getSticky()); Assertions.assertEquals("reconnect", config.getReconnect()); Assertions.assertEquals("version", config.getVersion()); Assertions.assertEquals("group", config.getGroup()); Assertions.assertNotSame(config, config2); } private static class ReferenceBuilder extends AbstractReferenceBuilder<ReferenceConfig, ReferenceBuilder> { public ReferenceConfig build() { ReferenceConfig parameterConfig = new ReferenceConfig(); super.build(parameterConfig); return parameterConfig; } @Override protected ReferenceBuilder getThis() { return this; } } private static class ReferenceConfig extends AbstractReferenceConfig {} }
8,460
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ApplicationBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MonitorConfig; import org.apache.dubbo.config.RegistryConfig; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ApplicationBuilderTest { @Test void name() { ApplicationBuilder builder = new ApplicationBuilder(); builder.name("app"); Assertions.assertEquals("app", builder.build().getName()); } @Test void version() { ApplicationBuilder builder = new ApplicationBuilder(); builder.version("version"); Assertions.assertEquals("version", builder.build().getVersion()); } @Test void owner() { ApplicationBuilder builder = new ApplicationBuilder(); builder.owner("owner"); Assertions.assertEquals("owner", builder.build().getOwner()); } @Test void organization() { ApplicationBuilder builder = new ApplicationBuilder(); builder.organization("organization"); Assertions.assertEquals("organization", builder.build().getOrganization()); } @Test void architecture() { ApplicationBuilder builder = new ApplicationBuilder(); builder.architecture("architecture"); Assertions.assertEquals("architecture", builder.build().getArchitecture()); } @Test void environment() { ApplicationBuilder builder = new ApplicationBuilder(); Assertions.assertEquals("product", builder.build().getEnvironment()); builder.environment("develop"); Assertions.assertEquals("develop", builder.build().getEnvironment()); builder.environment("test"); Assertions.assertEquals("test", builder.build().getEnvironment()); builder.environment("product"); Assertions.assertEquals("product", builder.build().getEnvironment()); } @Test void compiler() { ApplicationBuilder builder = new ApplicationBuilder(); builder.compiler("compiler"); Assertions.assertEquals("compiler", builder.build().getCompiler()); } @Test void logger() { ApplicationBuilder builder = new ApplicationBuilder(); builder.logger("log4j"); Assertions.assertEquals("log4j", builder.build().getLogger()); } @Test void addRegistry() { RegistryConfig registry = new RegistryConfig(); ApplicationBuilder builder = new ApplicationBuilder(); builder.addRegistry(registry); Assertions.assertNotNull(builder.build().getRegistry()); Assertions.assertEquals(1, builder.build().getRegistries().size()); Assertions.assertSame(registry, builder.build().getRegistry()); } @Test void addRegistries() { RegistryConfig registry = new RegistryConfig(); ApplicationBuilder builder = new ApplicationBuilder(); builder.addRegistries(Collections.singletonList(registry)); Assertions.assertNotNull(builder.build().getRegistry()); Assertions.assertEquals(1, builder.build().getRegistries().size()); Assertions.assertSame(registry, builder.build().getRegistry()); } @Test void registryIds() { ApplicationBuilder builder = new ApplicationBuilder(); builder.registryIds("registryIds"); Assertions.assertEquals("registryIds", builder.build().getRegistryIds()); } @Test void monitor() { MonitorConfig monitor = new MonitorConfig("monitor-addr"); ApplicationBuilder builder = new ApplicationBuilder(); builder.monitor(monitor); Assertions.assertSame(monitor, builder.build().getMonitor()); Assertions.assertEquals("monitor-addr", builder.build().getMonitor().getAddress()); } @Test void monitor1() { ApplicationBuilder builder = new ApplicationBuilder(); builder.monitor("monitor-addr"); Assertions.assertEquals("monitor-addr", builder.build().getMonitor().getAddress()); } @Test void isDefault() { ApplicationBuilder builder = new ApplicationBuilder(); builder.isDefault(true); Assertions.assertTrue(builder.build().isDefault()); builder.isDefault(false); Assertions.assertFalse(builder.build().isDefault()); builder.isDefault(null); Assertions.assertNull(builder.build().isDefault()); } @Test void dumpDirectory() { ApplicationBuilder builder = new ApplicationBuilder(); builder.dumpDirectory("dumpDirectory"); Assertions.assertEquals("dumpDirectory", builder.build().getDumpDirectory()); } @Test void qosEnable() { ApplicationBuilder builder = new ApplicationBuilder(); builder.qosEnable(true); Assertions.assertTrue(builder.build().getQosEnable()); builder.qosEnable(false); Assertions.assertFalse(builder.build().getQosEnable()); builder.qosEnable(null); Assertions.assertNull(builder.build().getQosEnable()); } @Test void qosPort() { ApplicationBuilder builder = new ApplicationBuilder(); builder.qosPort(8080); Assertions.assertEquals(8080, builder.build().getQosPort()); } @Test void qosAcceptForeignIp() { ApplicationBuilder builder = new ApplicationBuilder(); builder.qosAcceptForeignIp(true); Assertions.assertTrue(builder.build().getQosAcceptForeignIp()); builder.qosAcceptForeignIp(false); Assertions.assertFalse(builder.build().getQosAcceptForeignIp()); builder.qosAcceptForeignIp(null); Assertions.assertNull(builder.build().getQosAcceptForeignIp()); } @Test void shutwait() { ApplicationBuilder builder = new ApplicationBuilder(); builder.shutwait("shutwait"); Assertions.assertEquals("shutwait", builder.build().getShutwait()); } @Test void appendParameter() { ApplicationBuilder builder = new ApplicationBuilder(); builder.appendParameter("default.num", "one").appendParameter("num", "ONE"); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void appendParameters() { Map<String, String> source = new HashMap<>(); source.put("default.num", "one"); source.put("num", "ONE"); ApplicationBuilder builder = new ApplicationBuilder(); builder.appendParameters(source); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void metadataServicePort() { ApplicationBuilder builder = new ApplicationBuilder(); builder.metadataServicePort(12345); Assertions.assertEquals(12345, builder.build().getMetadataServicePort()); } @Test void livenessProbe() { ApplicationBuilder builder = new ApplicationBuilder(); builder.livenessProbe("TestProbe"); Assertions.assertEquals("TestProbe", builder.build().getLivenessProbe()); } @Test void readinessProbe() { ApplicationBuilder builder = new ApplicationBuilder(); builder.readinessProbe("TestProbe"); Assertions.assertEquals("TestProbe", builder.build().getReadinessProbe()); } @Test void startupProbe() { ApplicationBuilder builder = new ApplicationBuilder(); builder.startupProbe("TestProbe"); Assertions.assertEquals("TestProbe", builder.build().getStartupProbe()); } @Test void build() { MonitorConfig monitor = new MonitorConfig("monitor-addr"); RegistryConfig registry = new RegistryConfig(); ApplicationBuilder builder = new ApplicationBuilder(); builder.id("id") .name("name") .version("version") .owner("owner") .organization("organization") .architecture("architecture") .environment("develop") .compiler("compiler") .logger("log4j") .monitor(monitor) .isDefault(false) .dumpDirectory("dumpDirectory") .qosEnable(true) .qosPort(8080) .qosAcceptForeignIp(false) .shutwait("shutwait") .registryIds("registryIds") .addRegistry(registry) .appendParameter("default.num", "one") .metadataServicePort(12345) .livenessProbe("liveness") .readinessProbe("readiness") .startupProbe("startup"); ApplicationConfig config = builder.build(); ApplicationConfig config2 = builder.build(); Assertions.assertEquals("id", config.getId()); Assertions.assertEquals("name", config.getName()); Assertions.assertEquals("version", config.getVersion()); Assertions.assertEquals("owner", config.getOwner()); Assertions.assertEquals("organization", config.getOrganization()); Assertions.assertEquals("architecture", config.getArchitecture()); Assertions.assertEquals("develop", config.getEnvironment()); Assertions.assertEquals("compiler", config.getCompiler()); Assertions.assertEquals("log4j", config.getLogger()); Assertions.assertSame(monitor, config.getMonitor()); Assertions.assertFalse(config.isDefault()); Assertions.assertEquals("dumpDirectory", config.getDumpDirectory()); Assertions.assertTrue(config.getQosEnable()); Assertions.assertEquals(8080, config.getQosPort()); Assertions.assertFalse(config.getQosAcceptForeignIp()); Assertions.assertEquals("shutwait", config.getShutwait()); Assertions.assertEquals("registryIds", config.getRegistryIds()); Assertions.assertSame(registry, config.getRegistry()); Assertions.assertTrue(config.getParameters().containsKey("default.num")); Assertions.assertEquals("one", config.getParameters().get("default.num")); Assertions.assertEquals(12345, config.getMetadataServicePort()); Assertions.assertEquals("liveness", config.getLivenessProbe()); Assertions.assertEquals("readiness", config.getReadinessProbe()); Assertions.assertEquals("startup", config.getStartupProbe()); Assertions.assertNotSame(config, config2); } }
8,461
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/MonitorBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.MonitorConfig; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class MonitorBuilderTest { @Test void protocol() { MonitorBuilder builder = new MonitorBuilder(); builder.protocol("protocol"); Assertions.assertEquals("protocol", builder.build().getProtocol()); } @Test void address() { MonitorBuilder builder = new MonitorBuilder(); builder.address("address"); Assertions.assertEquals("address", builder.build().getAddress()); } @Test void username() { MonitorBuilder builder = new MonitorBuilder(); builder.username("username"); Assertions.assertEquals("username", builder.build().getUsername()); } @Test void password() { MonitorBuilder builder = new MonitorBuilder(); builder.password("password"); Assertions.assertEquals("password", builder.build().getPassword()); } @Test void group() { MonitorBuilder builder = new MonitorBuilder(); builder.group("group"); Assertions.assertEquals("group", builder.build().getGroup()); } @Test void version() { MonitorBuilder builder = new MonitorBuilder(); builder.version("version"); Assertions.assertEquals("version", builder.build().getVersion()); } @Test void interval() { MonitorBuilder builder = new MonitorBuilder(); builder.interval("interval"); Assertions.assertEquals("interval", builder.build().getInterval()); } @Test void isDefault() { MonitorBuilder builder = new MonitorBuilder(); builder.isDefault(true); Assertions.assertTrue(builder.build().isDefault()); } @Test void appendParameter() { MonitorBuilder builder = new MonitorBuilder(); builder.appendParameter("default.num", "one").appendParameter("num", "ONE"); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void appendParameters() { Map<String, String> source = new HashMap<>(); source.put("default.num", "one"); source.put("num", "ONE"); MonitorBuilder builder = new MonitorBuilder(); builder.appendParameters(source); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void build() { MonitorBuilder builder = new MonitorBuilder(); builder.protocol("protocol") .address("address") .group("group") .interval("interval") .isDefault(true) .password("password") .username("username") .version("version") .appendParameter("default.num", "one") .id("id"); MonitorConfig config = builder.build(); MonitorConfig config2 = builder.build(); Assertions.assertEquals("protocol", config.getProtocol()); Assertions.assertEquals("address", config.getAddress()); Assertions.assertEquals("group", config.getGroup()); Assertions.assertEquals("interval", config.getInterval()); Assertions.assertEquals("password", config.getPassword()); Assertions.assertEquals("username", config.getUsername()); Assertions.assertEquals("version", config.getVersion()); Assertions.assertTrue(config.isDefault()); Assertions.assertTrue(config.getParameters().containsKey("default.num")); Assertions.assertEquals("one", config.getParameters().get("default.num")); Assertions.assertEquals("id", config.getId()); Assertions.assertNotSame(config, config2); } }
8,462
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.AbstractConfig; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class AbstractBuilderTest { @Test void id() { Builder builder = new Builder(); builder.id("id"); Assertions.assertEquals("id", builder.build().getId()); } @Test void appendParameter() { Map<String, String> source = null; Map<String, String> parameters = new HashMap<>(); parameters.put("default.num", "one"); parameters.put("num", "ONE"); source = AbstractBuilder.appendParameters(source, parameters); Assertions.assertTrue(source.containsKey("default.num")); Assertions.assertEquals("ONE", source.get("num")); } @Test void appendParameter2() { Map<String, String> source = new HashMap<>(); source.put("default.num", "one1"); source.put("num", "ONE1"); Map<String, String> parameters = new HashMap<>(); parameters.put("default.num", "one"); parameters.put("num", "ONE"); source = AbstractBuilder.appendParameters(source, parameters); Assertions.assertTrue(source.containsKey("default.num")); Assertions.assertEquals("ONE", source.get("num")); } @Test void appendParameters() { Map<String, String> source = null; source = AbstractBuilder.appendParameter(source, "default.num", "one"); source = AbstractBuilder.appendParameter(source, "num", "ONE"); Assertions.assertTrue(source.containsKey("default.num")); Assertions.assertEquals("ONE", source.get("num")); } @Test void appendParameters2() { Map<String, String> source = new HashMap<>(); source.put("default.num", "one1"); source.put("num", "ONE1"); source = AbstractBuilder.appendParameter(source, "default.num", "one"); source = AbstractBuilder.appendParameter(source, "num", "ONE"); Assertions.assertTrue(source.containsKey("default.num")); Assertions.assertEquals("ONE", source.get("num")); } @Test void build() { Builder builder = new Builder(); builder.id("id"); Config config = builder.build(); Config config2 = builder.build(); Assertions.assertEquals("id", config.getId()); Assertions.assertNotSame(config, config2); } private static class Builder extends AbstractBuilder<Config, Builder> { public Config build() { Config parameterConfig = new Config(); super.build(parameterConfig); return parameterConfig; } @Override protected Builder getThis() { return this; } } private static class Config extends AbstractConfig {} }
8,463
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/ProtocolBuilderTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.builders; import org.apache.dubbo.config.ProtocolConfig; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ProtocolBuilderTest { @Test void name() { ProtocolBuilder builder = new ProtocolBuilder(); builder.name("name"); Assertions.assertEquals("name", builder.build().getName()); } @Test void host() { ProtocolBuilder builder = new ProtocolBuilder(); builder.host("host"); Assertions.assertEquals("host", builder.build().getHost()); } @Test void port() { ProtocolBuilder builder = new ProtocolBuilder(); builder.port(8080); Assertions.assertEquals(8080, builder.build().getPort()); } @Test void contextpath() { ProtocolBuilder builder = new ProtocolBuilder(); builder.contextpath("contextpath"); Assertions.assertEquals("contextpath", builder.build().getContextpath()); } @Test void path() { ProtocolBuilder builder = new ProtocolBuilder(); builder.path("path"); Assertions.assertEquals("path", builder.build().getPath()); } @Test void threadpool() { ProtocolBuilder builder = new ProtocolBuilder(); builder.threadpool("mockthreadpool"); Assertions.assertEquals("mockthreadpool", builder.build().getThreadpool()); } @Test void corethreads() { ProtocolBuilder builder = new ProtocolBuilder(); builder.corethreads(10); Assertions.assertEquals(10, builder.build().getCorethreads()); } @Test void threads() { ProtocolBuilder builder = new ProtocolBuilder(); builder.threads(20); Assertions.assertEquals(20, builder.build().getThreads()); } @Test void iothreads() { ProtocolBuilder builder = new ProtocolBuilder(); builder.iothreads(25); Assertions.assertEquals(25, builder.build().getIothreads()); } @Test void queues() { ProtocolBuilder builder = new ProtocolBuilder(); builder.queues(30); Assertions.assertEquals(30, builder.build().getQueues()); } @Test void accepts() { ProtocolBuilder builder = new ProtocolBuilder(); builder.accepts(35); Assertions.assertEquals(35, builder.build().getAccepts()); } @Test void codec() { ProtocolBuilder builder = new ProtocolBuilder(); builder.codec("mockcodec"); Assertions.assertEquals("mockcodec", builder.build().getCodec()); } @Test void serialization() { ProtocolBuilder builder = new ProtocolBuilder(); builder.serialization("serialization"); Assertions.assertEquals("serialization", builder.build().getSerialization()); } @Test void charset() { ProtocolBuilder builder = new ProtocolBuilder(); builder.charset("utf-8"); Assertions.assertEquals("utf-8", builder.build().getCharset()); } @Test void payload() { ProtocolBuilder builder = new ProtocolBuilder(); builder.payload(40); Assertions.assertEquals(40, builder.build().getPayload()); } @Test void buffer() { ProtocolBuilder builder = new ProtocolBuilder(); builder.buffer(1024); Assertions.assertEquals(1024, builder.build().getBuffer()); } @Test void heartbeat() { ProtocolBuilder builder = new ProtocolBuilder(); builder.heartbeat(1000); Assertions.assertEquals(1000, builder.build().getHeartbeat()); } @Test void accesslog() { ProtocolBuilder builder = new ProtocolBuilder(); builder.accesslog("accesslog"); Assertions.assertEquals("accesslog", builder.build().getAccesslog()); } @Test void transporter() { ProtocolBuilder builder = new ProtocolBuilder(); builder.transporter("mocktransporter"); Assertions.assertEquals("mocktransporter", builder.build().getTransporter()); } @Test void exchanger() { ProtocolBuilder builder = new ProtocolBuilder(); builder.exchanger("mockexchanger"); Assertions.assertEquals("mockexchanger", builder.build().getExchanger()); } @Test void dispatcher() { ProtocolBuilder builder = new ProtocolBuilder(); builder.dispatcher("mockdispatcher"); Assertions.assertEquals("mockdispatcher", builder.build().getDispatcher()); } @Test void dispather() { ProtocolBuilder builder = new ProtocolBuilder(); builder.dispather("mockdispatcher"); Assertions.assertEquals("mockdispatcher", builder.build().getDispather()); } @Test void networker() { ProtocolBuilder builder = new ProtocolBuilder(); builder.networker("networker"); Assertions.assertEquals("networker", builder.build().getNetworker()); } @Test void server() { ProtocolBuilder builder = new ProtocolBuilder(); builder.server("server"); Assertions.assertEquals("server", builder.build().getServer()); } @Test void client() { ProtocolBuilder builder = new ProtocolBuilder(); builder.client("client"); Assertions.assertEquals("client", builder.build().getClient()); } @Test void telnet() { ProtocolBuilder builder = new ProtocolBuilder(); builder.telnet("mocktelnethandler"); Assertions.assertEquals("mocktelnethandler", builder.build().getTelnet()); } @Test void prompt() { ProtocolBuilder builder = new ProtocolBuilder(); builder.prompt("prompt"); Assertions.assertEquals("prompt", builder.build().getPrompt()); } @Test void status() { ProtocolBuilder builder = new ProtocolBuilder(); builder.status("mockstatuschecker"); Assertions.assertEquals("mockstatuschecker", builder.build().getStatus()); } @Test void register() { ProtocolBuilder builder = new ProtocolBuilder(); builder.register(true); Assertions.assertTrue(builder.build().isRegister()); } @Test void keepAlive() { ProtocolBuilder builder = new ProtocolBuilder(); builder.keepAlive(true); Assertions.assertTrue(builder.build().getKeepAlive()); } @Test void optimizer() { ProtocolBuilder builder = new ProtocolBuilder(); builder.optimizer("optimizer"); Assertions.assertEquals("optimizer", builder.build().getOptimizer()); } @Test void extension() { ProtocolBuilder builder = new ProtocolBuilder(); builder.extension("extension"); Assertions.assertEquals("extension", builder.build().getExtension()); } @Test void appendParameter() { ProtocolBuilder builder = new ProtocolBuilder(); builder.appendParameter("default.num", "one").appendParameter("num", "ONE"); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void appendParameters() { Map<String, String> source = new HashMap<>(); source.put("default.num", "one"); source.put("num", "ONE"); ProtocolBuilder builder = new ProtocolBuilder(); builder.appendParameters(source); Map<String, String> parameters = builder.build().getParameters(); Assertions.assertTrue(parameters.containsKey("default.num")); Assertions.assertEquals("ONE", parameters.get("num")); } @Test void isDefault() { ProtocolBuilder builder = new ProtocolBuilder(); builder.isDefault(true); Assertions.assertTrue(builder.build().isDefault()); } @Test void build() { ProtocolBuilder builder = new ProtocolBuilder(); builder.name("name") .host("host") .port(8080) .contextpath("contextpath") .threadpool("mockthreadpool") .corethreads(1) .threads(2) .iothreads(3) .queues(4) .accepts(5) .codec("mockcodec") .serialization("serialization") .charset("utf-8") .payload(6) .buffer(1024) .heartbeat(1000) .accesslog("accesslog") .transporter("mocktransporter") .exchanger("mockexchanger") .dispatcher("mockdispatcher") .networker("networker") .server("server") .client("client") .telnet("mocktelnethandler") .prompt("prompt") .status("mockstatuschecker") .register(true) .keepAlive(false) .optimizer("optimizer") .extension("extension") .isDefault(true) .appendParameter("default.num", "one") .id("id"); ProtocolConfig config = builder.build(); ProtocolConfig config2 = builder.build(); Assertions.assertEquals(8080, config.getPort()); Assertions.assertEquals(1, config.getCorethreads()); Assertions.assertEquals(2, config.getThreads()); Assertions.assertEquals(3, config.getIothreads()); Assertions.assertEquals(4, config.getQueues()); Assertions.assertEquals(5, config.getAccepts()); Assertions.assertEquals(6, config.getPayload()); Assertions.assertEquals(1024, config.getBuffer()); Assertions.assertEquals(1000, config.getHeartbeat()); Assertions.assertEquals("name", config.getName()); Assertions.assertEquals("host", config.getHost()); Assertions.assertEquals("contextpath", config.getContextpath()); Assertions.assertEquals("mockthreadpool", config.getThreadpool()); Assertions.assertEquals("mockcodec", config.getCodec()); Assertions.assertEquals("serialization", config.getSerialization()); Assertions.assertEquals("utf-8", config.getCharset()); Assertions.assertEquals("accesslog", config.getAccesslog()); Assertions.assertEquals("mocktransporter", config.getTransporter()); Assertions.assertEquals("mockexchanger", config.getExchanger()); Assertions.assertEquals("mockdispatcher", config.getDispatcher()); Assertions.assertEquals("networker", config.getNetworker()); Assertions.assertEquals("server", config.getServer()); Assertions.assertEquals("client", config.getClient()); Assertions.assertEquals("mocktelnethandler", config.getTelnet()); Assertions.assertEquals("prompt", config.getPrompt()); Assertions.assertEquals("mockstatuschecker", config.getStatus()); Assertions.assertEquals("optimizer", config.getOptimizer()); Assertions.assertEquals("extension", config.getExtension()); Assertions.assertTrue(config.isRegister()); Assertions.assertFalse(config.getKeepAlive()); Assertions.assertTrue(config.isDefault()); Assertions.assertTrue(config.getParameters().containsKey("default.num")); Assertions.assertEquals("one", config.getParameters().get("default.num")); Assertions.assertEquals("id", config.getId()); Assertions.assertNotSame(config, config2); } }
8,464
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.rest; import org.apache.dubbo.rpc.protocol.rest.support.ContentType; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; @Path("users") @Consumes({MediaType.APPLICATION_JSON, MediaType.TEXT_XML}) @Produces({ContentType.APPLICATION_JSON_UTF_8, ContentType.TEXT_XML_UTF_8}) @Api(value = "UserService") public interface UserService { @GET @Path("{id : \\d+}") @ApiOperation(value = "getUser") User getUser(@ApiParam(value = "id") @PathParam("id") Long id); }
8,465
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/User.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.rest; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.io.Serializable; import org.codehaus.jackson.annotate.JsonProperty; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class User implements Serializable { @NotNull @Min(1L) private Long id; @JsonProperty("username") @XmlElement(name = "username") @NotNull @Size(min = 6, max = 50) private String name; public User() {} public User(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "User (" + "id=" + id + ", name='" + name + '\'' + ')'; } }
8,466
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/rest/UserServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.bootstrap.rest; import java.util.concurrent.atomic.AtomicLong; public class UserServiceImpl implements UserService { private final AtomicLong idGen = new AtomicLong(); @Override public User getUser(Long id) { return new User(id, "username" + id); } }
8,467
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.cache; /** * ValidationService */ public interface CacheService { String findCache(String id); }
8,468
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.cache; import java.util.concurrent.atomic.AtomicInteger; /** * ValidationServiceImpl */ public class CacheServiceImpl implements CacheService { private final AtomicInteger i = new AtomicInteger(); public String findCache(String id) { return "request: " + id + ", response: " + i.getAndIncrement(); } }
8,469
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/cache/CacheTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.cache; import org.apache.dubbo.cache.Cache; import org.apache.dubbo.cache.CacheFactory; import org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.common.url.component.ServiceConfigURL; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.MethodConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.RpcInvocation; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * CacheTest */ class CacheTest { @BeforeEach public void setUp() { DubboBootstrap.reset(); } @AfterEach public void tearDown() { // ApplicationModel.defaultModel().getConfigManager().clear(); } private void testCache(String type) throws Exception { ApplicationConfig applicationConfig = new ApplicationConfig("cache-test"); RegistryConfig registryConfig = new RegistryConfig("N/A"); ProtocolConfig protocolConfig = new ProtocolConfig("injvm"); ServiceConfig<CacheService> service = new ServiceConfig<CacheService>(); service.setApplication(applicationConfig); service.setRegistry(registryConfig); service.setProtocol(protocolConfig); service.setInterface(CacheService.class.getName()); service.setRef(new CacheServiceImpl()); service.export(); try { ReferenceConfig<CacheService> reference = new ReferenceConfig<CacheService>(); reference.setApplication(applicationConfig); reference.setInterface(CacheService.class); reference.setUrl("injvm://127.0.0.1?scope=remote&cache=true"); MethodConfig method = new MethodConfig(); method.setName("findCache"); method.setCache(type); reference.setMethods(Arrays.asList(method)); CacheService cacheService = reference.get(); try { // verify cache, same result is returned for multiple invocations (in fact, the return value increases // on every invocation on the server side) String fix = null; cacheService.findCache("0"); for (int i = 0; i < 3; i++) { String result = cacheService.findCache("0"); assertTrue(fix == null || fix.equals(result)); fix = result; Thread.sleep(100); } if ("lru".equals(type)) { // default cache.size is 1000 for LRU, should have cache expired if invoke more than 1001 times for (int n = 0; n < 1001; n++) { String pre = null; cacheService.findCache(String.valueOf(n)); for (int i = 0; i < 10; i++) { String result = cacheService.findCache(String.valueOf(n)); assertTrue(pre == null || pre.equals(result)); pre = result; } } // verify if the first cache item is expired in LRU cache String result = cacheService.findCache("0"); assertFalse(fix == null || fix.equals(result)); } } finally { reference.destroy(); } } finally { service.unexport(); } } @Test void testCacheLru() throws Exception { testCache("lru"); } @Test void testCacheThreadlocal() throws Exception { testCache("threadlocal"); } @Test void testCacheProvider() { CacheFactory cacheFactory = ExtensionLoader.getExtensionLoader(CacheFactory.class).getAdaptiveExtension(); Map<String, String> parameters = new HashMap<String, String>(); parameters.put("findCache.cache", "threadlocal"); URL url = new ServiceConfigURL( "dubbo", "127.0.0.1", 29582, "org.apache.dubbo.config.cache.CacheService", parameters); Invocation invocation = new RpcInvocation( "findCache", CacheService.class.getName(), "", new Class[] {String.class}, new String[] {"0"}, null, null, null); Cache cache = cacheFactory.getCache(url, invocation); assertTrue(cache instanceof ThreadLocalCache); } }
8,470
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/deploy/DefaultApplicationDeployerTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.deploy; import org.apache.dubbo.common.utils.Assert; import org.apache.dubbo.rpc.model.ApplicationModel; import org.junit.jupiter.api.Test; class DefaultApplicationDeployerTest { @Test void isSupportPrometheus() { boolean supportPrometheus = new DefaultApplicationDeployer(ApplicationModel.defaultModel()).isSupportPrometheus(); Assert.assertTrue(supportPrometheus, "DefaultApplicationDeployer.isSupportPrometheus() should return true"); } }
8,471
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterExporterListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.RpcException; import org.apache.dubbo.rpc.cluster.filter.FilterChainBuilder; import org.apache.dubbo.rpc.listener.ListenerExporterWrapper; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; /** * The abstraction of {@link ExporterListener} is to record exported exporters, which should be extended by different sub-classes. */ public abstract class AbstractRegistryCenterExporterListener implements ExporterListener { /** * Exported exporters. */ private List<Exporter<?>> exportedExporters = new ArrayList(); /** * Resolve all filters */ private Set<Filter> filters = new HashSet<>(); /** * Returns the interface of exported service. */ protected abstract Class<?> getInterface(); /** * {@inheritDoc} */ @Override public void exported(Exporter<?> exporter) throws RpcException { ListenerExporterWrapper listenerExporterWrapper = (ListenerExporterWrapper) exporter; Invoker invoker = listenerExporterWrapper.getInvoker(); if (!(invoker instanceof FilterChainBuilder.CallbackRegistrationInvoker)) { exportedExporters.add(exporter); return; } FilterChainBuilder.CallbackRegistrationInvoker callbackRegistrationInvoker = (FilterChainBuilder.CallbackRegistrationInvoker) invoker; if (callbackRegistrationInvoker == null || callbackRegistrationInvoker.getInterface() != getInterface()) { return; } exportedExporters.add(exporter); FilterChainBuilder.CopyOfFilterChainNode filterChainNode = getFilterChainNode(callbackRegistrationInvoker); do { Filter filter = this.getFilter(filterChainNode); if (filter != null) { filters.add(filter); } filterChainNode = this.getNextNode(filterChainNode); } while (filterChainNode != null); } /** * {@inheritDoc} */ @Override public void unexported(Exporter<?> exporter) { exportedExporters.remove(exporter); } /** * Returns the exported exporters. */ public List<Exporter<?>> getExportedExporters() { return Collections.unmodifiableList(exportedExporters); } /** * Returns all filters */ public Set<Filter> getFilters() { return Collections.unmodifiableSet(filters); } /** * Use reflection to obtain {@link Filter} */ private FilterChainBuilder.CopyOfFilterChainNode getFilterChainNode( FilterChainBuilder.CallbackRegistrationInvoker callbackRegistrationInvoker) { if (callbackRegistrationInvoker != null) { Field field = null; try { field = callbackRegistrationInvoker.getClass().getDeclaredField("filterInvoker"); field.setAccessible(true); return (FilterChainBuilder.CopyOfFilterChainNode) field.get(callbackRegistrationInvoker); } catch (NoSuchFieldException | IllegalAccessException e) { // ignore } } return null; } /** * Use reflection to obtain {@link Filter} */ private Filter getFilter(FilterChainBuilder.CopyOfFilterChainNode filterChainNode) { if (filterChainNode != null) { Field field = null; try { field = filterChainNode.getClass().getDeclaredField("filter"); field.setAccessible(true); return (Filter) field.get(filterChainNode); } catch (NoSuchFieldException | IllegalAccessException e) { // ignore } } return null; } /** * Use reflection to obtain {@link FilterChainBuilder.CopyOfFilterChainNode} */ private FilterChainBuilder.CopyOfFilterChainNode getNextNode( FilterChainBuilder.CopyOfFilterChainNode filterChainNode) { if (filterChainNode != null) { Field field = null; try { field = filterChainNode.getClass().getDeclaredField("nextNode"); field.setAccessible(true); Object object = field.get(filterChainNode); if (object instanceof FilterChainBuilder.CopyOfFilterChainNode) { return (FilterChainBuilder.CopyOfFilterChainNode) object; } } catch (NoSuchFieldException | IllegalAccessException e) { // ignore } } return null; } }
8,472
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/AbstractRegistryCenterServiceListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.ServiceListener; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * This implementation of {@link ServiceListener} is to record exported services, which should be extended by different sub-classes. */ public abstract class AbstractRegistryCenterServiceListener implements ServiceListener { private List<ServiceConfig> exportedServices = new ArrayList<>(2); /** * Return the interface name of exported service. */ protected abstract Class<?> getInterface(); /** * {@inheritDoc} */ @Override public void exported(ServiceConfig sc) { // All exported services will be added if (sc.getInterfaceClass() == getInterface()) { exportedServices.add(sc); } } /** * {@inheritDoc} */ @Override public void unexported(ServiceConfig sc) { // remove the exported services. exportedServices.remove(sc); } /** * Return all exported services. */ public List<ServiceConfig> getExportedServices() { return Collections.unmodifiableList(exportedServices); } }
8,473
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/IntegrationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration; /** * The interface for integration testcases. */ public interface IntegrationTest { /** * Run the integration testcases. */ void integrate(); }
8,474
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/Constants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration; public interface Constants { String MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY = "multipleConfigCenterServiceDiscoveryRegistry"; String SINGLE_CONFIG_CENTER_EXPORT_PROVIDER = "singleConfigCenterExportProvider"; }
8,475
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/Storage.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple; /** * This interface to store the given type instance in multiple registry center. * @param <T> The type to store */ public interface Storage<T> { /** * Gets the stored instance with the given host and port. * @param host the host in the register center. * @param port the port in the register center. * @return the stored instance. */ T get(String host, int port); /** * Sets the stored instance with the given host and port as key. * @param host the host in the register center. * @param port the port in the register center. * @param value the instance to store. */ void put(String host, int port, T value); /** * Checks if the instance exists with the given host and port. * @param host the host in the register center. * @param port the port in the register center. * @return {@code true} if the instance exists with the given host and port, otherwise {@code false} */ boolean contains(String host, int port); /** * Returns the size of all stored values. */ int size(); /** * Clear all data. */ void clear(); }
8,476
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/AbstractStorage.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * This abstraction class to implement the basic methods for {@link Storage}. * * @param <T> The type to store */ public abstract class AbstractStorage<T> implements Storage<T> { private Map<String, T> storage = new ConcurrentHashMap<>(); /** * Generate the key for storage * * @param host the host in the register center. * @param port the port in the register center. * @return the generated key with the given host and port. */ private String generateKey(String host, int port) { return String.format("%s:%d", host, port); } /** * {@inheritDoc} */ @Override public T get(String host, int port) { return storage.get(generateKey(host, port)); } /** * {@inheritDoc} */ @Override public void put(String host, int port, T value) { storage.put(generateKey(host, port), value); } /** * {@inheritDoc} */ @Override public boolean contains(String host, int port) { return storage.containsKey(generateKey(host, port)); } /** * {@inheritDoc} */ @Override public int size() { return storage.size(); } /** * {@inheritDoc} */ @Override public void clear() { storage.clear(); } }
8,477
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/package-info.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * There are two scenario in integration testcases.<p> * The one is single registry center, the other is multiple registry centers.<p> * The purpose of all of testcases in this package is to test for multiple registry center. */ package org.apache.dubbo.config.integration.multiple;
8,478
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.servicediscoveryregistry; /** * This interface is used to check if the exported service-discovery-registry protocol works well or not. */ public interface MultipleRegistryCenterServiceDiscoveryRegistryService { /** * The simple method for testing. */ String hello(String name); }
8,479
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.servicediscoveryregistry; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.integration.IntegrationTest; import org.apache.dubbo.registry.RegistryServiceListener; import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperConfig; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.dubbo.config.integration.Constants.MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY; /** * The testcases are only for checking the process of exporting provider using service-discovery-registry protocol. */ class MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest implements IntegrationTest { private static final Logger logger = LoggerFactory.getLogger(MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.class); /** * Define the provider application name. */ public static String PROVIDER_APPLICATION_NAME = "multiple-registry-center-provider-for-service-discovery-registry-protocol"; /** * Define the protocol's name. */ private static String PROTOCOL_NAME = CommonConstants.DUBBO; /** * Define the protocol's port. */ private static int PROTOCOL_PORT = 20880; /** * Define the {@link ServiceConfig} instance. */ private ServiceConfig<MultipleRegistryCenterServiceDiscoveryRegistryService> serviceConfig; /** * Define a {@link RegistryServiceListener} instance. */ private MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListener registryServiceListener; /** * The localhost. */ private static String HOST = "127.0.0.1"; /** * The port of register center. */ private Set<Integer> ports = new HashSet<>(2); @BeforeEach public void setUp() throws Exception { logger.info(getClass().getSimpleName() + " testcase is beginning..."); DubboBootstrap.reset(); // initialize service config serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(MultipleRegistryCenterServiceDiscoveryRegistryService.class); serviceConfig.setRef(new MultipleRegistryCenterServiceDiscoveryRegistryServiceImpl()); serviceConfig.setAsync(false); RegistryConfig registryConfig1 = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1()); Map<String, String> parameters1 = new HashMap<>(); parameters1.put("registry.listeners", MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY); registryConfig1.updateParameters(parameters1); DubboBootstrap.getInstance().registry(registryConfig1); ports.add(ZookeeperConfig.DEFAULT_CLIENT_PORT_1); RegistryConfig registryConfig2 = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2()); Map<String, String> parameters2 = new HashMap<>(); parameters2.put("registry.listeners", MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY); registryConfig2.updateParameters(parameters2); DubboBootstrap.getInstance().registry(registryConfig2); ports.add(ZookeeperConfig.DEFAULT_CLIENT_PORT_2); DubboBootstrap.getInstance() .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) .protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT)) .service(serviceConfig); // ---------------initialize--------------- // registryServiceListener = (MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListener) ExtensionLoader.getExtensionLoader(RegistryServiceListener.class) .getExtension(MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY); // RegistryServiceListener is not null Assertions.assertNotNull(registryServiceListener); registryServiceListener.getStorage().clear(); } /** * Define a {@link RegistryServiceListener} for helping check.<p> * There are some checkpoints need to verify as follow: * <ul> * <li>ServiceConfig is exported or not</li> * <li>ServiceDiscoveryRegistryStorage is empty or not</li> * </ul> */ private void beforeExport() { // ---------------checkpoints--------------- // // ServiceConfig isn't exported Assertions.assertFalse(serviceConfig.isExported()); // ServiceDiscoveryRegistryStorage is empty Assertions.assertEquals(registryServiceListener.getStorage().size(), 0); } /** * {@inheritDoc} */ @Test @Override public void integrate() { beforeExport(); DubboBootstrap.getInstance().start(); afterExport(); ReferenceConfig<MultipleRegistryCenterServiceDiscoveryRegistryService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(MultipleRegistryCenterServiceDiscoveryRegistryService.class); referenceConfig.get().hello("Dubbo in multiple registry center"); afterInvoke(); } /** * There are some checkpoints need to check after exported as follow: * <ul> * <li>ServiceDiscoveryRegistry is right or not</li> * <li>All register center has been registered and subscribed</li> * </ul> */ private void afterExport() { // ServiceDiscoveryRegistry is not null Assertions.assertEquals(registryServiceListener.getStorage().size(), 2); // All register center has been registered and subscribed for (int port : ports) { Assertions.assertTrue(registryServiceListener.getStorage().contains(HOST, port)); ServiceDiscoveryRegistryInfoWrapper serviceDiscoveryRegistryInfoWrapper = registryServiceListener.getStorage().get(HOST, port); // check if it's registered Assertions.assertTrue(serviceDiscoveryRegistryInfoWrapper.isRegistered()); // check if it's subscribed Assertions.assertFalse(serviceDiscoveryRegistryInfoWrapper.isSubscribed()); MetadataServiceDelegation metadataService = DubboBootstrap.getInstance() .getApplicationModel() .getBeanFactory() .getBean(MetadataServiceDelegation.class); // check if the count of exported urls is right or not Assertions.assertEquals(metadataService.getExportedURLs().size(), 1); // check the exported url is right or not. Assertions.assertTrue(metadataService .getExportedURLs() .first() .contains(MultipleRegistryCenterServiceDiscoveryRegistryService.class.getName())); // check the count of metadatainfo is right or not. Assertions.assertEquals(2, metadataService.getMetadataInfos().size()); } } /** * There are some checkpoints need to check after invoked as follow: */ private void afterInvoke() {} @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); PROVIDER_APPLICATION_NAME = null; serviceConfig = null; // TODO: we need to check whether this scenario is normal // TODO: the Exporter and ServiceDiscoveryRegistry are same in multiple registry center /* for (int port: ports) { Assertions.assertTrue(registryServiceListener.getStorage().contains(HOST, port)); ServiceDiscoveryRegistryInfoWrapper serviceDiscoveryRegistryInfoWrapper = registryServiceListener.getStorage().get(HOST, port); // check if it's registered Assertions.assertFalse(serviceDiscoveryRegistryInfoWrapper.isRegistered()); // check if it's subscribed Assertions.assertFalse(serviceDiscoveryRegistryInfoWrapper.isSubscribed()); } */ registryServiceListener.getStorage().clear(); registryServiceListener = null; logger.info(getClass().getSimpleName() + " testcase is ending..."); } }
8,480
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.servicediscoveryregistry; /** * The simple implementation for {@link MultipleRegistryCenterServiceDiscoveryRegistryService} */ public class MultipleRegistryCenterServiceDiscoveryRegistryServiceImpl implements MultipleRegistryCenterServiceDiscoveryRegistryService { /** * {@inheritDoc} */ @Override public String hello(String name) { return "Hello " + name; } }
8,481
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.servicediscoveryregistry; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryServiceListener; import org.apache.dubbo.registry.client.ServiceDiscoveryRegistry; import static org.apache.dubbo.config.integration.Constants.MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY; @Activate(value = MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY) public class MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListener implements RegistryServiceListener { private ServiceDiscoveryRegistryStorage storage = new ServiceDiscoveryRegistryStorage(); /** * Create an {@link ServiceDiscoveryRegistryInfoWrapper} instance. */ private ServiceDiscoveryRegistryInfoWrapper createServiceDiscoveryRegistryInfoWrapper( ServiceDiscoveryRegistry serviceDiscoveryRegistry) { URL url = serviceDiscoveryRegistry.getUrl(); String host = url.getHost(); int port = url.getPort(); ServiceDiscoveryRegistryInfoWrapper serviceDiscoveryRegistryInfoWrapper = new ServiceDiscoveryRegistryInfoWrapper(); serviceDiscoveryRegistryInfoWrapper.setHost(host); serviceDiscoveryRegistryInfoWrapper.setPort(port); serviceDiscoveryRegistryInfoWrapper.setServiceDiscoveryRegistry(serviceDiscoveryRegistry); serviceDiscoveryRegistryInfoWrapper.setRegistered(true); return serviceDiscoveryRegistryInfoWrapper; } /** * Checks if the registry is checked application */ private boolean isCheckedApplication(Registry registry) { return registry.getUrl() .getApplication() .equals(MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.PROVIDER_APPLICATION_NAME); } public void onRegister(URL url, Registry registry) { if (registry instanceof ServiceDiscoveryRegistry && isCheckedApplication(registry)) { ServiceDiscoveryRegistry serviceDiscoveryRegistry = (ServiceDiscoveryRegistry) registry; String host = serviceDiscoveryRegistry.getUrl().getHost(); int port = serviceDiscoveryRegistry.getUrl().getPort(); if (!storage.contains(host, port)) { storage.put(host, port, createServiceDiscoveryRegistryInfoWrapper(serviceDiscoveryRegistry)); } storage.get(host, port).setRegistered(true); } } public void onUnregister(URL url, Registry registry) { if (registry instanceof ServiceDiscoveryRegistry && isCheckedApplication(registry)) { String host = registry.getUrl().getHost(); int port = registry.getUrl().getPort(); storage.get(host, port).setRegistered(false); } } public void onSubscribe(URL url, Registry registry) { if (registry instanceof ServiceDiscoveryRegistry && isCheckedApplication(registry)) { ServiceDiscoveryRegistry serviceDiscoveryRegistry = (ServiceDiscoveryRegistry) registry; String host = serviceDiscoveryRegistry.getUrl().getHost(); int port = serviceDiscoveryRegistry.getUrl().getPort(); if (!storage.contains(host, port)) { storage.put(host, port, createServiceDiscoveryRegistryInfoWrapper(serviceDiscoveryRegistry)); } storage.get(host, port).setSubscribed(true); } } public void onUnsubscribe(URL url, Registry registry) { if (registry instanceof ServiceDiscoveryRegistry && isCheckedApplication(registry)) { String host = registry.getUrl().getHost(); int port = registry.getUrl().getPort(); storage.get(host, port).setSubscribed(false); } } /** * Return the stored {@link ServiceDiscoveryRegistryInfoWrapper} instances. */ public ServiceDiscoveryRegistryStorage getStorage() { return storage; } }
8,482
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/ServiceDiscoveryRegistryStorage.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.servicediscoveryregistry; import org.apache.dubbo.config.integration.multiple.AbstractStorage; /** * The storage to store {@link ServiceDiscoveryRegistryInfoWrapper} instances in multiple registry center. */ public class ServiceDiscoveryRegistryStorage extends AbstractStorage<ServiceDiscoveryRegistryInfoWrapper> {}
8,483
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/ServiceDiscoveryRegistryInfoWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.servicediscoveryregistry; import org.apache.dubbo.registry.client.ServiceDiscoveryRegistry; import org.apache.dubbo.registry.client.metadata.MetadataServiceDelegation; /** * The instance to wrap {@link org.apache.dubbo.registry.client.ServiceDiscoveryRegistry} */ public class ServiceDiscoveryRegistryInfoWrapper { private ServiceDiscoveryRegistry serviceDiscoveryRegistry; private MetadataServiceDelegation inMemoryWritableMetadataService; private boolean registered; private boolean subscribed; private String host; private int port; public ServiceDiscoveryRegistry getServiceDiscoveryRegistry() { return serviceDiscoveryRegistry; } public void setServiceDiscoveryRegistry(ServiceDiscoveryRegistry serviceDiscoveryRegistry) { this.serviceDiscoveryRegistry = serviceDiscoveryRegistry; } public boolean isRegistered() { return registered; } public void setRegistered(boolean registered) { this.registered = registered; } public boolean isSubscribed() { return subscribed; } public void setSubscribed(boolean subscribed) { this.subscribed = subscribed; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } }
8,484
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.injvm; /** * The simple implementation for {@link MultipleRegistryCenterInjvmService} */ public class MultipleRegistryCenterInjvmServiceImpl implements MultipleRegistryCenterInjvmService { /** * {@inheritDoc} */ @Override public String hello(String name) { return "Hello " + name; } }
8,485
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.injvm; /** * This interface is used to check if the exported injvm protocol works well or not. */ public interface MultipleRegistryCenterInjvmService { /** * The simple method for testing. */ String hello(String name); }
8,486
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmIntegrationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.injvm; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.ServiceListener; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.integration.IntegrationTest; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; import java.io.IOException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; /** * The testcases are only for checking the process of exporting provider using injvm protocol. */ class MultipleRegistryCenterInjvmIntegrationTest implements IntegrationTest { private static final Logger logger = LoggerFactory.getLogger(MultipleRegistryCenterInjvmIntegrationTest.class); /** * Define the provider application name. */ private static String PROVIDER_APPLICATION_NAME = "multiple-registry-center-provider-for-injvm-protocol"; /** * The name for getting the specified instance, which is loaded using SPI. */ private static String SPI_NAME = "multipleConfigCenterInjvm"; /** * Define the {@link ServiceConfig} instance. */ private ServiceConfig<MultipleRegistryCenterInjvmService> serviceConfig; /** * The listener to record exported services */ private MultipleRegistryCenterInjvmServiceListener serviceListener; /** * The listener to record exported exporters. */ private MultipleRegistryCenterInjvmExporterListener exporterListener; /** * The filter for checking filter chain. */ private MultipleRegistryCenterInjvmFilter filter; @BeforeEach public void setUp() throws Exception { logger.info(getClass().getSimpleName() + " testcase is beginning..."); DubboBootstrap.reset(); // initialize service config serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(MultipleRegistryCenterInjvmService.class); serviceConfig.setRef(new MultipleRegistryCenterInjvmServiceImpl()); serviceConfig.setAsync(false); serviceConfig.setScope(SCOPE_LOCAL); DubboBootstrap.getInstance() .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) .protocol(new ProtocolConfig("injvm")) .service(serviceConfig) .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1())) .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2())); } /** * Define {@link ServiceListener}, {@link ExporterListener} and {@link Filter} for helping check. * <p>Use SPI to load them before exporting. * <p>After that, there are some checkpoints need to verify as follow: * <ul> * <li>There is nothing in ServiceListener or not</li> * <li>There is nothing in ExporterListener or not</li> * <li>ServiceConfig is exported or not</li> * </ul> */ private void beforeExport() { // ---------------initialize--------------- // serviceListener = (MultipleRegistryCenterInjvmServiceListener) ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME); exporterListener = (MultipleRegistryCenterInjvmExporterListener) ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME); filter = (MultipleRegistryCenterInjvmFilter) ExtensionLoader.getExtensionLoader(Filter.class).getExtension(SPI_NAME); // ---------------checkpoints--------------- // // There is nothing in ServiceListener Assertions.assertTrue(serviceListener.getExportedServices().isEmpty()); // There is nothing in ExporterListener Assertions.assertTrue(exporterListener.getExportedExporters().isEmpty()); // ServiceConfig isn't exported Assertions.assertFalse(serviceConfig.isExported()); } /** * {@inheritDoc} */ @Test @Override public void integrate() { beforeExport(); DubboBootstrap.getInstance().start(); afterExport(); ReferenceConfig<MultipleRegistryCenterInjvmService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(MultipleRegistryCenterInjvmService.class); referenceConfig.setScope(SCOPE_LOCAL); referenceConfig.get().hello("Dubbo in multiple registry center"); afterInvoke(); } /** * There are some checkpoints need to check after exported as follow: * <ul> * <li>The exported service is only one or not</li> * <li>The exported service is MultipleRegistryCenterInjvmService or not</li> * <li>The MultipleRegistryCenterInjvmService is exported or not</li> * <li>The exported exporter is only one or not</li> * <li>The exported exporter contains MultipleRegistryCenterInjvmFilter or not</li> * </ul> */ private void afterExport() { // The exported service is only one Assertions.assertEquals(serviceListener.getExportedServices().size(), 1); // The exported service is MultipleRegistryCenterInjvmService Assertions.assertEquals( serviceListener.getExportedServices().get(0).getInterfaceClass(), MultipleRegistryCenterInjvmService.class); // The MultipleRegistryCenterInjvmService is exported Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported()); // The exported exporter is only one Assertions.assertEquals(exporterListener.getExportedExporters().size(), 3); // The exported exporter contains MultipleRegistryCenterInjvmFilter Assertions.assertTrue(exporterListener.getFilters().contains(filter)); } /** * There are some checkpoints need to check after invoked as follow: * <ul> * <li>The MultipleRegistryCenterInjvmFilter has called or not</li> * <li>The MultipleRegistryCenterInjvmFilter exists error after invoked</li> * <li>The MultipleRegistryCenterInjvmFilter's response is right or not</li> * </ul> */ private void afterInvoke() { // The MultipleRegistryCenterInjvmFilter has called Assertions.assertTrue(filter.hasCalled()); // The MultipleRegistryCenterInjvmFilter doesn't exist error Assertions.assertFalse(filter.hasError()); // Check the MultipleRegistryCenterInjvmFilter's response Assertions.assertEquals("Hello Dubbo in multiple registry center", filter.getResponse()); } @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); PROVIDER_APPLICATION_NAME = null; serviceConfig = null; // The exported service has been unexported Assertions.assertTrue(serviceListener.getExportedServices().isEmpty()); serviceListener = null; logger.info(getClass().getSimpleName() + " testcase is ending..."); } }
8,487
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.injvm; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; @Activate(group = CommonConstants.PROVIDER, order = 10200) public class MultipleRegistryCenterInjvmFilter implements Filter, Filter.Listener { /** * The filter is called or not */ private boolean called = false; /** * There has error after invoked */ private boolean error = false; /** * The returned result */ private String response; /** * Always call invoker.invoke() in the implementation to hand over the request to the next filter node. * * @param invoker * @param invocation */ @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { called = true; return invoker.invoke(invocation); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { response = String.valueOf(appResponse.getValue()); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { error = true; } /** * Returns if the filter has called. */ public boolean hasCalled() { return called; } /** * Returns if there exists error. */ public boolean hasError() { return error; } /** * Returns the response. */ public String getResponse() { return response; } }
8,488
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmServiceListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.injvm; import org.apache.dubbo.config.ServiceListener; import org.apache.dubbo.config.integration.AbstractRegistryCenterServiceListener; /** * This implementation of {@link ServiceListener} is to record exported services with injvm protocol in multiple registry center. */ public class MultipleRegistryCenterInjvmServiceListener extends AbstractRegistryCenterServiceListener { /** * {@inheritDoc} */ @Override protected Class<?> getInterface() { return MultipleRegistryCenterInjvmService.class; } }
8,489
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/injvm/MultipleRegistryCenterInjvmExporterListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.injvm; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.config.integration.AbstractRegistryCenterExporterListener; @Activate(group = CommonConstants.PROVIDER, order = 1000) public class MultipleRegistryCenterInjvmExporterListener extends AbstractRegistryCenterExporterListener { /** * {@inheritDoc} */ @Override protected Class<?> getInterface() { return MultipleRegistryCenterInjvmService.class; } }
8,490
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderIntegrationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.exportprovider; import org.apache.dubbo.common.config.configcenter.ConfigItem; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ReferenceConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.ServiceListener; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.integration.IntegrationTest; import org.apache.dubbo.metadata.ServiceNameMapping; import org.apache.dubbo.metadata.report.MetadataReportInstance; import org.apache.dubbo.registry.integration.RegistryProtocolListener; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.model.ApplicationModel; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; import java.io.IOException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The testcases are only for checking the core process of exporting provider. */ class MultipleRegistryCenterExportProviderIntegrationTest implements IntegrationTest { private static final Logger logger = LoggerFactory.getLogger(MultipleRegistryCenterExportProviderIntegrationTest.class); /** * Define the provider application name. */ private static String PROVIDER_APPLICATION_NAME = "multiple-registry-center-for-export-provider"; /** * The name for getting the specified instance, which is loaded using SPI. */ private static String SPI_NAME = "multipleConfigCenterExportProvider"; /** * Define the protocol's name. */ private static String PROTOCOL_NAME = CommonConstants.DUBBO; /** * Define the protocol's port. */ private static int PROTOCOL_PORT = 20800; /** * Define the {@link ServiceConfig} instance. */ private ServiceConfig<MultipleRegistryCenterExportProviderService> serviceConfig; /** * Define a {@link RegistryProtocolListener} instance. */ private MultipleRegistryCenterExportProviderRegistryProtocolListener registryProtocolListener; /** * Define a {@link ExporterListener} instance. */ private MultipleRegistryCenterExportProviderExporterListener exporterListener; /** * Define a {@link Filter} instance. */ private MultipleRegistryCenterExportProviderFilter filter; /** * Define a {@link ServiceListener} instance. */ private MultipleRegistryCenterExportProviderServiceListener serviceListener; @BeforeEach public void setUp() throws Exception { logger.info(getClass().getSimpleName() + " testcase is beginning..."); DubboBootstrap.reset(); // initialize service config serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(MultipleRegistryCenterExportProviderService.class); serviceConfig.setRef(new MultipleRegistryCenterExportProviderServiceImpl()); serviceConfig.setAsync(false); // initailize bootstrap DubboBootstrap.getInstance() .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) .protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT)) .service(serviceConfig) .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1())) .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2())); } /** * There are some checkpoints need to verify as follow: * <ul> * <li>ServiceConfig is exported or not</li> * <li>MultipleRegistryCenterExportProviderRegistryProtocolListener is null or not</li> * <li>There is nothing in ServiceListener or not</li> * <li>There is nothing in ExporterListener or not</li> * </ul> */ private void beforeExport() { registryProtocolListener = (MultipleRegistryCenterExportProviderRegistryProtocolListener) ExtensionLoader.getExtensionLoader(RegistryProtocolListener.class) .getExtension(SPI_NAME); exporterListener = (MultipleRegistryCenterExportProviderExporterListener) ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME); filter = (MultipleRegistryCenterExportProviderFilter) ExtensionLoader.getExtensionLoader(Filter.class).getExtension(SPI_NAME); serviceListener = (MultipleRegistryCenterExportProviderServiceListener) ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME); // ---------------checkpoints--------------- // // ServiceConfig isn't exported Assertions.assertFalse(serviceConfig.isExported()); // registryProtocolListener is just initialized by SPI // so, all of fields are the default value. Assertions.assertNotNull(registryProtocolListener); Assertions.assertFalse(registryProtocolListener.isExported()); // There is nothing in ServiceListener Assertions.assertTrue(serviceListener.getExportedServices().isEmpty()); // There is nothing in ExporterListener Assertions.assertTrue(exporterListener.getExportedExporters().isEmpty()); } /** * {@inheritDoc} */ @Test @Override public void integrate() { beforeExport(); DubboBootstrap.getInstance().start(); afterExport(); ReferenceConfig<MultipleRegistryCenterExportProviderService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(MultipleRegistryCenterExportProviderService.class); referenceConfig.get().hello(PROVIDER_APPLICATION_NAME); afterInvoke(); } /** * There are some checkpoints need to check after exported as follow: * <ul> * <li>the exporter is exported or not</li> * <li>The exported exporter are three</li> * <li>The exported service is MultipleRegistryCenterExportProviderService or not</li> * <li>The MultipleRegistryCenterExportProviderService is exported or not</li> * <li>The exported exporter contains MultipleRegistryCenterExportProviderFilter or not</li> * </ul> */ private void afterExport() { // The exporter is exported Assertions.assertTrue(registryProtocolListener.isExported()); // The exported service is only one Assertions.assertEquals(serviceListener.getExportedServices().size(), 1); // The exported service is MultipleRegistryCenterExportProviderService Assertions.assertEquals( serviceListener.getExportedServices().get(0).getInterfaceClass(), MultipleRegistryCenterExportProviderService.class); // The MultipleRegistryCenterExportProviderService is exported Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported()); // The exported exporter are three // 1. InjvmExporter // 2. DubboExporter with service-discovery-registry protocol // 3. DubboExporter with registry protocol Assertions.assertEquals(exporterListener.getExportedExporters().size(), 4); // The exported exporter contains MultipleRegistryCenterExportProviderFilter Assertions.assertTrue(exporterListener.getFilters().contains(filter)); // The consumer can be notified and get provider's metadata through metadata mapping info. // So, the metadata mapping is necessary to check after exported service (or provider) // The best way to verify this issue is to check if the exported service (or provider) // has been registered in the path of /dubbo/mapping/**** // FixME We should check if the exported service (or provider) has been registered in multiple registry centers. // However, the registered exporter are override in RegistryProtocol#export, so there is only the first // registry center // that can register the mapping relationship. This is really a problem that needs to be fix. // Now, we are discussing the solution for this issue. // For this testcase, we still check the only exported service (or provider). // all testcase below are temporary and will be replaced after the above problem is fixed. // What are the parameters? // registryKey: the registryKey is the default cluster, CommonConstants.DEFAULT_KEY // key: The exported interface's name // group: the group is "mapping", ServiceNameMapping.DEFAULT_MAPPING_GROUP ConfigItem configItem = ApplicationModel.defaultModel() .getBeanFactory() .getBean(MetadataReportInstance.class) .getMetadataReport(CommonConstants.DEFAULT_KEY) .getConfigItem(serviceConfig.getInterface(), ServiceNameMapping.DEFAULT_MAPPING_GROUP); // Check if the exported service (provider) is registered Assertions.assertNotNull(configItem); // Check if registered service (provider)'s name is right Assertions.assertEquals(PROVIDER_APPLICATION_NAME, configItem.getContent()); // Check if registered service (provider)'s version exists Assertions.assertNotNull(configItem.getTicket()); } /** * There are some checkpoints need to check after invoked as follow: * <ul> * <li>The MultipleRegistryCenterExportProviderFilter has called or not</li> * <li>The MultipleRegistryCenterExportProviderFilter exists error after invoked</li> * <li>The MultipleRegistryCenterExportProviderFilter's response is right or not</li> * </ul> */ private void afterInvoke() { // The MultipleRegistryCenterExportProviderFilter has called Assertions.assertTrue(filter.hasCalled()); // The MultipleRegistryCenterExportProviderFilter doesn't exist error Assertions.assertFalse(filter.hasError()); // Check the MultipleRegistryCenterExportProviderFilter's response Assertions.assertEquals("Hello " + PROVIDER_APPLICATION_NAME, filter.getResponse()); } @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); PROVIDER_APPLICATION_NAME = null; serviceConfig = null; // The exported service has been unexported Assertions.assertTrue(serviceListener.getExportedServices().isEmpty()); logger.info(getClass().getSimpleName() + " testcase is ending..."); registryProtocolListener = null; } }
8,491
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderServiceImpl.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.exportprovider; /** * The implementation of {@link MultipleRegistryCenterExportProviderService} */ public class MultipleRegistryCenterExportProviderServiceImpl implements MultipleRegistryCenterExportProviderService { /** * {@inheritDoc} */ @Override public String hello(String name) { return "Hello " + name; } }
8,492
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.exportprovider; /** * This interface is used to check if the exported provider works well or not in multiple registry center. */ public interface MultipleRegistryCenterExportProviderService { /** * The simple method for testing. */ String hello(String name); }
8,493
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderRegistryProtocolListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.exportprovider; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.registry.integration.InterfaceCompatibleRegistryProtocol; import org.apache.dubbo.registry.integration.RegistryProtocol; import org.apache.dubbo.registry.integration.RegistryProtocolListener; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.cluster.ClusterInvoker; /** * The {@link RegistryProtocolListener} for {@link MultipleRegistryCenterExportProviderService} */ @Activate(order = 100) public class MultipleRegistryCenterExportProviderRegistryProtocolListener implements RegistryProtocolListener { private boolean exported = false; /** * {@inheritDoc} */ @Override public void onExport(RegistryProtocol registryProtocol, Exporter<?> exporter) { if (registryProtocol instanceof InterfaceCompatibleRegistryProtocol && exporter != null && exporter.getInvoker() != null && exporter.getInvoker().getInterface().equals(MultipleRegistryCenterExportProviderService.class)) { this.exported = true; } } /** * {@inheritDoc} */ @Override public void onRefer(RegistryProtocol registryProtocol, ClusterInvoker<?> invoker, URL url, URL registryURL) {} /** * {@inheritDoc} */ @Override public void onDestroy() {} /** * Returns if this exporter is exported. */ public boolean isExported() { return exported; } }
8,494
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderExporterListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.exportprovider; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.config.integration.AbstractRegistryCenterExporterListener; @Activate(group = CommonConstants.PROVIDER, order = 1000) public class MultipleRegistryCenterExportProviderExporterListener extends AbstractRegistryCenterExporterListener { /** * Returns the interface of exported service. */ @Override protected Class<?> getInterface() { return MultipleRegistryCenterExportProviderService.class; } }
8,495
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.exportprovider; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.rpc.Invocation; import org.apache.dubbo.rpc.Invoker; import org.apache.dubbo.rpc.Result; import org.apache.dubbo.rpc.RpcException; @Activate(group = CommonConstants.PROVIDER, order = 10001) public class MultipleRegistryCenterExportProviderFilter implements Filter, Filter.Listener { /** * The filter is called or not */ private boolean called = false; /** * There has error after invoked */ private boolean error = false; /** * The returned result */ private String response; /** * Always call invoker.invoke() in the implementation to hand over the request to the next filter node. * * @param invoker * @param invocation */ @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { called = true; return invoker.invoke(invocation); } @Override public void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) { response = String.valueOf(appResponse.getValue()); } @Override public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) { error = true; } /** * Returns if the filter has called. */ public boolean hasCalled() { return called; } /** * Returns if there exists error. */ public boolean hasError() { return error; } /** * Returns the response. */ public String getResponse() { return response; } }
8,496
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportprovider/MultipleRegistryCenterExportProviderServiceListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.exportprovider; import org.apache.dubbo.config.ServiceListener; import org.apache.dubbo.config.integration.AbstractRegistryCenterServiceListener; /** * This implementation of {@link ServiceListener} is to record exported services with injvm protocol in single registry center. */ public class MultipleRegistryCenterExportProviderServiceListener extends AbstractRegistryCenterServiceListener { /** * {@inheritDoc} */ @Override protected Class<?> getInterface() { return MultipleRegistryCenterExportProviderService.class; } }
8,497
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportmetadata/MultipleRegistryCenterExportMetadataExporterListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.exportmetadata; import org.apache.dubbo.common.constants.CommonConstants; import org.apache.dubbo.common.extension.Activate; import org.apache.dubbo.config.integration.AbstractRegistryCenterExporterListener; import org.apache.dubbo.metadata.MetadataService; @Activate(group = CommonConstants.PROVIDER, order = 1000) public class MultipleRegistryCenterExportMetadataExporterListener extends AbstractRegistryCenterExporterListener { /** * Returns the interface of exported service. */ @Override protected Class<?> getInterface() { return MetadataService.class; } }
8,498
0
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple
Create_ds/dubbo/dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/exportmetadata/MultipleRegistryCenterExportMetadataIntegrationTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.dubbo.config.integration.multiple.exportmetadata; import org.apache.dubbo.common.extension.ExtensionLoader; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.ServiceConfig; import org.apache.dubbo.config.ServiceListener; import org.apache.dubbo.config.bootstrap.DubboBootstrap; import org.apache.dubbo.config.integration.IntegrationTest; import org.apache.dubbo.metadata.MetadataService; import org.apache.dubbo.rpc.Exporter; import org.apache.dubbo.rpc.ExporterListener; import org.apache.dubbo.rpc.Filter; import org.apache.dubbo.test.check.registrycenter.config.ZookeeperRegistryCenterConfig; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.dubbo.rpc.Constants.SCOPE_LOCAL; /** * The testcases are only for checking the process of exporting metadata service. */ class MultipleRegistryCenterExportMetadataIntegrationTest implements IntegrationTest { private static final Logger logger = LoggerFactory.getLogger(MultipleRegistryCenterExportMetadataIntegrationTest.class); /** * Define the provider application name. */ private static String PROVIDER_APPLICATION_NAME = "multiple-registry-center-export-metadata"; /** * The name for getting the specified instance, which is loaded using SPI. */ private static String SPI_NAME = "multipleConfigCenterExportMetadata"; /** * Define the protocol's name. */ private static String PROTOCOL_NAME = "injvm"; /** * Define the {@link ServiceConfig} instance. */ private ServiceConfig<MultipleRegistryCenterExportMetadataService> serviceConfig; /** * The listener to record exported services */ private MultipleRegistryCenterExportMetadataServiceListener serviceListener; /** * The listener to record exported exporters. */ private MultipleRegistryCenterExportMetadataExporterListener exporterListener; @BeforeEach public void setUp() throws Exception { logger.info(getClass().getSimpleName() + " testcase is beginning..."); DubboBootstrap.reset(); // initialize service config serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(MultipleRegistryCenterExportMetadataService.class); serviceConfig.setRef(new MultipleRegistryCenterExportMetadataServiceImpl()); serviceConfig.setAsync(false); serviceConfig.setScope(SCOPE_LOCAL); // initailize bootstrap DubboBootstrap.getInstance() .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) .protocol(new ProtocolConfig(PROTOCOL_NAME)) .service(serviceConfig) .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1())) .registry(new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2())); } /** * Define {@link ServiceListener}, {@link ExporterListener} and {@link Filter} for helping check. * <p>Use SPI to load them before exporting. * <p>After that, there are some checkpoints need to verify as follow: * <ul> * <li>There is nothing in ServiceListener or not</li> * <li>There is nothing in ExporterListener or not</li> * <li>ServiceConfig is exported or not</li> * </ul> */ private void beforeExport() { // ---------------initialize--------------- // serviceListener = (MultipleRegistryCenterExportMetadataServiceListener) ExtensionLoader.getExtensionLoader(ServiceListener.class).getExtension(SPI_NAME); exporterListener = (MultipleRegistryCenterExportMetadataExporterListener) ExtensionLoader.getExtensionLoader(ExporterListener.class).getExtension(SPI_NAME); // ---------------checkpoints--------------- // // There is nothing in ServiceListener Assertions.assertTrue(serviceListener.getExportedServices().isEmpty()); // There is nothing in ExporterListener Assertions.assertTrue(exporterListener.getExportedExporters().isEmpty()); // ServiceConfig isn't exported Assertions.assertFalse(serviceConfig.isExported()); } /** * {@inheritDoc} */ @Test @Override public void integrate() { beforeExport(); DubboBootstrap.getInstance().start(); afterExport(); } /** * There are some checkpoints need to check after exported as follow: * <ul> * <li>The metadata service is only one or not</li> * <li>The exported service is MetadataService or not</li> * <li>The MetadataService is exported or not</li> * <li>The exported exporters are right or not</li> * </ul> */ private void afterExport() { // The metadata service is only one Assertions.assertEquals(serviceListener.getExportedServices().size(), 1); // The exported service is MetadataService Assertions.assertEquals( serviceListener.getExportedServices().get(0).getInterfaceClass(), MetadataService.class); // The MetadataService is exported Assertions.assertTrue(serviceListener.getExportedServices().get(0).isExported()); // FIXME there may be something wrong with the whole process of // registering service-discovery-registry. // So, all testcases may need to be modified. // There are two exported exporters // 1. Metadata Service exporter with Injvm protocol // 2. MultipleRegistryCenterExportMetadataService exporter with Injvm protocol Assertions.assertEquals(exporterListener.getExportedExporters().size(), 2); List<Exporter<?>> injvmExporters = exporterListener.getExportedExporters().stream() .filter(exporter -> PROTOCOL_NAME.equalsIgnoreCase( exporter.getInvoker().getUrl().getProtocol())) .collect(Collectors.toList()); // Make sure there two injvmExporters Assertions.assertEquals(injvmExporters.size(), 2); } @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); PROVIDER_APPLICATION_NAME = null; serviceConfig = null; // The exported service has been unexported Assertions.assertTrue(serviceListener.getExportedServices().isEmpty()); serviceListener = null; logger.info(getClass().getSimpleName() + " testcase is ending..."); } }
8,499