com.alibaba.dubbo.config.spring.ServiceBean Java Examples

The following examples show how to use com.alibaba.dubbo.config.spring.ServiceBean. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ReferenceManager.java    From swagger-dubbo with Apache License 2.0 6 votes vote down vote up
public Object getProxy(String interfaceClass) {
    Set<Entry<Class<?>, Object>> entrySet = interfaceMapProxy.entrySet();
    for (Entry<Class<?>, Object> entry : entrySet) {
        if (entry.getKey().getName().equals(interfaceClass)) { return entry.getValue(); }
    }

    for (ServiceBean<?> service : services) {
        if (interfaceClass.equals(service.getInterfaceClass().getName())) {
            ReferenceConfig<Object> reference = new ReferenceConfig<Object>();
            reference.setApplication(service.getApplication());
            reference.setRegistry(service.getRegistry());
            reference.setRegistries(service.getRegistries());
            reference.setInterface(service.getInterfaceClass());
            reference.setVersion(service.getVersion());
            interfaceMapProxy.put(service.getInterfaceClass(), reference.get());
            return reference.get();
        }
    }
    return null;
}
 
Example #2
Source File: AlibabaDubboServiceBeanPostProcessor.java    From soul with Apache License 2.0 6 votes vote down vote up
private void handler(final ServiceBean serviceBean) {
    Class<?> clazz = serviceBean.getRef().getClass();
    if (ClassUtils.isCglibProxyClass(clazz)) {
        String superClassName = clazz.getGenericSuperclass().getTypeName();
        try {
            clazz = Class.forName(superClassName);
        } catch (ClassNotFoundException e) {
            log.error(String.format("class not found: %s", superClassName));
            return;
        }
    }
    final Method[] methods = ReflectionUtils.getUniqueDeclaredMethods(clazz);
    for (Method method : methods) {
        SoulDubboClient soulDubboClient = method.getAnnotation(SoulDubboClient.class);
        if (Objects.nonNull(soulDubboClient)) {
            post(buildJsonParams(serviceBean, soulDubboClient, method));
        }
    }
}
 
Example #3
Source File: AlibabaDubboServiceBeanPostProcessor.java    From soul with Apache License 2.0 5 votes vote down vote up
private String buildRpcExt(final ServiceBean serviceBean) {
    MetaDataDTO.RpcExt build = MetaDataDTO.RpcExt.builder()
            .group(serviceBean.getGroup())
            .version(serviceBean.getVersion())
            .loadbalance(serviceBean.getLoadbalance())
            .retries(serviceBean.getRetries())
            .timeout(serviceBean.getTimeout())
            .build();
    return OkHttpTools.getInstance().getGosn().toJson(build);
    
}
 
Example #4
Source File: TransactionBeanConfigValidator.java    From ByteJTA with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void validateServiceBean(String beanName, ServiceBean<?> serviceBean) throws BeansException {
	Integer retries = serviceBean.getRetries();
	String loadbalance = serviceBean.getLoadbalance();
	String cluster = serviceBean.getCluster();
	String filter = serviceBean.getFilter();
	String group = serviceBean.getGroup();

	if (StringUtils.isBlank(group)) {
		return;
	} else if (StringUtils.equalsIgnoreCase("x-bytejta", group) == false
			&& StringUtils.lowerCase(group).startsWith("x-bytejta-") == false) {
		return;
	}

	String[] filterArray = filter == null ? new String[0] : filter.split("\\s*,\\s*");

	if (retries != null && retries.intValue() >= 0) {
		throw new FatalBeanException(String.format("The value of attr 'retries'(beanId= %s) should be '-1'.", beanName));
	} else if (loadbalance == null || StringUtils.equals("bytejta", loadbalance) == false) {
		throw new FatalBeanException(
				String.format("The value of attr 'loadbalance'(beanId= %s) should be 'bytejta'.", beanName));
	} else if (cluster == null || StringUtils.equals("failfast", cluster) == false) {
		throw new FatalBeanException(
				String.format("The value of attribute 'cluster' (beanId= %s) must be 'failfast'.", beanName));
	} else if (filterArray.length == 0) {
		throw new FatalBeanException(String.format("The value of attr 'filter'(beanId= %s) must be null.", beanName));
	} else if (StringUtils.equalsIgnoreCase(filterArray[0], "bytejta") == false) {
		throw new FatalBeanException(
				String.format("The first value of attr 'filter'(beanId= %s) should be 'bytejta'.", beanName));
	}
}
 
