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-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/YamlPropertySourceFactory.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.spring.beans.factory.config;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.springframework.beans.factory.config.YamlProcessor;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.parser.ParserException;
import org.yaml.snakeyaml.representer.Representer;
import org.yaml.snakeyaml.resolver.Resolver;
/**
* YAML {@link PropertySourceFactory} implementation, some source code is copied Spring Boot
* org.springframework.boot.env.YamlPropertySourceLoader , see {@link #createYaml()} and {@link #process()}
*
* @since 2.6.5
*/
public class YamlPropertySourceFactory extends YamlProcessor implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
setResources(resource.getResource());
return new MapPropertySource(name, process());
}
@Override
protected Yaml createYaml() {
return new Yaml(
new Constructor(new LoaderOptions()) {
@Override
protected Map<Object, Object> constructMapping(MappingNode node) {
try {
return super.constructMapping(node);
} catch (IllegalStateException ex) {
throw new ParserException(
"while parsing MappingNode",
node.getStartMark(),
ex.getMessage(),
node.getEndMark());
}
}
@Override
protected Map<Object, Object> createDefaultMap(int initSize) {
final Map<Object, Object> delegate = super.createDefaultMap(initSize);
return new AbstractMap<Object, Object>() {
@Override
public Object put(Object key, Object value) {
if (delegate.containsKey(key)) {
throw new IllegalStateException("Duplicate key: " + key);
}
return delegate.put(key, value);
}
@Override
public Set<Entry<Object, Object>> entrySet() {
return delegate.entrySet();
}
};
}
},
new Representer(new DumperOptions()),
new DumperOptions(),
new Resolver() {
@Override
public void addImplicitResolver(Tag tag, Pattern regexp, String first) {
if (tag == Tag.TIMESTAMP) {
return;
}
super.addImplicitResolver(tag, regexp, first);
}
});
}
/**
* {@link Resolver} that limits {@link Tag#TIMESTAMP} tags.
*/
private static class LimitedResolver extends Resolver {
@Override
public void addImplicitResolver(Tag tag, Pattern regexp, String first) {
if (tag == Tag.TIMESTAMP) {
return;
}
super.addImplicitResolver(tag, regexp, first);
}
}
public Map<String, Object> process() {
final Map<String, Object> result = new LinkedHashMap<String, Object>();
process((properties, map) -> result.putAll(getFlattenedMap(map)));
return result;
}
}
| 8,700 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/config/MultipleServicesWithMethodConfigsTest.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.spring.beans.factory.config;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.ServiceBean;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ImportResource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = MultipleServicesWithMethodConfigsTest.class)
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
@ImportResource(locations = "classpath:/META-INF/spring/multiple-services-with-methods.xml")
class MultipleServicesWithMethodConfigsTest {
@BeforeAll
public static void setUp() {
DubboBootstrap.reset();
}
@Autowired
private ApplicationContext applicationContext;
@Test
void test() {
Map<String, ServiceBean> serviceBeanMap = applicationContext.getBeansOfType(ServiceBean.class);
for (ServiceBean serviceBean : serviceBeanMap.values()) {
Assertions.assertEquals(1, serviceBean.getMethods().size());
}
}
}
| 8,701 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ParameterConvertTest.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.spring.beans.factory.annotation;
import org.apache.dubbo.config.spring.util.DubboAnnotationUtils;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.test.annotation.DirtiesContext;
/**
* {@link DubboAnnotationUtils#convertParameters} Test
*/
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class ParameterConvertTest {
@Test
void test() {
/**
* (array->map)
* ["a","b"] ==> {a=b}
* [" a "," b "] ==> {a=b}
* ["a=b"] ==>{a=b}
* ["a:b"] ==>{a=b}
* ["a=b","c","d"] ==>{a=b,c=d}
* ["a=b","c:d"] ==>{a=b,c=d}
* ["a","a:b"] ==>{a=a:b}
*/
Map<String, String> parametersMap = new HashMap<>();
parametersMap.put("a", "b");
Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a", "b"}));
Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {" a ", " b "}));
Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a=b"}));
Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a:b"}));
parametersMap.put("c", "d");
Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a=b", "c", "d"}));
Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a:b", "c=d"}));
parametersMap.clear();
parametersMap.put("a", "a:b");
Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a", "a:b"}));
parametersMap.clear();
parametersMap.put("a", "0,100");
Assertions.assertEquals(parametersMap, DubboAnnotationUtils.convertParameters(new String[] {"a", "0,100"}));
}
}
| 8,702 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/MergedAnnotationTest.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.spring.beans.factory.annotation;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.config.spring.annotation.merged.MergedReference;
import org.apache.dubbo.config.spring.annotation.merged.MergedService;
import org.apache.dubbo.config.spring.api.DemoService;
import java.lang.reflect.Field;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.util.ReflectionUtils;
class MergedAnnotationTest {
@Test
void testMergedReference() {
Field field = ReflectionUtils.findField(TestBean1.class, "demoService");
Reference reference = AnnotatedElementUtils.getMergedAnnotation(field, Reference.class);
Assertions.assertEquals("dubbo", reference.group());
Assertions.assertEquals("1.0.0", reference.version());
Field field2 = ReflectionUtils.findField(TestBean2.class, "demoService");
Reference reference2 = AnnotatedElementUtils.getMergedAnnotation(field2, Reference.class);
Assertions.assertEquals("group", reference2.group());
Assertions.assertEquals("2.0", reference2.version());
}
@Test
void testMergedService() {
Service service1 = AnnotatedElementUtils.getMergedAnnotation(DemoServiceImpl1.class, Service.class);
Assertions.assertEquals("dubbo", service1.group());
Assertions.assertEquals("1.0.0", service1.version());
Service service2 = AnnotatedElementUtils.getMergedAnnotation(DemoServiceImpl2.class, Service.class);
Assertions.assertEquals("group", service2.group());
Assertions.assertEquals("2.0", service2.version());
}
@MergedService
public static class DemoServiceImpl1 {}
@MergedService(group = "group", version = "2.0")
public static class DemoServiceImpl2 {}
private static class TestBean1 {
@MergedReference
private DemoService demoService;
}
private static class TestBean2 {
@MergedReference(group = "group", version = "2.0")
private DemoService demoService;
}
}
| 8,703 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationPostProcessorTest.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.spring.beans.factory.annotation;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.ServiceBean;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.DubboComponentScan;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import java.util.Map;
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.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
/**
* {@link ServiceAnnotationPostProcessor} Test
*
* @since 2.7.7
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(
classes = {
ServiceAnnotationTestConfiguration.class,
ServiceAnnotationPostProcessorTest.class,
ServiceAnnotationPostProcessorTest.DuplicatedScanConfig.class
})
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
@TestPropertySource(
properties = {
"provider.package = org.apache.dubbo.config.spring.context.annotation.provider",
})
@EnableDubbo(scanBasePackages = "${provider.package}")
class ServiceAnnotationPostProcessorTest {
@BeforeAll
public static void setUp() {
DubboBootstrap.reset();
}
@AfterEach
public void tearDown() {
DubboBootstrap.reset();
}
@Autowired
private ConfigurableListableBeanFactory beanFactory;
@Test
void test() {
Map<String, HelloService> helloServicesMap = beanFactory.getBeansOfType(HelloService.class);
Assertions.assertEquals(2, helloServicesMap.size());
Map<String, ServiceBean> serviceBeansMap = beanFactory.getBeansOfType(ServiceBean.class);
Assertions.assertEquals(3, serviceBeansMap.size());
Map<String, ServiceAnnotationPostProcessor> beanPostProcessorsMap =
beanFactory.getBeansOfType(ServiceAnnotationPostProcessor.class);
Assertions.assertEquals(2, beanPostProcessorsMap.size());
}
@Test
void testMethodAnnotation() {
Map<String, ServiceBean> serviceBeansMap = beanFactory.getBeansOfType(ServiceBean.class);
Assertions.assertEquals(3, serviceBeansMap.size());
ServiceBean demoServiceBean =
serviceBeansMap.get("ServiceBean:org.apache.dubbo.config.spring.api.DemoService:2.5.7:");
Assertions.assertNotNull(demoServiceBean.getMethods());
}
@DubboComponentScan({"org.apache.dubbo.config.spring.context.annotation", "${provider.package}"})
static class DuplicatedScanConfig {}
}
| 8,704 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceAnnotationTestConfiguration.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.spring.beans.factory.annotation;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
/**
* {@link Service} Bean
*
* @since 2.6.5
*/
@PropertySource("classpath:/META-INF/default.properties")
public class ServiceAnnotationTestConfiguration {
/**
* Current application configuration, to replace XML config:
* <prev>
* <dubbo:application name="dubbo-demo-application"/>
* </prev>
*
* @return {@link ApplicationConfig} Bean
*/
@Bean("dubbo-demo-application")
public ApplicationConfig applicationConfig() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName("dubbo-demo-application");
return applicationConfig;
}
/**
* Current registry center configuration, to replace XML config:
* <prev>
* <dubbo:registry id="my-registry" address="N/A"/>
* </prev>
*
* @return {@link RegistryConfig} Bean
*/
@Bean("my-registry")
public RegistryConfig registryConfig() {
RegistryConfig registryConfig = new RegistryConfig();
registryConfig.setAddress("N/A");
return registryConfig;
}
/**
* Current protocol configuration, to replace XML config:
* <prev>
* <dubbo:protocol name="dubbo" port="12345"/>
* </prev>
*
* @return {@link ProtocolConfig} Bean
*/
@Bean // ("dubbo")
public ProtocolConfig protocolConfig() {
ProtocolConfig protocolConfig = new ProtocolConfig();
protocolConfig.setName("dubbo");
protocolConfig.setPort(12345);
return protocolConfig;
}
@Primary
@Bean
public PlatformTransactionManager platformTransactionManager() {
return new PlatformTransactionManager() {
@Override
public TransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {
return null;
}
@Override
public void commit(TransactionStatus status) throws TransactionException {}
@Override
public void rollback(TransactionStatus status) throws TransactionException {}
};
}
}
| 8,705 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/DubboConfigAliasPostProcessorTest.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.spring.beans.factory.annotation;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
class DubboConfigAliasPostProcessorTest {
private static final String APP_NAME = "APP_NAME";
private static final String APP_ID = "APP_ID";
@Test
void test() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfigurationX.class);
try {
context.start();
Assertions.assertEquals(context.getAliases(APP_NAME)[0], APP_ID);
Assertions.assertEquals(context.getAliases(APP_ID)[0], APP_NAME);
Assertions.assertEquals(context.getBean(APP_NAME), context.getBean(APP_ID));
} finally {
context.close();
}
}
@EnableDubbo(scanBasePackages = "")
@Configuration
static class TestConfigurationX {
@Bean(APP_NAME)
public ApplicationConfig applicationConfig() {
ApplicationConfig applicationConfig = new ApplicationConfig();
applicationConfig.setName(APP_NAME);
applicationConfig.setId(APP_ID);
return applicationConfig;
}
}
}
| 8,706 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceAnnotationBeanPostProcessorTest.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.spring.beans.factory.annotation;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.reference.ReferenceBeanManager;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.rpc.RpcContext;
import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
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.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.InjectionMetadata;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
/**
* {@link ReferenceAnnotationBeanPostProcessor} Test
*
* @since 2.5.7
*/
@EnableDubbo(scanBasePackages = "org.apache.dubbo.config.spring.context.annotation.provider")
@ExtendWith(SpringExtension.class)
@ContextConfiguration(
classes = {
ServiceAnnotationTestConfiguration.class,
ReferenceAnnotationBeanPostProcessorTest.class,
ReferenceAnnotationBeanPostProcessorTest.MyConfiguration.class,
ReferenceAnnotationBeanPostProcessorTest.TestAspect.class
})
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
@TestPropertySource(
properties = {
"consumer.version = ${demo.service.version}",
"consumer.url = dubbo://127.0.0.1:12345?version=2.5.7",
})
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
class ReferenceAnnotationBeanPostProcessorTest {
@BeforeAll
public static void setUp() {
DubboBootstrap.reset();
}
@AfterEach
public void tearDown() {
DubboBootstrap.reset();
}
private static final String AOP_SUFFIX = "(based on AOP)";
@Aspect
@Component
public static class TestAspect {
@Around("execution(* org.apache.dubbo.config.spring.context.annotation.provider.DemoServiceImpl.*(..))")
public Object aroundDemoService(ProceedingJoinPoint pjp) throws Throwable {
return pjp.proceed() + AOP_SUFFIX + " from "
+ RpcContext.getContext().getLocalAddress();
}
@Around("execution(* org.apache.dubbo.config.spring.context.annotation.provider.*HelloService*.*(..))")
public Object aroundHelloService(ProceedingJoinPoint pjp) throws Throwable {
return pjp.proceed() + AOP_SUFFIX + " from "
+ RpcContext.getContext().getLocalAddress();
}
}
@Autowired
private ConfigurableApplicationContext context;
@Autowired
private HelloService defaultHelloService;
@Autowired
private HelloService helloServiceImpl;
@Autowired
private DemoService demoServiceImpl;
// #5 ReferenceBean (Field Injection #3)
@Reference(id = "helloService", methods = @Method(name = "sayHello", timeout = 100))
private HelloService helloService;
// #6 ReferenceBean (Field Injection #4)
@DubboReference(version = "2", url = "dubbo://127.0.0.1:12345?version=2", tag = "demo_tag")
private HelloService helloService2;
// #7 ReferenceBean (Field Injection #5)
// The HelloService is the same as above service(#6 ReferenceBean (Field Injection #4)), helloService3 will be
// registered as an alias of helloService2
@DubboReference(version = "2", url = "dubbo://127.0.0.1:12345?version=2", tag = "demo_tag")
private HelloService helloService3;
// #8 ReferenceBean (Method Injection #3)
@DubboReference(version = "3", url = "dubbo://127.0.0.1:12345?version=2", tag = "demo_tag")
public void setHelloService2(HelloService helloService2) {
// The helloService2 beanName is the same as above(#6 ReferenceBean (Field Injection #4)), and this will rename
// to helloService2#2
renamedHelloService2 = helloService2;
}
// #9 ReferenceBean (Method Injection #4)
@DubboReference(version = "4", url = "dubbo://127.0.0.1:12345?version=2")
public void setHelloService3(DemoService helloService3) {
// The helloService3 beanName is the same as above(#7 ReferenceBean (Field Injection #5) is an alias),
// The current beanName(helloService3) is not registered in the beanDefinitionMap, but it is already an alias.
// so this will rename to helloService3#2
this.renamedHelloService3 = helloService3;
}
private HelloService renamedHelloService2;
private DemoService renamedHelloService3;
@Test
void testAop() throws Exception {
Assertions.assertTrue(context.containsBean("helloService"));
TestBean testBean = context.getBean(TestBean.class);
Map<String, DemoService> demoServicesMap = context.getBeansOfType(DemoService.class);
Assertions.assertNotNull(testBean.getDemoServiceFromAncestor());
Assertions.assertNotNull(testBean.getDemoServiceFromParent());
Assertions.assertNotNull(testBean.getDemoService());
Assertions.assertNotNull(testBean.myDemoService);
Assertions.assertEquals(3, demoServicesMap.size());
Assertions.assertNotNull(context.getBean("demoServiceImpl"));
Assertions.assertNotNull(context.getBean("myDemoService"));
Assertions.assertNotNull(context.getBean("demoService"));
Assertions.assertNotNull(context.getBean("demoServiceFromParent"));
String callSuffix = AOP_SUFFIX + " from " + InetSocketAddress.createUnresolved(NetUtils.getLocalHost(), 12345);
String localCallSuffix = AOP_SUFFIX + " from " + InetSocketAddress.createUnresolved("127.0.0.1", 0);
String directInvokeSuffix = AOP_SUFFIX + " from null";
String defaultHelloServiceResult = "Greeting, Mercy";
Assertions.assertEquals(defaultHelloServiceResult + directInvokeSuffix, defaultHelloService.sayHello("Mercy"));
Assertions.assertEquals(defaultHelloServiceResult + localCallSuffix, helloService.sayHello("Mercy"));
String helloServiceImplResult = "Hello, Mercy";
Assertions.assertEquals(helloServiceImplResult + directInvokeSuffix, helloServiceImpl.sayHello("Mercy"));
Assertions.assertEquals(helloServiceImplResult + callSuffix, helloService2.sayHello("Mercy"));
String demoServiceResult = "Hello,Mercy";
Assertions.assertEquals(demoServiceResult + directInvokeSuffix, demoServiceImpl.sayName("Mercy"));
Assertions.assertEquals(
demoServiceResult + callSuffix,
testBean.getDemoServiceFromAncestor().sayName("Mercy"));
Assertions.assertEquals(demoServiceResult + callSuffix, testBean.myDemoService.sayName("Mercy"));
Assertions.assertEquals(
demoServiceResult + callSuffix, testBean.getDemoService().sayName("Mercy"));
Assertions.assertEquals(
demoServiceResult + callSuffix,
testBean.getDemoServiceFromParent().sayName("Mercy"));
DemoService myDemoService = context.getBean("myDemoService", DemoService.class);
Assertions.assertEquals(demoServiceResult + callSuffix, myDemoService.sayName("Mercy"));
}
@Test
void testGetInjectedFieldReferenceBeanMap() {
ReferenceAnnotationBeanPostProcessor beanPostProcessor = getReferenceAnnotationBeanPostProcessor();
Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> referenceBeanMap =
beanPostProcessor.getInjectedFieldReferenceBeanMap();
Assertions.assertEquals(5, referenceBeanMap.size());
Map<String, Integer> checkingFieldNames = new HashMap<>();
checkingFieldNames.put(
"private org.apache.dubbo.config.spring.api.HelloService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest$MyConfiguration.helloService",
0);
checkingFieldNames.put(
"private org.apache.dubbo.config.spring.api.HelloService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest.helloService",
0);
checkingFieldNames.put(
"private org.apache.dubbo.config.spring.api.HelloService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest.helloService2",
0);
checkingFieldNames.put(
"private org.apache.dubbo.config.spring.api.HelloService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest.helloService3",
0);
checkingFieldNames.put(
"private org.apache.dubbo.config.spring.api.DemoService org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessorTest$ParentBean.demoServiceFromParent",
0);
for (Map.Entry<InjectionMetadata.InjectedElement, ReferenceBean<?>> entry : referenceBeanMap.entrySet()) {
InjectionMetadata.InjectedElement injectedElement = entry.getKey();
String member = injectedElement.getMember().toString();
Integer count = checkingFieldNames.get(member);
Assertions.assertNotNull(count);
checkingFieldNames.put(member, count + 1);
}
for (Map.Entry<String, Integer> entry : checkingFieldNames.entrySet()) {
Assertions.assertEquals(1, entry.getValue().intValue(), "check field element failed: " + entry.getKey());
}
}
private ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor() {
return DubboBeanUtils.getReferenceAnnotationBeanPostProcessor(context);
}
@Test
void testGetInjectedMethodReferenceBeanMap() {
ReferenceAnnotationBeanPostProcessor beanPostProcessor = getReferenceAnnotationBeanPostProcessor();
Map<InjectionMetadata.InjectedElement, ReferenceBean<?>> referenceBeanMap =
beanPostProcessor.getInjectedMethodReferenceBeanMap();
Assertions.assertEquals(4, referenceBeanMap.size());
Map<String, Integer> checkingMethodNames = new HashMap<>();
checkingMethodNames.put("setDemoServiceFromAncestor", 0);
checkingMethodNames.put("setDemoService", 0);
checkingMethodNames.put("setHelloService2", 0);
checkingMethodNames.put("setHelloService3", 0);
for (Map.Entry<InjectionMetadata.InjectedElement, ReferenceBean<?>> entry : referenceBeanMap.entrySet()) {
InjectionMetadata.InjectedElement injectedElement = entry.getKey();
java.lang.reflect.Method method = (java.lang.reflect.Method) injectedElement.getMember();
Integer count = checkingMethodNames.get(method.getName());
Assertions.assertNotNull(count);
Assertions.assertEquals(0, count.intValue());
checkingMethodNames.put(method.getName(), count + 1);
}
for (Map.Entry<String, Integer> entry : checkingMethodNames.entrySet()) {
Assertions.assertEquals(1, entry.getValue().intValue(), "check method element failed: " + entry.getKey());
}
}
@Test
void testReferenceBeansMethodAnnotation() {
ReferenceBeanManager referenceBeanManager =
context.getBean(ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class);
Collection<ReferenceBean> referenceBeans = referenceBeanManager.getReferences();
Assertions.assertEquals(5, referenceBeans.size());
for (ReferenceBean referenceBean : referenceBeans) {
ReferenceConfig referenceConfig = referenceBean.getReferenceConfig();
Assertions.assertNotNull(referenceConfig);
Assertions.assertNotNull(referenceConfig.get());
}
ReferenceBean helloServiceReferenceBean = referenceBeanManager.getById("helloService");
Assertions.assertEquals("helloService", helloServiceReferenceBean.getId());
ReferenceConfig referenceConfig = helloServiceReferenceBean.getReferenceConfig();
Assertions.assertEquals(1, referenceConfig.getMethods().size());
ReferenceBean demoServiceFromParentReferenceBean = referenceBeanManager.getById("demoServiceFromParent");
ReferenceBean demoServiceReferenceBean = referenceBeanManager.getById("demoService");
Assertions.assertEquals(demoServiceFromParentReferenceBean.getKey(), demoServiceReferenceBean.getKey());
Assertions.assertEquals(
demoServiceFromParentReferenceBean.getReferenceConfig(), demoServiceReferenceBean.getReferenceConfig());
Assertions.assertSame(demoServiceFromParentReferenceBean, demoServiceReferenceBean);
ReferenceBean helloService2Bean = referenceBeanManager.getById("helloService2");
Assertions.assertNotNull(helloService2Bean);
Assertions.assertNotNull(helloService2Bean.getReferenceConfig());
Assertions.assertEquals(
"demo_tag", helloService2Bean.getReferenceConfig().getTag());
Assertions.assertNotNull(referenceBeanManager.getById("myDemoService"));
Assertions.assertNotNull(referenceBeanManager.getById("helloService2#2"));
}
private static class AncestorBean {
private DemoService demoServiceFromAncestor;
@Autowired
private ApplicationContext applicationContext;
public DemoService getDemoServiceFromAncestor() {
return demoServiceFromAncestor;
}
// #4 ReferenceBean (Method Injection #2)
@Reference(id = "myDemoService", version = "2.5.7", url = "dubbo://127.0.0.1:12345?version=2.5.7")
public void setDemoServiceFromAncestor(DemoService demoServiceFromAncestor) {
this.demoServiceFromAncestor = demoServiceFromAncestor;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
}
private static class ParentBean extends AncestorBean {
// #2 ReferenceBean (Field Injection #2)
@Reference(version = "${consumer.version}", url = "${consumer.url}")
private DemoService demoServiceFromParent;
public DemoService getDemoServiceFromParent() {
return demoServiceFromParent;
}
}
static class TestBean extends ParentBean {
private DemoService demoService;
@Autowired
private DemoService myDemoService;
@Autowired
private ApplicationContext applicationContext;
public DemoService getDemoService() {
return demoService;
}
// #3 ReferenceBean (Method Injection #1)
@Reference(version = "2.5.7", url = "dubbo://127.0.0.1:12345?version=2.5.7")
public void setDemoService(DemoService demoService) {
this.demoService = demoService;
}
}
@Configuration
static class MyConfiguration {
// #1 ReferenceBean (Field Injection #1)
@Reference(methods = @Method(name = "sayHello", timeout = 100))
private HelloService helloService;
@Bean
public TestBean testBean() {
return new TestBean();
}
}
}
| 8,707 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/MethodConfigCallbackTest.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.spring.beans.factory.annotation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.api.MethodCallback;
import org.apache.dubbo.config.spring.context.annotation.provider.ProviderConfiguration;
import org.apache.dubbo.config.spring.impl.MethodCallbackImpl;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.awaitility.Awaitility.await;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(
classes = {
ProviderConfiguration.class,
MethodConfigCallbackTest.class,
MethodConfigCallbackTest.MethodCallbackConfiguration.class
})
@TestPropertySource(properties = {"dubbo.protocol.port=-1", "dubbo.registry.address=${zookeeper.connection.address}"})
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class MethodConfigCallbackTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
private ConfigurableApplicationContext context;
@DubboReference(
check = false,
async = true,
injvm = false, // Currently, local call is not supported method callback cause by Injvm protocol is not
// supported ClusterFilter
methods = {
@Method(
name = "sayHello",
oninvoke = "methodCallback.oninvoke1",
onreturn = "methodCallback.onreturn1",
onthrow = "methodCallback.onthrow1")
})
private HelloService helloServiceMethodCallBack;
@DubboReference(
check = false,
async = true,
injvm = false, // Currently, local call is not supported method callback cause by Injvm protocol is not
// supported ClusterFilter
methods = {
@Method(
name = "sayHello",
oninvoke = "methodCallback.oninvoke2",
onreturn = "methodCallback.onreturn2",
onthrow = "methodCallback.onthrow2")
})
private HelloService helloServiceMethodCallBack2;
@Test
void testMethodAnnotationCallBack() {
int threadCnt = Math.min(4, Runtime.getRuntime().availableProcessors());
int callCnt = 2 * threadCnt;
for (int i = 0; i < threadCnt; i++) {
new Thread(() -> {
for (int j = 0; j < callCnt; j++) {
helloServiceMethodCallBack.sayHello("dubbo");
helloServiceMethodCallBack2.sayHello("dubbo(2)");
}
})
.start();
}
await().until(() -> MethodCallbackImpl.cnt.get() >= (2 * threadCnt * callCnt));
MethodCallback notify = (MethodCallback) context.getBean("methodCallback");
StringBuilder invoke1Builder = new StringBuilder();
StringBuilder invoke2Builder = new StringBuilder();
StringBuilder return1Builder = new StringBuilder();
StringBuilder return2Builder = new StringBuilder();
for (int i = 0; i < threadCnt * callCnt; i++) {
invoke1Builder.append("dubbo invoke success!");
invoke2Builder.append("dubbo invoke success(2)!");
return1Builder.append("dubbo return success!");
return2Builder.append("dubbo return success(2)!");
}
Assertions.assertEquals(invoke1Builder.toString(), notify.getOnInvoke1());
Assertions.assertEquals(return1Builder.toString(), notify.getOnReturn1());
Assertions.assertEquals(invoke2Builder.toString(), notify.getOnInvoke2());
Assertions.assertEquals(return2Builder.toString(), notify.getOnReturn2());
}
@Configuration
static class MethodCallbackConfiguration {
@Bean("methodCallback")
public MethodCallback methodCallback() {
return new MethodCallbackImpl();
}
}
}
| 8,708 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ServiceBeanNameBuilderTest.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.spring.beans.factory.annotation;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.config.spring.api.DemoService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.mock.env.MockEnvironment;
import org.springframework.util.ReflectionUtils;
import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilderTest.GROUP;
import static org.apache.dubbo.config.spring.beans.factory.annotation.ServiceBeanNameBuilderTest.VERSION;
/**
* {@link ServiceBeanNameBuilder} Test
*
* @see ServiceBeanNameBuilder
* @since 2.6.6
*/
@Service(
interfaceClass = DemoService.class,
group = GROUP,
version = VERSION,
application = "application",
module = "module",
registry = {"1", "2", "3"})
class ServiceBeanNameBuilderTest {
@Reference(
interfaceClass = DemoService.class,
group = "DUBBO",
version = "${dubbo.version}",
application = "application",
module = "module",
registry = {"1", "2", "3"})
static final Class<?> INTERFACE_CLASS = DemoService.class;
static final String GROUP = "DUBBO";
static final String VERSION = "1.0.0";
private MockEnvironment environment;
@BeforeEach
public void prepare() {
environment = new MockEnvironment();
environment.setProperty("dubbo.version", "1.0.0");
}
@Test
void testServiceAnnotation() {
Service service = AnnotationUtils.getAnnotation(ServiceBeanNameBuilderTest.class, Service.class);
ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(service, INTERFACE_CLASS, environment);
Assertions.assertEquals(
"ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", builder.build());
}
@Test
void testReferenceAnnotation() {
Reference reference = AnnotationUtils.getAnnotation(
ReflectionUtils.findField(ServiceBeanNameBuilderTest.class, "INTERFACE_CLASS"), Reference.class);
ServiceBeanNameBuilder builder = ServiceBeanNameBuilder.create(reference, INTERFACE_CLASS, environment);
Assertions.assertEquals(
"ServiceBean:org.apache.dubbo.config.spring.api.DemoService:1.0.0:DUBBO", builder.build());
}
@Test
void testServiceNameBuild() {
ServiceBeanNameBuilder vBuilder = ServiceBeanNameBuilder.create(INTERFACE_CLASS, environment);
String vBeanName = vBuilder.version("DUBBO").build();
ServiceBeanNameBuilder gBuilder = ServiceBeanNameBuilder.create(INTERFACE_CLASS, environment);
String gBeanName = gBuilder.group("DUBBO").build();
Assertions.assertNotEquals(vBeanName, gBeanName);
}
}
| 8,709 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/beans/factory/annotation/ReferenceCreatorTest.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.spring.beans.factory.annotation;
import org.apache.dubbo.config.ArgumentConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MethodConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.annotation.Argument;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.impl.NotifyService;
import org.apache.dubbo.config.spring.reference.ReferenceCreator;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.spring.util.AnnotationUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.apache.dubbo.common.utils.CollectionUtils.ofSet;
import static org.springframework.core.annotation.AnnotationUtils.findAnnotation;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
import static org.springframework.util.ReflectionUtils.findField;
/**
* {@link ReferenceCreator} Test
*
* @see ReferenceCreator
* @see DubboReference
* @see Reference
* @since 2.6.4
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {ReferenceCreatorTest.class, ReferenceCreatorTest.ConsumerConfiguration.class})
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
class ReferenceCreatorTest {
private static final String MODULE_CONFIG_ID = "mymodule";
private static final String CONSUMER_CONFIG_ID = "myconsumer";
private static final String MONITOR_CONFIG_ID = "mymonitor";
private static final String REGISTRY_CONFIG_ID = "myregistry";
@DubboReference(
// interfaceClass = HelloService.class,
version = "1.0.0",
group = "TEST_GROUP",
url = "dubbo://localhost:12345",
client = "client",
generic = false,
injvm = false,
check = false,
init = false,
lazy = true,
stubevent = true,
reconnect = "reconnect",
sticky = true,
proxy = "javassist",
stub = "org.apache.dubbo.config.spring.api.HelloService",
cluster = "failover",
connections = 3,
callbacks = 1,
onconnect = "onconnect",
ondisconnect = "ondisconnect",
owner = "owner",
layer = "layer",
retries = 1,
loadbalance = "random",
async = true,
actives = 3,
sent = true,
mock = "mock",
validation = "validation",
timeout = 3,
cache = "cache",
filter = {"echo", "generic", "accesslog"},
listener = {"deprecated"},
parameters = {"n1=v1 ", "n2 = v2 ", " n3 = v3 "},
application = "application",
module = MODULE_CONFIG_ID,
consumer = CONSUMER_CONFIG_ID,
monitor = MONITOR_CONFIG_ID,
registry = {REGISTRY_CONFIG_ID},
// @since 2.7.3
id = "reference",
// @since 2.7.8
services = {"service1", "service2", "service3", "service2", "service1"},
providedBy = {"service1", "service2", "service3"},
methods =
@Method(
name = "sayHello",
isReturn = false,
loadbalance = "loadbalance",
oninvoke = "notifyService.onInvoke",
onreturn = "notifyService.onReturn",
onthrow = "notifyService.onThrow",
timeout = 1000,
retries = 2,
parameters = {"a", "1", "b", "2"},
arguments = @Argument(index = 0, callback = true)))
private HelloService helloService;
@Autowired
private ApplicationContext context;
@Autowired
private NotifyService notifyService;
@BeforeAll
public static void setUp() {
DubboBootstrap.reset();
}
@Test
void testBuild() throws Exception {
Field helloServiceField = findField(getClass(), "helloService");
DubboReference reference = findAnnotation(helloServiceField, DubboReference.class);
// filter default value
AnnotationAttributes attributes = AnnotationUtils.getAnnotationAttributes(reference, true);
ReferenceConfig referenceBean = ReferenceCreator.create(attributes, context)
.defaultInterfaceClass(helloServiceField.getType())
.build();
Assertions.assertEquals(HelloService.class, referenceBean.getInterfaceClass());
Assertions.assertEquals("org.apache.dubbo.config.spring.api.HelloService", referenceBean.getInterface());
Assertions.assertEquals("1.0.0", referenceBean.getVersion());
Assertions.assertEquals("TEST_GROUP", referenceBean.getGroup());
Assertions.assertEquals("dubbo://localhost:12345", referenceBean.getUrl());
Assertions.assertEquals("client", referenceBean.getClient());
Assertions.assertEquals(null, referenceBean.isGeneric());
Assertions.assertEquals(false, referenceBean.isInjvm());
Assertions.assertEquals(false, referenceBean.isCheck());
Assertions.assertEquals(false, referenceBean.isInit());
Assertions.assertEquals(true, referenceBean.getLazy());
Assertions.assertEquals(true, referenceBean.getStubevent());
Assertions.assertEquals("reconnect", referenceBean.getReconnect());
Assertions.assertEquals(true, referenceBean.getSticky());
Assertions.assertEquals("javassist", referenceBean.getProxy());
Assertions.assertEquals("org.apache.dubbo.config.spring.api.HelloService", referenceBean.getStub());
Assertions.assertEquals("failover", referenceBean.getCluster());
Assertions.assertEquals(Integer.valueOf(3), referenceBean.getConnections());
Assertions.assertEquals(Integer.valueOf(1), referenceBean.getCallbacks());
Assertions.assertEquals("onconnect", referenceBean.getOnconnect());
Assertions.assertEquals("ondisconnect", referenceBean.getOndisconnect());
Assertions.assertEquals("owner", referenceBean.getOwner());
Assertions.assertEquals("layer", referenceBean.getLayer());
Assertions.assertEquals(Integer.valueOf(1), referenceBean.getRetries());
Assertions.assertEquals("random", referenceBean.getLoadbalance());
Assertions.assertEquals(true, referenceBean.isAsync());
Assertions.assertEquals(Integer.valueOf(3), referenceBean.getActives());
Assertions.assertEquals(true, referenceBean.getSent());
Assertions.assertEquals("mock", referenceBean.getMock());
Assertions.assertEquals("validation", referenceBean.getValidation());
Assertions.assertEquals(Integer.valueOf(3), referenceBean.getTimeout());
Assertions.assertEquals("cache", referenceBean.getCache());
Assertions.assertEquals("echo,generic,accesslog", referenceBean.getFilter());
Assertions.assertEquals("deprecated", referenceBean.getListener());
Assertions.assertEquals("reference", referenceBean.getId());
Assertions.assertEquals(ofSet("service1", "service2", "service3"), referenceBean.getSubscribedServices());
Assertions.assertEquals("service1,service2,service3", referenceBean.getProvidedBy());
Assertions.assertEquals(REGISTRY_CONFIG_ID, referenceBean.getRegistryIds());
// parameters
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("n1", "v1");
parameters.put("n2", "v2");
parameters.put("n3", "v3");
Assertions.assertEquals(parameters, referenceBean.getParameters());
// methods
List<MethodConfig> methods = referenceBean.getMethods();
Assertions.assertNotNull(methods);
Assertions.assertEquals(1, methods.size());
MethodConfig methodConfig = methods.get(0);
Assertions.assertEquals("sayHello", methodConfig.getName());
Assertions.assertEquals(false, methodConfig.isReturn());
Assertions.assertEquals(1000, methodConfig.getTimeout());
Assertions.assertEquals(2, methodConfig.getRetries());
Assertions.assertEquals("loadbalance", methodConfig.getLoadbalance());
Assertions.assertEquals(notifyService, methodConfig.getOninvoke());
Assertions.assertEquals(notifyService, methodConfig.getOnreturn());
Assertions.assertEquals(notifyService, methodConfig.getOnthrow());
Assertions.assertEquals("onInvoke", methodConfig.getOninvokeMethod());
Assertions.assertEquals("onReturn", methodConfig.getOnreturnMethod());
Assertions.assertEquals("onThrow", methodConfig.getOnthrowMethod());
// method parameters
Map<String, String> methodParameters = new HashMap<String, String>();
methodParameters.put("a", "1");
methodParameters.put("b", "2");
Assertions.assertEquals(methodParameters, methodConfig.getParameters());
// method arguments
List<ArgumentConfig> arguments = methodConfig.getArguments();
Assertions.assertEquals(1, arguments.size());
ArgumentConfig argumentConfig = arguments.get(0);
Assertions.assertEquals(0, argumentConfig.getIndex());
Assertions.assertEquals(true, argumentConfig.isCallback());
// Asserts Null fields
Assertions.assertThrows(IllegalStateException.class, referenceBean::getApplication);
Assertions.assertNotNull(referenceBean.getModule());
Assertions.assertNotNull(referenceBean.getConsumer());
Assertions.assertNotNull(referenceBean.getMonitor());
}
@Configuration
public static class ConsumerConfiguration {
@Bean
public NotifyService notifyService() {
return new NotifyService();
}
@Bean("org.apache.dubbo.rpc.model.ModuleModel")
public ModuleModel moduleModel() {
return ApplicationModel.defaultModel().getDefaultModule();
}
@Bean(CONSUMER_CONFIG_ID)
public ConsumerConfig consumerConfig() {
return new ConsumerConfig();
}
@Bean(MONITOR_CONFIG_ID)
public MonitorConfig monitorConfig() {
return new MonitorConfig();
}
@Bean(MODULE_CONFIG_ID)
public ModuleConfig moduleConfig() {
return new ModuleConfig();
}
}
}
| 8,710 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockRegistry.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.spring.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.Registry;
import java.util.ArrayList;
import java.util.List;
public class MockRegistry implements Registry {
private URL url;
private List<URL> registered = new ArrayList<URL>();
private List<URL> subscribered = new ArrayList<URL>();
public MockRegistry(URL url) {
if (url == null) {
throw new NullPointerException();
}
this.url = url;
}
public List<URL> getRegistered() {
return registered;
}
public List<URL> getSubscribered() {
return subscribered;
}
public URL getUrl() {
return url;
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public void destroy() {}
@Override
public void register(URL url) {
registered.add(url);
}
@Override
public void unregister(URL url) {
registered.remove(url);
}
@Override
public void subscribe(URL url, NotifyListener listener) {
subscribered.add(url);
}
@Override
public void unsubscribe(URL url, NotifyListener listener) {
subscribered.remove(url);
}
@Override
public List<URL> lookup(URL url) {
return null;
}
}
| 8,711 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockRegistryFactory.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.spring.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.RegistryFactory;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class MockRegistryFactory implements RegistryFactory {
private static final Map<URL, Registry> REGISTRIES = new HashMap<URL, Registry>();
public static Collection<Registry> getCachedRegistry() {
return REGISTRIES.values();
}
public static void cleanCachedRegistry() {
REGISTRIES.clear();
}
@Override
public Registry getRegistry(URL url) {
MockRegistry registry = new MockRegistry(url);
REGISTRIES.put(url, registry);
return registry;
}
}
| 8,712 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/MockServiceDiscovery.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.spring.registry;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.AbstractServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class MockServiceDiscovery extends AbstractServiceDiscovery {
private URL registryURL;
public MockServiceDiscovery(ApplicationModel applicationModel, URL registryURL) {
super(applicationModel, registryURL);
}
public MockServiceDiscovery(String serviceName, URL registryURL) {
super(serviceName, registryURL);
}
@Override
public void doDestroy() throws Exception {}
@Override
public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {}
@Override
public void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance)
throws RuntimeException {}
@Override
public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException {}
@Override
public Set<String> getServices() {
return new HashSet<>();
}
@Override
public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException {
return Collections.emptyList();
}
@Override
public URL getUrl() {
return registryURL;
}
}
| 8,713 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderXmlBootstrap.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.spring.registry.nacos.demo.provider;
import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* {@link org.apache.dubbo.config.spring.registry.nacos.demo.service.DemoService} provider demo XML bootstrap
*/
public class DemoServiceProviderXmlBootstrap {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
context.setConfigLocation("/META-INF/spring/dubbo-nacos-provider-context.xml");
context.refresh();
System.out.println("DemoService provider (XML) is starting...");
System.in.read();
}
}
| 8,714 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/provider/DemoServiceProviderBootstrap.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.spring.registry.nacos.demo.provider;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import java.io.IOException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.PropertySource;
/**
* {@link org.apache.dubbo.config.spring.registry.nacos.demo.service.DemoService} provider demo
*/
@EnableDubbo(scanBasePackages = "org.apache.dubbo.demo.service")
@PropertySource(value = "classpath:/nacos-provider-config.properties")
public class DemoServiceProviderBootstrap {
public static void main(String[] args) throws IOException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(DemoServiceProviderBootstrap.class);
context.refresh();
System.out.println("DemoService provider is starting...");
System.in.read();
}
}
| 8,715 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerXmlBootstrap.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.spring.registry.nacos.demo.consumer;
import org.apache.dubbo.config.spring.registry.nacos.demo.service.DemoService;
import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* {@link DemoService} consumer demo XML bootstrap
*/
public class DemoServiceConsumerXmlBootstrap {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
context.setConfigLocation("/META-INF/spring/dubbo-nacos-consumer-context.xml");
context.refresh();
System.out.println("DemoService consumer (XML) is starting...");
for (int i = 1; i <= 5; i++) {
DemoService demoService = context.getBean("demoService" + i, DemoService.class);
for (int j = 0; j < 10; j++) {
System.out.println(demoService.sayName("小马哥(mercyblitz)"));
}
}
System.in.read();
context.close();
}
}
| 8,716 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/consumer/DemoServiceConsumerBootstrap.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.spring.registry.nacos.demo.consumer;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.registry.nacos.demo.service.DemoService;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.PropertySource;
/**
* {@link DemoService} consumer demo
*/
@EnableDubbo
@PropertySource(value = "classpath:/nacos-consumer-config.properties")
public class DemoServiceConsumerBootstrap {
@Reference(version = "${demo.service.version}")
private DemoService demoService;
@PostConstruct
public void init() throws InterruptedException {
for (int j = 0; j < 10; j++) {
System.out.println(demoService.sayName("小马哥(mercyblitz)"));
}
Thread.sleep(TimeUnit.SECONDS.toMillis(5));
}
public static void main(String[] args) throws IOException {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.register(DemoServiceConsumerBootstrap.class);
context.refresh();
System.in.read();
context.close();
}
}
| 8,717 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DefaultService.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.spring.registry.nacos.demo.service;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.beans.factory.annotation.Value;
/**
* Default {@link DemoService}
*
* @since 2.6.5
*/
@Service(version = "${demo.service.version}")
public class DefaultService implements DemoService {
@Value("${demo.service.name}")
private String serviceName;
public String sayName(String name) {
RpcContext rpcContext = RpcContext.getServiceContext();
return String.format(
"Service [name :%s , protocol: %s , port : %d] %s(\"%s\") : Hello,%s",
serviceName,
rpcContext.getUrl().getProtocol(),
rpcContext.getLocalPort(),
rpcContext.getMethodName(),
name,
name);
}
}
| 8,718 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/demo/service/DemoService.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.spring.registry.nacos.demo.service;
/**
* DemoService
*
* @since 2.6.5
*/
public interface DemoService {
String sayName(String name);
}
| 8,719 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/registry/nacos/nacos/NacosServiceNameTest.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.spring.registry.nacos.nacos;
import org.apache.dubbo.registry.nacos.NacosServiceName;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_CATEGORY;
import static org.apache.dubbo.registry.nacos.NacosServiceName.WILDCARD;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* {@link NacosServiceName} Test
*
* @since 2.7.3
*/
class NacosServiceNameTest {
private static final String category = DEFAULT_CATEGORY;
private static final String serviceInterface = "org.apache.dubbo.registry.nacos.NacosServiceName";
private static final String version = "1.0.0";
private static final String group = "default";
private final NacosServiceName name = new NacosServiceName();
@BeforeEach
public void init() {
name.setCategory(category);
name.setServiceInterface(serviceInterface);
name.setVersion(version);
name.setGroup(group);
}
@Test
void testGetter() {
assertEquals(category, name.getCategory());
assertEquals(serviceInterface, name.getServiceInterface());
assertEquals(version, name.getVersion());
assertEquals(group, name.getGroup());
assertEquals("providers:org.apache.dubbo.registry.nacos.NacosServiceName:1.0.0:default", name.getValue());
}
@Test
void testToString() {
assertEquals("providers:org.apache.dubbo.registry.nacos.NacosServiceName:1.0.0:default", name.toString());
}
@Test
void testIsConcrete() {
assertTrue(name.isConcrete());
name.setGroup(WILDCARD);
assertFalse(name.isConcrete());
init();
name.setVersion(WILDCARD);
assertFalse(name.isConcrete());
init();
name.setGroup(null);
name.setVersion(null);
assertTrue(name.isConcrete());
}
@Test
void testIsCompatible() {
NacosServiceName concrete = new NacosServiceName();
assertFalse(name.isCompatible(concrete));
// set category
concrete.setCategory(category);
assertFalse(name.isCompatible(concrete));
concrete.setServiceInterface(serviceInterface);
assertFalse(name.isCompatible(concrete));
concrete.setVersion(version);
assertFalse(name.isCompatible(concrete));
concrete.setGroup(group);
assertTrue(name.isCompatible(concrete));
// wildcard cases
name.setGroup(WILDCARD);
assertTrue(name.isCompatible(concrete));
init();
name.setVersion(WILDCARD);
assertTrue(name.isCompatible(concrete));
// range cases
init();
name.setGroup(group + ",2.0.0");
assertTrue(name.isCompatible(concrete));
init();
name.setVersion(version + ",2.0.0");
assertTrue(name.isCompatible(concrete));
}
}
| 8,720 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/SpringControllerService.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.spring.api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@RequestMapping("/controller")
public class SpringControllerService {
@GetMapping("/sayHello")
public String sayHello(String say) {
return say;
}
}
| 8,721 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/ProvidedByDemoService3.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.spring.api;
import org.apache.dubbo.config.annotation.ProvidedBy;
/**
* DemoService
*/
@ProvidedBy(name = {"provided-demo-service-interface1", "provided-demo-service-interface2"})
public interface ProvidedByDemoService3 {
String sayName(String name);
}
| 8,722 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/MethodCallback.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.spring.api;
public interface MethodCallback {
void oninvoke1(String request);
void onreturn1(String response, String request);
void onthrow1(Throwable ex, String request);
void oninvoke2(String request);
void onreturn2(String response, String request);
void onthrow2(Throwable ex, String request);
String getOnInvoke1();
String getOnReturn1();
String getOnThrow1();
String getOnInvoke2();
String getOnReturn2();
String getOnThrow2();
}
| 8,723 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/ProvidedByDemoService2.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.spring.api;
/**
* DemoService
*/
public interface ProvidedByDemoService2 {
String sayName(String name);
}
| 8,724 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/ProvidedByDemoService1.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.spring.api;
import org.apache.dubbo.config.annotation.ProvidedBy;
/**
* DemoService
*/
@ProvidedBy(name = "provided-demo-service-interface")
public interface ProvidedByDemoService1 {
String sayName(String name);
}
| 8,725 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/DemoServiceSon.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.spring.api;
/**
* DemoService
*/
public interface DemoServiceSon extends DemoService {
// no methods
}
| 8,726 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/DemoService.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.spring.api;
/**
* DemoService
*/
public interface DemoService {
String sayName(String name);
Box getBox();
}
| 8,727 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/Box.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.spring.api;
public interface Box {
String getName();
}
| 8,728 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/api/HelloService.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.spring.api;
public interface HelloService {
String sayHello(String name);
}
| 8,729 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockDaoImpl.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.spring.filter;
/**
* MockDaoImpl
*/
public class MockDaoImpl implements MockDao {}
| 8,730 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockDao.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.spring.filter;
/**
* MockDao
*/
public interface MockDao {}
| 8,731 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/filter/MockFilter.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.spring.filter;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.LoadBalance;
/**
* MockFilter
*/
public class MockFilter implements Filter {
private LoadBalance loadBalance;
private Protocol protocol;
private MockDao mockDao;
public MockDao getMockDao() {
return mockDao;
}
public void setMockDao(MockDao mockDao) {
this.mockDao = mockDao;
}
public LoadBalance getLoadBalance() {
return loadBalance;
}
public void setLoadBalance(LoadBalance loadBalance) {
this.loadBalance = loadBalance;
}
public Protocol getProtocol() {
return protocol;
}
public void setProtocol(Protocol protocol) {
this.protocol = protocol;
}
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
return invoker.invoke(invocation);
}
}
| 8,732 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue9172/MultipleConsumerAndProviderTest.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.spring.issues.issue9172;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.context.ModuleConfigManager;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.impl.DemoServiceImpl;
import org.apache.dubbo.config.spring.impl.HelloServiceImpl;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
/**
* Test for issue 9172
*/
class MultipleConsumerAndProviderTest {
@Test
void test() {
AnnotationConfigApplicationContext providerContext = null;
AnnotationConfigApplicationContext consumerContext = null;
try {
providerContext = new AnnotationConfigApplicationContext(ProviderConfiguration.class);
consumerContext = new AnnotationConfigApplicationContext(ConsumerConfiguration.class);
ModuleModel consumerModuleModel = DubboBeanUtils.getModuleModel(consumerContext);
ModuleConfigManager consumerConfigManager = consumerModuleModel.getConfigManager();
ReferenceConfigBase helloServiceOneConfig = consumerConfigManager.getReference("helloServiceOne");
ReferenceConfigBase demoServiceTwoConfig = consumerConfigManager.getReference("demoServiceTwo");
Assertions.assertEquals(
consumerConfigManager.getConsumer("consumer-one").get(), helloServiceOneConfig.getConsumer());
Assertions.assertEquals(
consumerConfigManager.getConsumer("consumer-two").get(), demoServiceTwoConfig.getConsumer());
Assertions.assertEquals(
consumerConfigManager.getRegistry("registry-one").get(), helloServiceOneConfig.getRegistry());
Assertions.assertEquals(
consumerConfigManager.getRegistry("registry-two").get(), demoServiceTwoConfig.getRegistry());
HelloService helloServiceOne = consumerContext.getBean("helloServiceOne", HelloService.class);
DemoService demoServiceTwo = consumerContext.getBean("demoServiceTwo", DemoService.class);
String sayHello = helloServiceOne.sayHello("dubbo");
String sayName = demoServiceTwo.sayName("dubbo");
Assertions.assertEquals("Hello, dubbo", sayHello);
Assertions.assertEquals("say:dubbo", sayName);
} finally {
if (providerContext != null) {
providerContext.close();
}
if (consumerContext != null) {
consumerContext.close();
}
}
}
@EnableDubbo(scanBasePackages = "")
@PropertySource("classpath:/META-INF/issues/issue9172/consumer.properties")
static class ConsumerConfiguration {
@DubboReference(consumer = "consumer-one")
private HelloService helloServiceOne;
@DubboReference(consumer = "consumer-two")
private DemoService demoServiceTwo;
}
@EnableDubbo(scanBasePackages = "")
@PropertySource("classpath:/META-INF/issues/issue9172/provider.properties")
static class ProviderConfiguration {
@Bean
@DubboService(provider = "provider-one")
public HelloService helloServiceOne() {
return new HelloServiceImpl();
}
@Bean
@DubboService(provider = "provider-two")
public DemoService demoServiceTwo() {
return new DemoServiceImpl();
}
}
}
| 8,733 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6000/Issue6000Test.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.spring.issues.issue6000;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.issues.issue6000.adubbo.HelloDubbo;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* The test-case for https://github.com/apache/dubbo/issues/6000
* Autowired a ReferenceBean failed in some situation in Spring enviroment
*/
@Configuration
@EnableDubbo
@ComponentScan
@PropertySource("classpath:/META-INF/issues/issue6000/config.properties")
class Issue6000Test {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Test
void test() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Issue6000Test.class);
try {
HelloDubbo helloDubbo = context.getBean(HelloDubbo.class);
String result = helloDubbo.sayHello("dubbo");
System.out.println(result);
} catch (Exception e) {
String s = e.toString();
Assertions.assertTrue(s.contains("No provider available"), s);
Assertions.assertTrue(s.contains("org.apache.dubbo.config.spring.api.HelloService:1.0.0"), s);
} finally {
context.close();
}
}
}
| 8,734 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6000
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6000/adubbo/HelloDubbo.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.spring.issues.issue6000.adubbo;
import org.apache.dubbo.config.spring.api.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class HelloDubbo {
HelloService helloService;
@Autowired
public void setHelloService(HelloService helloService) {
this.helloService = helloService;
}
public String sayHello(String name) {
return helloService.sayHello(name);
}
}
| 8,735 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6000
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6000/dubbo/MyReferenceConfig.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.spring.issues.issue6000.dubbo;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.spring.api.HelloService;
import org.springframework.context.annotation.Configuration;
/**
* This configuration class is considered to be initialized after HelloDubbo,
* but the reference bean defined in it can be injected into HelloDubbo
*/
@Configuration
public class MyReferenceConfig {
@Reference(version = "1.0.0", check = false)
HelloService helloService;
}
| 8,736 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue9207/ConfigCenterBeanTest.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.spring.issues.issue9207;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.spring.ConfigCenterBean;
import org.apache.dubbo.config.spring.SysProps;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
class ConfigCenterBeanTest {
private static final String DUBBO_PROPERTIES_FILE =
"/META-INF/issues/issue9207/dubbo-properties-in-configcenter.properties";
private static final String DUBBO_EXTERNAL_CONFIG_KEY = "my-dubbo.properties";
@Test
void testConfigCenterBeanFromProps() throws IOException {
SysProps.setProperty("dubbo.config-center.include-spring-env", "true");
SysProps.setProperty("dubbo.config-center.config-file", DUBBO_EXTERNAL_CONFIG_KEY);
AnnotationConfigApplicationContext applicationContext =
new AnnotationConfigApplicationContext(ProviderConfiguration.class);
try {
ConfigManager configManager =
DubboBeanUtils.getApplicationModel(applicationContext).getApplicationConfigManager();
Collection<ConfigCenterConfig> configCenters = configManager.getConfigCenters();
Assertions.assertEquals(1, configCenters.size());
ConfigCenterConfig cc = configCenters.stream().findFirst().get();
Assertions.assertFalse(cc.getExternalConfiguration().isEmpty());
Assertions.assertTrue(cc instanceof ConfigCenterBean);
// check loaded external config
String content = readContent(DUBBO_PROPERTIES_FILE);
content = applicationContext.getEnvironment().resolvePlaceholders(content);
Properties properties = new Properties();
properties.load(new StringReader(content));
Assertions.assertEquals(properties, cc.getExternalConfiguration());
} finally {
SysProps.clear();
if (applicationContext != null) {
applicationContext.close();
}
}
}
@EnableDubbo(scanBasePackages = "")
@Configuration
static class ProviderConfiguration {
@Bean
public BeanFactoryPostProcessor envPostProcessor(ConfigurableEnvironment environment) {
return new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
// add custom external configs to spring environment early before processing normal bean.
// e.g. we can do it in BeanFactoryPostProcessor or EnvironmentPostProcessor
Map<String, Object> dubboProperties = new HashMap<>();
String content = readContent(DUBBO_PROPERTIES_FILE);
dubboProperties.put(DUBBO_EXTERNAL_CONFIG_KEY, content);
MapPropertySource dubboPropertySource =
new MapPropertySource("dubbo external config", dubboProperties);
environment.getPropertySources().addLast(dubboPropertySource);
}
};
}
}
private static String readContent(String file) {
BufferedReader reader =
new BufferedReader(new InputStreamReader(ConfigCenterBeanTest.class.getResourceAsStream(file)));
String content = reader.lines().collect(Collectors.joining("\n"));
return content;
}
}
| 8,737 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue7003/Issue7003Test.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.spring.issues.issue7003;
import org.apache.dubbo.config.ReferenceConfigBase;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collection;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
*
* Multiple duplicate Dubbo Reference annotations with the same attribute generate only one instance.
* The test-case for https://github.com/apache/dubbo/issues/7003
*/
@Configuration
@EnableDubbo
@ComponentScan
@PropertySource("classpath:/META-INF/issues/issue7003/config.properties")
class Issue7003Test {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Test
void test() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Issue7003Test.class);
try {
Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(1, referenceBeanMap.size());
Collection<ReferenceConfigBase<?>> references = ApplicationModel.defaultModel()
.getDefaultModule()
.getConfigManager()
.getReferences();
Assertions.assertEquals(1, references.size());
} finally {
context.close();
}
}
@Component
static class ClassA {
@DubboReference(group = "demo", version = "1.2.3", check = false)
private HelloService helloService;
}
@Component
static class ClassB {
@DubboReference(check = false, version = "1.2.3", group = "demo")
private HelloService helloService;
}
}
| 8,738 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/issues/issue6252/Issue6252Test.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.spring.issues.issue6252;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubboConfig;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
/**
* The test-case for https://github.com/apache/dubbo/issues/6252
*
* @since 2.7.8
*/
@Configuration
@EnableDubboConfig
@PropertySource("classpath:/META-INF/issues/issue6252/config.properties")
class Issue6252Test {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@DubboReference
private DemoService demoService;
@Test
void test() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Issue6252Test.class);
try {
DemoService demoService = context.getBean(DemoService.class);
} finally {
context.close();
}
}
}
| 8,739 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/DubboConfigBeanInitializerTest.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.spring.reference;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.DubboConfigBeanInitializer;
import org.apache.dubbo.config.spring.context.annotation.provider.ProviderConfiguration;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit.jupiter.SpringExtension;
/**
* Tests for {@link org.apache.dubbo.config.spring.context.DubboConfigBeanInitializer}
*/
@ExtendWith(SpringExtension.class)
@ContextConfiguration(
classes = {
DubboConfigBeanInitializerTest.class,
DubboConfigBeanInitializerTest.AppConfiguration.class,
})
@TestPropertySource(properties = {"dubbo.protocol.port=-1", "dubbo.registry.address=${zookeeper.connection.address}"})
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
class DubboConfigBeanInitializerTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
private FooService fooService;
@Autowired
private ApplicationContext applicationContext;
@Test
void test() {
Assertions.assertNotNull(fooService, "fooService is null");
Assertions.assertNotNull(fooService.helloService, "ooService.helloService is null");
// expect fooService is registered before dubbo config bean
List<String> beanNames = Arrays.asList(applicationContext.getBeanDefinitionNames());
int fooServiceIndex = beanNames.indexOf("fooService");
int applicationConfigIndex = beanNames.indexOf("dubbo-demo-application");
int registryConfigIndex = beanNames.indexOf("my-registry");
int configInitializerIndex = beanNames.indexOf(DubboConfigBeanInitializer.BEAN_NAME);
Assertions.assertTrue(fooServiceIndex < applicationConfigIndex);
Assertions.assertTrue(fooServiceIndex < registryConfigIndex);
Assertions.assertTrue(fooServiceIndex < configInitializerIndex);
}
@Configuration
// Import BusinessConfig first, make sure FooService bean is register early,
// expect dubbo config beans are initialized before FooService bean
@Import({BusinessConfig.class, ConsumerConfig.class, ProviderConfiguration.class})
static class AppConfiguration {}
@Configuration
static class BusinessConfig {
@Bean
public FooService fooService(ApplicationContext applicationContext) {
// Dubbo config beans should be initialized at DubboConfigInitializer, before init FooService bean
Assertions.assertTrue(DubboBeanUtils.getModuleModel(applicationContext)
.getDeployer()
.isInitialized());
Assertions.assertTrue(DubboBeanUtils.getApplicationModel(applicationContext)
.getDeployer()
.isInitialized());
Assertions.assertTrue(DubboBootstrap.getInstance().isInitialized());
return new FooService();
}
}
@Configuration
static class ConsumerConfig {
@DubboReference
private HelloService helloService;
}
static class FooService {
@Autowired
private HelloService helloService;
}
}
| 8,740 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/ReferenceKeyTest.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.spring.reference;
import org.apache.dubbo.config.annotation.Argument;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.api.ProvidedByDemoService1;
import org.apache.dubbo.config.spring.api.ProvidedByDemoService2;
import org.apache.dubbo.config.spring.api.ProvidedByDemoService3;
import org.apache.dubbo.config.spring.impl.DemoServiceImpl;
import org.apache.dubbo.config.spring.impl.HelloServiceImpl;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.alibaba.spring.util.AnnotationUtils;
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 org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.core.annotation.AnnotationAttributes;
class ReferenceKeyTest {
@BeforeEach
protected void setUp() {
DubboBootstrap.reset();
}
@Test
void testReferenceKey() throws Exception {
String helloService1 = getReferenceKey("helloService");
String helloService2 = getReferenceKey("helloService2");
String helloService3 = getReferenceKey("helloService3");
String helloService4 = getReferenceKey("helloService4");
Assertions.assertEquals(
"ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(methods=[{name=sayHello, retries=0, timeout=100}])",
helloService1);
Assertions.assertEquals(helloService1, helloService2);
Assertions.assertEquals(
"ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(methods=[{arguments=[{callback=true, index=0}], name=sayHello, timeout=100}])",
helloService3);
Assertions.assertEquals(helloService3, helloService4);
String helloServiceWithArray0 = getReferenceKey("helloServiceWithArray0");
String helloServiceWithArray1 = getReferenceKey("helloServiceWithArray1");
String helloServiceWithArray2 = getReferenceKey("helloServiceWithArray2");
String helloServiceWithMethod1 = getReferenceKey("helloServiceWithMethod1");
String helloServiceWithMethod2 = getReferenceKey("helloServiceWithMethod2");
String helloServiceWithArgument1 = getReferenceKey("helloServiceWithArgument1");
String helloServiceWithArgument2 = getReferenceKey("helloServiceWithArgument2");
Assertions.assertEquals(
"ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],parameters={a=2, b=1})",
helloServiceWithArray0);
Assertions.assertNotEquals(helloServiceWithArray0, helloServiceWithArray1);
Assertions.assertEquals(
"ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],parameters={a=1, b=2})",
helloServiceWithArray1);
Assertions.assertEquals(helloServiceWithArray1, helloServiceWithArray2);
Assertions.assertEquals(
"ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],methods=[{name=sayHello, parameters={c=1, d=2}, timeout=100}],parameters={a=1, b=2})",
helloServiceWithMethod1);
Assertions.assertEquals(helloServiceWithMethod1, helloServiceWithMethod2);
Assertions.assertEquals(
"ReferenceBean:org.apache.dubbo.config.spring.api.HelloService(check=false,filter=[echo],methods=[{arguments=[{callback=true, type=String}, {type=int}], name=sayHello, timeout=100}],parameters={a=1, b=2})",
helloServiceWithArgument1);
Assertions.assertEquals(helloServiceWithArgument1, helloServiceWithArgument2);
}
@Test
void testConfig() {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ConsumerConfiguration.class);
context.start();
Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(2, referenceBeanMap.size());
Assertions.assertEquals(
"ReferenceBean:demo/org.apache.dubbo.config.spring.api.DemoService:1.2.3(consumer=my-consumer,init=false,methods=[{arguments=[{callback=true, index=0}], name=sayName, parameters={access-token=my-token, b=2}, retries=0}],parameters={connec.timeout=1000},protocol=dubbo,registryIds=my-registry,scope=remote,timeout=1000,url=dubbo://127.0.0.1:20813)",
referenceBeanMap.get("&demoService").getKey());
}
@Test
@Disabled("support multi reference config")
public void testConfig2() {
try {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ConsumerConfiguration2.class);
context.start();
Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class);
Assertions.fail("Reference bean check failed");
} catch (BeansException e) {
String msg = getStackTrace(e);
Assertions.assertTrue(
msg.contains(
"Found multiple ReferenceConfigs with unique service name [demo/org.apache.dubbo.config.spring.api.DemoService:1.2.3]"),
msg);
// Assertions.assertTrue(msg.contains("Already exists another reference bean with the same bean
// name and type but difference attributes"), msg);
// Assertions.assertTrue(msg.contains("ConsumerConfiguration2.demoService"), msg);
}
}
@Test
void testConfig3() {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ConsumerConfiguration3.class);
context.start();
Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(3, referenceBeanMap.size());
Assertions.assertNotNull(referenceBeanMap.get("&demoService#2"));
ConsumerConfiguration3 consumerConfiguration3 = context.getBean(ConsumerConfiguration3.class);
Assertions.assertEquals(consumerConfiguration3.demoService, consumerConfiguration3.helloService);
}
@Test
void testConfig4() {
AnnotationConfigApplicationContext context = null;
try {
context = new AnnotationConfigApplicationContext(ConsumerConfiguration4.class);
context.start();
Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class);
Assertions.fail("Reference bean check failed");
} catch (BeansException e) {
String msg = getStackTrace(e);
Assertions.assertTrue(msg.contains("Duplicate spring bean name: demoService"), msg);
} finally {
if (context != null) {
context.close();
}
}
}
@Test
void testConfig5() {
try {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ConsumerConfiguration5.class);
context.start();
Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class);
Assertions.fail("Reference bean check failed");
} catch (BeansException e) {
Assertions.assertTrue(getStackTrace(e).contains("Duplicate spring bean name: demoService"));
}
}
@Test
void testConfig6() {
try {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ConsumerConfiguration6.class);
context.start();
Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class);
Assertions.fail("Reference bean check failed");
} catch (BeansException e) {
String checkString =
"Already exists another bean definition with the same bean name [demoService], but cannot rename the reference bean name";
String msg = getStackTrace(e);
Assertions.assertTrue(msg.contains(checkString), msg);
Assertions.assertTrue(msg.contains("ConsumerConfiguration6.demoService"), msg);
}
}
@Test
void testConfig7() throws Exception {
String fieldName1 = "providedByDemoService1";
String fieldName2 = "providedByDemoService2";
String fieldName3 = "providedByDemoServiceInterface";
String fieldName4 = "multiProvidedByDemoServiceInterface";
Map<String, Object> attributes1 = getReferenceAttributes(fieldName1);
Map<String, Object> attributes2 = getReferenceAttributes(fieldName2);
Map<String, Object> attributes3 = getReferenceAttributes(fieldName3);
Map<String, Object> attributes4 = getReferenceAttributes(fieldName4);
Assertions.assertEquals("provided-demo-service-interface", ((String[]) attributes1.get("providedBy"))[0]);
Assertions.assertEquals("provided-demo-service1", ((String[]) attributes1.get("providedBy"))[1]);
Assertions.assertEquals("provided-demo-service2", ((String[]) attributes2.get("providedBy"))[0]);
Assertions.assertEquals("provided-demo-service-interface", ((String[]) attributes3.get("providedBy"))[0]);
String[] serviceName4 = (String[]) attributes4.get("providedBy");
List<String> expectServices = new ArrayList<>();
expectServices.add("provided-demo-service-interface1");
expectServices.add("provided-demo-service-interface2");
Assertions.assertTrue(serviceName4.length == 2
&& expectServices.contains(serviceName4[0])
&& expectServices.contains(serviceName4[1]));
Assertions.assertEquals("provided-demo-service-interface", ((String[]) attributes3.get("providedBy"))[0]);
}
private String getStackTrace(Throwable ex) {
StringWriter stringWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
private String getReferenceKey(String fieldName) throws NoSuchFieldException {
Field field = ReferenceConfiguration.class.getDeclaredField(fieldName);
AnnotationAttributes attributes =
AnnotationUtils.getAnnotationAttributes(field, DubboReference.class, null, true);
ReferenceBeanSupport.convertReferenceProps(attributes, field.getType());
return ReferenceBeanSupport.generateReferenceKey(attributes, null);
}
private Map<String, Object> getReferenceAttributes(String fieldName) throws NoSuchFieldException {
Field field = ConsumerConfiguration7.class.getDeclaredField(fieldName);
AnnotationAttributes attributes =
AnnotationUtils.getAnnotationAttributes(field, DubboReference.class, null, true);
ReferenceBeanSupport.convertReferenceProps(attributes, field.getType());
return attributes;
}
static class ReferenceConfiguration {
@DubboReference(methods = @Method(name = "sayHello", timeout = 100, retries = 0))
private HelloService helloService;
@DubboReference(methods = @Method(timeout = 100, name = "sayHello", retries = 0))
private HelloService helloService2;
@DubboReference(
methods = @Method(name = "sayHello", timeout = 100, arguments = @Argument(index = 0, callback = true)))
private HelloService helloService3;
@DubboReference(
methods = @Method(arguments = @Argument(callback = true, index = 0), name = "sayHello", timeout = 100))
private HelloService helloService4;
// Instance 1
@DubboReference(
check = false,
parameters = {"a", "2", "b", "1"},
filter = {"echo"})
private HelloService helloServiceWithArray0;
// Instance 2
@DubboReference(
check = false,
parameters = {"a=1", "b", "2"},
filter = {"echo"})
private HelloService helloServiceWithArray1;
@DubboReference(
parameters = {"b", "2", "a", "1"},
filter = {"echo"},
check = false)
private HelloService helloServiceWithArray2;
// Instance 3
@DubboReference(
check = false,
parameters = {"a", "1", "b", "2"},
filter = {"echo"},
methods = {
@Method(
parameters = {"d", "2", "c", "1"},
name = "sayHello",
timeout = 100)
})
private HelloService helloServiceWithMethod1;
@DubboReference(
parameters = {"b=2", "a=1"},
filter = {"echo"},
check = false,
methods = {
@Method(
name = "sayHello",
timeout = 100,
parameters = {"c", "1", "d", "2"})
})
private HelloService helloServiceWithMethod2;
// Instance 4
@DubboReference(
parameters = {"a", "1", "b", "2"},
filter = {"echo"},
methods = {
@Method(
name = "sayHello",
arguments = {
@Argument(callback = true, type = "String"),
@Argument(callback = false, type = "int")
},
timeout = 100)
},
check = false)
private HelloService helloServiceWithArgument1;
@DubboReference(
check = false,
filter = {"echo"},
parameters = {"b", "2", "a", "1"},
methods = {
@Method(
name = "sayHello",
timeout = 100,
arguments = {
@Argument(callback = false, type = "int"),
@Argument(callback = true, type = "String")
})
})
private HelloService helloServiceWithArgument2;
}
@Configuration
@ImportResource({
"classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml",
"classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml"
})
static class ConsumerConfiguration {
// both are reference beans, same as xml config
@DubboReference(
group = "demo",
version = "1.2.3",
consumer = "my-consumer",
init = false,
methods = {
@Method(
arguments = {@Argument(callback = true, index = 0)},
name = "sayName",
parameters = {"access-token", "my-token", "b", "2"},
retries = 0)
},
parameters = {"connec.timeout", "1000"},
protocol = "dubbo",
registry = "my-registry",
scope = "remote",
timeout = 1000,
url = "dubbo://127.0.0.1:20813")
private DemoService demoService;
}
@Configuration
@ImportResource({
"classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml",
"classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml"
})
static class ConsumerConfiguration2 {
// both are reference beans, same bean name and type, but difference attributes from xml config
@DubboReference(
group = "demo",
version = "1.2.3",
consumer = "my-consumer",
init = false,
scope = "local",
timeout = 100)
private DemoService demoService;
}
@Configuration
@ImportResource({
"classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml",
"classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml"
})
static class ConsumerConfiguration3 {
// both are reference beans, same bean name but difference interface type
@DubboReference(
group = "demo",
version = "1.2.4",
consumer = "my-consumer",
init = false,
url = "dubbo://127.0.0.1:20813")
private HelloService demoService;
@Autowired
private HelloService helloService;
}
@Configuration
@ImportResource({
"classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml",
"classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml"
})
static class ConsumerConfiguration4 {
// not reference bean: same bean name and type
@Bean
public DemoService demoService() {
return new DemoServiceImpl();
}
}
@Configuration
@ImportResource({
"classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml",
"classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml"
})
static class ConsumerConfiguration5 {
// not reference bean: same bean name but difference type
@Bean
public HelloService demoService() {
return new HelloServiceImpl();
}
}
@Configuration
@ImportResource({
"classpath:/org/apache/dubbo/config/spring/init-reference-keys.xml",
"classpath:/org/apache/dubbo/config/spring/init-reference-properties.xml"
})
static class ConsumerConfiguration6 {
// both are reference beans, same bean name but difference interface type, fixed bean name
@DubboReference(
id = "demoService",
group = "demo",
version = "1.2.3",
consumer = "my-consumer",
init = false,
url = "dubbo://127.0.0.1:20813")
private HelloService demoService;
// @Autowired
// private HelloService helloService;
}
@Configuration
static class ConsumerConfiguration7 {
// both are reference beans, same as xml config
@DubboReference(providedBy = "provided-demo-service1")
private ProvidedByDemoService1 providedByDemoService1;
@DubboReference(providedBy = "provided-demo-service2")
private ProvidedByDemoService2 providedByDemoService2;
@DubboReference(providedBy = {"provided-demo-service3", "provided-demo-service4"})
private ProvidedByDemoService2 multiProvidedByDemoService;
@DubboReference
private ProvidedByDemoService1 providedByDemoServiceInterface;
@DubboReference
private ProvidedByDemoService3 multiProvidedByDemoServiceInterface;
}
}
| 8,741 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallmix/LocalCallReferenceMixTest.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.spring.reference.localcallmix;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.rpc.RpcContext;
import java.net.InetSocketAddress;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
@EnableDubbo
@ExtendWith(SpringExtension.class)
@PropertySource("classpath:/org/apache/dubbo/config/spring/reference/localcallmix/local-call-config.properties")
@ContextConfiguration(
classes = {LocalCallReferenceMixTest.class, LocalCallReferenceMixTest.LocalCallConfiguration.class})
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
@ImportResource("classpath:/org/apache/dubbo/config/spring/reference/localcallmix/local-call-consumer.xml")
class LocalCallReferenceMixTest {
@BeforeAll
public static void setUp() {
DubboBootstrap.reset();
}
@AfterAll
public static void tearDown() {
DubboBootstrap.reset();
}
@Autowired
private HelloService helloService;
@Autowired
private ApplicationContext applicationContext;
@Test
void testLocalCall() {
// see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke
// InjvmInvoker set remote address to 127.0.0.1:0
String result = helloService.sayHello("world");
Assertions.assertEquals(
"Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result);
}
@Configuration
public static class LocalCallConfiguration {
@DubboReference(injvm = true)
private HelloService helloService;
}
@DubboService
public static class AnotherLocalHelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "Hello " + name + ", response from provider: "
+ RpcContext.getContext().getLocalAddress();
}
}
}
| 8,742 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcalla/LocalCallReferenceAnnotationTest.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.spring.reference.localcalla;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.rpc.RpcContext;
import java.net.InetSocketAddress;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
@EnableDubbo
@ExtendWith(SpringExtension.class)
@PropertySource("classpath:/org/apache/dubbo/config/spring/reference/localcalla/local-call-config.properties")
@ContextConfiguration(
classes = {LocalCallReferenceAnnotationTest.class, LocalCallReferenceAnnotationTest.LocalCallConfiguration.class
})
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
class LocalCallReferenceAnnotationTest {
@BeforeAll
public static void setUp() {
DubboBootstrap.reset();
}
@AfterAll
public static void tearDown() {
DubboBootstrap.reset();
}
@Autowired
private HelloService helloService;
@Autowired
private ApplicationContext applicationContext;
@Test
void testLocalCall() {
// see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke
// InjvmInvoker set remote address to 127.0.0.1:0
String result = helloService.sayHello("world");
Assertions.assertEquals(
"Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result);
}
@Configuration
public static class LocalCallConfiguration {
@DubboReference(injvm = true)
private HelloService helloService;
}
@DubboService
public static class AnotherLocalHelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "Hello " + name + ", response from provider: "
+ RpcContext.getContext().getLocalAddress();
}
}
}
| 8,743 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/provider/DubboXmlProviderTest.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.spring.reference.registryNA.provider;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.rpc.RpcException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author <a href = "mailto:[email protected]">KamTo Hung</a>
*/
public class DubboXmlProviderTest {
@Test
void testProvider() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml");
context.start();
Object bean = context.getBean("helloService");
Assertions.assertNotNull(bean);
}
@Test
void testProvider2() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:/org/apache/dubbo/config/spring/reference/registryNA/provider/dubbo-provider.xml");
context.start();
Assertions.assertNotNull(context.getBean("helloService"));
ClassPathXmlApplicationContext context2 = new ClassPathXmlApplicationContext(
"classpath:/org/apache/dubbo/config/spring/reference/registryNA/consumer/dubbo-consumer.xml");
context2.start();
HelloService helloService = context2.getBean("helloService", HelloService.class);
Assertions.assertNotNull(helloService);
RpcException exception = Assertions.assertThrows(RpcException.class, () -> helloService.sayHello("dubbo"));
Assertions.assertTrue(
exception
.getMessage()
.contains(
"Failed to invoke the method sayHello in the service org.apache.dubbo.config.spring.api.HelloService. No provider available for the service org.apache.dubbo.config.spring.api.HelloService"));
}
}
| 8,744 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/registryNA/consumer/DubboXmlConsumerTest.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.spring.reference.registryNA.consumer;
import org.apache.dubbo.config.spring.api.HelloService;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
class DubboXmlConsumerTest {
@Test
void testConsumer() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
"classpath:/org/apache/dubbo/config/spring/reference/registryNA/consumer/dubbo-registryNA-consumer.xml");
context.start();
HelloService helloService = context.getBean("helloService", HelloService.class);
IllegalStateException exception =
Assertions.assertThrows(IllegalStateException.class, () -> helloService.sayHello("dubbo"));
Assertions.assertTrue(exception
.getMessage()
.contains("No such any registry to reference org.apache.dubbo.config.spring.api.HelloService"));
}
}
| 8,745 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest2.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.spring.reference.localcall;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.HelloService;
import java.net.InetSocketAddress;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(
locations = {"classpath:/org/apache/dubbo/config/spring/reference/localcall/local-call-provider.xml"})
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
public class LocalCallTest2 {
@BeforeAll
public static void setUp() {
DubboBootstrap.reset();
}
@AfterAll
public static void tearDown() {
DubboBootstrap.reset();
}
@DubboReference
private HelloService helloService;
@Autowired
private ApplicationContext applicationContext;
@Test
public void testLocalCall() {
// see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke
// InjvmInvoker set remote address to 127.0.0.1:0
String result = helloService.sayHello("world");
Assertions.assertEquals(
"Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result);
}
}
| 8,746 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalHelloServiceImpl.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.spring.reference.localcall;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.rpc.RpcContext;
public class LocalHelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "Hello " + name + ", response from provider: "
+ RpcContext.getContext().getLocalAddress();
}
}
| 8,747 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest.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.spring.reference.localcall;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.api.HelloService;
import java.net.InetSocketAddress;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(
locations = {
"classpath:/org/apache/dubbo/config/spring/reference/localcall/local-call-provider.xml",
"classpath:/org/apache/dubbo/config/spring/reference/localcall/local-call-consumer.xml"
})
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
class LocalCallTest {
@BeforeAll
public static void beforeAll() {
DubboBootstrap.reset();
}
@AfterAll
public static void afterAll() {
DubboBootstrap.reset();
}
@Autowired
private HelloService helloService;
@Autowired
// @Qualifier("localHelloService")
private HelloService localHelloService;
@Test
void testLocalCall() {
// see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke
// InjvmInvoker set remote address to 127.0.0.1:0
String result = helloService.sayHello("world");
Assertions.assertEquals(
"Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result);
// direct call local service, the remote address is null
String originResult = localHelloService.sayHello("world");
Assertions.assertEquals("Hello world, response from provider: null", originResult);
}
}
| 8,748 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/javaconfig/JavaConfigReferenceBeanTest.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.spring.reference.javaconfig;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.api.DemoService;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.config.spring.impl.HelloServiceImpl;
import org.apache.dubbo.config.spring.reference.ReferenceBeanBuilder;
import org.apache.dubbo.rpc.service.GenericException;
import org.apache.dubbo.rpc.service.GenericService;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;
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.Disabled;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
class JavaConfigReferenceBeanTest {
@BeforeEach
public void setUp() {
DubboBootstrap.reset();
}
@AfterEach
public void tearDown() {
DubboBootstrap.reset();
}
@Test
void testAnnotationAtField() {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(CommonConfig.class, AnnotationAtFieldConfiguration.class);
try {
Map<String, HelloService> helloServiceMap = context.getBeansOfType(HelloService.class);
Assertions.assertEquals(2, helloServiceMap.size());
Assertions.assertNotNull(helloServiceMap.get("helloService"));
Assertions.assertNotNull(helloServiceMap.get("helloServiceImpl"));
Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(1, referenceBeanMap.size());
ReferenceBean referenceBean = referenceBeanMap.get("&helloService");
Assertions.assertEquals("demo", referenceBean.getGroup());
Assertions.assertEquals(HelloService.class, referenceBean.getInterfaceClass());
Assertions.assertEquals(HelloService.class.getName(), referenceBean.getServiceInterface());
} finally {
context.close();
}
}
@Test
@Disabled("support multi reference config")
public void testAnnotationAtField2() {
AnnotationConfigApplicationContext context = null;
try {
context = new AnnotationConfigApplicationContext(
CommonConfig.class, AnnotationAtFieldConfiguration.class, AnnotationAtFieldConfiguration2.class);
Assertions.fail("Should not load duplicated @DubboReference fields");
} catch (Exception e) {
String msg = getStackTrace(e);
Assertions.assertTrue(
msg.contains(
"Found multiple ReferenceConfigs with unique service name [demo/org.apache.dubbo.config.spring.api.HelloService]"),
msg);
} finally {
if (context != null) {
context.close();
}
}
}
@Test
void testLazyProxy1() {
AnnotationConfigApplicationContext context = null;
try {
context = new AnnotationConfigApplicationContext(CommonConfig.class, LazyProxyConfiguration1.class);
HelloService helloServiceClient = context.getBean("helloServiceClient", HelloService.class);
Assertions.assertNotNull(helloServiceClient);
Assertions.assertInstanceOf(HelloService.class, helloServiceClient);
Class<? extends HelloService> clientClass = helloServiceClient.getClass();
Assertions.assertFalse(Modifier.isFinal(clientClass.getModifiers()));
Assertions.assertEquals("Hello, dubbo", helloServiceClient.sayHello("dubbo"));
} finally {
if (context != null) {
context.close();
}
}
}
@Test
void testLazyProxy2() {
AnnotationConfigApplicationContext context = null;
try {
context = new AnnotationConfigApplicationContext(CommonConfig.class, LazyProxyConfiguration2.class);
HelloService helloServiceClient = context.getBean("helloServiceClient", HelloService.class);
Assertions.assertNotNull(helloServiceClient);
Assertions.assertInstanceOf(HelloService.class, helloServiceClient);
Class<? extends HelloService> clientClass = helloServiceClient.getClass();
Assertions.assertFalse(Modifier.isFinal(clientClass.getModifiers()));
Assertions.assertEquals("Hello, dubbo", helloServiceClient.sayHello("dubbo"));
} finally {
if (context != null) {
context.close();
}
}
}
@Test
void testLazyProxy3() {
AnnotationConfigApplicationContext context = null;
try {
context = new AnnotationConfigApplicationContext(CommonConfig.class, LazyProxyConfiguration3.class);
HelloService helloServiceClient = context.getBean("helloServiceClient", HelloService.class);
Assertions.assertNotNull(helloServiceClient);
Assertions.assertInstanceOf(HelloService.class, helloServiceClient);
Class<? extends HelloService> clientClass = helloServiceClient.getClass();
Assertions.assertTrue(Modifier.isFinal(clientClass.getModifiers()));
Assertions.assertEquals("Hello, dubbo", helloServiceClient.sayHello("dubbo"));
} finally {
if (context != null) {
context.close();
}
}
}
private String getStackTrace(Throwable ex) {
StringWriter stringWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
@Test
void testAnnotationBean() {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(CommonConfig.class, AnnotationBeanConfiguration.class);
try {
Map<String, HelloService> helloServiceMap = context.getBeansOfType(HelloService.class);
Assertions.assertEquals(2, helloServiceMap.size());
Assertions.assertNotNull(helloServiceMap.get("helloService"));
Assertions.assertNotNull(helloServiceMap.get("helloServiceImpl"));
Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(1, referenceBeanMap.size());
ReferenceBean referenceBean = referenceBeanMap.get("&helloService");
Assertions.assertEquals("demo", referenceBean.getGroup());
Assertions.assertEquals(HelloService.class, referenceBean.getInterfaceClass());
Assertions.assertEquals(HelloService.class.getName(), referenceBean.getServiceInterface());
} finally {
context.close();
}
}
@Test
void testGenericServiceAnnotationBean() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
CommonConfig.class, GenericServiceAnnotationBeanConfiguration.class);
try {
Map<String, HelloService> helloServiceMap = context.getBeansOfType(HelloService.class);
Assertions.assertEquals(1, helloServiceMap.size());
Assertions.assertNotNull(helloServiceMap.get("helloServiceImpl"));
Map<String, GenericService> genericServiceMap = context.getBeansOfType(GenericService.class);
Assertions.assertEquals(3, genericServiceMap.size());
Assertions.assertNotNull(genericServiceMap.get("genericHelloService"));
Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(2, referenceBeanMap.size());
ReferenceBean genericHelloServiceReferenceBean = referenceBeanMap.get("&genericHelloService");
Assertions.assertEquals("demo", genericHelloServiceReferenceBean.getGroup());
Assertions.assertEquals(GenericService.class, genericHelloServiceReferenceBean.getInterfaceClass());
Assertions.assertEquals(
HelloService.class.getName(), genericHelloServiceReferenceBean.getServiceInterface());
ReferenceBean genericServiceWithoutInterfaceBean = referenceBeanMap.get("&genericServiceWithoutInterface");
Assertions.assertEquals("demo", genericServiceWithoutInterfaceBean.getGroup());
Assertions.assertEquals(GenericService.class, genericServiceWithoutInterfaceBean.getInterfaceClass());
Assertions.assertEquals(
"org.apache.dubbo.config.spring.api.LocalMissClass",
genericServiceWithoutInterfaceBean.getServiceInterface());
GenericService genericServiceWithoutInterface =
context.getBean("genericServiceWithoutInterface", GenericService.class);
Assertions.assertNotNull(genericServiceWithoutInterface);
Object sayHelloResult = genericServiceWithoutInterface.$invoke(
"sayHello", new String[] {"java.lang.String"}, new Object[] {"Dubbo"});
Assertions.assertEquals("Hello Dubbo", sayHelloResult);
} finally {
context.close();
}
}
@Test
void testReferenceBean() {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(CommonConfig.class, ReferenceBeanConfiguration.class);
try {
Map<String, HelloService> helloServiceMap = context.getBeansOfType(HelloService.class);
Assertions.assertEquals(2, helloServiceMap.size());
Assertions.assertNotNull(helloServiceMap.get("helloService"));
Assertions.assertNotNull(helloServiceMap.get("helloServiceImpl"));
Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(2, referenceBeanMap.size());
ReferenceBean referenceBean = referenceBeanMap.get("&helloService");
Assertions.assertEquals(HelloService.class, referenceBean.getInterfaceClass());
Assertions.assertEquals(HelloService.class.getName(), referenceBean.getServiceInterface());
ReferenceBean demoServiceReferenceBean = referenceBeanMap.get("&demoService");
Assertions.assertEquals(DemoService.class, demoServiceReferenceBean.getInterfaceClass());
Assertions.assertEquals(DemoService.class.getName(), demoServiceReferenceBean.getServiceInterface());
} finally {
context.close();
}
}
@Test
void testGenericServiceReferenceBean() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
CommonConfig.class, GenericServiceReferenceBeanConfiguration.class);
try {
Map<String, HelloService> helloServiceMap = context.getBeansOfType(HelloService.class);
Assertions.assertEquals(1, helloServiceMap.size());
Assertions.assertNotNull(helloServiceMap.get("helloServiceImpl"));
Map<String, GenericService> genericServiceMap = context.getBeansOfType(GenericService.class);
Assertions.assertEquals(2, genericServiceMap.size());
Assertions.assertNotNull(genericServiceMap.get("localMissClassGenericServiceImpl"));
Assertions.assertNotNull(genericServiceMap.get("genericHelloService"));
Map<String, ReferenceBean> referenceBeanMap = context.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(1, referenceBeanMap.size());
ReferenceBean genericHelloServiceReferenceBean = referenceBeanMap.get("&genericHelloService");
Assertions.assertEquals("demo", genericHelloServiceReferenceBean.getGroup());
Assertions.assertEquals(GenericService.class, genericHelloServiceReferenceBean.getInterfaceClass());
Assertions.assertEquals(
HelloService.class.getName(), genericHelloServiceReferenceBean.getServiceInterface());
} finally {
context.close();
}
}
@Test
void testRawReferenceBean() {
AnnotationConfigApplicationContext context = null;
try {
context = new AnnotationConfigApplicationContext(
CommonConfig.class, ReferenceBeanWithoutGenericTypeConfiguration.class);
Assertions.fail("Should not load application");
} catch (Exception e) {
String s = e.toString();
Assertions.assertTrue(s.contains("The ReferenceBean is missing necessary generic type"), s);
Assertions.assertTrue(s.contains("ReferenceBeanWithoutGenericTypeConfiguration#helloService()"), s);
} finally {
if (context != null) {
context.close();
}
}
}
@Test
void testInconsistentBean() {
AnnotationConfigApplicationContext context = null;
try {
context = new AnnotationConfigApplicationContext(CommonConfig.class, InconsistentBeanConfiguration.class);
Assertions.fail("Should not load application");
} catch (Exception e) {
String s = e.toString();
Assertions.assertTrue(
s.contains("@DubboReference annotation is inconsistent with the generic type of the ReferenceBean"),
s);
Assertions.assertTrue(s.contains("ReferenceBean<org.apache.dubbo.config.spring.api.HelloService>"), s);
Assertions.assertTrue(s.contains("InconsistentBeanConfiguration#helloService()"), s);
} finally {
if (context != null) {
context.close();
}
}
}
@Test
void testMissingGenericTypeBean() {
AnnotationConfigApplicationContext context = null;
try {
context = new AnnotationConfigApplicationContext(
CommonConfig.class, MissingGenericTypeAnnotationBeanConfiguration.class);
Assertions.fail("Should not load application");
} catch (Exception e) {
String s = e.toString();
Assertions.assertTrue(s.contains("The ReferenceBean is missing necessary generic type"), s);
Assertions.assertTrue(s.contains("MissingGenericTypeAnnotationBeanConfiguration#helloService()"), s);
} finally {
if (context != null) {
context.close();
}
}
}
@Test
void testMissingInterfaceTypeBean() {
AnnotationConfigApplicationContext context = null;
try {
context = new AnnotationConfigApplicationContext(
CommonConfig.class, MissingInterfaceTypeAnnotationBeanConfiguration.class);
Assertions.fail("Should not load application");
} catch (Exception e) {
String s = e.toString();
Assertions.assertTrue(s.contains("The interface class or name of reference was not found"), s);
} finally {
if (context != null) {
context.close();
}
}
}
@Configuration
@EnableDubbo
@PropertySource("classpath:/org/apache/dubbo/config/spring/reference/javaconfig/consumer.properties")
public static class CommonConfig {
@Bean
public List<String> testBean(HelloService helloService) {
return Arrays.asList(helloService.getClass().getName());
}
@Bean
@DubboService(group = "${myapp.group}")
public HelloService helloServiceImpl() {
return new HelloServiceImpl();
}
@Bean
@DubboService(group = "${myapp.group}", interfaceName = "org.apache.dubbo.config.spring.api.LocalMissClass")
public GenericService localMissClassGenericServiceImpl() {
return new GenericService() {
@Override
public Object $invoke(String method, String[] parameterTypes, Object[] args) throws GenericException {
if ("sayHello".equals(method)) {
return "Hello " + args[0];
}
return null;
}
};
}
}
@Configuration
public static class LazyProxyConfiguration1 {
@DubboReference(group = "${myapp.group}")
private HelloService helloService;
@Bean(name = "helloServiceClient")
public HelloService helloService() {
return helloService;
}
}
@Configuration
public static class LazyProxyConfiguration2 {
@DubboReference(group = "${myapp.group}", proxy = "javassist")
private HelloService helloService;
@Bean(name = "helloServiceClient")
public HelloService helloService() {
return helloService;
}
}
@Configuration
public static class LazyProxyConfiguration3 {
@DubboReference(group = "${myapp.group}", proxy = "jdk")
private HelloService helloService;
@Bean(name = "helloServiceClient")
public HelloService helloService() {
return helloService;
}
}
@Configuration
public static class AnnotationAtFieldConfiguration {
@DubboReference(group = "${myapp.group}")
private HelloService helloService;
}
@Configuration
public static class AnnotationAtFieldConfiguration2 {
@DubboReference(group = "${myapp.group}", timeout = 2000)
private HelloService helloService;
}
@Configuration
public static class AnnotationBeanConfiguration {
@Bean
@DubboReference(group = "${myapp.group}")
public ReferenceBean<HelloService> helloService() {
return new ReferenceBean();
}
}
@Configuration
public static class GenericServiceAnnotationBeanConfiguration {
@Bean
@Reference(group = "${myapp.group}", interfaceClass = HelloService.class)
public ReferenceBean<GenericService> genericHelloService() {
return new ReferenceBean();
}
@Bean
@DubboReference(
group = "${myapp.group}",
interfaceName = "org.apache.dubbo.config.spring.api.LocalMissClass",
scope = "local")
public ReferenceBean<GenericService> genericServiceWithoutInterface() {
return new ReferenceBean();
}
}
@Configuration
public static class ReferenceBeanConfiguration {
@Bean
public ReferenceBean<HelloService> helloService() {
return new ReferenceBeanBuilder().setGroup("${myapp.group}").build();
}
@Bean
public ReferenceBean<DemoService> demoService() {
return new ReferenceBean();
}
}
@Configuration
public static class GenericServiceReferenceBeanConfiguration {
@Bean
public ReferenceBean<GenericService> genericHelloService() {
return new ReferenceBeanBuilder()
.setGroup("${myapp.group}")
.setInterface(HelloService.class)
.build();
}
}
@Configuration
public static class ReferenceBeanWithoutGenericTypeConfiguration {
// The ReferenceBean is missing necessary generic type
@Bean
public ReferenceBean helloService() {
return new ReferenceBeanBuilder()
.setGroup("${myapp.group}")
.setInterface(HelloService.class)
.build();
}
}
@Configuration
public static class InconsistentBeanConfiguration {
// The 'interfaceClass' or 'interfaceName' attribute value of @DubboReference annotation is inconsistent with
// the generic type of the ReferenceBean returned by the bean method.
@Bean
@DubboReference(group = "${myapp.group}", interfaceClass = DemoService.class)
public ReferenceBean<HelloService> helloService() {
return new ReferenceBean();
}
}
@Configuration
public static class MissingGenericTypeAnnotationBeanConfiguration {
// The ReferenceBean is missing necessary generic type
@Bean
@DubboReference(group = "${myapp.group}", interfaceClass = DemoService.class)
public ReferenceBean helloService() {
return new ReferenceBean();
}
}
@Configuration
public static class MissingInterfaceTypeAnnotationBeanConfiguration {
// The ReferenceBean is missing necessary generic type
@Bean
@DubboReference(group = "${myapp.group}")
public ReferenceBean<GenericService> helloService() {
return new ReferenceBean();
}
}
}
| 8,749 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcallam/LocalCallMultipleReferenceAnnotationsTest.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.spring.reference.localcallam;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.ReferenceBean;
import org.apache.dubbo.config.spring.api.HelloService;
import org.apache.dubbo.config.spring.context.annotation.EnableDubbo;
import org.apache.dubbo.rpc.RpcContext;
import java.net.InetSocketAddress;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
@EnableDubbo
@ExtendWith(SpringExtension.class)
@PropertySource("classpath:/org/apache/dubbo/config/spring/reference/localcallam/local-call-config.properties")
@ContextConfiguration(
classes = {
LocalCallMultipleReferenceAnnotationsTest.class,
LocalCallMultipleReferenceAnnotationsTest.LocalCallConfiguration.class
})
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
class LocalCallMultipleReferenceAnnotationsTest {
@BeforeAll
public static void setUp() {
DubboBootstrap.reset();
}
@Autowired
private HelloService helloService;
@Autowired
private HelloService demoHelloService;
@Autowired
private ApplicationContext applicationContext;
@Test
void testLocalCall() {
// see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke
// InjvmInvoker set remote address to 127.0.0.1:0
String result = helloService.sayHello("world");
Assertions.assertEquals(
"Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result);
String demoResult = demoHelloService.sayHello("world");
Assertions.assertEquals(
"Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0),
demoResult);
Map<String, ReferenceBean> referenceBeanMap = applicationContext.getBeansOfType(ReferenceBean.class);
Assertions.assertEquals(2, referenceBeanMap.size());
Assertions.assertTrue(referenceBeanMap.containsKey("&helloService"));
Assertions.assertTrue(referenceBeanMap.containsKey("&demoHelloService"));
// helloService3 and demoHelloService share the same ReferenceConfig instance
ReferenceBean helloService3ReferenceBean = applicationContext.getBean("&helloService3", ReferenceBean.class);
ReferenceBean demoHelloServiceReferenceBean =
applicationContext.getBean("&demoHelloService", ReferenceBean.class);
Assertions.assertSame(helloService3ReferenceBean, demoHelloServiceReferenceBean);
}
@Configuration
public static class LocalCallConfiguration {
@DubboReference
private HelloService helloService;
@DubboReference(group = "demo", version = "2.0.0")
private HelloService demoHelloService;
@DubboReference(group = "${biz.group}", version = "${biz.version}")
private HelloService helloService3;
}
@Configuration
public static class LocalCallConfiguration2 {
@DubboReference
private HelloService helloService;
@DubboReference(group = "${biz.group}", version = "2.0.0")
private HelloService demoHelloService;
}
@Configuration
public static class LocalCallConfiguration3 {
@DubboReference(group = "foo")
private HelloService demoHelloService;
}
@DubboService
public static class AnotherLocalHelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "Hello " + name + ", response from provider: "
+ RpcContext.getContext().getLocalAddress();
}
}
@DubboService(group = "demo", version = "2.0.0")
public static class DemoHelloServiceImpl implements HelloService {
@Override
public String sayHello(String name) {
return "Hello " + name + ", response from provider: "
+ RpcContext.getContext().getLocalAddress();
}
}
}
| 8,750 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ReferenceBean.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.spring;
import org.apache.dubbo.common.bytecode.Proxy;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.ClassUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.spring.context.DubboConfigApplicationListener;
import org.apache.dubbo.config.spring.context.DubboConfigBeanInitializer;
import org.apache.dubbo.config.spring.reference.ReferenceAttributes;
import org.apache.dubbo.config.spring.reference.ReferenceBeanManager;
import org.apache.dubbo.config.spring.reference.ReferenceBeanSupport;
import org.apache.dubbo.config.spring.schema.DubboBeanDefinitionParser;
import org.apache.dubbo.config.spring.util.LazyTargetInvocationHandler;
import org.apache.dubbo.config.spring.util.LazyTargetSource;
import org.apache.dubbo.config.spring.util.LockUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.proxy.AbstractProxyFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROXY_FAILED;
/**
* <p>
* Spring FactoryBean for {@link ReferenceConfig}.
* </p>
*
*
* <p></p>
* Step 1: Register ReferenceBean in Java-config class:
* <pre class="code">
* @Configuration
* public class ReferenceConfiguration {
* @Bean
* @DubboReference(group = "demo")
* public ReferenceBean<HelloService> helloService() {
* return new ReferenceBean();
* }
*
* // As GenericService
* @Bean
* @DubboReference(group = "demo", interfaceClass = HelloService.class)
* public ReferenceBean<GenericService> genericHelloService() {
* return new ReferenceBean();
* }
* }
* </pre>
*
* Or register ReferenceBean in xml:
* <pre class="code">
* <dubbo:reference id="helloService" interface="org.apache.dubbo.config.spring.api.HelloService"/>
* <!-- As GenericService -->
* <dubbo:reference id="genericHelloService" interface="org.apache.dubbo.config.spring.api.HelloService" generic="true"/>
* </pre>
*
* Step 2: Inject ReferenceBean by @Autowired
* <pre class="code">
* public class FooController {
* @Autowired
* private HelloService helloService;
*
* @Autowired
* private GenericService genericHelloService;
* }
* </pre>
*
*
* @see org.apache.dubbo.config.annotation.DubboReference
* @see org.apache.dubbo.config.spring.reference.ReferenceBeanBuilder
*/
public class ReferenceBean<T>
implements FactoryBean<T>,
ApplicationContextAware,
BeanClassLoaderAware,
BeanNameAware,
InitializingBean,
DisposableBean {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private transient ApplicationContext applicationContext;
private ClassLoader beanClassLoader;
// lazy proxy of reference
private Object lazyProxy;
// beanName
protected String id;
// reference key
private String key;
/**
* The interface class of the reference service
*/
private Class<?> interfaceClass;
/*
* remote service interface class name
*/
// 'interfaceName' field for compatible with seata-1.4.0:
// io.seata.rm.tcc.remoting.parser.DubboRemotingParser#getServiceDesc()
private String interfaceName;
// proxy style
private String proxy;
// from annotation attributes
private Map<String, Object> referenceProps;
// from xml bean definition
private MutablePropertyValues propertyValues;
// actual reference config
private ReferenceConfig referenceConfig;
// ReferenceBeanManager
private ReferenceBeanManager referenceBeanManager;
// Registration sources of this reference, may be xml file or annotation location
private List<Map<String, Object>> sources = new ArrayList<>();
public ReferenceBean() {
super();
}
public ReferenceBean(Map<String, Object> referenceProps) {
this.referenceProps = referenceProps;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public void setBeanClassLoader(ClassLoader classLoader) {
this.beanClassLoader = classLoader;
}
@Override
public void setBeanName(String name) {
this.setId(name);
}
/**
* Create bean instance.
*
* <p></p>
* Why we need a lazy proxy?
*
* <p/>
* When Spring searches beans by type, if Spring cannot determine the type of a factory bean, it may try to initialize it.
* The ReferenceBean is also a FactoryBean.
* <br/>
* (This has already been resolved by decorating the BeanDefinition: {@link DubboBeanDefinitionParser#configReferenceBean})
*
* <p/>
* In addition, if some ReferenceBeans are dependent on beans that are initialized very early,
* and dubbo config beans are not ready yet, there will be many unexpected problems if initializing the dubbo reference immediately.
*
* <p/>
* When it is initialized, only a lazy proxy object will be created,
* and dubbo reference-related resources will not be initialized.
* <br/>
* In this way, the influence of Spring is eliminated, and the dubbo configuration initialization is controllable.
*
*
* @see DubboConfigBeanInitializer
* @see ReferenceBeanManager#initReferenceBean(ReferenceBean)
* @see DubboBeanDefinitionParser#configReferenceBean
*/
@Override
public T getObject() {
if (lazyProxy == null) {
createLazyProxy();
}
return (T) lazyProxy;
}
@Override
public Class<?> getObjectType() {
return getInterfaceClass();
}
@Override
@Parameter(excluded = true)
public boolean isSingleton() {
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// pre init xml reference bean or @DubboReference annotation
Assert.notEmptyString(getId(), "The id of ReferenceBean cannot be empty");
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(getId());
this.interfaceClass = (Class<?>) beanDefinition.getAttribute(ReferenceAttributes.INTERFACE_CLASS);
this.interfaceName = (String) beanDefinition.getAttribute(ReferenceAttributes.INTERFACE_NAME);
Assert.notNull(this.interfaceClass, "The interface class of ReferenceBean is not initialized");
if (beanDefinition.hasAttribute(Constants.REFERENCE_PROPS)) {
// @DubboReference annotation at java-config class @Bean method
// @DubboReference annotation at reference field or setter method
referenceProps = (Map<String, Object>) beanDefinition.getAttribute(Constants.REFERENCE_PROPS);
} else {
if (beanDefinition instanceof AnnotatedBeanDefinition) {
// Return ReferenceBean in java-config class @Bean method
if (referenceProps == null) {
referenceProps = new LinkedHashMap<>();
}
ReferenceBeanSupport.convertReferenceProps(referenceProps, interfaceClass);
if (this.interfaceName == null) {
this.interfaceName = (String) referenceProps.get(ReferenceAttributes.INTERFACE);
}
} else {
// xml reference bean
propertyValues = beanDefinition.getPropertyValues();
}
}
if (referenceProps != null) {
this.proxy = (String) referenceProps.get(ReferenceAttributes.PROXY);
}
Assert.notNull(this.interfaceName, "The interface name of ReferenceBean is not initialized");
this.referenceBeanManager = beanFactory.getBean(ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class);
referenceBeanManager.addReference(this);
}
private ConfigurableListableBeanFactory getBeanFactory() {
return (ConfigurableListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
}
@Override
public void destroy() {
// do nothing
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* The interface of this ReferenceBean, for injection purpose
* @return
*/
public Class<?> getInterfaceClass() {
// Compatible with seata-1.4.0: io.seata.rm.tcc.remoting.parser.DubboRemotingParser#getServiceDesc()
return interfaceClass;
}
/**
* The interface of remote service
*/
public String getServiceInterface() {
return interfaceName;
}
/**
* The group of the service
*/
public String getGroup() {
// Compatible with seata-1.4.0: io.seata.rm.tcc.remoting.parser.DubboRemotingParser#getServiceDesc()
return referenceConfig.getGroup();
}
/**
* The version of the service
*/
public String getVersion() {
// Compatible with seata-1.4.0: io.seata.rm.tcc.remoting.parser.DubboRemotingParser#getServiceDesc()
return referenceConfig.getVersion();
}
public String getKey() {
return key;
}
public Map<String, Object> getReferenceProps() {
return referenceProps;
}
public MutablePropertyValues getPropertyValues() {
return propertyValues;
}
public ReferenceConfig getReferenceConfig() {
return referenceConfig;
}
public void setKeyAndReferenceConfig(String key, ReferenceConfig referenceConfig) {
this.key = key;
this.referenceConfig = referenceConfig;
}
/**
* Create lazy proxy for reference.
*/
private void createLazyProxy() {
// set proxy interfaces
// see also: org.apache.dubbo.rpc.proxy.AbstractProxyFactory.getProxy(org.apache.dubbo.rpc.Invoker<T>, boolean)
List<Class<?>> interfaces = new ArrayList<>();
interfaces.add(interfaceClass);
Class<?>[] internalInterfaces = AbstractProxyFactory.getInternalInterfaces();
Collections.addAll(interfaces, internalInterfaces);
if (!StringUtils.isEquals(interfaceClass.getName(), interfaceName)) {
// add service interface
try {
Class<?> serviceInterface = ClassUtils.forName(interfaceName, beanClassLoader);
interfaces.add(serviceInterface);
} catch (ClassNotFoundException e) {
// generic call maybe without service interface class locally
}
}
if (StringUtils.isEmpty(this.proxy) || CommonConstants.DEFAULT_PROXY.equalsIgnoreCase(this.proxy)) {
generateFromJavassistFirst(interfaces);
}
if (this.lazyProxy == null) {
generateFromJdk(interfaces);
}
}
private void generateFromJavassistFirst(List<Class<?>> interfaces) {
try {
this.lazyProxy = Proxy.getProxy(interfaces.toArray(new Class[0]))
.newInstance(new LazyTargetInvocationHandler(new DubboReferenceLazyInitTargetSource()));
} catch (Throwable fromJavassist) {
// try fall back to JDK proxy factory
try {
this.lazyProxy = java.lang.reflect.Proxy.newProxyInstance(
beanClassLoader,
interfaces.toArray(new Class[0]),
new LazyTargetInvocationHandler(new DubboReferenceLazyInitTargetSource()));
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate proxy by Javassist failed. Fallback to use JDK proxy success. "
+ "Interfaces: " + interfaces,
fromJavassist);
} catch (Throwable fromJdk) {
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. "
+ "Interfaces: " + interfaces + " Javassist Error.",
fromJavassist);
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. "
+ "Interfaces: " + interfaces + " JDK Error.",
fromJdk);
throw fromJavassist;
}
}
}
private void generateFromJdk(List<Class<?>> interfaces) {
try {
this.lazyProxy = java.lang.reflect.Proxy.newProxyInstance(
beanClassLoader,
interfaces.toArray(new Class[0]),
new LazyTargetInvocationHandler(new DubboReferenceLazyInitTargetSource()));
} catch (Throwable fromJdk) {
logger.error(
PROXY_FAILED,
"",
"",
"Failed to generate proxy by Javassist failed. Fallback to use JDK proxy is also failed. "
+ "Interfaces: " + interfaces + " JDK Error.",
fromJdk);
throw fromJdk;
}
}
private Object getCallProxy() throws Exception {
if (referenceConfig == null) {
referenceBeanManager.initReferenceBean(this);
applicationContext
.getBean(DubboConfigApplicationListener.class.getName(), DubboConfigApplicationListener.class)
.init();
logger.warn(
CONFIG_DUBBO_BEAN_INITIALIZER,
"",
"",
"ReferenceBean is not ready yet, please make sure to call reference interface method after dubbo is started.");
}
// get reference proxy
// Subclasses should synchronize on the given Object if they perform any sort of extended singleton creation
// phase.
// In particular, subclasses should not have their own mutexes involved in singleton creation, to avoid the
// potential for deadlocks in lazy-init situations.
// The redundant type cast is to be compatible with earlier than spring-4.2
if (referenceConfig.configInitialized()) {
return referenceConfig.get();
}
synchronized (LockUtils.getSingletonMutex(applicationContext)) {
return referenceConfig.get();
}
}
private class DubboReferenceLazyInitTargetSource implements LazyTargetSource {
@Override
public Object getTarget() throws Exception {
return getCallProxy();
}
}
}
| 8,751 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ServiceBean.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.spring;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ServiceConfig;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.config.spring.context.event.ServiceBeanExportedEvent;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.config.support.Parameter;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
/**
* ServiceFactoryBean
*
* @export
*/
public class ServiceBean<T> extends ServiceConfig<T>
implements InitializingBean,
DisposableBean,
ApplicationContextAware,
BeanNameAware,
ApplicationEventPublisherAware {
private static final long serialVersionUID = 213195494150089726L;
private final transient Service service;
private transient ApplicationContext applicationContext;
private transient String beanName;
private ApplicationEventPublisher applicationEventPublisher;
public ServiceBean(ApplicationContext applicationContext) {
super();
this.service = null;
this.applicationContext = applicationContext;
this.setScopeModel(DubboBeanUtils.getModuleModel(applicationContext));
}
public ServiceBean(ApplicationContext applicationContext, ModuleModel moduleModel) {
super(moduleModel);
this.service = null;
this.applicationContext = applicationContext;
}
public ServiceBean(ApplicationContext applicationContext, Service service) {
super(service);
this.service = service;
this.applicationContext = applicationContext;
this.setScopeModel(DubboBeanUtils.getModuleModel(applicationContext));
}
public ServiceBean(ApplicationContext applicationContext, ModuleModel moduleModel, Service service) {
super(moduleModel, service);
this.service = service;
this.applicationContext = applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public void setBeanName(String name) {
this.beanName = name;
}
/**
* Gets associated {@link Service}
*
* @return associated {@link Service}
*/
public Service getService() {
return service;
}
@Override
public void afterPropertiesSet() throws Exception {
if (StringUtils.isEmpty(getPath())) {
if (StringUtils.isNotEmpty(getInterface())) {
setPath(getInterface());
}
}
// register service bean
ModuleModel moduleModel = DubboBeanUtils.getModuleModel(applicationContext);
moduleModel.getConfigManager().addService(this);
moduleModel.getDeployer().setPending();
}
/**
* Get the name of {@link ServiceBean}
*
* @return {@link ServiceBean}'s name
* @since 2.6.5
*/
@Parameter(excluded = true, attribute = false)
public String getBeanName() {
return this.beanName;
}
/**
* @since 2.6.5
*/
@Override
protected void exported() {
super.exported();
// Publish ServiceBeanExportedEvent
publishExportEvent();
}
/**
* @since 2.6.5
*/
private void publishExportEvent() {
ServiceBeanExportedEvent exportEvent = new ServiceBeanExportedEvent(this);
applicationEventPublisher.publishEvent(exportEvent);
}
@Override
public void destroy() throws Exception {
// no need to call unexport() here, see
// org.apache.dubbo.config.spring.extension.SpringExtensionInjector.ShutdownHookListener
}
// merged from dubbox
@Override
protected Class getServiceClass(T ref) {
if (AopUtils.isAopProxy(ref)) {
return AopUtils.getTargetClass(ref);
}
return super.getServiceClass(ref);
}
/**
* @param applicationEventPublisher
* @since 2.6.5
*/
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}
| 8,752 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/SpringScopeModelInitializer.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.spring;
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.ScopeModelInitializer;
/**
* Register scope beans in spring module
*/
public class SpringScopeModelInitializer implements ScopeModelInitializer {
@Override
public void initializeFrameworkModel(FrameworkModel frameworkModel) {}
@Override
public void initializeApplicationModel(ApplicationModel applicationModel) {}
@Override
public void initializeModuleModel(ModuleModel moduleModel) {}
}
| 8,753 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/ConfigCenterBean.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.spring;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.ConfigCenterConfig;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
/**
* Starting from 2.7.0+, export and refer will only be executed when Spring is fully initialized.
* <p>
* Each Config bean will get refreshed on the start of the exporting and referring process.
* <p>
* So it's ok for this bean not to be the first Dubbo Config bean being initialized.
* <p>
*/
public class ConfigCenterBean extends ConfigCenterConfig
implements ApplicationContextAware, DisposableBean, EnvironmentAware {
private transient ApplicationContext applicationContext;
private Boolean includeSpringEnv = false;
public ConfigCenterBean() {}
public ConfigCenterBean(ApplicationModel applicationModel) {
super(applicationModel);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public void destroy() throws Exception {}
@Override
public void setEnvironment(Environment environment) {
if (includeSpringEnv) {
// Get PropertySource mapped to 'dubbo.properties' in Spring Environment.
setExternalConfig(getConfigurations(getConfigFile(), environment));
// Get PropertySource mapped to 'application.dubbo.properties' in Spring Environment.
setAppExternalConfig(getConfigurations(
StringUtils.isNotEmpty(getAppConfigFile())
? getAppConfigFile()
: ("application." + getConfigFile()),
environment));
}
}
private Map<String, String> getConfigurations(String key, Environment environment) {
Object rawProperties = environment.getProperty(key, Object.class);
Map<String, String> externalProperties = new HashMap<>();
try {
if (rawProperties instanceof Map) {
externalProperties.putAll((Map<String, String>) rawProperties);
} else if (rawProperties instanceof String) {
externalProperties.putAll(ConfigurationUtils.parseProperties((String) rawProperties));
}
if (environment instanceof ConfigurableEnvironment && externalProperties.isEmpty()) {
ConfigurableEnvironment configurableEnvironment = (ConfigurableEnvironment) environment;
PropertySource propertySource =
configurableEnvironment.getPropertySources().get(key);
if (propertySource != null) {
Object source = propertySource.getSource();
if (source instanceof Map) {
((Map<String, Object>) source).forEach((k, v) -> {
externalProperties.put(k, (String) v);
});
}
}
}
} catch (Exception e) {
throw new IllegalStateException(e);
}
return externalProperties;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
public Boolean getIncludeSpringEnv() {
return includeSpringEnv;
}
public void setIncludeSpringEnv(Boolean includeSpringEnv) {
this.includeSpringEnv = includeSpringEnv;
}
}
| 8,754 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/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.spring;
/**
* Constants of dubbo spring config
*/
public interface Constants {
/**
* attributes of reference annotation
*/
String REFERENCE_PROPS = "referenceProps";
/**
* Registration sources of the reference, may be xml file or annotation location
*/
String REFERENCE_SOURCES = "referenceSources";
/**
* The name of an attribute that can be
* {@link org.springframework.core.AttributeAccessor#setAttribute set} on a
* {@link org.springframework.beans.factory.config.BeanDefinition} so that
* factory beans can signal their object type when it can't be deduced from
* the factory bean class.
* <p/>
* From FactoryBean.OBJECT_TYPE_ATTRIBUTE of Spring 5.2.
*/
String OBJECT_TYPE_ATTRIBUTE = "factoryBeanObjectType";
}
| 8,755 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapStartStopListenerSpringAdapter.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.spring.context;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.bootstrap.DubboBootstrapStartStopListener;
import org.apache.dubbo.config.spring.context.event.DubboBootstrapStatedEvent;
import org.apache.dubbo.config.spring.context.event.DubboBootstrapStopedEvent;
import org.springframework.context.ApplicationContext;
/**
* convcert Dubbo bootstrap event to spring environment.
*
* @scene 2.7.9
*/
@Deprecated
public class DubboBootstrapStartStopListenerSpringAdapter implements DubboBootstrapStartStopListener {
static ApplicationContext applicationContext;
@Override
public void onStart(DubboBootstrap bootstrap) {
if (applicationContext != null) {
applicationContext.publishEvent(new DubboBootstrapStatedEvent(bootstrap));
}
}
@Override
public void onStop(DubboBootstrap bootstrap) {
if (applicationContext != null) {
applicationContext.publishEvent(new DubboBootstrapStopedEvent(bootstrap));
}
}
}
| 8,756 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitContext.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.spring.context;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModelConstants;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
/**
* Dubbo spring initialization context object
*/
public class DubboSpringInitContext {
private BeanDefinitionRegistry registry;
private ConfigurableListableBeanFactory beanFactory;
private ApplicationContext applicationContext;
private ModuleModel moduleModel;
private final Map<String, Object> moduleAttributes = new HashMap<>();
private volatile boolean bound;
public void markAsBound() {
bound = true;
}
public BeanDefinitionRegistry getRegistry() {
return registry;
}
void setRegistry(BeanDefinitionRegistry registry) {
this.registry = registry;
}
public ConfigurableListableBeanFactory getBeanFactory() {
return beanFactory;
}
void setBeanFactory(ConfigurableListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
public ApplicationModel getApplicationModel() {
return (moduleModel == null) ? null : moduleModel.getApplicationModel();
}
public ModuleModel getModuleModel() {
return moduleModel;
}
/**
* Change the binding ModuleModel, the ModuleModel and DubboBootstrap must be matched.
*
* @param moduleModel
*/
public void setModuleModel(ModuleModel moduleModel) {
if (bound) {
throw new IllegalStateException("Cannot change ModuleModel after bound context");
}
this.moduleModel = moduleModel;
}
public boolean isKeepRunningOnSpringClosed() {
return (boolean) moduleAttributes.get(ModelConstants.KEEP_RUNNING_ON_SPRING_CLOSED);
}
/**
* Keep Dubbo running when spring is stopped
* @param keepRunningOnSpringClosed
*/
public void setKeepRunningOnSpringClosed(boolean keepRunningOnSpringClosed) {
this.setModuleAttribute(ModelConstants.KEEP_RUNNING_ON_SPRING_CLOSED, keepRunningOnSpringClosed);
}
public Map<String, Object> getModuleAttributes() {
return moduleAttributes;
}
public void setModuleAttribute(String key, Object value) {
this.moduleAttributes.put(key, value);
}
}
| 8,757 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboBootstrapApplicationListener.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.spring.context;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.bootstrap.BootstrapTakeoverMode;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.config.spring.context.event.DubboConfigInitEvent;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_INITIALIZER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_NOT_FOUND;
import static org.springframework.util.ObjectUtils.nullSafeEquals;
/**
* The {@link ApplicationListener} for {@link DubboBootstrap}'s lifecycle when the {@link ContextRefreshedEvent}
* and {@link ContextClosedEvent} raised
*
* @since 2.7.5
*/
@Deprecated
public class DubboBootstrapApplicationListener implements ApplicationListener, ApplicationContextAware, Ordered {
/**
* The bean name of {@link DubboBootstrapApplicationListener}
*
* @since 2.7.6
*/
public static final String BEAN_NAME = "dubboBootstrapApplicationListener";
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private ApplicationContext applicationContext;
private DubboBootstrap bootstrap;
private boolean shouldInitConfigBeans;
private ModuleModel moduleModel;
public DubboBootstrapApplicationListener() {}
public DubboBootstrapApplicationListener(boolean shouldInitConfigBeans) {
// maybe register DubboBootstrapApplicationListener manual during spring context starting
this.shouldInitConfigBeans = shouldInitConfigBeans;
}
private void setBootstrap(DubboBootstrap bootstrap) {
this.bootstrap = bootstrap;
if (bootstrap.getTakeoverMode() != BootstrapTakeoverMode.MANUAL) {
bootstrap.setTakeoverMode(BootstrapTakeoverMode.SPRING);
}
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (isOriginalEventSource(event)) {
if (event instanceof DubboConfigInitEvent) {
// This event will be notified at AbstractApplicationContext.registerListeners(),
// init dubbo config beans before spring singleton beans
initDubboConfigBeans();
} else if (event instanceof ApplicationContextEvent) {
this.onApplicationContextEvent((ApplicationContextEvent) event);
}
}
}
private void initDubboConfigBeans() {
// load DubboConfigBeanInitializer to init config beans
if (applicationContext.containsBean(DubboConfigBeanInitializer.BEAN_NAME)) {
applicationContext.getBean(DubboConfigBeanInitializer.BEAN_NAME, DubboConfigBeanInitializer.class);
} else {
logger.warn(
CONFIG_DUBBO_BEAN_NOT_FOUND,
"",
"",
"Bean '" + DubboConfigBeanInitializer.BEAN_NAME + "' was not found");
}
// All infrastructure config beans are loaded, initialize dubbo here
moduleModel.getDeployer().initialize();
}
private void onApplicationContextEvent(ApplicationContextEvent event) {
if (DubboBootstrapStartStopListenerSpringAdapter.applicationContext == null) {
DubboBootstrapStartStopListenerSpringAdapter.applicationContext = event.getApplicationContext();
}
if (event instanceof ContextRefreshedEvent) {
onContextRefreshedEvent((ContextRefreshedEvent) event);
} else if (event instanceof ContextClosedEvent) {
onContextClosedEvent((ContextClosedEvent) event);
}
}
private void onContextRefreshedEvent(ContextRefreshedEvent event) {
if (bootstrap.getTakeoverMode() == BootstrapTakeoverMode.SPRING) {
moduleModel.getDeployer().start();
}
}
private void onContextClosedEvent(ContextClosedEvent event) {
if (bootstrap.getTakeoverMode() == BootstrapTakeoverMode.SPRING) {
// will call dubboBootstrap.stop() through shutdown callback.
// bootstrap.getApplicationModel().getBeanFactory().getBean(DubboShutdownHook.class).run();
moduleModel.getDeployer().stop();
}
}
/**
* Is original {@link ApplicationContext} as the event source
*
* @param event {@link ApplicationEvent}
* @return if original, return <code>true</code>, or <code>false</code>
*/
private boolean isOriginalEventSource(ApplicationEvent event) {
boolean originalEventSource = nullSafeEquals(getApplicationContext(), event.getSource());
return originalEventSource;
}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
moduleModel = DubboBeanUtils.getModuleModel(applicationContext);
this.setBootstrap(DubboBootstrap.getInstance(moduleModel.getApplicationModel()));
if (shouldInitConfigBeans) {
checkCallStackAndInit();
}
}
private void checkCallStackAndInit() {
// check call stack whether contains
// org.springframework.context.support.AbstractApplicationContext.registerListeners()
Exception exception = new Exception();
StackTraceElement[] stackTrace = exception.getStackTrace();
boolean found = false;
for (StackTraceElement frame : stackTrace) {
if (frame.getMethodName().equals("registerListeners")
&& frame.getClassName().endsWith("AbstractApplicationContext")) {
found = true;
break;
}
}
if (found) {
// init config beans here, compatible with spring 3.x/4.1.x
initDubboConfigBeans();
} else {
logger.warn(
CONFIG_DUBBO_BEAN_INITIALIZER,
"",
"",
"DubboBootstrapApplicationListener initialization is unexpected, "
+ "it should be created in AbstractApplicationContext.registerListeners() method",
exception);
}
}
public ApplicationContext getApplicationContext() {
return applicationContext;
}
}
| 8,758 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboDeployApplicationListener.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.spring.context;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.deploy.DeployListenerAdapter;
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.Assert;
import org.apache.dubbo.config.spring.context.event.DubboApplicationStateEvent;
import org.apache.dubbo.config.spring.context.event.DubboModuleStateEvent;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.config.spring.util.LockUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModelConstants;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.concurrent.Future;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.Ordered;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_START_MODEL;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_STOP_DUBBO_ERROR;
import static org.springframework.util.ObjectUtils.nullSafeEquals;
/**
* An ApplicationListener to control Dubbo application.
*/
public class DubboDeployApplicationListener
implements ApplicationListener<ApplicationContextEvent>, ApplicationContextAware, Ordered {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DubboDeployApplicationListener.class);
private ApplicationContext applicationContext;
private ApplicationModel applicationModel;
private ModuleModel moduleModel;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
this.applicationModel = DubboBeanUtils.getApplicationModel(applicationContext);
this.moduleModel = DubboBeanUtils.getModuleModel(applicationContext);
// listen deploy events and publish DubboApplicationStateEvent
applicationModel.getDeployer().addDeployListener(new DeployListenerAdapter<ApplicationModel>() {
@Override
public void onStarting(ApplicationModel scopeModel) {
publishApplicationEvent(DeployState.STARTING);
}
@Override
public void onStarted(ApplicationModel scopeModel) {
publishApplicationEvent(DeployState.STARTED);
}
@Override
public void onStopping(ApplicationModel scopeModel) {
publishApplicationEvent(DeployState.STOPPING);
}
@Override
public void onStopped(ApplicationModel scopeModel) {
publishApplicationEvent(DeployState.STOPPED);
}
@Override
public void onFailure(ApplicationModel scopeModel, Throwable cause) {
publishApplicationEvent(DeployState.FAILED, cause);
}
});
moduleModel.getDeployer().addDeployListener(new DeployListenerAdapter<ModuleModel>() {
@Override
public void onStarting(ModuleModel scopeModel) {
publishModuleEvent(DeployState.STARTING);
}
@Override
public void onStarted(ModuleModel scopeModel) {
publishModuleEvent(DeployState.STARTED);
}
@Override
public void onStopping(ModuleModel scopeModel) {
publishModuleEvent(DeployState.STOPPING);
}
@Override
public void onStopped(ModuleModel scopeModel) {
publishModuleEvent(DeployState.STOPPED);
}
@Override
public void onFailure(ModuleModel scopeModel, Throwable cause) {
publishModuleEvent(DeployState.FAILED, cause);
}
});
}
private void publishApplicationEvent(DeployState state) {
applicationContext.publishEvent(new DubboApplicationStateEvent(applicationModel, state));
}
private void publishApplicationEvent(DeployState state, Throwable cause) {
applicationContext.publishEvent(new DubboApplicationStateEvent(applicationModel, state, cause));
}
private void publishModuleEvent(DeployState state) {
applicationContext.publishEvent(new DubboModuleStateEvent(moduleModel, state));
}
private void publishModuleEvent(DeployState state, Throwable cause) {
applicationContext.publishEvent(new DubboModuleStateEvent(moduleModel, state, cause));
}
@Override
public void onApplicationEvent(ApplicationContextEvent event) {
if (nullSafeEquals(applicationContext, event.getSource())) {
if (event instanceof ContextRefreshedEvent) {
onContextRefreshedEvent((ContextRefreshedEvent) event);
} else if (event instanceof ContextClosedEvent) {
onContextClosedEvent((ContextClosedEvent) event);
}
}
}
private void onContextRefreshedEvent(ContextRefreshedEvent event) {
ModuleDeployer deployer = moduleModel.getDeployer();
Assert.notNull(deployer, "Module deployer is null");
Object singletonMutex = LockUtils.getSingletonMutex(applicationContext);
// start module
Future future = null;
synchronized (singletonMutex) {
future = deployer.start();
}
// if the module does not start in background, await finish
if (!deployer.isBackground()) {
try {
future.get();
} catch (InterruptedException e) {
logger.warn(
CONFIG_FAILED_START_MODEL,
"",
"",
"Interrupted while waiting for dubbo module start: " + e.getMessage());
} catch (Exception e) {
logger.warn(
CONFIG_FAILED_START_MODEL,
"",
"",
"An error occurred while waiting for dubbo module start: " + e.getMessage(),
e);
}
}
}
private void onContextClosedEvent(ContextClosedEvent event) {
try {
Object value = moduleModel.getAttribute(ModelConstants.KEEP_RUNNING_ON_SPRING_CLOSED);
if (value == null) {
value = ConfigurationUtils.getProperty(moduleModel, ModelConstants.KEEP_RUNNING_ON_SPRING_CLOSED_KEY);
}
boolean keepRunningOnClosed = Boolean.parseBoolean(String.valueOf(value));
if (!keepRunningOnClosed && !moduleModel.isDestroyed()) {
moduleModel.destroy();
}
} catch (Exception e) {
logger.error(
CONFIG_STOP_DUBBO_ERROR,
"",
"",
"Unexpected error occurred when stop dubbo module: " + e.getMessage(),
e);
}
// remove context bind cache
DubboSpringInitializer.remove(event.getApplicationContext());
}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE;
}
}
| 8,759 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboInfraBeanRegisterPostProcessor.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.spring.context;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor;
import org.apache.dubbo.config.spring.extension.SpringExtensionInjector;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.config.spring.util.EnvironmentUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.SortedMap;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.ConfigurableEnvironment;
/**
* Register some infrastructure beans if not exists.
* This post-processor MUST impl BeanDefinitionRegistryPostProcessor,
* in order to enable the registered BeanFactoryPostProcessor bean to be loaded and executed.
*
* @see org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(
*org.springframework.beans.factory.config.ConfigurableListableBeanFactory, java.util.List)
*/
public class DubboInfraBeanRegisterPostProcessor
implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware {
/**
* The bean name of {@link ReferenceAnnotationBeanPostProcessor}
*/
public static final String BEAN_NAME = "dubboInfraBeanRegisterPostProcessor";
private BeanDefinitionRegistry registry;
private ApplicationContext applicationContext;
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
this.registry = registry;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
// In Spring 3.2.x, registry may be null because do not call postProcessBeanDefinitionRegistry method before
// postProcessBeanFactory
if (registry != null) {
// register ReferenceAnnotationBeanPostProcessor early before
// PropertySourcesPlaceholderConfigurer/PropertyPlaceholderConfigurer
// for processing early init ReferenceBean
ReferenceAnnotationBeanPostProcessor referenceAnnotationBeanPostProcessor = beanFactory.getBean(
ReferenceAnnotationBeanPostProcessor.BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class);
beanFactory.addBeanPostProcessor(referenceAnnotationBeanPostProcessor);
// register PropertySourcesPlaceholderConfigurer bean if not exits
DubboBeanUtils.registerPlaceholderConfigurerBeanIfNotExists(beanFactory, registry);
}
ApplicationModel applicationModel = DubboBeanUtils.getApplicationModel(beanFactory);
ModuleModel moduleModel = DubboBeanUtils.getModuleModel(beanFactory);
// Initialize SpringExtensionInjector
SpringExtensionInjector.get(applicationModel).init(applicationContext);
SpringExtensionInjector.get(moduleModel).init(applicationContext);
DubboBeanUtils.getInitializationContext(beanFactory).setApplicationContext(applicationContext);
// Initialize dubbo Environment before ConfigManager
// Extract dubbo props from Spring env and put them to app config
ConfigurableEnvironment environment = (ConfigurableEnvironment) applicationContext.getEnvironment();
SortedMap<String, String> dubboProperties = EnvironmentUtils.filterDubboProperties(environment);
applicationModel.modelEnvironment().getAppConfigMap().putAll(dubboProperties);
// register ConfigManager singleton
beanFactory.registerSingleton(ConfigManager.BEAN_NAME, applicationModel.getApplicationConfigManager());
// fix https://github.com/apache/dubbo/issues/10278
if (registry != null) {
registry.removeBeanDefinition(BEAN_NAME);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
| 8,760 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizerHolder.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.spring.context;
import java.util.HashSet;
import java.util.Set;
/**
* Hold a set of DubboSpringInitCustomizer, for register customizers by programming.
* <p>All customizers are store in thread local, and they will be clear after apply once.</p>
*
* <p>Usages:</p>
*<pre>
* DubboSpringInitCustomizerHolder.get().addCustomizer(context -> {...});
* ClassPathXmlApplicationContext providerContext = new ClassPathXmlApplicationContext(..);
* ...
* DubboSpringInitCustomizerHolder.get().addCustomizer(context -> {...});
* ClassPathXmlApplicationContext consumerContext = new ClassPathXmlApplicationContext(..);
* </pre>
*/
public class DubboSpringInitCustomizerHolder {
private static final ThreadLocal<DubboSpringInitCustomizerHolder> holders =
ThreadLocal.withInitial(DubboSpringInitCustomizerHolder::new);
public static DubboSpringInitCustomizerHolder get() {
return holders.get();
}
private Set<DubboSpringInitCustomizer> customizers = new HashSet<>();
public void addCustomizer(DubboSpringInitCustomizer customizer) {
this.customizers.add(customizer);
}
public void clearCustomizers() {
this.customizers = new HashSet<>();
}
public Set<DubboSpringInitCustomizer> getCustomizers() {
return customizers;
}
}
| 8,761 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigBeanInitializer.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.spring.context;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.config.TracingConfig;
import org.apache.dubbo.config.context.AbstractConfigManager;
import org.apache.dubbo.config.context.ConfigManager;
import org.apache.dubbo.config.spring.ConfigCenterBean;
import org.apache.dubbo.config.spring.reference.ReferenceBeanManager;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
/**
*
* Dubbo config bean initializer.
*
* NOTE: Dubbo config beans MUST be initialized after registering all BeanPostProcessors,
* that is after the AbstractApplicationContext#registerBeanPostProcessors() method.
*/
public class DubboConfigBeanInitializer implements BeanFactoryAware, InitializingBean {
public static String BEAN_NAME = "dubboConfigBeanInitializer";
private final Logger logger = LoggerFactory.getLogger(getClass());
private final AtomicBoolean initialized = new AtomicBoolean(false);
private ConfigurableListableBeanFactory beanFactory;
private ReferenceBeanManager referenceBeanManager;
@Autowired
private ConfigManager configManager;
@Autowired
@Qualifier("org.apache.dubbo.rpc.model.ModuleModel")
private ModuleModel moduleModel;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;
}
@Override
public void afterPropertiesSet() throws Exception {
init();
}
private void init() {
if (initialized.compareAndSet(false, true)) {
referenceBeanManager = beanFactory.getBean(ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class);
try {
prepareDubboConfigBeans();
referenceBeanManager.prepareReferenceBeans();
} catch (Throwable e) {
throw new FatalBeanException("Initialization dubbo config beans failed", e);
}
}
}
/**
* Initializes there Dubbo's Config Beans before @Reference bean autowiring
*/
private void prepareDubboConfigBeans() {
logger.info("loading dubbo config beans ...");
// Make sure all these config beans are initialed and registered to ConfigManager
// load application config beans
loadConfigBeansOfType(ApplicationConfig.class, configManager);
loadConfigBeansOfType(RegistryConfig.class, configManager);
loadConfigBeansOfType(ProtocolConfig.class, configManager);
loadConfigBeansOfType(MonitorConfig.class, configManager);
loadConfigBeansOfType(ConfigCenterBean.class, configManager);
loadConfigBeansOfType(MetadataReportConfig.class, configManager);
loadConfigBeansOfType(MetricsConfig.class, configManager);
loadConfigBeansOfType(TracingConfig.class, configManager);
loadConfigBeansOfType(SslConfig.class, configManager);
// load module config beans
loadConfigBeansOfType(ModuleConfig.class, moduleModel.getConfigManager());
loadConfigBeansOfType(ProviderConfig.class, moduleModel.getConfigManager());
loadConfigBeansOfType(ConsumerConfig.class, moduleModel.getConfigManager());
// load ConfigCenterBean from properties, fix https://github.com/apache/dubbo/issues/9207
List<ConfigCenterBean> configCenterBeans = configManager.loadConfigsOfTypeFromProps(ConfigCenterBean.class);
for (ConfigCenterBean configCenterBean : configCenterBeans) {
String beanName = configCenterBean.getId() != null ? configCenterBean.getId() : "configCenterBean";
beanFactory.initializeBean(configCenterBean, beanName);
}
logger.info("dubbo config beans are loaded.");
}
private void loadConfigBeansOfType(
Class<? extends AbstractConfig> configClass, AbstractConfigManager configManager) {
String[] beanNames = beanFactory.getBeanNamesForType(configClass, true, false);
for (String beanName : beanNames) {
AbstractConfig configBean = beanFactory.getBean(beanName, configClass);
// Register config bean here, avoid relying on unreliable @PostConstruct init method
configManager.addConfig(configBean);
}
}
}
| 8,762 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitCustomizer.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.spring.context;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import static org.apache.dubbo.common.extension.ExtensionScope.FRAMEWORK;
/**
* Custom dubbo spring initialization
*/
@SPI(scope = FRAMEWORK)
public interface DubboSpringInitCustomizer {
/**
* <p>Customize dubbo spring initialization on bean registry processing phase.</p>
* <p>You can register a {@link BeanFactoryPostProcessor} or {@link BeanPostProcessor} for custom processing.</p>
* <p>Or change the bind module model via {@link DubboSpringInitContext#setModuleModel(ModuleModel)}.</p>
*
* <p><b>Note:</b></p>
* <p>1. The bean factory may be not ready yet when triggered by parsing dubbo xml definition.</p>
* <p>2. Some bean definitions may be not registered at this moment. If you plan to process all bean definitions,
* it is recommended to register a custom {@link BeanFactoryPostProcessor} to do so.</p>
*
* @param context
*/
void customize(DubboSpringInitContext context);
}
| 8,763 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboSpringInitializer.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.spring.context;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
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.ScopeModel;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.util.ObjectUtils;
/**
* Dubbo spring initialization entry point
*/
public class DubboSpringInitializer {
private static final Logger logger = LoggerFactory.getLogger(DubboSpringInitializer.class);
private static final Map<BeanDefinitionRegistry, DubboSpringInitContext> contextMap = new ConcurrentHashMap<>();
private DubboSpringInitializer() {}
public static void initialize(BeanDefinitionRegistry registry) {
// prepare context and do customize
DubboSpringInitContext context = new DubboSpringInitContext();
// Spring ApplicationContext may not ready at this moment (e.g. load from xml), so use registry as key
if (contextMap.putIfAbsent(registry, context) != null) {
return;
}
// find beanFactory
ConfigurableListableBeanFactory beanFactory = findBeanFactory(registry);
// init dubbo context
initContext(context, registry, beanFactory);
}
public static boolean remove(BeanDefinitionRegistry registry) {
return contextMap.remove(registry) != null;
}
public static boolean remove(ApplicationContext springContext) {
AutowireCapableBeanFactory autowireCapableBeanFactory = springContext.getAutowireCapableBeanFactory();
for (Map.Entry<BeanDefinitionRegistry, DubboSpringInitContext> entry : contextMap.entrySet()) {
DubboSpringInitContext initContext = entry.getValue();
if (initContext.getApplicationContext() == springContext
|| initContext.getBeanFactory() == autowireCapableBeanFactory
|| initContext.getRegistry() == autowireCapableBeanFactory) {
DubboSpringInitContext context = contextMap.remove(entry.getKey());
logger.info("Unbind " + safeGetModelDesc(context.getModuleModel()) + " from spring container: "
+ ObjectUtils.identityToString(entry.getKey()));
return true;
}
}
return false;
}
static Map<BeanDefinitionRegistry, DubboSpringInitContext> getContextMap() {
return contextMap;
}
static DubboSpringInitContext findBySpringContext(ApplicationContext applicationContext) {
for (DubboSpringInitContext initContext : contextMap.values()) {
if (initContext.getApplicationContext() == applicationContext) {
return initContext;
}
}
return null;
}
private static void initContext(
DubboSpringInitContext context,
BeanDefinitionRegistry registry,
ConfigurableListableBeanFactory beanFactory) {
context.setRegistry(registry);
context.setBeanFactory(beanFactory);
// customize context, you can change the bind module model via DubboSpringInitCustomizer SPI
customize(context);
// init ModuleModel
ModuleModel moduleModel = context.getModuleModel();
if (moduleModel == null) {
ApplicationModel applicationModel;
if (findContextForApplication(ApplicationModel.defaultModel()) == null) {
// first spring context use default application instance
applicationModel = ApplicationModel.defaultModel();
logger.info("Use default application: " + applicationModel.getDesc());
} else {
// create a new application instance for later spring context
applicationModel = FrameworkModel.defaultModel().newApplication();
logger.info("Create new application: " + applicationModel.getDesc());
}
// init ModuleModel
moduleModel = applicationModel.getDefaultModule();
context.setModuleModel(moduleModel);
logger.info("Use default module model of target application: " + moduleModel.getDesc());
} else {
logger.info("Use module model from customizer: " + moduleModel.getDesc());
}
logger.info(
"Bind " + moduleModel.getDesc() + " to spring container: " + ObjectUtils.identityToString(registry));
// set module attributes
Map<String, Object> moduleAttributes = context.getModuleAttributes();
if (moduleAttributes.size() > 0) {
moduleModel.getAttributes().putAll(moduleAttributes);
}
// bind dubbo initialization context to spring context
registerContextBeans(beanFactory, context);
// mark context as bound
context.markAsBound();
moduleModel.setLifeCycleManagedExternally(true);
// register common beans
DubboBeanUtils.registerCommonBeans(registry);
}
private static String safeGetModelDesc(ScopeModel scopeModel) {
return scopeModel != null ? scopeModel.getDesc() : null;
}
private static ConfigurableListableBeanFactory findBeanFactory(BeanDefinitionRegistry registry) {
ConfigurableListableBeanFactory beanFactory;
if (registry instanceof ConfigurableListableBeanFactory) {
beanFactory = (ConfigurableListableBeanFactory) registry;
} else if (registry instanceof GenericApplicationContext) {
GenericApplicationContext genericApplicationContext = (GenericApplicationContext) registry;
beanFactory = genericApplicationContext.getBeanFactory();
} else {
throw new IllegalStateException("Can not find Spring BeanFactory from registry: "
+ registry.getClass().getName());
}
return beanFactory;
}
private static void registerContextBeans(
ConfigurableListableBeanFactory beanFactory, DubboSpringInitContext context) {
// register singleton
registerSingleton(beanFactory, context);
registerSingleton(beanFactory, context.getApplicationModel());
registerSingleton(beanFactory, context.getModuleModel());
}
private static void registerSingleton(ConfigurableListableBeanFactory beanFactory, Object bean) {
beanFactory.registerSingleton(bean.getClass().getName(), bean);
}
private static DubboSpringInitContext findContextForApplication(ApplicationModel applicationModel) {
for (DubboSpringInitContext initializationContext : contextMap.values()) {
if (initializationContext.getApplicationModel() == applicationModel) {
return initializationContext;
}
}
return null;
}
private static void customize(DubboSpringInitContext context) {
// find initialization customizers
Set<DubboSpringInitCustomizer> customizers = FrameworkModel.defaultModel()
.getExtensionLoader(DubboSpringInitCustomizer.class)
.getSupportedExtensionInstances();
for (DubboSpringInitCustomizer customizer : customizers) {
customizer.customize(context);
}
// load customizers in thread local holder
DubboSpringInitCustomizerHolder customizerHolder = DubboSpringInitCustomizerHolder.get();
customizers = customizerHolder.getCustomizers();
for (DubboSpringInitCustomizer customizer : customizers) {
customizer.customize(context);
}
customizerHolder.clearCustomizers();
}
}
| 8,764 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/DubboConfigApplicationListener.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.spring.context;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.config.spring.context.event.DubboConfigInitEvent;
import org.apache.dubbo.config.spring.util.DubboBeanUtils;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_DUBBO_BEAN_NOT_FOUND;
import static org.springframework.util.ObjectUtils.nullSafeEquals;
/**
* An ApplicationListener to load config beans
*/
public class DubboConfigApplicationListener
implements ApplicationListener<DubboConfigInitEvent>, ApplicationContextAware {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DubboConfigApplicationListener.class);
private ApplicationContext applicationContext;
private ModuleModel moduleModel;
private final AtomicBoolean initialized = new AtomicBoolean();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
this.moduleModel = DubboBeanUtils.getModuleModel(applicationContext);
}
@Override
public void onApplicationEvent(DubboConfigInitEvent event) {
if (nullSafeEquals(applicationContext, event.getSource())) {
init();
}
}
public void init() {
// It's expected to be notified at
// org.springframework.context.support.AbstractApplicationContext.registerListeners(),
// before loading non-lazy singleton beans. At this moment, all BeanFactoryPostProcessor have been processed,
if (initialized.compareAndSet(false, true)) {
initDubboConfigBeans();
}
}
private void initDubboConfigBeans() {
// load DubboConfigBeanInitializer to init config beans
if (applicationContext.containsBean(DubboConfigBeanInitializer.BEAN_NAME)) {
applicationContext.getBean(DubboConfigBeanInitializer.BEAN_NAME, DubboConfigBeanInitializer.class);
} else {
logger.warn(
CONFIG_DUBBO_BEAN_NOT_FOUND,
"",
"",
"Bean '" + DubboConfigBeanInitializer.BEAN_NAME + "' was not found");
}
// All infrastructure config beans are loaded, initialize dubbo here
moduleModel.getDeployer().prepare();
}
}
| 8,765 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/NamePropertyDefaultValueDubboConfigBeanCustomizer.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.spring.context.config;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.spring.beans.factory.config.DubboConfigDefaultPropertyValueBeanPostProcessor;
import org.apache.dubbo.config.spring.util.ObjectUtils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.springframework.util.ReflectionUtils;
import static org.springframework.beans.BeanUtils.getPropertyDescriptor;
/**
* {@link DubboConfigBeanCustomizer} for the default value for the "name" property that will be taken bean name
* if absent.
*
* @since 2.6.6
* @deprecated {@link DubboConfigDefaultPropertyValueBeanPostProcessor} instead
*/
@Deprecated
public class NamePropertyDefaultValueDubboConfigBeanCustomizer implements DubboConfigBeanCustomizer {
/**
* The bean name of {@link NamePropertyDefaultValueDubboConfigBeanCustomizer}
*
* @since 2.7.1
*/
public static final String BEAN_NAME = "namePropertyDefaultValueDubboConfigBeanCustomizer";
/**
* The name of property that is "name" maybe is absent in target class
*/
private static final String PROPERTY_NAME = "name";
@Override
public void customize(String beanName, AbstractConfig dubboConfigBean) {
PropertyDescriptor propertyDescriptor = getPropertyDescriptor(dubboConfigBean.getClass(), PROPERTY_NAME);
if (propertyDescriptor != null) { // "name" property is present
Method getNameMethod = propertyDescriptor.getReadMethod();
if (getNameMethod == null) { // if "getName" method is absent
return;
}
Object propertyValue = ReflectionUtils.invokeMethod(getNameMethod, dubboConfigBean);
if (propertyValue != null) { // If The return value of "getName" method is not null
return;
}
Method setNameMethod = propertyDescriptor.getWriteMethod();
if (setNameMethod != null) { // "setName" and "getName" methods are present
if (Arrays.equals(
ObjectUtils.of(String.class), setNameMethod.getParameterTypes())) { // the param type is String
// set bean name to the value of the "name" property
ReflectionUtils.invokeMethod(setNameMethod, dubboConfigBean, beanName);
}
}
}
}
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
}
| 8,766 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/config/DubboConfigBeanCustomizer.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.spring.context.config;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.spring.context.properties.DubboConfigBinder;
import com.alibaba.spring.context.config.ConfigurationBeanCustomizer;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
/**
* The Bean customizer for {@link AbstractConfig Dubbo Config}. Generally, The subclass will be registered as a Spring
* Bean that is used to {@link #customize(String, AbstractConfig) customize} {@link AbstractConfig Dubbo Config} bean
* after {@link DubboConfigBinder#bind(String, AbstractConfig) its binding}.
* <p>
* If There are multiple {@link DubboConfigBeanCustomizer} beans in the Spring {@link ApplicationContext context}, they
* are executed orderly, thus the subclass should be aware to implement the {@link #getOrder()} method.
*
* @see DubboConfigBinder#bind(String, AbstractConfig)
* @since 2.6.6
*/
public interface DubboConfigBeanCustomizer extends ConfigurationBeanCustomizer, Ordered {
/**
* Customize {@link AbstractConfig Dubbo Config Bean}
*
* @param beanName the name of {@link AbstractConfig Dubbo Config Bean}
* @param dubboConfigBean the instance of {@link AbstractConfig Dubbo Config Bean}
*/
void customize(String beanName, AbstractConfig dubboConfigBean);
@Override
default void customize(String beanName, Object configurationBean) {
if (configurationBean instanceof AbstractConfig) {
customize(beanName, (AbstractConfig) configurationBean);
}
}
}
| 8,767 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubbo.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.spring.context.annotation;
import org.apache.dubbo.config.AbstractConfig;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
/**
* Enables Dubbo components as Spring Beans, equals
* {@link DubboComponentScan} and {@link EnableDubboConfig} combination.
* <p>
* Note : {@link EnableDubbo} must base on Spring Framework 4.2 and above
*
* @see DubboComponentScan
* @see EnableDubboConfig
* @since 2.5.8
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@EnableDubboConfig
@DubboComponentScan
public @interface EnableDubbo {
/**
* Base packages to scan for annotated @Service classes.
* <p>
* Use {@link #scanBasePackageClasses()} for a type-safe alternative to String-based
* package names.
*
* @return the base packages to scan
* @see DubboComponentScan#basePackages()
*/
@AliasFor(annotation = DubboComponentScan.class, attribute = "basePackages")
String[] scanBasePackages() default {};
/**
* Type-safe alternative to {@link #scanBasePackages()} for specifying the packages to
* scan for annotated @Service classes. The package of each class specified will be
* scanned.
*
* @return classes from the base packages to scan
* @see DubboComponentScan#basePackageClasses
*/
@AliasFor(annotation = DubboComponentScan.class, attribute = "basePackageClasses")
Class<?>[] scanBasePackageClasses() default {};
/**
* It indicates whether {@link AbstractConfig} binding to multiple Spring Beans.
*
* @return the default value is <code>true</code>
* @see EnableDubboConfig#multiple()
*/
@AliasFor(annotation = EnableDubboConfig.class, attribute = "multiple")
boolean multipleConfig() default true;
}
| 8,768 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/EnableDubboConfig.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.spring.context.annotation;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.alibaba.spring.beans.factory.annotation.EnableConfigurationBeanBinding;
import org.springframework.context.annotation.Import;
/**
* As a convenient and multiple {@link EnableConfigurationBeanBinding}
* in default behavior , is equal to single bean bindings with below convention prefixes of properties:
* <ul>
* <li>{@link ApplicationConfig} binding to property : "dubbo.application"</li>
* <li>{@link ModuleConfig} binding to property : "dubbo.module"</li>
* <li>{@link RegistryConfig} binding to property : "dubbo.registry"</li>
* <li>{@link ProtocolConfig} binding to property : "dubbo.protocol"</li>
* <li>{@link MonitorConfig} binding to property : "dubbo.monitor"</li>
* <li>{@link ProviderConfig} binding to property : "dubbo.provider"</li>
* <li>{@link ConsumerConfig} binding to property : "dubbo.consumer"</li>
* </ul>
* <p>
* In contrast, on multiple bean bindings that requires to set {@link #multiple()} to be <code>true</code> :
* <ul>
* <li>{@link ApplicationConfig} binding to property : "dubbo.applications"</li>
* <li>{@link ModuleConfig} binding to property : "dubbo.modules"</li>
* <li>{@link RegistryConfig} binding to property : "dubbo.registries"</li>
* <li>{@link ProtocolConfig} binding to property : "dubbo.protocols"</li>
* <li>{@link MonitorConfig} binding to property : "dubbo.monitors"</li>
* <li>{@link ProviderConfig} binding to property : "dubbo.providers"</li>
* <li>{@link ConsumerConfig} binding to property : "dubbo.consumers"</li>
* </ul>
*
* @see EnableConfigurationBeanBinding
* @see DubboConfigConfiguration
* @see DubboConfigConfigurationRegistrar
* @since 2.5.8
*/
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@Import(DubboConfigConfigurationRegistrar.class)
public @interface EnableDubboConfig {
/**
* It indicates whether binding to multiple Spring Beans.
*
* @return the default value is <code>true</code>
* @revised 2.5.9
*/
boolean multiple() default true;
}
| 8,769 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboClassPathBeanDefinitionScanner.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.spring.context.annotation;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import static org.springframework.context.annotation.AnnotationConfigUtils.registerAnnotationConfigProcessors;
/**
* Dubbo {@link ClassPathBeanDefinitionScanner} that exposes some methods to be public.
*
* @see #doScan(String...)
* @see #registerDefaultFilters()
* @since 2.5.7
*/
public class DubboClassPathBeanDefinitionScanner extends ClassPathBeanDefinitionScanner {
/**
* key is package to scan, value is BeanDefinition
*/
private final ConcurrentMap<String, Set<BeanDefinition>> beanDefinitionMap = new ConcurrentHashMap<>();
public DubboClassPathBeanDefinitionScanner(
BeanDefinitionRegistry registry,
boolean useDefaultFilters,
Environment environment,
ResourceLoader resourceLoader) {
super(registry, useDefaultFilters);
setEnvironment(environment);
setResourceLoader(resourceLoader);
registerAnnotationConfigProcessors(registry);
}
public DubboClassPathBeanDefinitionScanner(
BeanDefinitionRegistry registry, Environment environment, ResourceLoader resourceLoader) {
this(registry, false, environment, resourceLoader);
}
@Override
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
Set<BeanDefinition> beanDefinitions = beanDefinitionMap.get(basePackage);
// if beanDefinitions size is null => scan
if (Objects.isNull(beanDefinitions)) {
beanDefinitions = super.findCandidateComponents(basePackage);
beanDefinitionMap.put(basePackage, beanDefinitions);
}
return beanDefinitions;
}
}
| 8,770 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScan.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.spring.context.annotation;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
/**
* Dubbo Component Scan {@link Annotation},scans the classpath for annotated components that will be auto-registered as
* Spring beans. Dubbo-provided {@link Service} and {@link Reference}.
*
* @see Service
* @see Reference
* @since 2.5.7
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(DubboComponentScanRegistrar.class)
public @interface DubboComponentScan {
/**
* Alias for the {@link #basePackages()} attribute. Allows for more concise annotation
* declarations e.g.: {@code @DubboComponentScan("org.my.pkg")} instead of
* {@code @DubboComponentScan(basePackages="org.my.pkg")}.
*
* @return the base packages to scan
*/
String[] value() default {};
/**
* Base packages to scan for annotated @Service classes. {@link #value()} is an
* alias for (and mutually exclusive with) this attribute.
* <p>
* Use {@link #basePackageClasses()} for a type-safe alternative to String-based
* package names.
*
* @return the base packages to scan
*/
String[] basePackages() default {};
/**
* Type-safe alternative to {@link #basePackages()} for specifying the packages to
* scan for annotated @Service classes. The package of each class specified will be
* scanned.
*
* @return classes from the base packages to scan
*/
Class<?>[] basePackageClasses() default {};
}
| 8,771 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboComponentScanRegistrar.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.spring.context.annotation;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor;
import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor;
import org.apache.dubbo.config.spring.context.DubboSpringInitializer;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.Set;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.ClassUtils;
import static org.springframework.beans.factory.support.BeanDefinitionBuilder.rootBeanDefinition;
/**
* Dubbo {@link DubboComponentScan} Bean Registrar
*
* @see Service
* @see DubboComponentScan
* @see ImportBeanDefinitionRegistrar
* @see ServiceAnnotationPostProcessor
* @see ReferenceAnnotationBeanPostProcessor
* @since 2.5.7
*/
public class DubboComponentScanRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
// initialize dubbo beans
DubboSpringInitializer.initialize(registry);
Set<String> packagesToScan = getPackagesToScan(importingClassMetadata);
registerServiceAnnotationPostProcessor(packagesToScan, registry);
}
/**
* Registers {@link ServiceAnnotationPostProcessor}
*
* @param packagesToScan packages to scan without resolving placeholders
* @param registry {@link BeanDefinitionRegistry}
* @since 2.5.8
*/
private void registerServiceAnnotationPostProcessor(Set<String> packagesToScan, BeanDefinitionRegistry registry) {
BeanDefinitionBuilder builder = rootBeanDefinition(ServiceAnnotationPostProcessor.class);
builder.addConstructorArgValue(packagesToScan);
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
BeanDefinitionReaderUtils.registerWithGeneratedName(beanDefinition, registry);
}
private Set<String> getPackagesToScan(AnnotationMetadata metadata) {
// get from @DubboComponentScan
Set<String> packagesToScan =
getPackagesToScan0(metadata, DubboComponentScan.class, "basePackages", "basePackageClasses");
// get from @EnableDubbo, compatible with spring 3.x
if (packagesToScan.isEmpty()) {
packagesToScan =
getPackagesToScan0(metadata, EnableDubbo.class, "scanBasePackages", "scanBasePackageClasses");
}
if (packagesToScan.isEmpty()) {
return Collections.singleton(ClassUtils.getPackageName(metadata.getClassName()));
}
return packagesToScan;
}
private Set<String> getPackagesToScan0(
AnnotationMetadata metadata,
Class annotationClass,
String basePackagesName,
String basePackageClassesName) {
AnnotationAttributes attributes =
AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(annotationClass.getName()));
if (attributes == null) {
return Collections.emptySet();
}
Set<String> packagesToScan = new LinkedHashSet<>();
// basePackages
String[] basePackages = attributes.getStringArray(basePackagesName);
packagesToScan.addAll(Arrays.asList(basePackages));
// basePackageClasses
Class<?>[] basePackageClasses = attributes.getClassArray(basePackageClassesName);
for (Class<?> basePackageClass : basePackageClasses) {
packagesToScan.add(ClassUtils.getPackageName(basePackageClass));
}
// value
if (attributes.containsKey("value")) {
String[] value = attributes.getStringArray("value");
packagesToScan.addAll(Arrays.asList(value));
}
return packagesToScan;
}
}
| 8,772 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfiguration.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.spring.context.annotation;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.MetadataReportConfig;
import org.apache.dubbo.config.MetricsConfig;
import org.apache.dubbo.config.ModuleConfig;
import org.apache.dubbo.config.MonitorConfig;
import org.apache.dubbo.config.ProtocolConfig;
import org.apache.dubbo.config.ProviderConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.config.TracingConfig;
import org.apache.dubbo.config.spring.ConfigCenterBean;
import com.alibaba.spring.beans.factory.annotation.EnableConfigurationBeanBinding;
import com.alibaba.spring.beans.factory.annotation.EnableConfigurationBeanBindings;
import org.springframework.context.annotation.Configuration;
/**
* Dubbo {@link AbstractConfig Config} {@link Configuration}
*
* @revised 2.7.5
* @see Configuration
* @see EnableConfigurationBeanBindings
* @see EnableConfigurationBeanBinding
* @see ApplicationConfig
* @see ModuleConfig
* @see RegistryConfig
* @see ProtocolConfig
* @see MonitorConfig
* @see ProviderConfig
* @see ConsumerConfig
* @see org.apache.dubbo.config.ConfigCenterConfig
* @since 2.5.8
*/
public class DubboConfigConfiguration {
/**
* Single Dubbo {@link AbstractConfig Config} Bean Binding
*/
@EnableConfigurationBeanBindings({
@EnableConfigurationBeanBinding(prefix = "dubbo.application", type = ApplicationConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.module", type = ModuleConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.registry", type = RegistryConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.protocol", type = ProtocolConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.monitor", type = MonitorConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.provider", type = ProviderConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.consumer", type = ConsumerConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.config-center", type = ConfigCenterBean.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.metadata-report", type = MetadataReportConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.metrics", type = MetricsConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.tracing", type = TracingConfig.class),
@EnableConfigurationBeanBinding(prefix = "dubbo.ssl", type = SslConfig.class)
})
public static class Single {}
/**
* Multiple Dubbo {@link AbstractConfig Config} Bean Binding
*/
@EnableConfigurationBeanBindings({
@EnableConfigurationBeanBinding(prefix = "dubbo.applications", type = ApplicationConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.modules", type = ModuleConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.registries", type = RegistryConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.protocols", type = ProtocolConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.monitors", type = MonitorConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.providers", type = ProviderConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.consumers", type = ConsumerConfig.class, multiple = true),
@EnableConfigurationBeanBinding(
prefix = "dubbo.config-centers",
type = ConfigCenterBean.class,
multiple = true),
@EnableConfigurationBeanBinding(
prefix = "dubbo.metadata-reports",
type = MetadataReportConfig.class,
multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.metricses", type = MetricsConfig.class, multiple = true),
@EnableConfigurationBeanBinding(prefix = "dubbo.tracings", type = TracingConfig.class, multiple = true)
})
public static class Multiple {}
}
| 8,773 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/annotation/DubboConfigConfigurationRegistrar.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.spring.context.annotation;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.spring.context.DubboSpringInitializer;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.Ordered;
import org.springframework.core.type.AnnotationMetadata;
/**
* Dubbo {@link AbstractConfig Config} {@link ImportBeanDefinitionRegistrar register}, which order can be configured
*
* @see EnableDubboConfig
* @see DubboConfigConfiguration
* @see Ordered
* @since 2.5.8
*/
public class DubboConfigConfigurationRegistrar implements ImportBeanDefinitionRegistrar {
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
// initialize dubbo beans
DubboSpringInitializer.initialize(registry);
}
}
| 8,774 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DubboConfigBinder.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.spring.context.properties;
import org.apache.dubbo.config.AbstractConfig;
import org.springframework.context.EnvironmentAware;
/**
* {@link AbstractConfig DubboConfig} Binder
*
* @see AbstractConfig
* @see EnvironmentAware
* @since 2.5.11
*/
public interface DubboConfigBinder extends EnvironmentAware {
/**
* Set whether to ignore unknown fields, that is, whether to ignore bind
* parameters that do not have corresponding fields in the target object.
* <p>Default is "true". Turn this off to enforce that all bind parameters
* must have a matching field in the target object.
*
* @see #bind
*/
void setIgnoreUnknownFields(boolean ignoreUnknownFields);
/**
* Set whether to ignore invalid fields, that is, whether to ignore bind
* parameters that have corresponding fields in the target object which are
* not accessible (for example because of null values in the nested path).
* <p>Default is "false".
*
* @see #bind
*/
void setIgnoreInvalidFields(boolean ignoreInvalidFields);
/**
* Bind the properties to Dubbo Config Object under specified prefix.
*
* @param prefix
* @param dubboConfig
*/
<C extends AbstractConfig> void bind(String prefix, C dubboConfig);
}
| 8,775 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/DefaultDubboConfigBinder.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.spring.context.properties;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.config.spring.util.PropertySourcesUtils;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.validation.FieldError;
/**
* Default {@link DubboConfigBinder} implementation based on Spring {@link DataBinder}
*/
public class DefaultDubboConfigBinder extends AbstractDubboConfigBinder {
@Override
public <C extends AbstractConfig> void bind(String prefix, C dubboConfig) {
DataBinder dataBinder = new DataBinder(dubboConfig);
// Set ignored*
dataBinder.setIgnoreInvalidFields(isIgnoreInvalidFields());
dataBinder.setIgnoreUnknownFields(isIgnoreUnknownFields());
// Get properties under specified prefix from PropertySources
Map<String, Object> properties = PropertySourcesUtils.getSubProperties(getPropertySources(), prefix);
// Convert Map to MutablePropertyValues
MutablePropertyValues propertyValues = new MutablePropertyValues(properties);
// Bind
dataBinder.bind(propertyValues);
BindingResult bindingResult = dataBinder.getBindingResult();
if (bindingResult.hasGlobalErrors()) {
throw new RuntimeException(
"Data bind global error, please check config. config: " + bindingResult.getGlobalError() + "");
}
if (bindingResult.hasFieldErrors()) {
throw new RuntimeException(buildErrorMsg(
bindingResult.getFieldErrors(),
prefix,
dubboConfig.getClass().getSimpleName()));
}
}
private String buildErrorMsg(List<FieldError> errors, String prefix, String config) {
StringBuilder builder = new StringBuilder("Data bind error, please check config. config: " + config
+ ", prefix: " + prefix + " , error fields: [" + errors.get(0).getField());
if (errors.size() > 1) {
IntStream.range(1, errors.size()).forEach(i -> {
builder.append(", " + errors.get(i).getField());
});
}
builder.append(']');
return builder.toString();
}
}
| 8,776 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/properties/AbstractDubboConfigBinder.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.spring.context.properties;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource;
/**
* Abstract {@link DubboConfigBinder} implementation
*/
public abstract class AbstractDubboConfigBinder implements DubboConfigBinder {
private Iterable<PropertySource<?>> propertySources;
private boolean ignoreUnknownFields = true;
private boolean ignoreInvalidFields = false;
/**
* Get multiple {@link PropertySource propertySources}
*
* @return multiple {@link PropertySource propertySources}
*/
protected Iterable<PropertySource<?>> getPropertySources() {
return propertySources;
}
public boolean isIgnoreUnknownFields() {
return ignoreUnknownFields;
}
@Override
public void setIgnoreUnknownFields(boolean ignoreUnknownFields) {
this.ignoreUnknownFields = ignoreUnknownFields;
}
public boolean isIgnoreInvalidFields() {
return ignoreInvalidFields;
}
@Override
public void setIgnoreInvalidFields(boolean ignoreInvalidFields) {
this.ignoreInvalidFields = ignoreInvalidFields;
}
@Override
public final void setEnvironment(Environment environment) {
if (environment instanceof ConfigurableEnvironment) {
this.propertySources = ((ConfigurableEnvironment) environment).getPropertySources();
}
}
}
| 8,777 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboApplicationStateEvent.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.spring.context.event;
import org.apache.dubbo.common.deploy.DeployState;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.springframework.context.ApplicationEvent;
/**
* Dubbo's application state event on starting/started/stopping/stopped
*/
public class DubboApplicationStateEvent extends ApplicationEvent {
private final DeployState state;
private Throwable cause;
public DubboApplicationStateEvent(ApplicationModel applicationModel, DeployState state) {
super(applicationModel);
this.state = state;
}
public DubboApplicationStateEvent(ApplicationModel applicationModel, DeployState state, Throwable cause) {
super(applicationModel);
this.state = state;
this.cause = cause;
}
public ApplicationModel getApplicationModel() {
return (ApplicationModel) getSource();
}
public DeployState getState() {
return state;
}
public Throwable getCause() {
return cause;
}
}
| 8,778 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboModuleStateEvent.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.spring.context.event;
import org.apache.dubbo.common.deploy.DeployState;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.springframework.context.ApplicationEvent;
/**
* Dubbo's module state event on starting/started/stopping/stopped
*/
public class DubboModuleStateEvent extends ApplicationEvent {
private final DeployState state;
private Throwable cause;
public DubboModuleStateEvent(ModuleModel applicationModel, DeployState state) {
super(applicationModel);
this.state = state;
}
public DubboModuleStateEvent(ModuleModel applicationModel, DeployState state, Throwable cause) {
super(applicationModel);
this.state = state;
this.cause = cause;
}
public ModuleModel getModule() {
return (ModuleModel) getSource();
}
public DeployState getState() {
return state;
}
public Throwable getCause() {
return cause;
}
}
| 8,779 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboConfigInitEvent.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.spring.context.event;
import org.apache.dubbo.config.spring.context.DubboConfigBeanInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
/**
* An {@link ApplicationEvent} to trigger init {@link DubboConfigBeanInitializer}.
*
*/
public class DubboConfigInitEvent extends ApplicationEvent {
/**
* Create a new {@code ApplicationEvent}.
*
* @param source the object on which the event initially occurred or with
* which the event is associated (never {@code null})
*/
public DubboConfigInitEvent(ApplicationContext source) {
super(source);
}
/**
* Get the {@code ApplicationContext} that the event was raised for.
*/
public final ApplicationContext getApplicationContext() {
return (ApplicationContext) getSource();
}
}
| 8,780 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboBootstrapStatedEvent.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.spring.context.event;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.springframework.context.ApplicationEvent;
/**
* A {@link org.springframework.context.ApplicationEvent} after {@link org.apache.dubbo.config.bootstrap.DubboBootstrap#start()} success
*
* @see org.springframework.context.ApplicationEvent
* @see org.springframework.context.ApplicationListener
* @see org.apache.dubbo.config.bootstrap.DubboBootstrap
* @since 2.7.9
*/
@Deprecated
public class DubboBootstrapStatedEvent extends ApplicationEvent {
/**
* Create a new ApplicationEvent.
*
* @param bootstrap {@link org.apache.dubbo.config.bootstrap.DubboBootstrap} bootstrap
*/
public DubboBootstrapStatedEvent(DubboBootstrap bootstrap) {
super(bootstrap);
}
/**
* Get {@link org.apache.dubbo.config.bootstrap.DubboBootstrap} instance
*
* @return non-null
*/
public DubboBootstrap getDubboBootstrap() {
return (DubboBootstrap) super.getSource();
}
}
| 8,781 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/DubboBootstrapStopedEvent.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.spring.context.event;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.springframework.context.ApplicationEvent;
/**
* A {@link org.springframework.context.ApplicationEvent} after {@link org.apache.dubbo.config.bootstrap.DubboBootstrap#stop()} success
*
* @see org.springframework.context.ApplicationEvent
* @see org.springframework.context.ApplicationListener
* @see org.apache.dubbo.config.bootstrap.DubboBootstrap
* @since 2.7.9
*/
@Deprecated
public class DubboBootstrapStopedEvent extends ApplicationEvent {
/**
* Create a new ApplicationEvent.
*
* @param bootstrap {@link org.apache.dubbo.config.bootstrap.DubboBootstrap} bootstrap
*/
public DubboBootstrapStopedEvent(DubboBootstrap bootstrap) {
super(bootstrap);
}
/**
* Get {@link org.apache.dubbo.config.bootstrap.DubboBootstrap} instance
*
* @return non-null
*/
public DubboBootstrap getDubboBootstrap() {
return (DubboBootstrap) super.getSource();
}
}
| 8,782 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/context/event/ServiceBeanExportedEvent.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.spring.context.event;
import org.apache.dubbo.config.spring.ServiceBean;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
/**
* A {@link ApplicationEvent} after {@link ServiceBean} {@link ServiceBean#export() export} invocation
*
* @see ApplicationEvent
* @see ApplicationListener
* @see ServiceBean
* @since 2.6.5
*/
public class ServiceBeanExportedEvent extends ApplicationEvent {
/**
* Create a new ApplicationEvent.
*
* @param serviceBean {@link ServiceBean} bean
*/
public ServiceBeanExportedEvent(ServiceBean serviceBean) {
super(serviceBean);
}
/**
* Get {@link ServiceBean} instance
*
* @return non-null
*/
public ServiceBean getServiceBean() {
return (ServiceBean) super.getSource();
}
}
| 8,783 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/extension/SpringExtensionInjector.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.spring.extension;
import org.apache.dubbo.common.extension.ExtensionAccessor;
import org.apache.dubbo.common.extension.ExtensionInjector;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.Arrays;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.context.ApplicationContext;
/**
* SpringExtensionInjector
*/
public class SpringExtensionInjector implements ExtensionInjector {
private ApplicationContext context;
@Deprecated
public static void addApplicationContext(final ApplicationContext context) {}
public static SpringExtensionInjector get(final ExtensionAccessor extensionAccessor) {
return (SpringExtensionInjector) extensionAccessor.getExtension(ExtensionInjector.class, "spring");
}
public ApplicationContext getContext() {
return context;
}
public void init(final ApplicationContext context) {
this.context = context;
}
@Override
@SuppressWarnings("unchecked")
public <T> T getInstance(Class<T> type, String name) {
if (context == null) {
// ignore if spring context is not bound
return null;
}
// check @SPI annotation
if (type.isInterface() && type.isAnnotationPresent(SPI.class)) {
return null;
}
T bean = getOptionalBean(context, name, type);
if (bean != null) {
return bean;
}
// logger.warn("No spring extension (bean) named:" + name + ", try to find an extension (bean) of type " +
// type.getName());
return null;
}
private <T> T getOptionalBean(final ListableBeanFactory beanFactory, final String name, final Class<T> type) {
if (StringUtils.isEmpty(name)) {
return getOptionalBeanByType(beanFactory, type);
}
if (beanFactory.containsBean(name)) {
return beanFactory.getBean(name, type);
}
return null;
}
private <T> T getOptionalBeanByType(final ListableBeanFactory beanFactory, final Class<T> type) {
String[] beanNamesForType = beanFactory.getBeanNamesForType(type, true, false);
if (beanNamesForType == null) {
return null;
}
if (beanNamesForType.length > 1) {
throw new IllegalStateException("Expect single but found " + beanNamesForType.length
+ " beans in spring context: " + Arrays.toString(beanNamesForType));
}
return beanFactory.getBean(beanNamesForType[0], type);
}
}
| 8,784 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/EnvironmentUtils.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.spring.util;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.util.ObjectUtils;
/**
* The utilities class for {@link Environment}
*
* @see Environment
* @since 2.7.0
*/
public abstract class EnvironmentUtils {
/**
* The separator of property name
*/
public static final String PROPERTY_NAME_SEPARATOR = ".";
/**
* The prefix of property name of Dubbo
*/
public static final String DUBBO_PREFIX = "dubbo";
/**
* Extras The properties from {@link ConfigurableEnvironment}
*
* @param environment {@link ConfigurableEnvironment}
* @return Read-only Map
*/
public static Map<String, Object> extractProperties(ConfigurableEnvironment environment) {
return Collections.unmodifiableMap(doExtraProperties(environment));
}
private static Map<String, Object> doExtraProperties(ConfigurableEnvironment environment) {
Map<String, Object> properties = new LinkedHashMap<>(); // orderly
Map<String, PropertySource<?>> map = doGetPropertySources(environment);
for (PropertySource<?> source : map.values()) {
if (source instanceof EnumerablePropertySource) {
EnumerablePropertySource propertySource = (EnumerablePropertySource) source;
String[] propertyNames = propertySource.getPropertyNames();
if (ObjectUtils.isEmpty(propertyNames)) {
continue;
}
for (String propertyName : propertyNames) {
if (!properties.containsKey(propertyName)) { // put If absent
properties.put(propertyName, propertySource.getProperty(propertyName));
}
}
}
}
return properties;
}
private static Map<String, PropertySource<?>> doGetPropertySources(ConfigurableEnvironment environment) {
Map<String, PropertySource<?>> map = new LinkedHashMap<>();
MutablePropertySources sources = environment.getPropertySources();
for (PropertySource<?> source : sources) {
extract("", map, source);
}
return map;
}
private static void extract(String root, Map<String, PropertySource<?>> map, PropertySource<?> source) {
if (source instanceof CompositePropertySource) {
for (PropertySource<?> nest : ((CompositePropertySource) source).getPropertySources()) {
extract(source.getName() + ":", map, nest);
}
} else {
map.put(root + source.getName(), source);
}
}
/**
* Filters Dubbo Properties from {@link ConfigurableEnvironment}
*
* @param environment {@link ConfigurableEnvironment}
* @return Read-only SortedMap
*/
public static SortedMap<String, String> filterDubboProperties(ConfigurableEnvironment environment) {
SortedMap<String, String> dubboProperties = new TreeMap<>();
Map<String, Object> properties = extractProperties(environment);
for (Map.Entry<String, Object> entry : properties.entrySet()) {
String propertyName = entry.getKey();
if (propertyName.startsWith(DUBBO_PREFIX + PROPERTY_NAME_SEPARATOR) && entry.getValue() != null) {
dubboProperties.put(
propertyName,
environment.resolvePlaceholders(entry.getValue().toString()));
}
}
return Collections.unmodifiableSortedMap(dubboProperties);
}
}
| 8,785 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/PropertySourcesUtils.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.spring.util;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertyResolver;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.PropertySources;
import org.springframework.core.env.PropertySourcesPropertyResolver;
import static java.util.Collections.unmodifiableMap;
/**
* {@link PropertySources} Utilities
*
* @see PropertySources
*/
public abstract class PropertySourcesUtils {
/**
* Get Sub {@link Properties}
*
* @param propertySources {@link PropertySource} Iterable
* @param prefix the prefix of property name
* @return Map
* @see Properties
*/
public static Map<String, Object> getSubProperties(Iterable<PropertySource<?>> propertySources, String prefix) {
MutablePropertySources mutablePropertySources = new MutablePropertySources();
for (PropertySource<?> source : propertySources) {
mutablePropertySources.addLast(source);
}
return getSubProperties(mutablePropertySources, prefix);
}
/**
* Get Sub {@link Properties}
*
* @param environment {@link ConfigurableEnvironment}
* @param prefix the prefix of property name
* @return Map
* @see Properties
*/
public static Map<String, Object> getSubProperties(ConfigurableEnvironment environment, String prefix) {
return getSubProperties(environment.getPropertySources(), environment, prefix);
}
/**
* Normalize the prefix
*
* @param prefix the prefix
* @return the prefix
*/
public static String normalizePrefix(String prefix) {
return prefix.endsWith(".") ? prefix : prefix + ".";
}
/**
* Get prefixed {@link Properties}
*
* @param propertySources {@link PropertySources}
* @param prefix the prefix of property name
* @return Map
* @see Properties
*/
public static Map<String, Object> getSubProperties(PropertySources propertySources, String prefix) {
return getSubProperties(propertySources, new PropertySourcesPropertyResolver(propertySources), prefix);
}
/**
* Get prefixed {@link Properties}
*
* @param propertySources {@link PropertySources}
* @param propertyResolver {@link PropertyResolver} to resolve the placeholder if present
* @param prefix the prefix of property name
* @return Map
* @see Properties
*/
public static Map<String, Object> getSubProperties(
PropertySources propertySources, PropertyResolver propertyResolver, String prefix) {
Map<String, Object> subProperties = new LinkedHashMap<String, Object>();
String normalizedPrefix = normalizePrefix(prefix);
Iterator<PropertySource<?>> iterator = propertySources.iterator();
while (iterator.hasNext()) {
PropertySource<?> source = iterator.next();
for (String name : getPropertyNames(source)) {
if (!subProperties.containsKey(name) && name.startsWith(normalizedPrefix)) {
String subName = name.substring(normalizedPrefix.length());
if (!subProperties.containsKey(subName)) { // take first one
Object value = source.getProperty(name);
if (value instanceof String) {
// Resolve placeholder
value = propertyResolver.resolvePlaceholders((String) value);
}
subProperties.put(subName, value);
}
}
}
}
return unmodifiableMap(subProperties);
}
/**
* Get the property names as the array from the specified {@link PropertySource} instance.
*
* @param propertySource {@link PropertySource} instance
* @return non-null
*/
public static String[] getPropertyNames(PropertySource propertySource) {
String[] propertyNames = propertySource instanceof EnumerablePropertySource
? ((EnumerablePropertySource) propertySource).getPropertyNames()
: null;
if (propertyNames == null) {
propertyNames = ObjectUtils.EMPTY_STRING_ARRAY;
}
return propertyNames;
}
}
| 8,786 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboBeanUtils.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.spring.util;
import org.apache.dubbo.config.spring.beans.factory.annotation.DubboConfigAliasPostProcessor;
import org.apache.dubbo.config.spring.beans.factory.annotation.ReferenceAnnotationBeanPostProcessor;
import org.apache.dubbo.config.spring.beans.factory.annotation.ServicePackagesHolder;
import org.apache.dubbo.config.spring.beans.factory.config.DubboConfigDefaultPropertyValueBeanPostProcessor;
import org.apache.dubbo.config.spring.context.DubboConfigApplicationListener;
import org.apache.dubbo.config.spring.context.DubboConfigBeanInitializer;
import org.apache.dubbo.config.spring.context.DubboDeployApplicationListener;
import org.apache.dubbo.config.spring.context.DubboInfraBeanRegisterPostProcessor;
import org.apache.dubbo.config.spring.context.DubboSpringInitContext;
import org.apache.dubbo.config.spring.reference.ReferenceBeanManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.AbstractBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
/**
* Dubbo Bean utilities class
*
* @since 2.7.6
*/
public interface DubboBeanUtils {
Log log = LogFactory.getLog(DubboBeanUtils.class);
/**
* Register the common beans
*
* @param registry {@link BeanDefinitionRegistry}
* @see ReferenceAnnotationBeanPostProcessor
* @see DubboConfigDefaultPropertyValueBeanPostProcessor
* @see DubboConfigAliasPostProcessor
*/
static void registerCommonBeans(BeanDefinitionRegistry registry) {
registerInfrastructureBean(registry, ServicePackagesHolder.BEAN_NAME, ServicePackagesHolder.class);
registerInfrastructureBean(registry, ReferenceBeanManager.BEAN_NAME, ReferenceBeanManager.class);
// Since 2.5.7 Register @Reference Annotation Bean Processor as an infrastructure Bean
registerInfrastructureBean(
registry, ReferenceAnnotationBeanPostProcessor.BEAN_NAME, ReferenceAnnotationBeanPostProcessor.class);
// TODO Whether DubboConfigAliasPostProcessor can be removed ?
// Since 2.7.4 [Feature] https://github.com/apache/dubbo/issues/5093
registerInfrastructureBean(
registry, DubboConfigAliasPostProcessor.BEAN_NAME, DubboConfigAliasPostProcessor.class);
// register ApplicationListeners
registerInfrastructureBean(
registry, DubboDeployApplicationListener.class.getName(), DubboDeployApplicationListener.class);
registerInfrastructureBean(
registry, DubboConfigApplicationListener.class.getName(), DubboConfigApplicationListener.class);
// Since 2.7.6 Register DubboConfigDefaultPropertyValueBeanPostProcessor as an infrastructure Bean
registerInfrastructureBean(
registry,
DubboConfigDefaultPropertyValueBeanPostProcessor.BEAN_NAME,
DubboConfigDefaultPropertyValueBeanPostProcessor.class);
// Dubbo config initializer
registerInfrastructureBean(registry, DubboConfigBeanInitializer.BEAN_NAME, DubboConfigBeanInitializer.class);
// register infra bean if not exists later
registerInfrastructureBean(
registry, DubboInfraBeanRegisterPostProcessor.BEAN_NAME, DubboInfraBeanRegisterPostProcessor.class);
}
/**
* Register Infrastructure Bean
*
* @param beanDefinitionRegistry {@link BeanDefinitionRegistry}
* @param beanType the type of bean
* @param beanName the name of bean
* @return if it's a first time to register, return <code>true</code>, or <code>false</code>
*/
static boolean registerInfrastructureBean(
BeanDefinitionRegistry beanDefinitionRegistry, String beanName, Class<?> beanType) {
boolean registered = false;
if (!beanDefinitionRegistry.containsBeanDefinition(beanName)) {
RootBeanDefinition beanDefinition = new RootBeanDefinition(beanType);
beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
beanDefinitionRegistry.registerBeanDefinition(beanName, beanDefinition);
registered = true;
if (log.isDebugEnabled()) {
log.debug("The Infrastructure bean definition [" + beanDefinition + "with name [" + beanName
+ "] has been registered.");
}
}
return registered;
}
/**
* Register a placeholder configurer beans if not exists.
* Call this method in BeanDefinitionRegistryPostProcessor,
* in order to enable the registered BeanFactoryPostProcessor bean to be loaded and executed.
*
* @param beanFactory
* @param registry
* @see DubboInfraBeanRegisterPostProcessor
* @see org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(org.springframework.beans.factory.config.ConfigurableListableBeanFactory, java.util.List)
*/
static void registerPlaceholderConfigurerBeanIfNotExists(
ConfigurableListableBeanFactory beanFactory, BeanDefinitionRegistry registry) {
// Auto register a PropertyPlaceholderConfigurer bean to resolve placeholders with Spring Environment
// PropertySources
// when loading dubbo xml config with @ImportResource
if (!checkBeanExists(beanFactory, PropertySourcesPlaceholderConfigurer.class)) {
Map<String, Object> propertySourcesPlaceholderPropertyValues = new HashMap<>();
propertySourcesPlaceholderPropertyValues.put("ignoreUnresolvablePlaceholders", true);
registerBeanDefinition(
registry,
PropertySourcesPlaceholderConfigurer.class.getName(),
PropertySourcesPlaceholderConfigurer.class,
propertySourcesPlaceholderPropertyValues);
}
}
static boolean registerBeanDefinition(
BeanDefinitionRegistry registry,
String beanName,
Class<?> beanClass,
Map<String, Object> extraPropertyValues) {
if (registry.containsBeanDefinition(beanName)) {
return false;
}
BeanDefinition beanDefinition =
BeanDefinitionBuilder.genericBeanDefinition(beanClass).getBeanDefinition();
if (extraPropertyValues != null) {
for (Map.Entry<String, Object> entry : extraPropertyValues.entrySet()) {
beanDefinition.getPropertyValues().add(entry.getKey(), entry.getValue());
}
}
registry.registerBeanDefinition(beanName, beanDefinition);
return true;
}
static boolean checkBeanExists(ConfigurableListableBeanFactory beanFactory, Class<?> targetClass) {
String[] beanNames = beanFactory.getBeanNamesForType(targetClass, true, false);
return (beanNames != null && beanNames.length > 0);
}
static ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor(
AbstractBeanFactory beanFactory) {
for (BeanPostProcessor beanPostProcessor : beanFactory.getBeanPostProcessors()) {
if (beanPostProcessor instanceof ReferenceAnnotationBeanPostProcessor) {
return (ReferenceAnnotationBeanPostProcessor) beanPostProcessor;
}
}
return null;
}
static ReferenceAnnotationBeanPostProcessor getReferenceAnnotationBeanPostProcessor(
ApplicationContext applicationContext) {
return getReferenceAnnotationBeanPostProcessor(
(AbstractBeanFactory) applicationContext.getAutowireCapableBeanFactory());
}
static DubboSpringInitContext getInitializationContext(BeanFactory beanFactory) {
String beanName = DubboSpringInitContext.class.getName();
if (beanFactory != null && beanFactory.containsBean(beanName)) {
return beanFactory.getBean(beanName, DubboSpringInitContext.class);
}
return null;
}
static ApplicationModel getApplicationModel(BeanFactory beanFactory) {
String beanName = ApplicationModel.class.getName();
if (beanFactory != null && beanFactory.containsBean(beanName)) {
return beanFactory.getBean(beanName, ApplicationModel.class);
}
return null;
}
static ModuleModel getModuleModel(BeanFactory beanFactory) {
String beanName = ModuleModel.class.getName();
if (beanFactory != null && beanFactory.containsBean(beanName)) {
return beanFactory.getBean(beanName, ModuleModel.class);
}
return null;
}
}
| 8,787 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/DubboAnnotationUtils.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.spring.util;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.apache.dubbo.rpc.service.GenericService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.util.Assert;
import static org.springframework.util.ClassUtils.getAllInterfacesForClass;
import static org.springframework.util.StringUtils.hasText;
/**
* Dubbo Annotation Utilities Class
*
* @see org.springframework.core.annotation.AnnotationUtils
* @since 2.5.11
*/
public class DubboAnnotationUtils {
@Deprecated
public static String resolveInterfaceName(Service service, Class<?> defaultInterfaceClass)
throws IllegalStateException {
String interfaceName;
if (hasText(service.interfaceName())) {
interfaceName = service.interfaceName();
} else if (!void.class.equals(service.interfaceClass())) {
interfaceName = service.interfaceClass().getName();
} else if (defaultInterfaceClass.isInterface()) {
interfaceName = defaultInterfaceClass.getName();
} else {
throw new IllegalStateException("The @Service undefined interfaceClass or interfaceName, and the type "
+ defaultInterfaceClass.getName() + " is not a interface.");
}
return interfaceName;
}
/**
* Resolve the service interface name from @Service annotation attributes.
* <p/>
* Note: the service interface class maybe not found locally if is a generic service.
*
* @param attributes annotation attributes of {@link Service @Service}
* @param defaultInterfaceClass the default class of interface
* @return the interface name if found
* @throws IllegalStateException if interface name was not found
*/
public static String resolveInterfaceName(Map<String, Object> attributes, Class<?> defaultInterfaceClass) {
// 1. get from DubboService.interfaceName()
String interfaceClassName = AnnotationUtils.getAttribute(attributes, "interfaceName");
if (StringUtils.hasText(interfaceClassName)) {
if ("org.apache.dubbo.rpc.service.GenericService".equals(interfaceClassName)
|| "com.alibaba.dubbo.rpc.service.GenericService".equals(interfaceClassName)) {
throw new IllegalStateException(
"@Service interfaceName() cannot be GenericService: " + interfaceClassName);
}
return interfaceClassName;
}
// 2. get from DubboService.interfaceClass()
Class<?> interfaceClass = AnnotationUtils.getAttribute(attributes, "interfaceClass");
if (interfaceClass == null || void.class.equals(interfaceClass)) { // default or set void.class for purpose.
interfaceClass = null;
} else if (GenericService.class.isAssignableFrom(interfaceClass)) {
throw new IllegalStateException(
"@Service interfaceClass() cannot be GenericService :" + interfaceClass.getName());
}
// 3. get from annotation element type, ignore GenericService
if (interfaceClass == null
&& defaultInterfaceClass != null
&& !GenericService.class.isAssignableFrom(defaultInterfaceClass)) {
// Find all interfaces from the annotated class
// To resolve an issue : https://github.com/apache/dubbo/issues/3251
Class<?>[] allInterfaces = getAllInterfacesForClass(defaultInterfaceClass);
if (allInterfaces.length > 0) {
interfaceClass = allInterfaces[0];
}
}
Assert.notNull(
interfaceClass, "@Service interfaceClass() or interfaceName() or interface class must be present!");
Assert.isTrue(interfaceClass.isInterface(), "The annotated type must be an interface!");
return interfaceClass.getName();
}
@Deprecated
public static String resolveInterfaceName(Reference reference, Class<?> defaultInterfaceClass)
throws IllegalStateException {
String interfaceName;
if (!"".equals(reference.interfaceName())) {
interfaceName = reference.interfaceName();
} else if (!void.class.equals(reference.interfaceClass())) {
interfaceName = reference.interfaceClass().getName();
} else if (defaultInterfaceClass.isInterface()) {
interfaceName = defaultInterfaceClass.getName();
} else {
throw new IllegalStateException("The @Reference undefined interfaceClass or interfaceName, and the type "
+ defaultInterfaceClass.getName() + " is not a interface.");
}
return interfaceName;
}
/**
* Resolve the parameters of {@link org.apache.dubbo.config.annotation.DubboService}
* and {@link org.apache.dubbo.config.annotation.DubboReference} from the specified.
* It iterates elements in order.The former element plays as key or key&value role, it would be
* spilt if it contains specific string, for instance, ":" and "=". As for later element can't
* be split in anytime.It will throw IllegalArgumentException If converted array length isn't
* even number.
* The convert cases below work in right way,which are best practice.
* <p>
* (array->map)
* ["a","b"] ==> {a=b}
* [" a "," b "] ==> {a=b}
* ["a=b"] ==>{a=b}
* ["a:b"] ==>{a=b}
* ["a=b","c","d"] ==>{a=b,c=d}
* ["a","a:b"] ==>{a="a:b"}
* ["a","a,b"] ==>{a="a,b"}
* </p>
*
* @param parameters
* @return
*/
public static Map<String, String> convertParameters(String[] parameters) {
if (ArrayUtils.isEmpty(parameters)) {
return new HashMap<>();
}
List<String> compatibleParameterArray = Arrays.stream(parameters)
.map(String::trim)
.reduce(
new ArrayList<>(parameters.length),
(list, parameter) -> {
if (list.size() % 2 == 1) {
// value doesn't split
list.add(parameter);
return list;
}
String[] sp1 = parameter.split(":");
if (sp1.length > 0 && sp1.length % 2 == 0) {
// key split
list.addAll(Arrays.stream(sp1).map(String::trim).collect(Collectors.toList()));
return list;
}
sp1 = parameter.split("=");
if (sp1.length > 0 && sp1.length % 2 == 0) {
list.addAll(Arrays.stream(sp1).map(String::trim).collect(Collectors.toList()));
return list;
}
list.add(parameter);
return list;
},
(a, b) -> a);
return CollectionUtils.toStringMap(compatibleParameterArray.toArray(new String[0]));
}
}
| 8,788 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/GenericBeanPostProcessorAdapter.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.spring.util;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ClassUtils;
/**
* Generic {@link BeanPostProcessor} Adapter
*
* @see BeanPostProcessor
*/
@SuppressWarnings("unchecked")
public abstract class GenericBeanPostProcessorAdapter<T> implements BeanPostProcessor {
private final Class<T> beanType;
public GenericBeanPostProcessorAdapter() {
ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
this.beanType = (Class<T>) actualTypeArguments[0];
}
@Override
public final Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (ClassUtils.isAssignableValue(beanType, bean)) {
return doPostProcessBeforeInitialization((T) bean, beanName);
}
return bean;
}
@Override
public final Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (ClassUtils.isAssignableValue(beanType, bean)) {
return doPostProcessAfterInitialization((T) bean, beanName);
}
return bean;
}
/**
* Bean Type
*
* @return Bean Type
*/
public final Class<T> getBeanType() {
return beanType;
}
/**
* Adapter BeanPostProcessor#postProcessBeforeInitialization(Object, String) method , sub-type
* could override this method.
*
* @param bean Bean Object
* @param beanName Bean Name
* @return Bean Object
* @see BeanPostProcessor#postProcessBeforeInitialization(Object, String)
*/
protected T doPostProcessBeforeInitialization(T bean, String beanName) throws BeansException {
processBeforeInitialization(bean, beanName);
return bean;
}
/**
* Adapter BeanPostProcessor#postProcessAfterInitialization(Object, String) method , sub-type
* could override this method.
*
* @param bean Bean Object
* @param beanName Bean Name
* @return Bean Object
* @see BeanPostProcessor#postProcessAfterInitialization(Object, String)
*/
protected T doPostProcessAfterInitialization(T bean, String beanName) throws BeansException {
processAfterInitialization(bean, beanName);
return bean;
}
/**
* Process {@link T Bean} with name without return value before initialization,
* <p>
* This method will be invoked by BeanPostProcessor#postProcessBeforeInitialization(Object, String)
*
* @param bean Bean Object
* @param beanName Bean Name
* @throws BeansException in case of errors
*/
protected void processBeforeInitialization(T bean, String beanName) throws BeansException {}
/**
* Process {@link T Bean} with name without return value after initialization,
* <p>
* This method will be invoked by BeanPostProcessor#postProcessAfterInitialization(Object, String)
*
* @param bean Bean Object
* @param beanName Bean Name
* @throws BeansException in case of errors
*/
protected void processAfterInitialization(T bean, String beanName) throws BeansException {}
}
| 8,789 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/BeanRegistrar.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.spring.util;
import org.springframework.core.AliasRegistry;
import static org.springframework.util.ObjectUtils.containsElement;
import static org.springframework.util.StringUtils.hasText;
/**
* Bean Registrar
*/
public abstract class BeanRegistrar {
/**
* Detect the alias is present or not in the given bean name from {@link AliasRegistry}
*
* @param registry {@link AliasRegistry}
* @param beanName the bean name
* @param alias alias to test
* @return if present, return <code>true</code>, or <code>false</code>
*/
public static boolean hasAlias(AliasRegistry registry, String beanName, String alias) {
return hasText(beanName) && hasText(alias) && containsElement(registry.getAliases(beanName), alias);
}
}
| 8,790 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LazyTargetInvocationHandler.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.spring.util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class LazyTargetInvocationHandler implements InvocationHandler {
private final LazyTargetSource lazyTargetSource;
private volatile Object target;
public LazyTargetInvocationHandler(LazyTargetSource lazyTargetSource) {
this.lazyTargetSource = lazyTargetSource;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 0) {
if ("toString".equals(methodName)) {
if (target != null) {
return target.toString();
} else {
return this.toString();
}
} else if ("hashCode".equals(methodName)) {
return this.hashCode();
}
} else if (parameterTypes.length == 1 && "equals".equals(methodName)) {
return this.equals(args[0]);
}
if (target == null) {
target = lazyTargetSource.getTarget();
}
if (method.getDeclaringClass().isInstance(target)) {
try {
return method.invoke(target, args);
} catch (InvocationTargetException exception) {
Throwable targetException = exception.getTargetException();
if (targetException != null) {
throw targetException;
}
}
}
throw new IllegalStateException("The proxied interface [" + method.getDeclaringClass() + "] contains a method ["
+ method + "] that is not implemented by the proxy class [" + target.getClass() + "]");
}
}
| 8,791 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/ObjectUtils.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.spring.util;
/**
* Object Utilities
*/
@SuppressWarnings("unchecked")
public abstract class ObjectUtils {
/**
* Empty String array
*/
public static final String[] EMPTY_STRING_ARRAY = {};
/**
* Convert from variable arguments to array
*
* @param values variable arguments
* @param <T> The class
* @return array
*/
public static <T> T[] of(T... values) {
return values;
}
}
| 8,792 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/SpringCompatUtils.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.spring.util;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.core.type.MethodMetadata;
import org.springframework.core.type.StandardMethodMetadata;
/**
* Spring Compatibility Utils for spring 3.x/4.x/5.x
*/
public class SpringCompatUtils {
private static volatile Boolean factoryMethodMetadataEnabled = null;
private static final Log logger = LogFactory.getLog(SpringCompatUtils.class);
public static <T> T getPropertyValue(PropertyValues pvs, String propertyName) {
PropertyValue pv = pvs.getPropertyValue(propertyName);
Object val = pv != null ? pv.getValue() : null;
if (val instanceof TypedStringValue) {
TypedStringValue typedString = (TypedStringValue) val;
return (T) typedString.getValue();
}
return (T) val;
}
public static boolean isFactoryMethodMetadataEnabled() {
if (factoryMethodMetadataEnabled == null) {
try {
// check AnnotatedBeanDefinition.getFactoryMethodMetadata() since spring 4.1
AnnotatedBeanDefinition.class.getMethod("getFactoryMethodMetadata");
// check MethodMetadata.getReturnTypeName() since spring 4.2
MethodMetadata.class.getMethod("getReturnTypeName");
factoryMethodMetadataEnabled = true;
} catch (NoSuchMethodException e) {
factoryMethodMetadataEnabled = false;
}
}
return factoryMethodMetadataEnabled;
}
public static String getFactoryMethodReturnType(AnnotatedBeanDefinition annotatedBeanDefinition) {
try {
if (isFactoryMethodMetadataEnabled()) {
MethodMetadata factoryMethodMetadata = annotatedBeanDefinition.getFactoryMethodMetadata();
return factoryMethodMetadata != null ? factoryMethodMetadata.getReturnTypeName() : null;
} else {
Object source = annotatedBeanDefinition.getSource();
if (source instanceof StandardMethodMetadata) {
StandardMethodMetadata methodMetadata = (StandardMethodMetadata) source;
Method introspectedMethod = methodMetadata.getIntrospectedMethod();
if (introspectedMethod != null) {
return introspectedMethod.getReturnType().getName();
}
}
}
} catch (Throwable e) {
if (logger.isInfoEnabled()) {
logger.info("get return type of AnnotatedBeanDefinition failed", e);
}
}
return null;
}
public static MethodMetadata getFactoryMethodMetadata(AnnotatedBeanDefinition annotatedBeanDefinition) {
if (isFactoryMethodMetadataEnabled()) {
return annotatedBeanDefinition.getFactoryMethodMetadata();
} else {
Object source = annotatedBeanDefinition.getSource();
if (source instanceof StandardMethodMetadata) {
return (MethodMetadata) source;
}
return null;
}
}
/**
* Get the generic type of return type of the method.
*
* <pre>
* Source method:
* ReferenceBean<DemoService> demoService()
*
* Result: DemoService.class
* </pre>
*
* @param factoryMethodMetadata
* @return
*/
public static Class getGenericTypeOfReturnType(MethodMetadata factoryMethodMetadata) {
if (factoryMethodMetadata instanceof StandardMethodMetadata) {
Method introspectedMethod = ((StandardMethodMetadata) factoryMethodMetadata).getIntrospectedMethod();
Type returnType = introspectedMethod.getGenericReturnType();
if (returnType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) returnType;
Type actualTypeArgument = parameterizedType.getActualTypeArguments()[0];
if (actualTypeArgument instanceof Class) {
return (Class) actualTypeArgument;
}
}
}
return null;
}
}
| 8,793 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/AnnotationUtils.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.spring.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertyResolver;
import org.springframework.util.ClassUtils;
import static java.lang.String.valueOf;
import static java.util.Arrays.asList;
import static org.springframework.core.annotation.AnnotationAttributes.fromMap;
import static org.springframework.core.annotation.AnnotationUtils.getDefaultValue;
import static org.springframework.util.ClassUtils.resolveClassName;
import static org.springframework.util.CollectionUtils.isEmpty;
import static org.springframework.util.ObjectUtils.nullSafeEquals;
import static org.springframework.util.ReflectionUtils.findMethod;
import static org.springframework.util.ReflectionUtils.invokeMethod;
import static org.springframework.util.StringUtils.trimWhitespace;
@SuppressWarnings("unchecked")
public abstract class AnnotationUtils {
/**
* The class name of AnnotatedElementUtils that is introduced since Spring Framework 4
*/
public static final String ANNOTATED_ELEMENT_UTILS_CLASS_NAME =
"org.springframework.core.annotation.AnnotatedElementUtils";
private static final Map<Integer, Boolean> annotatedElementUtilsPresentCache = new ConcurrentHashMap<>();
/**
* Get the {@link Annotation} attributes
*
* @param annotation specified {@link Annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return non-null
*/
public static Map<String, Object> getAttributes(
Annotation annotation,
PropertyResolver propertyResolver,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
return getAttributes(annotation, propertyResolver, false, false, ignoreDefaultValue, ignoreAttributeNames);
}
/**
* Get the {@link Annotation} attributes
*
* @param annotationAttributes the attributes of specified {@link Annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return non-null
*/
public static Map<String, Object> getAttributes(
Map<String, Object> annotationAttributes,
PropertyResolver propertyResolver,
String... ignoreAttributeNames) {
Set<String> ignoreAttributeNamesSet = new HashSet<>(Arrays.asList(ignoreAttributeNames));
Map<String, Object> actualAttributes = new LinkedHashMap<String, Object>();
for (Map.Entry<String, Object> annotationAttribute : annotationAttributes.entrySet()) {
String attributeName = annotationAttribute.getKey();
Object attributeValue = annotationAttribute.getValue();
// ignore attribute name
if (ignoreAttributeNamesSet.contains(attributeName)) {
continue;
}
if (attributeValue instanceof String) {
attributeValue = resolvePlaceholders(valueOf(attributeValue), propertyResolver);
} else if (attributeValue instanceof String[]) {
String[] values = (String[]) attributeValue;
for (int i = 0; i < values.length; i++) {
values[i] = resolvePlaceholders(values[i], propertyResolver);
}
attributeValue = values;
}
actualAttributes.put(attributeName, attributeValue);
}
return actualAttributes;
}
/**
* @param annotation specified {@link Annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param classValuesAsString whether to turn Class references into Strings (for
* compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to turn nested Annotation instances into
* {@link AnnotationAttributes} maps (for compatibility with
* {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as
* Annotation instances
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return
*/
public static Map<String, Object> getAttributes(
Annotation annotation,
PropertyResolver propertyResolver,
boolean classValuesAsString,
boolean nestedAnnotationsAsMap,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
Map<String, Object> annotationAttributes =
org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes(
annotation, classValuesAsString, nestedAnnotationsAsMap);
String[] actualIgnoreAttributeNames = ignoreAttributeNames;
if (ignoreDefaultValue && !isEmpty(annotationAttributes)) {
List<String> attributeNamesToIgnore = new LinkedList<String>(asList(ignoreAttributeNames));
for (Map.Entry<String, Object> annotationAttribute : annotationAttributes.entrySet()) {
String attributeName = annotationAttribute.getKey();
Object attributeValue = annotationAttribute.getValue();
if (nullSafeEquals(attributeValue, getDefaultValue(annotation, attributeName))) {
attributeNamesToIgnore.add(attributeName);
}
}
// extends the ignored list
actualIgnoreAttributeNames = attributeNamesToIgnore.toArray(new String[attributeNamesToIgnore.size()]);
}
return getAttributes(annotationAttributes, propertyResolver, actualIgnoreAttributeNames);
}
private static String resolvePlaceholders(String attributeValue, PropertyResolver propertyResolver) {
String resolvedValue = attributeValue;
if (propertyResolver != null) {
resolvedValue = propertyResolver.resolvePlaceholders(resolvedValue);
resolvedValue = trimWhitespace(resolvedValue);
}
return resolvedValue;
}
/**
* Get the attribute value
*
* @param attributes {@link Map the annotation attributes} or {@link AnnotationAttributes}
* @param attributeName the name of attribute
* @param <T> the type of attribute value
* @return the attribute value if found
*/
public static <T> T getAttribute(Map<String, Object> attributes, String attributeName) {
return getAttribute(attributes, attributeName, false);
}
/**
* Get the attribute value the will
*
* @param attributes {@link Map the annotation attributes} or {@link AnnotationAttributes}
* @param attributeName the name of attribute
* @param required the required attribute or not
* @param <T> the type of attribute value
* @return the attribute value if found
* @throws IllegalStateException if attribute value can't be found
*/
public static <T> T getAttribute(Map<String, Object> attributes, String attributeName, boolean required) {
T value = getAttribute(attributes, attributeName, null);
if (required && value == null) {
throw new IllegalStateException("The attribute['" + attributeName + "] is required!");
}
return value;
}
/**
* Get the attribute value with default value
*
* @param attributes {@link Map the annotation attributes} or {@link AnnotationAttributes}
* @param attributeName the name of attribute
* @param defaultValue the default value of attribute
* @param <T> the type of attribute value
* @return the attribute value if found
*/
public static <T> T getAttribute(Map<String, Object> attributes, String attributeName, T defaultValue) {
T value = (T) attributes.get(attributeName);
return value == null ? defaultValue : value;
}
/**
* Get the required attribute value
*
* @param attributes {@link Map the annotation attributes} or {@link AnnotationAttributes}
* @param attributeName the name of attribute
* @param <T> the type of attribute value
* @return the attribute value if found
* @throws IllegalStateException if attribute value can't be found
*/
public static <T> T getRequiredAttribute(Map<String, Object> attributes, String attributeName) {
return getAttribute(attributes, attributeName, true);
}
/**
* Get the {@link AnnotationAttributes}
*
* @param annotation specified {@link Annotation}
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return non-null
* @see #getAnnotationAttributes(Annotation, PropertyResolver, boolean, String...)
*/
public static AnnotationAttributes getAnnotationAttributes(
Annotation annotation, boolean ignoreDefaultValue, String... ignoreAttributeNames) {
return getAnnotationAttributes(annotation, null, ignoreDefaultValue, ignoreAttributeNames);
}
/**
* Get the {@link AnnotationAttributes}
*
* @param annotation specified {@link Annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param classValuesAsString whether to turn Class references into Strings (for
* compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to turn nested Annotation instances into
* {@link AnnotationAttributes} maps (for compatibility with
* {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as
* Annotation instances
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @param ignoreDefaultValue whether ignore default value or not
* @return non-null
* @see #getAttributes(Annotation, PropertyResolver, boolean, String...)
* @see #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...)
*/
public static AnnotationAttributes getAnnotationAttributes(
Annotation annotation,
PropertyResolver propertyResolver,
boolean classValuesAsString,
boolean nestedAnnotationsAsMap,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
return fromMap(getAttributes(
annotation,
propertyResolver,
classValuesAsString,
nestedAnnotationsAsMap,
ignoreDefaultValue,
ignoreAttributeNames));
}
/**
* Get the {@link AnnotationAttributes}
*
* @param annotation specified {@link Annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return non-null
* @see #getAttributes(Annotation, PropertyResolver, boolean, String...)
* @see #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...)
*/
public static AnnotationAttributes getAnnotationAttributes(
Annotation annotation,
PropertyResolver propertyResolver,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
return getAnnotationAttributes(
annotation, propertyResolver, false, false, ignoreDefaultValue, ignoreAttributeNames);
}
/**
* Get the {@link AnnotationAttributes}
*
* @param annotatedElement {@link AnnotatedElement the annotated element}
* @param annotationType the {@link Class tyoe} pf {@link Annotation annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return if <code>annotatedElement</code> can't be found in <code>annotatedElement</code>, return <code>null</code>
*/
public static AnnotationAttributes getAnnotationAttributes(
AnnotatedElement annotatedElement,
Class<? extends Annotation> annotationType,
PropertyResolver propertyResolver,
boolean classValuesAsString,
boolean nestedAnnotationsAsMap,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
Annotation annotation = annotatedElement.getAnnotation(annotationType);
return annotation == null
? null
: getAnnotationAttributes(
annotation,
propertyResolver,
classValuesAsString,
nestedAnnotationsAsMap,
ignoreDefaultValue,
ignoreAttributeNames);
}
/**
* Get the {@link AnnotationAttributes}, if the argument <code>tryMergedAnnotation</code> is <code>true</code>,
* the {@link AnnotationAttributes} will be got from
* {@link #tryGetMergedAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...) merged annotation} first,
* if failed, and then to get from
* {@link #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, boolean, String...) normal one}
*
* @param annotatedElement {@link AnnotatedElement the annotated element}
* @param annotationType the {@link Class tyoe} pf {@link Annotation annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param ignoreDefaultValue whether ignore default value or not
* @param tryMergedAnnotation whether try merged annotation or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return if <code>annotatedElement</code> can't be found in <code>annotatedElement</code>, return <code>null</code>
*/
public static AnnotationAttributes getAnnotationAttributes(
AnnotatedElement annotatedElement,
Class<? extends Annotation> annotationType,
PropertyResolver propertyResolver,
boolean ignoreDefaultValue,
boolean tryMergedAnnotation,
String... ignoreAttributeNames) {
return getAnnotationAttributes(
annotatedElement,
annotationType,
propertyResolver,
false,
false,
ignoreDefaultValue,
tryMergedAnnotation,
ignoreAttributeNames);
}
/**
* Get the {@link AnnotationAttributes}, if the argument <code>tryMergedAnnotation</code> is <code>true</code>,
* the {@link AnnotationAttributes} will be got from
* {@link #tryGetMergedAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, String...) merged annotation} first,
* if failed, and then to get from
* {@link #getAnnotationAttributes(AnnotatedElement, Class, PropertyResolver, boolean, boolean, String...) normal one}
*
* @param annotatedElement {@link AnnotatedElement the annotated element}
* @param annotationType the {@link Class tyoe} pf {@link Annotation annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param classValuesAsString whether to turn Class references into Strings (for
* compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to turn nested Annotation instances into
* {@link AnnotationAttributes} maps (for compatibility with
* {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as
* Annotation instances
* @param ignoreDefaultValue whether ignore default value or not
* @param tryMergedAnnotation whether try merged annotation or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return if <code>annotatedElement</code> can't be found in <code>annotatedElement</code>, return <code>null</code>
*/
public static AnnotationAttributes getAnnotationAttributes(
AnnotatedElement annotatedElement,
Class<? extends Annotation> annotationType,
PropertyResolver propertyResolver,
boolean classValuesAsString,
boolean nestedAnnotationsAsMap,
boolean ignoreDefaultValue,
boolean tryMergedAnnotation,
String... ignoreAttributeNames) {
AnnotationAttributes attributes = null;
if (tryMergedAnnotation) {
attributes = tryGetMergedAnnotationAttributes(
annotatedElement,
annotationType,
propertyResolver,
classValuesAsString,
nestedAnnotationsAsMap,
ignoreDefaultValue,
ignoreAttributeNames);
}
if (attributes == null) {
attributes = getAnnotationAttributes(
annotatedElement,
annotationType,
propertyResolver,
classValuesAsString,
nestedAnnotationsAsMap,
ignoreDefaultValue,
ignoreAttributeNames);
}
return attributes;
}
/**
* Try to get the merged {@link Annotation annotation}
*
* @param annotatedElement {@link AnnotatedElement the annotated element}
* @param annotationType the {@link Class tyoe} pf {@link Annotation annotation}
* @param classValuesAsString whether to turn Class references into Strings (for
* compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to turn nested Annotation instances into
* {@link AnnotationAttributes} maps (for compatibility with
* {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as
* Annotation instances
* @return If current version of Spring Framework is below 4.2, return <code>null</code>
*/
public static Annotation tryGetMergedAnnotation(
AnnotatedElement annotatedElement,
Class<? extends Annotation> annotationType,
boolean classValuesAsString,
boolean nestedAnnotationsAsMap) {
Annotation mergedAnnotation = null;
ClassLoader classLoader = annotationType.getClassLoader();
if (annotatedElementUtilsPresentCache.computeIfAbsent(
System.identityHashCode(classLoader),
(_k) -> ClassUtils.isPresent(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, classLoader))) {
Class<?> annotatedElementUtilsClass = resolveClassName(ANNOTATED_ELEMENT_UTILS_CLASS_NAME, classLoader);
// getMergedAnnotation method appears in the Spring Framework 4.2
Method getMergedAnnotationMethod = findMethod(
annotatedElementUtilsClass,
"getMergedAnnotation",
AnnotatedElement.class,
Class.class,
boolean.class,
boolean.class);
if (getMergedAnnotationMethod != null) {
mergedAnnotation = (Annotation) invokeMethod(
getMergedAnnotationMethod,
null,
annotatedElement,
annotationType,
classValuesAsString,
nestedAnnotationsAsMap);
}
}
return mergedAnnotation;
}
/**
* Try to get {@link AnnotationAttributes the annotation attributes} after merging and resolving the placeholders
*
* @param annotatedElement {@link AnnotatedElement the annotated element}
* @param annotationType the {@link Class tyoe} pf {@link Annotation annotation}
* @param propertyResolver {@link PropertyResolver} instance, e.g {@link Environment}
* @param classValuesAsString whether to turn Class references into Strings (for
* compatibility with {@link org.springframework.core.type.AnnotationMetadata} or to
* preserve them as Class references
* @param nestedAnnotationsAsMap whether to turn nested Annotation instances into
* {@link AnnotationAttributes} maps (for compatibility with
* {@link org.springframework.core.type.AnnotationMetadata} or to preserve them as
* Annotation instances
* @param ignoreDefaultValue whether ignore default value or not
* @param ignoreAttributeNames the attribute names of annotation should be ignored
* @return If the specified annotation type is not found, return <code>null</code>
*/
public static AnnotationAttributes tryGetMergedAnnotationAttributes(
AnnotatedElement annotatedElement,
Class<? extends Annotation> annotationType,
PropertyResolver propertyResolver,
boolean classValuesAsString,
boolean nestedAnnotationsAsMap,
boolean ignoreDefaultValue,
String... ignoreAttributeNames) {
Annotation annotation =
tryGetMergedAnnotation(annotatedElement, annotationType, classValuesAsString, nestedAnnotationsAsMap);
return annotation == null
? null
: getAnnotationAttributes(
annotation,
propertyResolver,
classValuesAsString,
nestedAnnotationsAsMap,
ignoreDefaultValue,
ignoreAttributeNames);
}
}
| 8,794 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LockUtils.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.spring.util;
import java.lang.reflect.Method;
import org.springframework.beans.factory.support.DefaultSingletonBeanRegistry;
import org.springframework.context.ApplicationContext;
public class LockUtils {
private static final String DUBBO_SINGLETON_MUTEX_KEY = "DUBBO_SINGLETON_MUTEX";
/**
* Get the mutex to lock the singleton in the specified {@link ApplicationContext}
*/
public static synchronized Object getSingletonMutex(ApplicationContext applicationContext) {
DefaultSingletonBeanRegistry autowireCapableBeanFactory =
(DefaultSingletonBeanRegistry) applicationContext.getAutowireCapableBeanFactory();
try {
return autowireCapableBeanFactory.getSingletonMutex();
} catch (Throwable t1) {
try {
// try protected
Method method = DefaultSingletonBeanRegistry.class.getDeclaredMethod("getSingletonMutex");
method.setAccessible(true);
return method.invoke(autowireCapableBeanFactory);
} catch (Throwable t2) {
// Before Spring 4.2, there is no getSingletonMutex method
if (!autowireCapableBeanFactory.containsSingleton(DUBBO_SINGLETON_MUTEX_KEY)) {
autowireCapableBeanFactory.registerSingleton(DUBBO_SINGLETON_MUTEX_KEY, new Object());
}
return autowireCapableBeanFactory.getSingleton(DUBBO_SINGLETON_MUTEX_KEY);
}
}
}
}
| 8,795 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/util/LazyTargetSource.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.spring.util;
public interface LazyTargetSource {
Object getTarget() throws Exception;
}
| 8,796 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/DataSourceStatusChecker.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.spring.status;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.status.Status;
import org.apache.dubbo.common.status.StatusChecker;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.spring.extension.SpringExtensionInjector;
import org.apache.dubbo.rpc.model.ApplicationModel;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_WARN_STATUS_CHECKER;
/**
* DataSourceStatusChecker
*/
@Activate
public class DataSourceStatusChecker implements StatusChecker {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DataSourceStatusChecker.class);
private ApplicationModel applicationModel;
private ApplicationContext applicationContext;
public DataSourceStatusChecker(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
public DataSourceStatusChecker(ApplicationContext context) {
this.applicationContext = context;
}
@Override
public Status check() {
if (applicationContext == null) {
SpringExtensionInjector springExtensionInjector = SpringExtensionInjector.get(applicationModel);
applicationContext = springExtensionInjector.getContext();
}
if (applicationContext == null) {
return new Status(Status.Level.UNKNOWN);
}
Map<String, DataSource> dataSources = applicationContext.getBeansOfType(DataSource.class, false, false);
if (CollectionUtils.isEmptyMap(dataSources)) {
return new Status(Status.Level.UNKNOWN);
}
Status.Level level = Status.Level.OK;
StringBuilder buf = new StringBuilder();
for (Map.Entry<String, DataSource> entry : dataSources.entrySet()) {
DataSource dataSource = entry.getValue();
if (buf.length() > 0) {
buf.append(", ");
}
buf.append(entry.getKey());
try (Connection connection = dataSource.getConnection()) {
DatabaseMetaData metaData = connection.getMetaData();
try (ResultSet resultSet = metaData.getTypeInfo()) {
if (!resultSet.next()) {
level = Status.Level.ERROR;
}
}
buf.append(metaData.getURL());
buf.append('(');
buf.append(metaData.getDatabaseProductName());
buf.append('-');
buf.append(metaData.getDatabaseProductVersion());
buf.append(')');
} catch (Throwable e) {
logger.warn(CONFIG_WARN_STATUS_CHECKER, "", "", e.getMessage(), e);
return new Status(level, e.getMessage());
}
}
return new Status(level, buf.toString());
}
}
| 8,797 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/status/SpringStatusChecker.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.spring.status;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.status.Status;
import org.apache.dubbo.common.status.StatusChecker;
import org.apache.dubbo.config.spring.extension.SpringExtensionInjector;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.lang.reflect.Method;
import org.springframework.context.ApplicationContext;
import org.springframework.context.Lifecycle;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_WARN_STATUS_CHECKER;
/**
* SpringStatusChecker
*/
@Activate
public class SpringStatusChecker implements StatusChecker {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SpringStatusChecker.class);
private ApplicationModel applicationModel;
private ApplicationContext applicationContext;
public SpringStatusChecker(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
public SpringStatusChecker(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public Status check() {
if (applicationContext == null && applicationModel != null) {
SpringExtensionInjector springExtensionInjector = SpringExtensionInjector.get(applicationModel);
applicationContext = springExtensionInjector.getContext();
}
if (applicationContext == null) {
return new Status(Status.Level.UNKNOWN);
}
Status.Level level;
if (applicationContext instanceof Lifecycle) {
if (((Lifecycle) applicationContext).isRunning()) {
level = Status.Level.OK;
} else {
level = Status.Level.ERROR;
}
} else {
level = Status.Level.UNKNOWN;
}
StringBuilder buf = new StringBuilder();
try {
Class<?> cls = applicationContext.getClass();
Method method = null;
while (cls != null && method == null) {
try {
method = cls.getDeclaredMethod("getConfigLocations", new Class<?>[0]);
} catch (NoSuchMethodException t) {
cls = cls.getSuperclass();
}
}
if (method != null) {
if (!method.isAccessible()) {
method.setAccessible(true);
}
String[] configs = (String[]) method.invoke(applicationContext, new Object[0]);
if (configs != null && configs.length > 0) {
for (String config : configs) {
if (buf.length() > 0) {
buf.append(',');
}
buf.append(config);
}
}
}
} catch (Throwable t) {
if (t.getCause() instanceof UnsupportedOperationException) {
logger.debug(t.getMessage(), t);
} else {
logger.warn(CONFIG_WARN_STATUS_CHECKER, "", "", t.getMessage(), t);
}
}
return new Status(level, buf.toString());
}
}
| 8,798 |
0 |
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring
|
Create_ds/dubbo/dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/schema/AnnotationBeanDefinitionParser.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.spring.schema;
import org.apache.dubbo.config.spring.beans.factory.annotation.ServiceAnnotationPostProcessor;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;
import static org.springframework.util.StringUtils.commaDelimitedListToStringArray;
import static org.springframework.util.StringUtils.trimArrayElements;
/**
* @link BeanDefinitionParser}
* @see ServiceAnnotationPostProcessor
* @see ReferenceAnnotationBeanPostProcessor
* @since 2.5.9
*/
public class AnnotationBeanDefinitionParser extends AbstractSingleBeanDefinitionParser {
/**
* parse
* <prev>
* <dubbo:annotation package="" />
* </prev>
*
* @param element
* @param parserContext
* @param builder
*/
@Override
protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
String packageToScan = element.getAttribute("package");
String[] packagesToScan = trimArrayElements(commaDelimitedListToStringArray(packageToScan));
builder.addConstructorArgValue(packagesToScan);
builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
/**
* @since 2.7.6 Register the common beans
* @since 2.7.8 comment this code line, and migrated to
* @see DubboNamespaceHandler#parse(Element, ParserContext)
* @see https://github.com/apache/dubbo/issues/6174
*/
// registerCommonBeans(parserContext.getRegistry());
}
@Override
protected boolean shouldGenerateIdAsFallback() {
return true;
}
@Override
protected Class<?> getBeanClass(Element element) {
return ServiceAnnotationPostProcessor.class;
}
}
| 8,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.