1
0
mirror of https://gitee.com/mirrors/Spring-Cloud-Alibaba.git synced 2021-06-26 13:25:11 +08:00

Merge code from upstream

This commit is contained in:
ly
2019-07-23 21:40:11 +08:00
parent af09456b7d
commit 1de313079c
475 changed files with 40536 additions and 0 deletions

View File

@@ -0,0 +1,131 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba</artifactId>
<version>0.9.1.BUILD-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-alibaba-sentinel-datasource</artifactId>
<name>Spring Cloud Alibaba Sentinel DataSource</name>
<dependencies>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-extension</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-parameter-flow-control</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-api-gateway-adapter-common</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-nacos</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-zookeeper</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-datasource-apollo</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<scope>provided</scope>
</dependency>
<!--spring boot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>${jacoco.version}</version>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>test</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,127 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource;
import java.util.Arrays;
import java.util.Optional;
import org.springframework.util.StringUtils;
import com.alibaba.cloud.sentinel.datasource.config.AbstractDataSourceProperties;
import com.alibaba.csp.sentinel.slots.block.AbstractRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
/**
* Enum for {@link AbstractRule} class, using in
* {@link AbstractDataSourceProperties#ruleType}
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public enum RuleType {
/**
* flow
*/
FLOW("flow", FlowRule.class),
/**
* degrade
*/
DEGRADE("degrade", DegradeRule.class),
/**
* param flow
*/
PARAM_FLOW("param-flow", ParamFlowRule.class),
/**
* system
*/
SYSTEM("system", SystemRule.class),
/**
* authority
*/
AUTHORITY("authority", AuthorityRule.class),
/**
* gateway flow
*/
GW_FLOW("gw-flow",
"com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule"),
/**
* api
*/
GW_API_GROUP("gw-api-group",
"com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition");
/**
* alias for {@link AbstractRule}
*/
private final String name;
/**
* concrete {@link AbstractRule} class
*/
private Class clazz;
/**
* concrete {@link AbstractRule} class name
*/
private String clazzName;
RuleType(String name, Class clazz) {
this.name = name;
this.clazz = clazz;
}
RuleType(String name, String clazzName) {
this.name = name;
this.clazzName = clazzName;
}
public String getName() {
return name;
}
public Class getClazz() {
if (clazz != null) {
return clazz;
}
else {
try {
return Class.forName(clazzName);
}
catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
}
public static Optional<RuleType> getByName(String name) {
if (StringUtils.isEmpty(name)) {
return Optional.empty();
}
return Arrays.stream(RuleType.values())
.filter(ruleType -> name.equals(ruleType.getName())).findFirst();
}
public static Optional<RuleType> getByClass(Class clazz) {
return Arrays.stream(RuleType.values())
.filter(ruleType -> clazz == ruleType.getClazz()).findFirst();
}
}

View File

@@ -0,0 +1,26 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public interface SentinelDataSourceConstants {
String PROPERTY_PREFIX = "spring.cloud.sentinel";
}

View File