Example #5
Source File: TransactionBeanConfigValidator.java    From ByteJTA with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
	if (ProtocolConfig.class.isInstance(bean)) {
		this.validateProtocolConfig(beanName, (ProtocolConfig) bean);
	} else if (ServiceBean.class.isInstance(bean)) {
		this.validateServiceBean(beanName, (ServiceBean<?>) bean);
	}

	return bean;
}
 
Example #6
Source File: DubboNamespaceHandler.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void init() {
 registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true));
    registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true));
    registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true));
    registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true));
    registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true));
    registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true));
    registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true));
    registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true));
    registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false));
    registerBeanDefinitionParser("annotation", new DubboBeanDefinitionParser(AnnotationBean.class, true));
}
 
Example #7
Source File: DubboNamespaceHandler.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void init() {
 registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true));
    registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true));
    registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true));
    registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true));
    registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true));
    registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true));
    registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true));
    registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true));
    registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false));
    registerBeanDefinitionParser("annotation", new DubboBeanDefinitionParser(AnnotationBean.class, true));
}
 
Example #8
Source File: DubboNamespaceHandler.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
public void init() {
 registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true));
    registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true));
    registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true));
    registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true));
    registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true));
    registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true));
    registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true));
    registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true));
    registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false));
    registerBeanDefinitionParser("annotation", new DubboBeanDefinitionParser(AnnotationBean.class, true));
}
 
Example #9
Source File: DataSourceStatusChecker.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Status check() {
    ApplicationContext context = ServiceBean.getSpringContext();
    if (context == null) {
        return new Status(Status.Level.UNKNOWN);
    }
    Map<String, DataSource> dataSources = context.getBeansOfType(DataSource.class, false, false);
    if (dataSources == null || dataSources.size() == 0) {
        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 {
            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(e.getMessage(), e);
            return new Status(level, e.getMessage());
        }
    }
    return new Status(level, buf.toString());
}
 
Example #10
Source File: DubboProviderAutoConfiguration.java    From dubbo-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
private void initProviderBean(String beanName, Object bean) throws Exception {
  Service service = this.applicationContext.findAnnotationOnBean(beanName, Service.class);
  ServiceBean<Object> serviceConfig = new ServiceBean<Object>(service);
  if ((service.interfaceClass() == null || service.interfaceClass() == void.class)
      && (service.interfaceName() == null || "".equals(service.interfaceName()))) {
    Class<?>[] interfaces = bean.getClass().getInterfaces();
    if (interfaces.length > 0) {
      serviceConfig.setInterface(interfaces[0]);
    }
  }

  Environment environment = this.applicationContext.getEnvironment();
  String application = service.application();
  serviceConfig.setApplication(this.parseApplication(application, this.properties, environment,
      beanName, "application", application));
  String module = service.module();
  serviceConfig.setModule(
      this.parseModule(module, this.properties, environment, beanName, "module", module));
  String[] registries = service.registry();
  serviceConfig.setRegistries(
      this.parseRegistries(registries, this.properties, environment, beanName, "registry"));
  String[] protocols = service.protocol();
  serviceConfig.setProtocols(
      this.parseProtocols(protocols, this.properties, environment, beanName, "registry"));
  String monitor = service.monitor();
  serviceConfig.setMonitor(
      this.parseMonitor(monitor, this.properties, environment, beanName, "monitor", monitor));
  String provider = service.provider();
  serviceConfig.setProvider(
      this.parseProvider(provider, this.properties, environment, beanName, "provider", provider));

  serviceConfig.setApplicationContext(this.applicationContext);
  serviceConfig.afterPropertiesSet();
  serviceConfig.setRef(bean);
  serviceConfig.export();
}
 
