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

resolve conflict

This commit is contained in:
flystar32 2019-01-30 13:43:08 +08:00
commit 30b6456558
31 changed files with 1521 additions and 29 deletions

45
CODE_OF_CONDUCT.adoc Normal file
View File

@ -0,0 +1,45 @@
= Contributor Code of Conduct
As contributors and maintainers of this project, and in the interest of fostering an open
and welcoming community, we pledge to respect all people who contribute through reporting
issues, posting feature requests, updating documentation, submitting pull requests or
patches, and other activities.
We are committed to making participation in this project a harassment-free experience for
everyone, regardless of level of experience, gender, gender identity and expression,
sexual orientation, disability, personal appearance, body size, race, ethnicity, age,
religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information, such as physical or electronic addresses,
without explicit permission
* Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, or reject comments,
commits, code, wiki edits, issues, and other contributions that are not aligned to this
Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors
that they deem inappropriate, threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselves to fairly and
consistently applying these principles to every aspect of managing this project. Project
maintainers who do not follow or enforce the Code of Conduct may be permanently removed
from the project team.
This Code of Conduct applies both within project spaces and in public spaces when an
individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by
contacting a project maintainer at spring-code-of-conduct@pivotal.io . All complaints will
be reviewed and investigated and will result in a response that is deemed necessary and
appropriate to the circumstances. Maintainers are obligated to maintain confidentiality
with regard to the reporter of an incident.
This Code of Conduct is adapted from the
http://contributor-covenant.org[Contributor Covenant], version 1.3.0, available at
http://contributor-covenant.org/version/1/3/0/[contributor-covenant.org/version/1/3/0/]

29
CODE_OF_CONDUCT.md Normal file
View File