@@ -0,0 +1,124 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource.config;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.springframework.core.env.Environment;
import com.alibaba.cloud.sentinel.datasource.RuleType;
import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.datasource.AbstractDataSource;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* Abstract class Using by {@link DataSourcePropertiesConfiguration}
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class AbstractDataSourceProperties {
@NotEmpty
private String dataType = "json";
@NotNull
private RuleType ruleType;
private String converterClass;
@JsonIgnore
private final String factoryBeanName;
@JsonIgnore
private Environment env;
public AbstractDataSourceProperties(String factoryBeanName) {
this.factoryBeanName = factoryBeanName;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public RuleType getRuleType() {
return ruleType;
}
public void setRuleType(RuleType ruleType) {
this.ruleType = ruleType;
}
public String getConverterClass() {
return converterClass;
}
public void setConverterClass(String converterClass) {
this.converterClass = converterClass;
}
public String getFactoryBeanName() {
return factoryBeanName;
}
protected Environment getEnv() {
return env;
}
public void setEnv(Environment env) {
this.env = env;
}
public void preCheck(String dataSourceName) {
}
public void postRegister(AbstractDataSource dataSource) {
switch (this.getRuleType()) {
case FLOW:
FlowRuleManager.register2Property(dataSource.getProperty());
break;
case DEGRADE:
DegradeRuleManager.register2Property(dataSource.getProperty());
break;
case PARAM_FLOW:
ParamFlowRuleManager.register2Property(dataSource.getProperty());
break;
case SYSTEM:
SystemRuleManager.register2Property(dataSource.getProperty());
break;
case AUTHORITY:
AuthorityRuleManager.register2Property(dataSource.getProperty());
break;
case GW_FLOW:
GatewayRuleManager.register2Property(dataSource.getProperty());
break;
case GW_API_GROUP:
GatewayApiDefinitionManager.register2Property(dataSource.getProperty());
break;
default:
break;
}
}
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource.config;
import javax.validation.constraints.NotEmpty;
import com.alibaba.cloud.sentinel.datasource.factorybean.ApolloDataSourceFactoryBean;
/**
* Apollo Properties class Using by {@link DataSourcePropertiesConfiguration} and
* {@link ApolloDataSourceFactoryBean}
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class ApolloDataSourceProperties extends AbstractDataSourceProperties {
@NotEmpty
private String namespaceName;
@NotEmpty
private String flowRulesKey;
private String defaultFlowRuleValue;
public ApolloDataSourceProperties() {
super(ApolloDataSourceFactoryBean.class.getName());
}
public String getNamespaceName() {
return namespaceName;
}
public void setNamespaceName(String namespaceName) {
this.namespaceName = namespaceName;
}
public String getFlowRulesKey() {
return flowRulesKey;
}
public void setFlowRulesKey(String flowRulesKey) {
this.flowRulesKey = flowRulesKey;
}
public String getDefaultFlowRuleValue() {
return defaultFlowRuleValue;
}
public void setDefaultFlowRuleValue(String defaultFlowRuleValue) {
this.defaultFlowRuleValue = defaultFlowRuleValue;
}
}

View File

@@ -0,0 +1,134 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource.config;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.util.ObjectUtils;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* Using By ConfigurationProperties.
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
* @see NacosDataSourceProperties
* @see ApolloDataSourceProperties
* @see ZookeeperDataSourceProperties
* @see FileDataSourceProperties
*/
public class DataSourcePropertiesConfiguration {
private FileDataSourceProperties file;
private NacosDataSourceProperties nacos;
private ZookeeperDataSourceProperties zk;
private ApolloDataSourceProperties apollo;
public DataSourcePropertiesConfiguration() {
}
public DataSourcePropertiesConfiguration(FileDataSourceProperties file) {
this.file = file;
}
public DataSourcePropertiesConfiguration(NacosDataSourceProperties nacos) {
this.nacos = nacos;
}
public DataSourcePropertiesConfiguration(ZookeeperDataSourceProperties zk) {
this.zk = zk;
}
public DataSourcePropertiesConfiguration(ApolloDataSourceProperties apollo) {
this.apollo = apollo;
}
public FileDataSourceProperties getFile() {
return file;
}
public void setFile(FileDataSourceProperties file) {
this.file = file;
}
public NacosDataSourceProperties getNacos() {
return nacos;
}
public void setNacos(NacosDataSourceProperties nacos) {
this.nacos = nacos;
}
public ZookeeperDataSourceProperties getZk() {
return zk;
}
public void setZk(ZookeeperDataSourceProperties zk) {
this.zk = zk;
}
public ApolloDataSourceProperties getApollo() {
return apollo;
}
public void setApollo(ApolloDataSourceProperties apollo) {
this.apollo = apollo;
}
@JsonIgnore
public List<String> getValidField() {
return Arrays.stream(this.getClass().getDeclaredFields()).map(field -> {
try {
if (!ObjectUtils.isEmpty(field.get(this))) {
return field.getName();
}
return null;
}
catch (IllegalAccessException e) {
// won't happen
}
return null;
}).filter(Objects::nonNull).collect(Collectors.toList());
}
@JsonIgnore
public AbstractDataSourceProperties getValidDataSourceProperties() {
List<String> invalidFields = getValidField();
if (invalidFields.size() == 1) {
try {
this.getClass().getDeclaredField(invalidFields.get(0))
.setAccessible(true);
return (AbstractDataSourceProperties) this.getClass()
.getDeclaredField(invalidFields.get(0)).get(this);
}
catch (IllegalAccessException e) {
// won't happen
}
catch (NoSuchFieldException e) {
// won't happen
}
}
return null;
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource.config;
import java.io.IOException;
import javax.validation.constraints.NotEmpty;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import com.alibaba.cloud.sentinel.datasource.factorybean.FileRefreshableDataSourceFactoryBean;
/**
* File Properties class Using by {@link DataSourcePropertiesConfiguration} and
* {@link FileRefreshableDataSourceFactoryBean}
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class FileDataSourceProperties extends AbstractDataSourceProperties {
@NotEmpty
private String file;
private String charset = "utf-8";
private long recommendRefreshMs = 3000L;
private int bufSize = 1024 * 1024;
public FileDataSourceProperties() {
super(FileRefreshableDataSourceFactoryBean.class.getName());
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public long getRecommendRefreshMs() {
return recommendRefreshMs;
}
public void setRecommendRefreshMs(long recommendRefreshMs) {
this.recommendRefreshMs = recommendRefreshMs;
}
public int getBufSize() {
return bufSize;
}
public void setBufSize(int bufSize) {
this.bufSize = bufSize;
}
@Override
public void preCheck(String dataSourceName) {
super.preCheck(dataSourceName);
try {
this.setFile(
ResourceUtils.getFile(StringUtils.trimAllWhitespace(this.getFile()))
.getAbsolutePath());
}
catch (IOException e) {
throw new RuntimeException("[Sentinel Starter] DataSource " + dataSourceName
+ " handle file [" + this.getFile() + "] error: " + e.getMessage(),
e);
}
}
}

View File

@@ -0,0 +1,118 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource.config;
import javax.validation.constraints.NotEmpty;
import org.springframework.util.StringUtils;
import com.alibaba.cloud.sentinel.datasource.factorybean.NacosDataSourceFactoryBean;
/**
* Nacos Properties class Using by {@link DataSourcePropertiesConfiguration} and
* {@link NacosDataSourceFactoryBean}
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class NacosDataSourceProperties extends AbstractDataSourceProperties {
private String serverAddr;
@NotEmpty
private String groupId = "DEFAULT_GROUP";
@NotEmpty
private String dataId;
private String endpoint;
private String namespace;
private String accessKey;
private String secretKey;
public NacosDataSourceProperties() {
super(NacosDataSourceFactoryBean.class.getName());
}
@Override
public void preCheck(String dataSourceName) {
if (StringUtils.isEmpty(serverAddr)) {
serverAddr = this.getEnv().getProperty(
"spring.cloud.sentinel.datasource.nacos.server-addr", "");
if (StringUtils.isEmpty(serverAddr)) {
throw new IllegalArgumentException(
"NacosDataSource server-addr is empty");
}
}
}
public String getServerAddr() {
return serverAddr;
}
public void setServerAddr(String serverAddr) {
this.serverAddr = serverAddr;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
}

View File

@@ -0,0 +1,86 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource.config;
import org.springframework.util.StringUtils;
import com.alibaba.cloud.sentinel.datasource.factorybean.ZookeeperDataSourceFactoryBean;
/**
* Zookeeper Properties class Using by {@link DataSourcePropertiesConfiguration} and
* {@link ZookeeperDataSourceFactoryBean}
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class ZookeeperDataSourceProperties extends AbstractDataSourceProperties {
public ZookeeperDataSourceProperties() {
super(ZookeeperDataSourceFactoryBean.class.getName());
}
private String serverAddr;
private String path;
private String groupId;
private String dataId;
@Override
public void preCheck(String dataSourceName) {
if (StringUtils.isEmpty(serverAddr)) {
serverAddr = this.getEnv()
.getProperty("spring.cloud.sentinel.datasource.zk.server-addr", "");
if (StringUtils.isEmpty(serverAddr)) {
throw new IllegalArgumentException(
"ZookeeperDataSource server-addr is empty");
}
}
}
public String getServerAddr() {
return serverAddr;
}
public void setServerAddr(String serverAddr) {
this.serverAddr = serverAddr;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
}

View File

@@ -0,0 +1,44 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource.converter;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Convert sentinel rules for json array Using strict mode to parse json
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
* @see FlowRule
* @see DegradeRule
* @see SystemRule
* @see AuthorityRule
* @see ParamFlowRule
* @see ObjectMapper
*/
public class JsonConverter<T> extends SentinelConverter {
public JsonConverter(ObjectMapper objectMapper, Class<T> ruleClass) {
super(objectMapper, ruleClass);
}
}

View File

@@ -0,0 +1,143 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource.converter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.alibaba.cloud.sentinel.datasource.RuleType;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleUtil;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Convert sentinel rules for json or xml array Using strict mode to parse json or xml
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
* @see FlowRule
* @see DegradeRule
* @see SystemRule
* @see AuthorityRule
* @see ParamFlowRule
* @see ObjectMapper
*/
public abstract class SentinelConverter<T extends Object>
implements Converter<String, Collection<Object>> {
private static final Logger log = LoggerFactory.getLogger(SentinelConverter.class);
private final ObjectMapper objectMapper;
private final Class<T> ruleClass;
public SentinelConverter(ObjectMapper objectMapper, Class<T> ruleClass) {
this.objectMapper = objectMapper;
this.ruleClass = ruleClass;
}
@Override
public Collection<Object> convert(String source) {
Collection<Object> ruleCollection;
// hard code
if (ruleClass == FlowRule.class || ruleClass == DegradeRule.class
|| ruleClass == SystemRule.class || ruleClass == AuthorityRule.class
|| ruleClass == ParamFlowRule.class) {
ruleCollection = new ArrayList<>();
}
else {
ruleCollection = new HashSet<>();
}
if (StringUtils.isEmpty(source)) {
log.warn("converter can not convert rules because source is empty");
return ruleCollection;
}
try {
List sourceArray = objectMapper.readValue(source,
new TypeReference<List<HashMap>>() {
});
sourceArray.stream().forEach(obj -> {
String item = null;
try {
item = objectMapper.writeValueAsString(obj);
}
catch (JsonProcessingException e) {
// won't be happen
}
Optional.ofNullable(convertRule(item))
.ifPresent(convertRule -> ruleCollection.add(convertRule));
});
if (ruleCollection.size() != sourceArray.size()) {
throw new IllegalArgumentException("convert " + ruleCollection.size()
+ " rules but there are " + sourceArray.size()
+ " rules from datasource. RuleClass: "
+ ruleClass.getSimpleName());
}
}
catch (Exception e) {
throw new RuntimeException("convert error: " + e.getMessage(), e);
}
return ruleCollection;
}
private Object convertRule(String ruleStr) {
try {
final Object rule = objectMapper.readValue(ruleStr, ruleClass);
RuleType ruleType = RuleType.getByClass(ruleClass).get();
switch (ruleType) {
case FLOW:
if (!FlowRuleUtil.isValidRule((FlowRule) rule)) {
return null;
}
break;
case DEGRADE:
if (!DegradeRuleManager.isValidRule((DegradeRule) rule)) {
return null;
}
default:
break;
}
return rule;
}
catch (Exception e) {
// ignore
}
return null;
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource.converter;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
/**
* Convert sentinel rules for xml array Using strict mode to parse xml
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
* @see FlowRule
* @see DegradeRule
* @see SystemRule
* @see AuthorityRule
* @see ParamFlowRule
* @see ObjectMapper
*/
public class XmlConverter<T> extends SentinelConverter {
public XmlConverter(XmlMapper xmlMapper, Class<T> ruleClass) {
super(xmlMapper, ruleClass);
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource.factorybean;
import org.springframework.beans.factory.FactoryBean;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.apollo.ApolloDataSource;
/**
* A {@link FactoryBean} for creating {@link ApolloDataSource} instance.
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
* @see ApolloDataSource
*/
public class ApolloDataSourceFactoryBean implements FactoryBean<ApolloDataSource> {
private String namespaceName;
private String flowRulesKey;
private String defaultFlowRuleValue;
private Converter converter;
@Override
public ApolloDataSource getObject() throws Exception {
return new ApolloDataSource(namespaceName, flowRulesKey, defaultFlowRuleValue,
converter);
}
@Override
public Class<?> getObjectType() {
return ApolloDataSource.class;
}
public String getNamespaceName() {
return namespaceName;
}
public void setNamespaceName(String namespaceName) {
this.namespaceName = namespaceName;
}
public String getFlowRulesKey() {
return flowRulesKey;
}
public void setFlowRulesKey(String flowRulesKey) {
this.flowRulesKey = flowRulesKey;
}
public String getDefaultFlowRuleValue() {
return defaultFlowRuleValue;
}
public void setDefaultFlowRuleValue(String defaultFlowRuleValue) {
this.defaultFlowRuleValue = defaultFlowRuleValue;
}
public Converter getConverter() {
return converter;
}
public void setConverter(Converter converter) {
this.converter = converter;
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource.factorybean;
import java.io.File;
import java.nio.charset.Charset;
import org.springframework.beans.factory.FactoryBean;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
/**
* A {@link FactoryBean} for creating {@link FileRefreshableDataSource} instance.
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
* @see FileRefreshableDataSource
*/
public class FileRefreshableDataSourceFactoryBean
implements FactoryBean<FileRefreshableDataSource> {
private String file;
private String charset;
private long recommendRefreshMs;
private int bufSize;
private Converter converter;
@Override
public FileRefreshableDataSource getObject() throws Exception {
return new FileRefreshableDataSource(new File(file), converter,
recommendRefreshMs, bufSize, Charset.forName(charset));
}
@Override
public Class<?> getObjectType() {
return FileRefreshableDataSource.class;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public long getRecommendRefreshMs() {
return recommendRefreshMs;
}
public void setRecommendRefreshMs(long recommendRefreshMs) {
this.recommendRefreshMs = recommendRefreshMs;
}
public int getBufSize() {
return bufSize;
}
public void setBufSize(int bufSize) {
this.bufSize = bufSize;
}
public Converter getConverter() {
return converter;
}
public void setConverter(Converter converter) {
this.converter = converter;
}
}

View File

@@ -0,0 +1,131 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource.factorybean;
import java.util.Properties;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.util.StringUtils;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.nacos.api.PropertyKeyConst;
/**
* A {@link FactoryBean} for creating {@link NacosDataSource} instance.
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
* @see NacosDataSource
*/
public class NacosDataSourceFactoryBean implements FactoryBean<NacosDataSource> {
private String serverAddr;
private String groupId;
private String dataId;
private Converter converter;
private String endpoint;
private String namespace;
private String accessKey;
private String secretKey;
@Override
public NacosDataSource getObject() throws Exception {
Properties properties = new Properties();
if (!StringUtils.isEmpty(this.serverAddr)) {
properties.setProperty(PropertyKeyConst.SERVER_ADDR, this.serverAddr);
}
else {
properties.setProperty(PropertyKeyConst.ACCESS_KEY, this.accessKey);
properties.setProperty(PropertyKeyConst.SECRET_KEY, this.secretKey);
properties.setProperty(PropertyKeyConst.ENDPOINT, this.endpoint);
}
if (!StringUtils.isEmpty(this.namespace)) {
properties.setProperty(PropertyKeyConst.NAMESPACE, this.namespace);
}
return new NacosDataSource(properties, groupId, dataId, converter);
}
@Override
public Class<?> getObjectType() {
return NacosDataSource.class;
}
public String getServerAddr() {
return serverAddr;
}
public void setServerAddr(String serverAddr) {
this.serverAddr = serverAddr;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public Converter getConverter() {
return converter;
}
public void setConverter(Converter converter) {
this.converter = converter;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource.factorybean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.FactoryBean;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.zookeeper.ZookeeperDataSource;
/**
* A {@link FactoryBean} for creating {@link ZookeeperDataSource} instance.
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
* @see ZookeeperDataSource
*/
public class ZookeeperDataSourceFactoryBean implements FactoryBean<ZookeeperDataSource> {
private String serverAddr;
private String path;
private String groupId;
private String dataId;
private Converter converter;
@Override
public ZookeeperDataSource getObject() throws Exception {
if (StringUtils.isNotEmpty(groupId) && StringUtils.isNotEmpty(dataId)) {
// the path will be /{groupId}/{dataId}
return new ZookeeperDataSource(serverAddr, groupId, dataId, converter);
}
else {
// using path directly
return new ZookeeperDataSource(serverAddr, path, converter);
}
}
@Override
public Class<?> getObjectType() {
return ZookeeperDataSource.class;
}
public String getServerAddr() {
return serverAddr;
}
public void setServerAddr(String serverAddr) {
this.serverAddr = serverAddr;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getDataId() {
return dataId;
}
public void setDataId(String dataId) {
this.dataId = dataId;
}
public Converter getConverter() {
return converter;
}
public void setConverter(Converter converter) {
this.converter = converter;
}
}

View File

@@ -0,0 +1,4 @@
nacos = com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource
file =com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource
apollo = com.alibaba.csp.sentinel.datasource.apollo.ApolloDataSource
zk = com.alibaba.csp.sentinel.datasource.zookeeper.ZookeeperDataSource

View File

@@ -0,0 +1,71 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import org.junit.Test;
import com.alibaba.cloud.sentinel.datasource.converter.JsonConverter;
import com.alibaba.cloud.sentinel.datasource.factorybean.ApolloDataSourceFactoryBean;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.apollo.ApolloDataSource;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class ApolloDataSourceFactoryBeanTests {
private String flowRuleKey = "sentinel";
private String namespace = "namespace";
private String defaultFlowValue = "{}";
@Test
public void testApolloFactoryBean() throws Exception {
ApolloDataSourceFactoryBean factoryBean = spy(new ApolloDataSourceFactoryBean());
Converter converter = mock(JsonConverter.class);
factoryBean.setDefaultFlowRuleValue(defaultFlowValue);
factoryBean.setFlowRulesKey(flowRuleKey);
factoryBean.setNamespaceName(namespace);
factoryBean.setConverter(converter);
ApolloDataSource apolloDataSource = mock(ApolloDataSource.class);
when(apolloDataSource.readSource()).thenReturn("{}");
doReturn(apolloDataSource).when(factoryBean).getObject();
assertEquals("ApolloDataSourceFactoryBean getObject error", apolloDataSource,
factoryBean.getObject());
assertEquals("ApolloDataSource read source value was wrong", "{}",
factoryBean.getObject().readSource());
assertEquals("ApolloDataSource converter was wrong", converter,
factoryBean.getConverter());
assertEquals("ApolloDataSourceFactoryBean flowRuleKey was wrong", flowRuleKey,
factoryBean.getFlowRulesKey());
assertEquals("ApolloDataSourceFactoryBean namespace was wrong", namespace,
factoryBean.getNamespaceName());
assertEquals("ApolloDataSourceFactoryBean defaultFlowValue was wrong",
defaultFlowValue, factoryBean.getDefaultFlowRuleValue());
}
}

View File

@@ -0,0 +1,250 @@
/// *
// * Copyright (C) 2018 the original author or authors.
// *
// * Licensed 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 com.alibaba.cloud.sentinel.datasource;
//
// import static org.junit.Assert.assertEquals;
// import static org.junit.Assert.assertNotNull;
// import static org.junit.Assert.assertNull;
//
// import org.junit.Test;
// import ApolloDataSourceProperties;
// import DataSourcePropertiesConfiguration;
// import FileDataSourceProperties;
// import NacosDataSourceProperties;
// import ZookeeperDataSourceProperties;
//
/// **
// * @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
// */
// public class DataSourcePropertiesConfigurationTests {
//
// @Test
// public void testFileAttr() {
// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new
/// DataSourcePropertiesConfiguration();
// assertEquals("DataSourcePropertiesConfiguration valid field size was wrong", 0,
// dataSourcePropertiesConfiguration.getValidField().size());
// assertNull("DataSourcePropertiesConfiguration valid properties was not null",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
//
// FileDataSourceProperties fileDataSourceProperties = buildFileProperties();
//
// dataSourcePropertiesConfiguration.setFile(fileDataSourceProperties);
//
// assertEquals(
// "DataSourcePropertiesConfiguration valid field size was wrong after set file
/// attribute",
// 1, dataSourcePropertiesConfiguration.getValidField().size());
// assertNotNull(
// "DataSourcePropertiesConfiguration file properties was null after set file attribute",
// dataSourcePropertiesConfiguration.getFile());
// assertNotNull(
// "DataSourcePropertiesConfiguration valid properties was null after set file attribute",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
// }
//
// @Test
// public void testNacosAttr() {
// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new
/// DataSourcePropertiesConfiguration();
// assertEquals("DataSourcePropertiesConfiguration valid field size was wrong", 0,
// dataSourcePropertiesConfiguration.getValidField().size());
// assertNull("DataSourcePropertiesConfiguration valid properties was not null",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
//
// NacosDataSourceProperties nacosDataSourceProperties = buildNacosProperties();
//
// dataSourcePropertiesConfiguration.setNacos(nacosDataSourceProperties);
//
// assertEquals(
// "DataSourcePropertiesConfiguration valid field size was wrong after set nacos
/// attribute",
// 1, dataSourcePropertiesConfiguration.getValidField().size());
// assertNotNull(
// "DataSourcePropertiesConfiguration nacos properties was null after set nacos
/// attribute",
// dataSourcePropertiesConfiguration.getNacos());
// assertNotNull(
// "DataSourcePropertiesConfiguration valid properties was null after set nacos
/// attribute",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
// }
//
// @Test
// public void testZKAttr() {
// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new
/// DataSourcePropertiesConfiguration();
// assertEquals("DataSourcePropertiesConfiguration valid field size was wrong", 0,
// dataSourcePropertiesConfiguration.getValidField().size());
// assertNull("DataSourcePropertiesConfiguration valid properties was not null",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
//
// ZookeeperDataSourceProperties zookeeperDataSourceProperties = buildZKProperties();
//
// dataSourcePropertiesConfiguration.setZk(zookeeperDataSourceProperties);
//
// assertEquals(
// "DataSourcePropertiesConfiguration valid field size was wrong after set zk attribute",
// 1, dataSourcePropertiesConfiguration.getValidField().size());
// assertNotNull(
// "DataSourcePropertiesConfiguration zk properties was null after set zk attribute",
// dataSourcePropertiesConfiguration.getZk());
// assertNotNull(
// "DataSourcePropertiesConfiguration valid properties was null after set zk attribute",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
// }
//
// @Test
// public void testApolloAttr() {
// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new
/// DataSourcePropertiesConfiguration();
// assertEquals("DataSourcePropertiesConfiguration valid field size was wrong", 0,
// dataSourcePropertiesConfiguration.getValidField().size());
// assertNull("DataSourcePropertiesConfiguration valid properties was not null",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
//
// ApolloDataSourceProperties apolloDataSourceProperties = buildApolloProperties();
//
// dataSourcePropertiesConfiguration.setApollo(apolloDataSourceProperties);
//
// assertEquals(
// "DataSourcePropertiesConfiguration valid field size was wrong after set apollo
/// attribute",
// 1, dataSourcePropertiesConfiguration.getValidField().size());
// assertNotNull(
// "DataSourcePropertiesConfiguration apollo properties was null after set apollo
/// attribute",
// dataSourcePropertiesConfiguration.getApollo());
// assertNotNull(
// "DataSourcePropertiesConfiguration valid properties was null after set apollo
/// attribute",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
// }
//
// @Test
// public void testMultiAttr() {
// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new
/// DataSourcePropertiesConfiguration();
// assertEquals("DataSourcePropertiesConfiguration valid field size was wrong", 0,
// dataSourcePropertiesConfiguration.getValidField().size());
// assertNull("DataSourcePropertiesConfiguration valid properties was not null",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
//
// FileDataSourceProperties fileDataSourceProperties = buildFileProperties();
// NacosDataSourceProperties nacosDataSourceProperties = buildNacosProperties();
//
// dataSourcePropertiesConfiguration.setFile(fileDataSourceProperties);
// dataSourcePropertiesConfiguration.setNacos(nacosDataSourceProperties);
//
// assertEquals(
// "DataSourcePropertiesConfiguration valid field size was wrong after set file and nacos
/// attribute",
// 2, dataSourcePropertiesConfiguration.getValidField().size());
// assertNull(
// "DataSourcePropertiesConfiguration valid properties was not null after set file and
/// nacos attribute",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
// }
//
// @Test
// public void testFileConstructor() {
// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new
/// DataSourcePropertiesConfiguration(
// buildFileProperties());
// assertEquals(
// "DataSourcePropertiesConfiguration file constructor valid field size was wrong",
// 1, dataSourcePropertiesConfiguration.getValidField().size());
// assertNotNull(
// "DataSourcePropertiesConfiguration file constructor valid properties was null",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
// }
//
// @Test
// public void testNacosConstructor() {
// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new
/// DataSourcePropertiesConfiguration(
// buildNacosProperties());
// assertEquals(
// "DataSourcePropertiesConfiguration nacos constructor valid field size was wrong",
// 1, dataSourcePropertiesConfiguration.getValidField().size());
// assertNotNull(
// "DataSourcePropertiesConfiguration nacos constructor valid properties was null",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
// }
//
// @Test
// public void testApolloConstructor() {
// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new
/// DataSourcePropertiesConfiguration(
// buildApolloProperties());
// assertEquals(
// "DataSourcePropertiesConfiguration apollo constructor valid field size was wrong",
// 1, dataSourcePropertiesConfiguration.getValidField().size());
// assertNotNull(
// "DataSourcePropertiesConfiguration apollo constructor valid properties was null",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
// }
//
// @Test
// public void testZKConstructor() {
// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new
/// DataSourcePropertiesConfiguration(
// buildZKProperties());
// assertEquals(
// "DataSourcePropertiesConfiguration zk constructor valid field size was wrong",
// 1, dataSourcePropertiesConfiguration.getValidField().size());
// assertNotNull(
// "DataSourcePropertiesConfiguration zk constructor valid properties was null",
// dataSourcePropertiesConfiguration.getValidDataSourceProperties());
// }
//
// private FileDataSourceProperties buildFileProperties() {
// FileDataSourceProperties fileDataSourceProperties = new FileDataSourceProperties();
//
// fileDataSourceProperties.setFile("/tmp/test.json");
// fileDataSourceProperties.setBufSize(1024);
// fileDataSourceProperties.setRecommendRefreshMs(2000);
// return fileDataSourceProperties;
// }
//
// private NacosDataSourceProperties buildNacosProperties() {
// NacosDataSourceProperties nacosDataSourceProperties = new NacosDataSourceProperties();
// nacosDataSourceProperties.setServerAddr("127.0.0.1:8848");
// nacosDataSourceProperties.setDataId("sentinel");
// nacosDataSourceProperties.setGroupId("custom-group");
// return nacosDataSourceProperties;
// }
//
// private ApolloDataSourceProperties buildApolloProperties() {
// ApolloDataSourceProperties apolloDataSourceProperties = new
/// ApolloDataSourceProperties();
// apolloDataSourceProperties.setFlowRulesKey("test-key");
// apolloDataSourceProperties.setDefaultFlowRuleValue("dft-val");
// apolloDataSourceProperties.setNamespaceName("namespace");
// return apolloDataSourceProperties;
// }
//
// private ZookeeperDataSourceProperties buildZKProperties() {
// ZookeeperDataSourceProperties zookeeperDataSourceProperties = new
/// ZookeeperDataSourceProperties();
//
// zookeeperDataSourceProperties.setServerAddr("localhost:2181");
// zookeeperDataSourceProperties.setPath("/path");
// return zookeeperDataSourceProperties;
// }
//
// }

View File

@@ -0,0 +1,182 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import com.alibaba.cloud.sentinel.datasource.config.ApolloDataSourceProperties;
import com.alibaba.cloud.sentinel.datasource.config.FileDataSourceProperties;
import com.alibaba.cloud.sentinel.datasource.config.ZookeeperDataSourceProperties;
import com.alibaba.cloud.sentinel.datasource.factorybean.ApolloDataSourceFactoryBean;
import com.alibaba.cloud.sentinel.datasource.factorybean.FileRefreshableDataSourceFactoryBean;
import com.alibaba.cloud.sentinel.datasource.factorybean.ZookeeperDataSourceFactoryBean;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class DataSourcePropertiesTests {
@Test
public void testApollo() {
ApolloDataSourceProperties apolloDataSourceProperties = new ApolloDataSourceProperties();
apolloDataSourceProperties.setFlowRulesKey("test-key");
apolloDataSourceProperties.setDefaultFlowRuleValue("dft-val");
apolloDataSourceProperties.setNamespaceName("namespace");
apolloDataSourceProperties.setRuleType(RuleType.DEGRADE);
assertEquals("Apollo flow rule key was wrong", "test-key",
apolloDataSourceProperties.getFlowRulesKey());
assertEquals("Apollo namespace was wrong", "namespace",
apolloDataSourceProperties.getNamespaceName());
assertEquals("Apollo default data type was wrong", "json",
apolloDataSourceProperties.getDataType());
Assert.assertEquals("Apollo rule type was wrong", RuleType.DEGRADE,
apolloDataSourceProperties.getRuleType());
assertEquals("Apollo default flow value was wrong", "dft-val",
apolloDataSourceProperties.getDefaultFlowRuleValue());
assertEquals("Apollo factory bean was wrong",
ApolloDataSourceFactoryBean.class.getName(),
apolloDataSourceProperties.getFactoryBeanName());
assertNull("Apollo converterClass was not null",
apolloDataSourceProperties.getConverterClass());
}
@Test
public void testZK() {
ZookeeperDataSourceProperties zookeeperDataSourceProperties = new ZookeeperDataSourceProperties();
zookeeperDataSourceProperties.setServerAddr("localhost:2181");
zookeeperDataSourceProperties.setGroupId("groupId");
zookeeperDataSourceProperties.setDataId("dataId");
zookeeperDataSourceProperties.setPath("/path");
zookeeperDataSourceProperties.setConverterClass("test.ConverterClass");
zookeeperDataSourceProperties.setRuleType(RuleType.AUTHORITY);
assertEquals("ZK serverAddr was wrong", "localhost:2181",
zookeeperDataSourceProperties.getServerAddr());
assertEquals("ZK groupId was wrong", "groupId",
zookeeperDataSourceProperties.getGroupId());
assertEquals("ZK dataId was wrong", "dataId",
zookeeperDataSourceProperties.getDataId());
assertEquals("ZK path was wrong", "/path",
zookeeperDataSourceProperties.getPath());
assertEquals("ZK factory bean was wrong",
ZookeeperDataSourceFactoryBean.class.getName(),
zookeeperDataSourceProperties.getFactoryBeanName());
assertEquals("ZK custom converter class was wrong", "test.ConverterClass",
zookeeperDataSourceProperties.getConverterClass());
Assert.assertEquals("ZK rule type was wrong", RuleType.AUTHORITY,
zookeeperDataSourceProperties.getRuleType());
}
@Test
public void testFileDefaultValue() {
FileDataSourceProperties fileDataSourceProperties = new FileDataSourceProperties();
fileDataSourceProperties.setFile("/tmp/test.json");
fileDataSourceProperties.setRuleType(RuleType.PARAM_FLOW);
assertEquals("File path was wrong", "/tmp/test.json",
fileDataSourceProperties.getFile());
assertEquals("File charset was wrong", "utf-8",
fileDataSourceProperties.getCharset());
assertEquals("File refresh time was wrong", 3000L,
fileDataSourceProperties.getRecommendRefreshMs());
assertEquals("File buf size was wrong", 1024 * 1024,
fileDataSourceProperties.getBufSize());
assertEquals("File factory bean was wrong",
FileRefreshableDataSourceFactoryBean.class.getName(),
fileDataSourceProperties.getFactoryBeanName());
Assert.assertEquals("File rule type was wrong", RuleType.PARAM_FLOW,
fileDataSourceProperties.getRuleType());
}
@Test
public void testFileCustomValue() {
FileDataSourceProperties fileDataSourceProperties = new FileDataSourceProperties();
fileDataSourceProperties.setFile("/tmp/test.json");
fileDataSourceProperties.setBufSize(1024);
fileDataSourceProperties.setRecommendRefreshMs(2000);
fileDataSourceProperties.setCharset("ISO8859-1");
assertEquals("File path was wrong", "/tmp/test.json",
fileDataSourceProperties.getFile());
assertEquals("File charset was wrong", "ISO8859-1",
fileDataSourceProperties.getCharset());
assertEquals("File refresh time was wrong", 2000L,
fileDataSourceProperties.getRecommendRefreshMs());
assertEquals("File buf size was wrong", 1024,
fileDataSourceProperties.getBufSize());
}
@Test(expected = RuntimeException.class)
public void testFileException() {
FileDataSourceProperties fileDataSourceProperties = new FileDataSourceProperties();
fileDataSourceProperties.setFile("classpath: 1.json");
fileDataSourceProperties.preCheck("test-ds");
}
@Test
public void testPostRegister() throws Exception {
FileDataSourceProperties fileDataSourceProperties = new FileDataSourceProperties();
fileDataSourceProperties.setFile("classpath: flowrule.json");
fileDataSourceProperties.setRuleType(RuleType.FLOW);
FileRefreshableDataSource fileRefreshableDataSource = new FileRefreshableDataSource(
ResourceUtils
.getFile(StringUtils
.trimAllWhitespace(fileDataSourceProperties.getFile()))
.getAbsolutePath(),
new Converter<String, List<FlowRule>>() {
ObjectMapper objectMapper = new ObjectMapper();
@Override
public List<FlowRule> convert(String source) {
try {
return objectMapper.readValue(source,
new TypeReference<List<FlowRule>>() {
});
}
catch (IOException e) {
// ignore
}
return null;
}
});
fileDataSourceProperties.postRegister(fileRefreshableDataSource);
assertEquals("DataSourceProperties postRegister error",
fileRefreshableDataSource.loadConfig(), FlowRuleManager.getRules());
}
}

View File

@@ -0,0 +1,110 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import com.alibaba.cloud.sentinel.datasource.factorybean.FileRefreshableDataSourceFactoryBean;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class FileRefreshableDataSourceFactoryBeanTests {
@Test
public void testFile() throws Exception {
AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(
TestConfig.class);
assertNotNull("FileRefreshableDataSourceFactoryBean was not created",
annotationConfigApplicationContext.getBean("fileBean"));
FileRefreshableDataSource fileRefreshableDataSource = annotationConfigApplicationContext
.getBean("fileBean", FileRefreshableDataSource.class);
assertEquals("FileRefreshableDataSourceFactoryBean flow rule size was wrong", 1,
((List<FlowRule>) fileRefreshableDataSource.loadConfig()).size());
FileRefreshableDataSourceFactoryBean factoryBean = annotationConfigApplicationContext
.getBean("&fileBean", FileRefreshableDataSourceFactoryBean.class);
assertEquals("FileRefreshableDataSourceFactoryBean buf size was wrong", 1024,
factoryBean.getBufSize());
assertEquals("FileRefreshableDataSourceFactoryBean charset was wrong", "utf-8",
factoryBean.getCharset());
assertEquals("FileRefreshableDataSourceFactoryBean recommendRefreshMs was wrong",
2000, factoryBean.getRecommendRefreshMs());
assertNotNull("FileRefreshableDataSourceFactoryBean file was null",
factoryBean.getFile());
assertNotNull("FileRefreshableDataSourceFactoryBean converter was null",
factoryBean.getConverter());
}
@Configuration
public static class TestConfig {
@Bean
public FileRefreshableDataSourceFactoryBean fileBean() {
FileRefreshableDataSourceFactoryBean factoryBean = new FileRefreshableDataSourceFactoryBean();
factoryBean.setBufSize(1024);
factoryBean.setCharset("utf-8");
factoryBean.setRecommendRefreshMs(2000);
try {
factoryBean.setFile(ResourceUtils.getFile("classpath:flowrule.json")
.getAbsolutePath());
}
catch (FileNotFoundException e) {
// ignore
}
factoryBean.setConverter(buildConverter());
return factoryBean;
}
private Converter buildConverter() {
return new Converter<String, List<FlowRule>>() {
ObjectMapper objectMapper = new ObjectMapper();
@Override
public List<FlowRule> convert(String source) {
try {
return objectMapper.readValue(source,
new TypeReference<List<FlowRule>>() {
});
}
catch (IOException e) {
// ignore
}
return null;
}
};
}
}
}

View File

@@ -0,0 +1,115 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import org.junit.Test;
import com.alibaba.cloud.sentinel.datasource.converter.SentinelConverter;
import com.alibaba.cloud.sentinel.datasource.factorybean.NacosDataSourceFactoryBean;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class NacosDataSourceFactoryBeanTests {
private String dataId = "sentinel";
private String groupId = "DEFAULT_GROUP";
private String serverAddr = "localhost:8848";
private String accessKey = "ak";
private String secretKey = "sk";
private String endpoint = "endpoint";
private String namespace = "namespace";
@Test
public void testNacosFactoryBeanServerAddr() throws Exception {
NacosDataSourceFactoryBean factoryBean = spy(new NacosDataSourceFactoryBean());
Converter converter = mock(SentinelConverter.class);
factoryBean.setDataId(dataId);
factoryBean.setGroupId(groupId);
factoryBean.setServerAddr(serverAddr);
factoryBean.setConverter(converter);
NacosDataSource nacosDataSource = mock(NacosDataSource.class);
doReturn(nacosDataSource).when(factoryBean).getObject();
when(nacosDataSource.readSource()).thenReturn("{}");
assertEquals("NacosDataSourceFactoryBean getObject was wrong", nacosDataSource,
factoryBean.getObject());
assertEquals("NacosDataSource read source value was wrong", "{}",
factoryBean.getObject().readSource());
assertEquals("NacosDataSource converter was wrong", converter,
factoryBean.getConverter());
assertEquals("NacosDataSourceFactoryBean dataId was wrong", dataId,
factoryBean.getDataId());
assertEquals("NacosDataSourceFactoryBean groupId was wrong", groupId,
factoryBean.getGroupId());
assertEquals("NacosDataSourceFactoryBean serverAddr was wrong", serverAddr,
factoryBean.getServerAddr());
}
@Test
public void testNacosFactoryBeanProperties() throws Exception {
NacosDataSourceFactoryBean factoryBean = spy(new NacosDataSourceFactoryBean());
Converter converter = mock(SentinelConverter.class);
factoryBean.setDataId(dataId);
factoryBean.setGroupId(groupId);
factoryBean.setAccessKey(accessKey);
factoryBean.setSecretKey(secretKey);
factoryBean.setEndpoint(endpoint);
factoryBean.setNamespace(namespace);
factoryBean.setConverter(converter);
NacosDataSource nacosDataSource = mock(NacosDataSource.class);
doReturn(nacosDataSource).when(factoryBean).getObject();
when(nacosDataSource.readSource()).thenReturn("{}");
assertEquals("NacosDataSourceFactoryBean getObject was wrong", nacosDataSource,
factoryBean.getObject());
assertEquals("NacosDataSource read source value was wrong", "{}",
factoryBean.getObject().readSource());
assertEquals("NacosDataSource converter was wrong", converter,
factoryBean.getConverter());
assertEquals("NacosDataSourceFactoryBean dataId was wrong", dataId,
factoryBean.getDataId());
assertEquals("NacosDataSourceFactoryBean groupId was wrong", groupId,
factoryBean.getGroupId());
assertEquals("NacosDataSourceFactoryBean namespace was wrong", namespace,
factoryBean.getNamespace());
assertEquals("NacosDataSourceFactoryBean endpoint was wrong", endpoint,
factoryBean.getEndpoint());
assertEquals("NacosDataSourceFactoryBean ak was wrong", accessKey,
factoryBean.getAccessKey());
assertEquals("NacosDataSourceFactoryBean sk was wrong", secretKey,
factoryBean.getSecretKey());
}
}

View File

@@ -0,0 +1,75 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource;
import static org.junit.Assert.assertEquals;
import org.junit.Assert;
import org.junit.Test;
import com.alibaba.cloud.sentinel.datasource.config.NacosDataSourceProperties;
import com.alibaba.cloud.sentinel.datasource.factorybean.NacosDataSourceFactoryBean;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class NacosDataSourcePropertiesTests {
@Test
public void testNacosWithAddr() {
NacosDataSourceProperties nacosDataSourceProperties = new NacosDataSourceProperties();
nacosDataSourceProperties.setServerAddr("127.0.0.1:8848");
nacosDataSourceProperties.setRuleType(RuleType.FLOW);
nacosDataSourceProperties.setDataId("sentinel");
nacosDataSourceProperties.setGroupId("custom-group");
nacosDataSourceProperties.setDataType("xml");
assertEquals("Nacos groupId was wrong", "custom-group",
nacosDataSourceProperties.getGroupId());
assertEquals("Nacos dataId was wrong", "sentinel",
nacosDataSourceProperties.getDataId());
assertEquals("Nacos default data type was wrong", "xml",
nacosDataSourceProperties.getDataType());
Assert.assertEquals("Nacos rule type was wrong", RuleType.FLOW,
nacosDataSourceProperties.getRuleType());
assertEquals("Nacos default factory bean was wrong",
NacosDataSourceFactoryBean.class.getName(),
nacosDataSourceProperties.getFactoryBeanName());
}
@Test
public void testNacosWithProperties() {
NacosDataSourceProperties nacosDataSourceProperties = new NacosDataSourceProperties();
nacosDataSourceProperties.setAccessKey("ak");
nacosDataSourceProperties.setSecretKey("sk");
nacosDataSourceProperties.setEndpoint("endpoint");
nacosDataSourceProperties.setNamespace("namespace");
nacosDataSourceProperties.setRuleType(RuleType.SYSTEM);
assertEquals("Nacos ak was wrong", "ak",
nacosDataSourceProperties.getAccessKey());
assertEquals("Nacos sk was wrong", "sk",
nacosDataSourceProperties.getSecretKey());
assertEquals("Nacos endpoint was wrong", "endpoint",
nacosDataSourceProperties.getEndpoint());
assertEquals("Nacos namespace was wrong", "namespace",
nacosDataSourceProperties.getNamespace());
Assert.assertEquals("Nacos rule type was wrong", RuleType.SYSTEM,
nacosDataSourceProperties.getRuleType());
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.alibaba.csp.sentinel.slots.block.AbstractRule;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class RuleTypeTests {
@Test
public void testGetByName() {
assertFalse("empty str rule name was not null",
RuleType.getByName("").isPresent());
assertFalse("test rule name was not null",
RuleType.getByName("test").isPresent());
assertFalse("param_flow rule name was not null",
RuleType.getByName("param_flow").isPresent());
assertFalse("param rule name was not null",
RuleType.getByName("param").isPresent());
assertFalse("FLOW rule name was not null",
RuleType.getByName("FLOW").isPresent());
assertTrue("flow rule name was null", RuleType.getByName("flow").isPresent());
assertTrue("degrade rule name was null",
RuleType.getByName("degrade").isPresent());
assertTrue("param-flow rule name was null",
RuleType.getByName("param-flow").isPresent());
assertTrue("system rule name was null", RuleType.getByName("system").isPresent());
assertTrue("authority rule name was null",
RuleType.getByName("authority").isPresent());
assertEquals("flow rule name was not equals RuleType.FLOW", RuleType.FLOW,
RuleType.getByName("flow").get());
assertEquals("flow rule name was not equals RuleType.DEGRADE", RuleType.DEGRADE,
RuleType.getByName("degrade").get());
assertEquals("flow rule name was not equals RuleType.PARAM_FLOW",
RuleType.PARAM_FLOW, RuleType.getByName("param-flow").get());
assertEquals("flow rule name was not equals RuleType.SYSTEM", RuleType.SYSTEM,
RuleType.getByName("system").get());
assertEquals("flow rule name was not equals RuleType.AUTHORITY",
RuleType.AUTHORITY, RuleType.getByName("authority").get());
}
@Test
public void testGetByClass() {
assertFalse("Object.class type type was not null",
RuleType.getByClass(Object.class).isPresent());
assertFalse("AbstractRule.class rule type was not null",
RuleType.getByClass(AbstractRule.class).isPresent());
assertTrue("FlowRule.class rule type was null",
RuleType.getByClass(FlowRule.class).isPresent());
assertTrue("DegradeRule.class rule type was null",
RuleType.getByClass(DegradeRule.class).isPresent());
assertTrue("ParamFlowRule.class rule type was null",
RuleType.getByClass(ParamFlowRule.class).isPresent());
assertTrue("SystemRule.class rule type was null",
RuleType.getByClass(SystemRule.class).isPresent());
assertTrue("AuthorityRule.class rule type was null",
RuleType.getByClass(AuthorityRule.class).isPresent());
}
}

View File

@@ -0,0 +1,131 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import com.alibaba.cloud.sentinel.datasource.converter.JsonConverter;
import com.alibaba.cloud.sentinel.datasource.converter.XmlConverter;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class SentinelConverterTests {
private ObjectMapper objectMapper = new ObjectMapper();
private XmlMapper xmlMapper = new XmlMapper();
@Test
public void testJsonConverter() {
JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class);
List<FlowRule> flowRules = (List<FlowRule>) jsonConverter
.convert(readFileContent("classpath: flowrule.json"));
assertEquals("json converter flow rule size was wrong", 1, flowRules.size());
assertEquals("json converter flow rule resource name was wrong", "resource",
flowRules.get(0).getResource());
assertEquals("json converter flow rule limit app was wrong", "default",
flowRules.get(0).getLimitApp());
assertEquals("json converter flow rule count was wrong", "1.0",
String.valueOf(flowRules.get(0).getCount()));
assertEquals("json converter flow rule control behavior was wrong",
RuleConstant.CONTROL_BEHAVIOR_DEFAULT,
flowRules.get(0).getControlBehavior());
assertEquals("json converter flow rule strategy was wrong",
RuleConstant.STRATEGY_DIRECT, flowRules.get(0).getStrategy());
assertEquals("json converter flow rule grade was wrong",
RuleConstant.FLOW_GRADE_QPS, flowRules.get(0).getGrade());
}
@Test
public void testConverterEmptyContent() {
JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class);
List<FlowRule> flowRules = (List<FlowRule>) jsonConverter.convert("");
assertEquals("json converter flow rule size was not empty", 0, flowRules.size());
}
@Test(expected = RuntimeException.class)
public void testConverterErrorFormat() {
JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class);
jsonConverter.convert(readFileContent("classpath: flowrule-errorformat.json"));
}
@Test(expected = RuntimeException.class)
public void testConverterErrorContent() {
JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class);
jsonConverter.convert(readFileContent("classpath: flowrule-errorcontent.json"));
}
@Test
public void testXmlConverter() {
XmlConverter jsonConverter = new XmlConverter(xmlMapper, FlowRule.class);
List<FlowRule> flowRules = (List<FlowRule>) jsonConverter
.convert(readFileContent("classpath: flowrule.xml"));
assertEquals("xml converter flow rule size was wrong", 2, flowRules.size());
assertEquals("xml converter flow rule1 resource name was wrong", "resource",
flowRules.get(0).getResource());
assertEquals("xml converter flow rule2 limit app was wrong", "default",
flowRules.get(0).getLimitApp());
assertEquals("xml converter flow rule1 count was wrong", "1.0",
String.valueOf(flowRules.get(0).getCount()));
assertEquals("xml converter flow rule1 control behavior was wrong",
RuleConstant.CONTROL_BEHAVIOR_DEFAULT,
flowRules.get(0).getControlBehavior());
assertEquals("xml converter flow rule1 strategy was wrong",
RuleConstant.STRATEGY_DIRECT, flowRules.get(0).getStrategy());
assertEquals("xml converter flow rule1 grade was wrong",
RuleConstant.FLOW_GRADE_QPS, flowRules.get(0).getGrade());
assertEquals("xml converter flow rule2 resource name was wrong", "test",
flowRules.get(1).getResource());
assertEquals("xml converter flow rule2 limit app was wrong", "default",
flowRules.get(1).getLimitApp());
assertEquals("xml converter flow rule2 count was wrong", "1.0",
String.valueOf(flowRules.get(1).getCount()));
assertEquals("xml converter flow rule2 control behavior was wrong",
RuleConstant.CONTROL_BEHAVIOR_DEFAULT,
flowRules.get(1).getControlBehavior());
assertEquals("xml converter flow rule2 strategy was wrong",
RuleConstant.STRATEGY_DIRECT, flowRules.get(1).getStrategy());
assertEquals("xml converter flow rule2 grade was wrong",
RuleConstant.FLOW_GRADE_QPS, flowRules.get(1).getGrade());
}
private String readFileContent(String file) {
try {
return FileUtils.readFileToString(
ResourceUtils.getFile(StringUtils.trimAllWhitespace(file)));
}
catch (IOException e) {
return "";
}
}
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* Licensed 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 com.alibaba.cloud.sentinel.datasource;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
import org.junit.Test;
import com.alibaba.cloud.sentinel.datasource.converter.XmlConverter;
import com.alibaba.cloud.sentinel.datasource.factorybean.ZookeeperDataSourceFactoryBean;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.zookeeper.ZookeeperDataSource;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class ZookeeperDataSourceFactoryBeanTests {
private String dataId = "dataId";
private String groupId = "groupId";
private String serverAddr = "localhost:2181";
private String path = "/sentinel";
@Test
public void testZKWithoutPathFactoryBean() throws Exception {
ZookeeperDataSourceFactoryBean factoryBean = spy(
ZookeeperDataSourceFactoryBean.class);
Converter converter = mock(XmlConverter.class);
ZookeeperDataSource zookeeperDataSource = mock(ZookeeperDataSource.class);
factoryBean.setConverter(converter);
factoryBean.setDataId(dataId);
factoryBean.setGroupId(groupId);
factoryBean.setServerAddr(serverAddr);
when(zookeeperDataSource.readSource()).thenReturn("{}");
doReturn(zookeeperDataSource).when(factoryBean).getObject();
assertEquals("ZookeeperDataSource getObject was wrong", zookeeperDataSource,
factoryBean.getObject());
assertEquals("ZookeeperDataSource read source value was wrong", "{}",
factoryBean.getObject().readSource());
assertEquals("ZookeeperDataSourceFactoryBean dataId was wrong", dataId,
factoryBean.getDataId());
assertEquals("ZookeeperDataSourceFactoryBean converter was wrong", converter,
factoryBean.getConverter());
assertEquals("ZookeeperDataSourceFactoryBean groupId was wrong", groupId,
factoryBean.getGroupId());
assertEquals("ZookeeperDataSourceFactoryBean serverAddr was wrong", serverAddr,
factoryBean.getServerAddr());
}
@Test
public void testZKWithPathFactoryBean() throws Exception {
ZookeeperDataSourceFactoryBean factoryBean = spy(
ZookeeperDataSourceFactoryBean.class);
Converter converter = mock(XmlConverter.class);
ZookeeperDataSource zookeeperDataSource = mock(ZookeeperDataSource.class);
factoryBean.setConverter(converter);
factoryBean.setPath(path);
factoryBean.setServerAddr(serverAddr);
when(zookeeperDataSource.readSource()).thenReturn("{}");
doReturn(zookeeperDataSource).when(factoryBean).getObject();
assertEquals("ZookeeperDataSource value was wrong", zookeeperDataSource,
factoryBean.getObject());
assertEquals("ZookeeperDataSource read source value was wrong", "{}",
factoryBean.getObject().readSource());
assertEquals("ZookeeperDataSourceFactoryBean converter was wrong", converter,
factoryBean.getConverter());
assertEquals("ZookeeperDataSourceFactoryBean path was wrong", path,
factoryBean.getPath());
assertEquals("ZookeeperDataSourceFactoryBean serverAddr was wrong", serverAddr,
factoryBean.getServerAddr());
}
}

View File

@@ -0,0 +1,11 @@
[
{
"test": 1,
"controlBehavior": 0,
"count": 1,
"grade": 1,
"limitApp": "default",
"strategy": 0
}
]

View File

@@ -0,0 +1,10 @@
[
{
"resource": "resource",
"controlBehavior": 0,
"count": 1,
"grade": 1,
"limitApp": "default",
"strategy": 0
}==
]

View File

@@ -0,0 +1,10 @@
[
{
"resource": "resource",
"controlBehavior": 0,
"count": 1,
"grade": 1,
"limitApp": "default",
"strategy": 0
}
]

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8" ?>
<Rules>
<FlowRule>
<resource>resource</resource>
<controlBehavior>0</controlBehavior>
<count>1</count>
<grade>1</grade>
<limitApp>default</limitApp>
<strategy>0</strategy>
</FlowRule>
<FlowRule>
<resource>test</resource>
<controlBehavior>0</controlBehavior>
<count>1</count>
<grade>1</grade>
<limitApp>default</limitApp>
<strategy>0</strategy>
</FlowRule>
</Rules>