Example #11
Source File: DubboNamespaceHandler.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
public void init() {
 registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true));
    registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true));
    registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true));
    registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true));
    registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true));
    registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true));
    registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true));
    registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true));
    registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false));
    registerBeanDefinitionParser("annotation", new DubboBeanDefinitionParser(AnnotationBean.class, true));
}
 
Example #12
Source File: DubboNamespaceHandler.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public void init() {
 registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true));
    registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true));
    registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true));
    registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true));
    registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true));
    registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true));
    registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true));
    registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true));
    registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false));
    registerBeanDefinitionParser("annotation", new DubboBeanDefinitionParser(AnnotationBean.class, true));
}
 
Example #13
Source File: AlibabaDubboServiceBeanPostProcessor.java    From soul with Apache License 2.0 5 votes vote down vote up
@Override
public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
    if (bean instanceof ServiceBean) {
        executorService.execute(() -> handler((ServiceBean) bean));
    }
    return bean;
}
 
Example #14
Source File: ApiRequestHandlerProvider.java    From swagger-more with Apache License 2.0 5 votes vote down vote up
private BiFunction<List<HandlerMethod>, ? super ServiceBean,
        List<HandlerMethod>> toMappingEntries() {
    return (list, bean) -> {
        Object object = AopUtils.isAopProxy(bean.getRef())
                ? AopProxyUtils.getSingletonTarget(bean.getRef()) : bean.getRef();
        list.addAll(Arrays.stream(bean.getInterfaceClass().getDeclaredMethods())
                .filter(method -> !Modifier.isStatic(method.getModifiers()))
                .filter(method -> AnnotatedElementUtils.hasAnnotation(method, ApiMethod.class))
                .map(method -> new HandlerMethod(object, method))
                .collect(Collectors.toList()));
        return list;
    };
}
 
Example #15
Source File: ApiRequestHandlerProvider.java    From swagger-more with Apache License 2.0 5 votes vote down vote up
@Autowired
public ApiRequestHandlerProvider(List<ServiceBean> serviceBeans,
                                 HandlerMethodResolver methodResolver,
                                 TypeResolver typeResolver) {
    this.serviceBeans = serviceBeans;
    this.methodResolver = methodResolver;
    this.typeResolver = typeResolver;
}
 
Example #16
Source File: DubboNamespaceHandlerTest.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Test
public void testProperty() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/service-class.xml");
    ctx.start();

    ServiceBean serviceBean = ctx.getBean(ServiceBean.class);

    String prefix = ((DemoServiceImpl) serviceBean.getRef()).getPrefix();
    assertThat(prefix, is("welcome:"));
}
 
Example #17
Source File: DubboNamespaceHandlerTest.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Test
public void testDelayFixedTime() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/delay-fixed-time.xml");
    ctx.start();

    assertThat(ctx.getBean(ServiceBean.class).getDelay(), is(300));
}
 
Example #18
Source File: DubboNamespaceHandlerTest.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomParameter() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(ConfigTest.class.getPackage().getName().replace('.', '/') + "/customize-parameter.xml");
    ctx.start();

    ProtocolConfig protocolConfig = ctx.getBean(ProtocolConfig.class);
    assertThat(protocolConfig.getParameters().size(), is(1));
    assertThat(protocolConfig.getParameters().get("protocol-paramA"), is("protocol-paramA"));

    ServiceBean serviceBean = ctx.getBean(ServiceBean.class);
    assertThat(serviceBean.getParameters().size(), is(1));
    assertThat(serviceBean.getParameters().get("service-paramA"), is("service-paramA"));
}
 
Example #19
Source File: ReferenceAnnotationBeanPostProcessor.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
private void initReferenceBeanInvocationHandler(ServiceBean serviceBean) {
    String serviceBeanName = serviceBean.getBeanName();
    // Remove ServiceBean when it's exported
    ReferenceBeanInvocationHandler handler = localReferenceBeanInvocationHandlerCache.remove(serviceBeanName);
    // Initialize
    if (handler != null) {
        handler.init();
    }
}
 