@ -0,0 +1,29 @@
## Contributor Code of Conduct
As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
- The use of sexualized language or imagery
- Personal attacks
- Trolling or insulting/derogatory comments
- Public or private harassment
- Publishing others private information, such as physical or electronic addresses, without explicit permission
- Other unethical or unprofessional conduct
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team.
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer at spring-code-of-conduct@pivotal.io . All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident.
This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org/), version 1.3.0, available at [contributor-covenant.org/version/1/3/0/](http://contributor-covenant.org/version/1/3/0/)

15
PULL_REQUEST_TEMPLATE.md Normal file
View File

@ -0,0 +1,15 @@
### Describe what this PR does / why we need it
### Does this pull request fix one issue?
<!--If that, add "Fixes #xxxx" below in the next line. For example, Fixes #15. Otherwise, add "NONE" -->
### Describe how you did it
### Describe how to verify it
### Special notes for reviews

View File

@ -120,6 +120,28 @@ During the incubation period, the version management of the project will follow
* Functional updates will be reflected in the 3rd number of the version, for example, the next version of 0.1.0 will be 0.1.1.
## Code of Conduct
This project is a sub-project of Spring Cloud, it adheres to the Contributor Covenant [code of conduct](https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io.
## Code Conventions and Housekeeping
None of these is essential for a pull request, but they will all help. They can also be added after the original pull request but before a merge.
Use the Spring Framework code format conventions. If you use Eclipse you can import formatter settings using the eclipse-code-formatter.xml file from the Spring Cloud Build project. If using IntelliJ, you can use the Eclipse Code Formatter Plugin to import the same file.
Make sure all new .java files to have a simple Javadoc class comment with at least an @author tag identifying you, and preferably at least a paragraph on what the class is for.
Add the ASF license header comment to all new .java files (copy from existing files in the project)
Add yourself as an @author to the .java files that you modify substantially (more than cosmetic changes).
Add some Javadocs and, if you change the namespace, some XSD doc elements.
A few unit tests would help a lot as wellsomeone has to do it.
If no-one else is using your branch, please rebase it against the current master (or other target branch in the main project).
When writing a commit message please follow these conventions, if you are fixing an existing issue please add Fixes gh-XXXX at the end of the commit message (where XXXX is the issue number).
## Contact Us
Mailing list is recommended for discussing almost anything related to spring-cloud-alibaba.

View File

@ -20,8 +20,8 @@
<sentinel.version>1.4.1</sentinel.version>
<oss.version>3.1.0</oss.version>
<fescar.version>0.1.3</fescar.version>
<nacos.client.version>0.6.2</nacos.client.version>
<nacos.config.version>0.6.1</nacos.config.version>
<nacos.client.version>0.8.0</nacos.client.version>
<nacos.config.version>0.8.0</nacos.config.version>
<acm.version>1.0.8</acm.version>
<ans.version>1.0.1</ans.version>
<aliyun.sdk.version>4.0.1</aliyun.sdk.version>

View File

@ -113,11 +113,11 @@ Nacos Client 从 Nacos Server 端获取数据时,调用的是此接口 `Config
在 Nacos Config Starter 中dataId 的拼接格式如下
${prefix} - ${spring.active.profile} . ${file-extension}
${prefix} - ${spring.profiles.active} . ${file-extension}
* `prefix` 默认为 `spring.application.name` 的值,也可以通过配置项 `spring.cloud.nacos.config.prefix`来配置。
* `spring.active.profile` 即为当前环境对应的 profile详情可以参考 [Spring Boot文档](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html#boot-features-profiles)
* `spring.profiles.active` 即为当前环境对应的 profile详情可以参考 [Spring Boot文档](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html#boot-features-profiles)
**注意,当 activeprofile 为空时,对应的连接符 `-` 也将不存在dataId 的拼接格式变成 `${prefix}`.`${file-extension}`**

View File

@ -114,11 +114,11 @@ Nacos Client gets data from Nacos Server through this method. `ConfigService.get
In Nacos Config Starter, the splicing format of dataId is as follows
${prefix} - ${spring.active.profile} . ${file-extension}
${prefix} - ${spring.profiles.active} . ${file-extension}
* `prefix` default value is `spring.application.name` value, which can also be configured via the configuration item `spring.cloud.nacos.config.prefix`.
* `spring.active.profile` is the profile corresponding to the current environment. For details, please refer to [Spring Boot Doc](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html#boot-features-profiles)
* `spring.profiles.active` is the profile corresponding to the current environment. For details, please refer to [Spring Boot Doc](https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html#boot-features-profiles)
**Note: when the activeprofile is empty, the corresponding connector `-` will also not exist, and the splicing format of the dataId becomes `${prefix}`.`${file-extension}`**

View File

@ -10,3 +10,4 @@ spring.cloud.sentinel.eager=true
spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json
spring.cloud.sentinel.datasource.ds1.file.data-type=json
spring.cloud.sentinel.datasource.ds1.file.rule-type=flow

View File

@ -160,7 +160,7 @@ public class NacosDiscoveryProperties {
else {
NetworkInterface netInterface = NetworkInterface
.getByName(networkInterface);
if (null == networkInterface) {
if (null == netInterface) {
throw new IllegalArgumentException(
"no such interface " + networkInterface);
}

View File

@ -27,7 +27,7 @@ public class AbstractDataSourceProperties {
private RuleType ruleType;
private String converterClass;
@JsonIgnore
protected String factoryBeanName;
private final String factoryBeanName;
public AbstractDataSourceProperties(String factoryBeanName) {
this.factoryBeanName = factoryBeanName;
@ -61,10 +61,6 @@ public class AbstractDataSourceProperties {
return factoryBeanName;
}
public void setFactoryBeanName(String factoryBeanName) {
this.factoryBeanName = factoryBeanName;
}
public void preCheck(String dataSourceName) {
}

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 org.springframework.cloud.alibaba.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 org.springframework.cloud.alibaba.sentinel.datasource.converter.JsonConverter;
import org.springframework.cloud.alibaba.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,230 @@
/*
* 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 org.springframework.cloud.alibaba.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 org.springframework.cloud.alibaba.sentinel.datasource.config.ApolloDataSourceProperties;
import org.springframework.cloud.alibaba.sentinel.datasource.config.DataSourcePropertiesConfiguration;
import org.springframework.cloud.alibaba.sentinel.datasource.config.FileDataSourceProperties;
import org.springframework.cloud.alibaba.sentinel.datasource.config.NacosDataSourceProperties;
import org.springframework.cloud.alibaba.sentinel.datasource.config.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,180 @@
/*
* 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 org.springframework.cloud.alibaba.sentinel.datasource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.junit.Test;
import org.springframework.cloud.alibaba.sentinel.datasource.config.ApolloDataSourceProperties;
import org.springframework.cloud.alibaba.sentinel.datasource.config.FileDataSourceProperties;
import org.springframework.cloud.alibaba.sentinel.datasource.config.ZookeeperDataSourceProperties;
import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.ApolloDataSourceFactoryBean;
import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.FileRefreshableDataSourceFactoryBean;
import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.ZookeeperDataSourceFactoryBean;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
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;
/**
* @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());
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());
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());
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,109 @@
/*
* 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 org.springframework.cloud.alibaba.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.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.junit.Test;
import org.springframework.cloud.alibaba.sentinel.datasource.factorybean.FileRefreshableDataSourceFactoryBean;
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.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
/**
* @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 org.springframework.cloud.alibaba.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 org.springframework.cloud.alibaba.sentinel.datasource.converter.SentinelConverter;
import org.springframework.cloud.alibaba.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,140 @@
/*
* 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 org.springframework.cloud.alibaba.sentinel.datasource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.springframework.cloud.alibaba.sentinel.datasource.config.NacosDataSourceProperties;
import org.springframework.cloud.alibaba.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());
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());
assertEquals("Nacos rule type was wrong", RuleType.SYSTEM,
nacosDataSourceProperties.getRuleType());
}
@Test
public void testNacosWithEDASAndWithoutSystemProperties() {
NacosDataSourceProperties nacosDataSourceProperties = NacosDataSourceProperties
.buildByEDAS(RuleType.DEGRADE.getName());
assertEquals("Nacos groupId was wrong", "nacos-sentinel",
nacosDataSourceProperties.getGroupId());
assertEquals("Nacos dataId was wrong", "null-" + RuleType.DEGRADE.getName(),
nacosDataSourceProperties.getDataId());
assertEquals("Nacos default data type was wrong", "json",
nacosDataSourceProperties.getDataType());
assertEquals("Nacos rule type was wrong", RuleType.DEGRADE,
nacosDataSourceProperties.getRuleType());
assertNull("Nacos ak was not null", nacosDataSourceProperties.getAccessKey());
assertNull("Nacos sk was not null", nacosDataSourceProperties.getSecretKey());
assertNull("Nacos endpoint was not null",
nacosDataSourceProperties.getEndpoint());
assertNull("Nacos namespace was not null",
nacosDataSourceProperties.getNamespace());
assertNull("Nacos serverAddr was not null",
nacosDataSourceProperties.getServerAddr());
}
@Test
public void testNacosWithEDASDegradeAndWithoutSystemProperties() {
NacosDataSourceProperties nacosDataSourceProperties = NacosDataSourceProperties
.buildDegradeByEDAS();
assertEquals("Nacos groupId was wrong", "nacos-sentinel",
nacosDataSourceProperties.getGroupId());
assertEquals("Nacos dataId was wrong", "null-" + RuleType.DEGRADE.getName(),
nacosDataSourceProperties.getDataId());
assertEquals("Nacos default data type was wrong", "json",
nacosDataSourceProperties.getDataType());
assertEquals("Nacos rule type was wrong", RuleType.DEGRADE,
nacosDataSourceProperties.getRuleType());
assertNull("Nacos ak was not null", nacosDataSourceProperties.getAccessKey());
assertNull("Nacos sk was not null", nacosDataSourceProperties.getSecretKey());
assertNull("Nacos endpoint was not null",
nacosDataSourceProperties.getEndpoint());
assertNull("Nacos namespace was not null",
nacosDataSourceProperties.getNamespace());
assertNull("Nacos serverAddr was not null",
nacosDataSourceProperties.getServerAddr());
}
@Test
public void testNacosWithEDASFlowAndWithoutSystemProperties() {
NacosDataSourceProperties nacosDataSourceProperties = NacosDataSourceProperties
.buildFlowByEDAS();
assertEquals("Nacos groupId was wrong", "nacos-sentinel",
nacosDataSourceProperties.getGroupId());
assertEquals("Nacos dataId was wrong", "null-" + RuleType.FLOW.getName(),
nacosDataSourceProperties.getDataId());
assertEquals("Nacos default data type was wrong", "json",
nacosDataSourceProperties.getDataType());
assertEquals("Nacos rule type was wrong", RuleType.FLOW,
nacosDataSourceProperties.getRuleType());
assertNull("Nacos ak was not null", nacosDataSourceProperties.getAccessKey());
assertNull("Nacos sk was not null", nacosDataSourceProperties.getSecretKey());
assertNull("Nacos endpoint was not null",
nacosDataSourceProperties.getEndpoint());
assertNull("Nacos namespace was not null",
nacosDataSourceProperties.getNamespace());
assertNull("Nacos serverAddr was not null",
nacosDataSourceProperties.getServerAddr());
}
}

View File

@ -0,0 +1,151 @@
/*
* 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 org.springframework.cloud.alibaba.sentinel.datasource;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.springframework.cloud.alibaba.sentinel.datasource.config.NacosDataSourceProperties;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class NacosDataSourcePropertiesWithSystemPropertiesTests {
@Test
public void testNacosWithSystemProperties() {
setSystemProperties();
NacosDataSourceProperties nacosDataSourceProperties = new NacosDataSourceProperties();
nacosDataSourceProperties.setServerAddr("127.0.0.1:8848");
nacosDataSourceProperties.setGroupId("custom-group");
nacosDataSourceProperties.setDataId("sentinel");
nacosDataSourceProperties.preCheck("test-ds");
assertEquals("Nacos groupId was wrong", "custom-group",
nacosDataSourceProperties.getGroupId());
assertEquals("Nacos dataId was wrong", "sentinel",
nacosDataSourceProperties.getDataId());
assertEquals("Nacos default data type was wrong", "json",
nacosDataSourceProperties.getDataType());
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());
assertNull("Nacos serverAddr was not null",
nacosDataSourceProperties.getServerAddr());
}
@Test
public void testNacosWithEDASAndSystemProperties() {
setSystemProperties();
NacosDataSourceProperties nacosDataSourceProperties = NacosDataSourceProperties
.buildByEDAS(RuleType.FLOW.getName());
assertEquals("Nacos groupId was wrong", "nacos-sentinel",
nacosDataSourceProperties.getGroupId());
assertEquals("Nacos dataId was wrong", "project-name-" + RuleType.FLOW.getName(),
nacosDataSourceProperties.getDataId());
assertEquals("Nacos default data type was wrong", "json",
nacosDataSourceProperties.getDataType());
assertEquals("Nacos rule type was wrong", RuleType.FLOW,
nacosDataSourceProperties.getRuleType());
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());
assertNull("Nacos serverAddr was not null",
nacosDataSourceProperties.getServerAddr());
}
@Test
public void testNacosWithEDASDegradeAndSystemProperties() {
setSystemProperties();
NacosDataSourceProperties nacosDataSourceProperties = NacosDataSourceProperties
.buildDegradeByEDAS();
assertEquals("Nacos groupId was wrong", "nacos-sentinel",
nacosDataSourceProperties.getGroupId());
assertEquals("Nacos dataId was wrong",
"project-name-" + RuleType.DEGRADE.getName(),
nacosDataSourceProperties.getDataId());
assertEquals("Nacos default data type was wrong", "json",
nacosDataSourceProperties.getDataType());
assertEquals("Nacos rule type was wrong", RuleType.DEGRADE,
nacosDataSourceProperties.getRuleType());
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());
assertNull("Nacos serverAddr was not null",
nacosDataSourceProperties.getServerAddr());
}
@Test
public void testNacosWithEDASFlowAndSystemProperties() {
setSystemProperties();
NacosDataSourceProperties nacosDataSourceProperties = NacosDataSourceProperties
.buildFlowByEDAS();
assertEquals("Nacos groupId was wrong", "nacos-sentinel",
nacosDataSourceProperties.getGroupId());
assertEquals("Nacos dataId was wrong", "project-name-" + RuleType.FLOW.getName(),
nacosDataSourceProperties.getDataId());
assertEquals("Nacos default data type was wrong", "json",
nacosDataSourceProperties.getDataType());
assertEquals("Nacos rule type was wrong", RuleType.FLOW,
nacosDataSourceProperties.getRuleType());
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());
assertNull("Nacos serverAddr was not null",
nacosDataSourceProperties.getServerAddr());
}
private void setSystemProperties() {
System.setProperty(SentinelDataSourceConstants.NACOS_DATASOURCE_ENDPOINT,
"endpoint");
System.setProperty(SentinelDataSourceConstants.NACOS_DATASOURCE_NAMESPACE,
"namespace");
System.setProperty(SentinelDataSourceConstants.NACOS_DATASOURCE_AK, "ak");
System.setProperty(SentinelDataSourceConstants.NACOS_DATASOURCE_SK, "sk");
System.setProperty(SentinelDataSourceConstants.PROJECT_NAME, "project-name");
}
}

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 org.springframework.cloud.alibaba.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 org.springframework.cloud.alibaba.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.cloud.alibaba.sentinel.datasource.converter.JsonConverter;
import org.springframework.cloud.alibaba.sentinel.datasource.converter.XmlConverter;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
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 = 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 = 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 = 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 org.springframework.cloud.alibaba.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 org.springframework.cloud.alibaba.sentinel.datasource.converter.XmlConverter;
import org.springframework.cloud.alibaba.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>

View File

@ -51,6 +51,7 @@ public class AcmEndpointAutoConfiguration {
}
@Bean
@ConditionalOnMissingBean
public AcmHealthIndicator acmHealthIndicator(AcmProperties acmProperties,
AcmPropertySourceRepository acmPropertySourceRepository) {
return new AcmHealthIndicator(acmProperties, acmPropertySourceRepository);

View File

@ -27,12 +27,13 @@ public class NacosParameterInitListener
EdasChangeOrderConfiguration edasChangeOrderConfiguration = EdasChangeOrderConfigurationFactory
.getEdasChangeOrderConfiguration();
log.info("Initialize Nacos Parameter from edas change order,is edas managed {}.",
edasChangeOrderConfiguration.isEdasManaged());
if (!edasChangeOrderConfiguration.isEdasManaged()) {
return;
}
log.info("Initialize Nacos Parameter from edas change order,is edas managed {}.",
edasChangeOrderConfiguration.isEdasManaged());
// initialize nacos configuration
System.getProperties().setProperty("spring.cloud.nacos.config.server-addr", "");
System.getProperties().setProperty("spring.cloud.nacos.config.endpoint",

View File

@ -26,22 +26,23 @@ import org.springframework.context.event.ContextClosedEvent;
import com.aliyun.oss.OSS;
/**
* Shutdown All OSS Clients when {@code ApplicationContext} gets closed {@link ApplicationListener}
* Shutdown All OSS Clients when {@code ApplicationContext} gets closed
* {@link ApplicationListener}
*
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
public class OssApplicationListener implements ApplicationListener<ContextClosedEvent> {
private static final Logger logger = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(OssApplicationListener.class);
@Override
public void onApplicationEvent(ContextClosedEvent event) {
Map<String, OSS> ossClientMap = event.getApplicationContext()
.getBeansOfType(OSS.class);
logger.info("{} OSSClients will be shutdown soon", ossClientMap.size());
log.info("{} OSSClients will be shutdown soon", ossClientMap.size());
ossClientMap.keySet().forEach(beanName -> {
logger.info("shutdown ossClient: {}", beanName);
log.info("shutdown ossClient: {}", beanName);
ossClientMap.get(beanName).shutdown();
});
}

View File

@ -34,7 +34,7 @@ public class OssEndpointAutoConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnEnabledEndpoint
public OssEndpoint sentinelEndPoint() {
public OssEndpoint ossEndpoint() {
return new OssEndpoint();
}

View File

@ -39,7 +39,7 @@ public class OssStorageProtocolResolver
public static final String PROTOCOL = "oss://";
private static final Logger logger = LoggerFactory
private static final Logger log = LoggerFactory
.getLogger(OssStorageProtocolResolver.class);
private ConfigurableListableBeanFactory beanFactory;
@ -49,8 +49,9 @@ public class OssStorageProtocolResolver
private OSS getOSS() {
if (this.oss == null) {
if (this.beanFactory.getBeansOfType(OSS.class).size() > 1) {
logger.warn(
"There are multiple OSS instances, consider marking one of them as @Primary to resolve oss protocol.");
log.warn(
"There are multiple OSS instances, consider marking one of them as @Primary to resolve oss "
+ "protocol.");
}
this.oss = this.beanFactory.getBean(OSS.class);
}
@ -71,7 +72,7 @@ public class OssStorageProtocolResolver
((DefaultResourceLoader) resourceLoader).addProtocolResolver(this);
}
else {
logger.warn("The provided delegate resource loader is not an implementation "
log.warn("The provided delegate resource loader is not an implementation "
+ "of DefaultResourceLoader. Custom Protocol using oss:// prefix will not be enabled.");
}
}

View File

@ -38,6 +38,12 @@
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>

View File

@ -16,8 +16,10 @@
package org.springframework.cloud.alicloud.scx.endpoint;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.cloud.alicloud.context.edas.EdasProperties;
import org.springframework.cloud.alicloud.context.scx.ScxProperties;
@ -31,7 +33,11 @@ import org.springframework.context.annotation.Bean;
public class ScxEndpointAutoConfiguration {
@Bean
public ScxEndpoint scxEndpoint(EdasProperties edasProperties, ScxProperties scxProperties) {
@ConditionalOnMissingBean
@ConditionalOnEnabledEndpoint
public ScxEndpoint scxEndpoint(EdasProperties edasProperties,
ScxProperties scxProperties) {
return new ScxEndpoint(edasProperties, scxProperties);
}
}