Example #20
Source File: DubboNamespaceHandler.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
    public void init() {
//        xml配置解析=》
        registerBeanDefinitionParser("application", new DubboBeanDefinitionParser(ApplicationConfig.class, true));
        registerBeanDefinitionParser("module", new DubboBeanDefinitionParser(ModuleConfig.class, true));
        registerBeanDefinitionParser("registry", new DubboBeanDefinitionParser(RegistryConfig.class, true));
        registerBeanDefinitionParser("monitor", new DubboBeanDefinitionParser(MonitorConfig.class, true));
        registerBeanDefinitionParser("provider", new DubboBeanDefinitionParser(ProviderConfig.class, true));
        registerBeanDefinitionParser("consumer", new DubboBeanDefinitionParser(ConsumerConfig.class, true));
        registerBeanDefinitionParser("protocol", new DubboBeanDefinitionParser(ProtocolConfig.class, true));
        registerBeanDefinitionParser("service", new DubboBeanDefinitionParser(ServiceBean.class, true));
        registerBeanDefinitionParser("reference", new DubboBeanDefinitionParser(ReferenceBean.class, false));
//        annotation解析<dubbo:annotation package="" />xml配置=》
        registerBeanDefinitionParser("annotation", new AnnotationBeanDefinitionParser());
    }
 
Example #21
Source File: SpringStatusCheckerTest.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithoutLifeCycleRunning() {
    ApplicationLifeCycle applicationLifeCycle = mock(ApplicationLifeCycle.class);
    new ServiceBean<Object>().setApplicationContext(applicationLifeCycle);
    given(applicationLifeCycle.isRunning()).willReturn(false);

    Status status = springStatusChecker.check();

    assertThat(status.getLevel(), is(Status.Level.ERROR));
}
 
Example #22
Source File: SpringStatusCheckerTest.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithLifeCycleRunning() {
    ApplicationLifeCycle applicationLifeCycle = mock(ApplicationLifeCycle.class);
    new ServiceBean<Object>().setApplicationContext(applicationLifeCycle);
    given(applicationLifeCycle.getConfigLocations()).willReturn(new String[]{"test1", "test2"});
    given(applicationLifeCycle.isRunning()).willReturn(true);

    Status status = springStatusChecker.check();

    assertThat(status.getLevel(), is(Status.Level.OK));
    assertThat(status.getMessage(), is("test1,test2"));
}
 
Example #23
Source File: FeignClientToDubboProviderBeanPostProcessor.java    From spring-cloud-alibaba-dubbo with Apache License 2.0 4 votes vote down vote up
private AbstractBeanDefinition buildServiceBeanDefinition(Service service, Class<?> interfaceClass,
                                                          String annotatedServiceBeanName) {

    BeanDefinitionBuilder builder = rootBeanDefinition(ServiceBean.class);

    AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();

    MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();

    String[] ignoreAttributeNames = of("provider", "monitor", "application", "module", "registry", "protocol", "interface");

    propertyValues.addPropertyValues(new AnnotationPropertyValuesAdapter(service, environment, ignoreAttributeNames));

    // References "ref" property to annotated-@Service Bean
    addPropertyReference(builder, "ref", annotatedServiceBeanName);
    // Set interface
    builder.addPropertyValue("interface", interfaceClass.getName());

    /**
     * Add {@link com.alibaba.dubbo.config.ProviderConfig} Bean reference
     */
    String providerConfigBeanName = service.provider();
    if (StringUtils.hasText(providerConfigBeanName)) {
        addPropertyReference(builder, "provider", providerConfigBeanName);
    }

    /**
     * Add {@link com.alibaba.dubbo.config.MonitorConfig} Bean reference
     */
    String monitorConfigBeanName = service.monitor();
    if (StringUtils.hasText(monitorConfigBeanName)) {
        addPropertyReference(builder, "monitor", monitorConfigBeanName);
    }

    /**
     * Add {@link com.alibaba.dubbo.config.ApplicationConfig} Bean reference
     */
    String applicationConfigBeanName = service.application();
    if (StringUtils.hasText(applicationConfigBeanName)) {
        addPropertyReference(builder, "application", applicationConfigBeanName);
    }

    /**
     * Add {@link com.alibaba.dubbo.config.ModuleConfig} Bean reference
     */
    String moduleConfigBeanName = service.module();
    if (StringUtils.hasText(moduleConfigBeanName)) {
        addPropertyReference(builder, "module", moduleConfigBeanName);
    }


    /**
     * Add {@link com.alibaba.dubbo.config.RegistryConfig} Bean reference
     */
    String[] registryConfigBeanNames = service.registry();

    List<RuntimeBeanReference> registryRuntimeBeanReferences = toRuntimeBeanReferences(registryConfigBeanNames);

    if (!registryRuntimeBeanReferences.isEmpty()) {
        builder.addPropertyValue("registries", registryRuntimeBeanReferences);
    }

    /**
     * Add {@link com.alibaba.dubbo.config.ProtocolConfig} Bean reference
     */
    String[] protocolConfigBeanNames = service.protocol();

    List<RuntimeBeanReference> protocolRuntimeBeanReferences = toRuntimeBeanReferences(protocolConfigBeanNames);

    if (!protocolRuntimeBeanReferences.isEmpty()) {
        builder.addPropertyValue("protocols", protocolRuntimeBeanReferences);
    }

    return builder.getBeanDefinition();

}
 
Example #24
Source File: ReferenceAnnotationBeanPostProcessor.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
private void onServiceBeanExportEvent(ServiceBeanExportedEvent event) {
    ServiceBean serviceBean = event.getServiceBean();
    initReferenceBeanInvocationHandler(serviceBean);
}
 
Example #25
Source File: DataSourceStatusChecker.java    From dubbox with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public Status check() {
    ApplicationContext context = ServiceBean.getSpringContext();
    if (context == null) {
        return new Status(Status.Level.UNKNOWN);
    }
    Map<String, DataSource> dataSources = context.getBeansOfType(DataSource.class, false, false);
    if (dataSources == null || dataSources.size() == 0) {
        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();
            try {
                DatabaseMetaData metaData = connection.getMetaData();
                ResultSet resultSet = metaData.getTypeInfo();
                try {
                    if (! resultSet.next()) {
                        level = Status.Level.ERROR;
                    }
                } finally {
                    resultSet.close();
                }
                buf.append(metaData.getURL());
                buf.append("(");
                buf.append(metaData.getDatabaseProductName());
                buf.append("-");
                buf.append(metaData.getDatabaseProductVersion());
                buf.append(")");
            } finally {
                connection.close();
            }
        } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
            return new Status(level, e.getMessage());
        }
    }
    return new Status(level, buf.toString());
}
 
Example #26
Source File: CompensableBeanConfigValidator.java    From ByteTCC with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
public void validateServiceBean(String beanId, ServiceBean serviceBean) throws BeansException {
	Integer retries = serviceBean.getRetries();
	String loadBalance = serviceBean.getLoadbalance();
	String cluster = serviceBean.getCluster();
	String filter = serviceBean.getFilter();
	String group = serviceBean.getGroup();

	if (StringUtils.equalsIgnoreCase("x-bytetcc", group) == false
			&& StringUtils.trimToEmpty(group).startsWith("x-bytetcc-") == false) {
		throw new FatalBeanException(String.format(
				"The value of attr 'group'(beanId= %s) should be 'x-bytetcc' or starts with 'x-bytetcc-'.", beanId));
	} else if (retries != null && retries >= 0) {
		throw new FatalBeanException(String.format("The value of attr 'retries'(beanId= %s) should be '-1'.", beanId));
	} else if (this.statefully && StringUtils.equals(loadBalance, "bytetcc") == false) {
		throw new FatalBeanException(
				String.format("The value of attr 'loadbalance'(beanId= %s) should be 'bytetcc'.", beanId));
	} else if (StringUtils.equals("failfast", cluster) == false) {
		throw new FatalBeanException(
				String.format("The value of attribute 'cluster' (beanId= %s) must be 'failfast'.", beanId));
	} else if (filter == null) {
		throw new FatalBeanException(String
				.format("The value of attr 'filter'(beanId= %s) must be java.lang.String and cannot be null.", beanId));
	} else {
		String filterValue = StringUtils.trimToEmpty(filter);
		String[] filterArray = filterValue.split("\\s*,\\s*");
		int filters = 0, index = -1;
		for (int i = 0; i < filterArray.length; i++) {
			String element = filterArray[i];
			boolean filterEquals = StringUtils.equalsIgnoreCase("bytetcc", element);
			index = filterEquals ? i : index;
			filters = filterEquals ? filters + 1 : filters;
		}

		if (filters != 1) {
			throw new FatalBeanException(
					String.format("The value of attr 'filter'(beanId= %s) should contains 'bytetcc'.", beanId));
		} else if (index != 0) {
			throw new FatalBeanException(
					String.format("The first filter of bean(beanId= %s) should be 'bytetcc'.", beanId));
		}
	}

}
 
Example #27
Source File: DataSourceStatusChecker.java    From dubbox with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public Status check() {
    ApplicationContext context = ServiceBean.getSpringContext();
    if (context == null) {
        return new Status(Status.Level.UNKNOWN);
    }
    Map<String, DataSource> dataSources = context.getBeansOfType(DataSource.class, false, false);
    if (dataSources == null || dataSources.size() == 0) {
        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();
            try {
                DatabaseMetaData metaData = connection.getMetaData();
                ResultSet resultSet = metaData.getTypeInfo();
                try {
                    if (! resultSet.next()) {
                        level = Status.Level.ERROR;
                    }
                } finally {
                    resultSet.close();
                }
                buf.append(metaData.getURL());
                buf.append("(");
                buf.append(metaData.getDatabaseProductName());
                buf.append("-");
                buf.append(metaData.getDatabaseProductVersion());
                buf.append(")");
            } finally {
                connection.close();
            }
        } catch (Throwable e) {
            logger.warn(e.getMessage(), e);
            return new Status(level, e.getMessage());
        }
    }
    return new Status(level, buf.toString());
}
 
Example #28
Source File: ServiceAnnotationBeanPostProcessor.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
private AbstractBeanDefinition buildServiceBeanDefinition(Service service, Class<?> interfaceClass,
                                                              String annotatedServiceBeanName) {

        BeanDefinitionBuilder builder = rootBeanDefinition(ServiceBean.class);

        AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();

        MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();

//        @Service注解可以有这些属性值
        String[] ignoreAttributeNames = of("provider", "monitor", "application", "module", "registry", "protocol", "interface");

        propertyValues.addPropertyValues(new AnnotationPropertyValuesAdapter(service, environment, ignoreAttributeNames));

        // References "ref" property to annotated-@Service Bean
        addPropertyReference(builder, "ref", annotatedServiceBeanName);
        // Set interface 设置interface对象的引用关系
        builder.addPropertyValue("interface", interfaceClass.getName());

        /**
         * Add {@link com.alibaba.dubbo.config.ProviderConfig} Bean reference
         */
//        设置provider对象的引用关系
        String providerConfigBeanName = service.provider();
        if (StringUtils.hasText(providerConfigBeanName)) {
            addPropertyReference(builder, "provider", providerConfigBeanName);
        }

        /**
         * Add {@link com.alibaba.dubbo.config.MonitorConfig} Bean reference
         */
//        设置monitor对象的引用关系
        String monitorConfigBeanName = service.monitor();
        if (StringUtils.hasText(monitorConfigBeanName)) {
            addPropertyReference(builder, "monitor", monitorConfigBeanName);
        }

        /**
         * Add {@link com.alibaba.dubbo.config.ApplicationConfig} Bean reference
         */
//        设置application对象的引用关系
        String applicationConfigBeanName = service.application();
        if (StringUtils.hasText(applicationConfigBeanName)) {
            addPropertyReference(builder, "application", applicationConfigBeanName);
        }

        /**
         * Add {@link com.alibaba.dubbo.config.ModuleConfig} Bean reference
         */
//        设置module对象的引用关系
        String moduleConfigBeanName = service.module();
        if (StringUtils.hasText(moduleConfigBeanName)) {
            addPropertyReference(builder, "module", moduleConfigBeanName);
        }


        /**
         * Add {@link com.alibaba.dubbo.config.RegistryConfig} Bean reference
         */
//        设置registries对象的引用关系
        String[] registryConfigBeanNames = service.registry();

        List<RuntimeBeanReference> registryRuntimeBeanReferences = toRuntimeBeanReferences(registryConfigBeanNames);

        if (!registryRuntimeBeanReferences.isEmpty()) {
            builder.addPropertyValue("registries", registryRuntimeBeanReferences);
        }

        /**
         * Add {@link com.alibaba.dubbo.config.ProtocolConfig} Bean reference
         */
//        设置protocols对象的引用关系
        String[] protocolConfigBeanNames = service.protocol();

        List<RuntimeBeanReference> protocolRuntimeBeanReferences = toRuntimeBeanReferences(protocolConfigBeanNames);

        if (!protocolRuntimeBeanReferences.isEmpty()) {
            builder.addPropertyValue("protocols", protocolRuntimeBeanReferences);
        }

        return builder.getBeanDefinition();

    }
 
Example #29
Source File: SpringStatusCheckerTest.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    initMocks(this);
    this.springStatusChecker = new SpringStatusChecker();
    new ServiceBean<Object>().setApplicationContext(applicationContext);
}
 
Example #30
Source File: AnnotationBean.java    From spring-boot-starter-dubbo with Apache License 2.0 4 votes vote down vote up
private AbstractBeanDefinition buildServiceBeanDefinition(Service service, Class<?> interfaceClass,
		String annotatedServiceBeanName) {
	BeanDefinitionBuilder builder = 
			rootBeanDefinition(ServiceBean.class)
			.addConstructorArgValue(service)
			.addPropertyReference("ref", annotatedServiceBeanName)
			.addPropertyValue("interfaceClass", interfaceClass);
	/**
	 * Add {@link com.alibaba.dubbo.config.ProviderConfig} Bean reference
	 */
	String providerConfigBeanName = service.provider();
	if (StringUtils.hasText(providerConfigBeanName)) {
		builder.addPropertyReference("provider", providerConfigBeanName);
	}
	/**
	 * Add {@link com.alibaba.dubbo.config.MonitorConfig} Bean reference
	 */
	String monitorConfigBeanName = service.monitor();
	if (StringUtils.hasText(monitorConfigBeanName)) {
		builder.addPropertyReference("monitor", monitorConfigBeanName);
	}
	/**
	 * Add {@link com.alibaba.dubbo.config.ApplicationConfig} Bean reference
	 */
	String applicationConfigBeanName = service.application();
	if (StringUtils.hasText(applicationConfigBeanName)) {
		builder.addPropertyReference("application", applicationConfigBeanName);
	}
	/**
	 * Add {@link com.alibaba.dubbo.config.ModuleConfig} Bean reference
	 */
	String moduleConfigBeanName = service.module();
	if (StringUtils.hasText(moduleConfigBeanName)) {
		builder.addPropertyReference("application", moduleConfigBeanName);
	}
	/**
	 * Add {@link com.alibaba.dubbo.config.RegistryConfig} Bean reference
	 */
	String[] registryConfigBeanNames = service.registry();
	List<RuntimeBeanReference> registryRuntimeBeanReferences = toRuntimeBeanReferences(registryConfigBeanNames);
	if (!registryRuntimeBeanReferences.isEmpty()) {
		builder.addPropertyValue("registries", registryRuntimeBeanReferences);
	}
	/**
	 * Add {@link com.alibaba.dubbo.config.ProtocolConfig} Bean reference
	 */
	String[] protocolConfigBeanNames = service.protocol();
	List<RuntimeBeanReference> protocolRuntimeBeanReferences = toRuntimeBeanReferences(protocolConfigBeanNames);
	if (!registryRuntimeBeanReferences.isEmpty()) {
		builder.addPropertyValue("protocols", protocolRuntimeBeanReferences);
	}
	return builder.getBeanDefinition();

}