repo_name
stringclasses 5
values | pr_number
int64 1.52k
15.5k
| pr_title
stringlengths 8
143
| pr_description
stringlengths 0
10.2k
| author
stringlengths 3
18
| date_created
timestamp[ns, tz=UTC] | date_merged
timestamp[ns, tz=UTC] | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 11
10.2k
| filepath
stringlengths 6
220
| before_content
stringlengths 0
597M
| after_content
stringlengths 0
597M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-demo/src/main/java/com/ctrip/framework/apollo/demo/spring/javaConfigDemo/AnnotationApplication.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.demo.spring.javaConfigDemo;
import com.ctrip.framework.apollo.demo.spring.common.bean.AnnotatedBean;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author Jason Song([email protected])
*/
public class AnnotationApplication {
public static void main(String[] args) throws IOException {
ApplicationContext context = new AnnotationConfigApplicationContext("com.ctrip.framework.apollo.demo.spring.common");
AnnotatedBean annotatedBean = context.getBean(AnnotatedBean.class);
System.out.println("AnnotationApplication Demo. Input any key except quit to print the values. Input quit to exit.");
while (true) {
System.out.print("> ");
String input = new BufferedReader(new InputStreamReader(System.in, Charsets.UTF_8)).readLine();
if (!Strings.isNullOrEmpty(input) && input.trim().equalsIgnoreCase("quit")) {
System.exit(0);
}
System.out.println(annotatedBean.toString());
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.demo.spring.javaConfigDemo;
import com.ctrip.framework.apollo.demo.spring.common.bean.AnnotatedBean;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* @author Jason Song([email protected])
*/
public class AnnotationApplication {
public static void main(String[] args) throws IOException {
ApplicationContext context = new AnnotationConfigApplicationContext("com.ctrip.framework.apollo.demo.spring.common");
AnnotatedBean annotatedBean = context.getBean(AnnotatedBean.class);
System.out.println("AnnotationApplication Demo. Input any key except quit to print the values. Input quit to exit.");
while (true) {
System.out.print("> ");
String input = new BufferedReader(new InputStreamReader(System.in, Charsets.UTF_8)).readLine();
if (!Strings.isNullOrEmpty(input) && input.trim().equalsIgnoreCase("quit")) {
System.exit(0);
}
System.out.println(annotatedBean.toString());
}
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer;
import com.ctrip.framework.apollo.spi.ConfigFactory;
import com.ctrip.framework.apollo.spi.ConfigFactoryManager;
import com.ctrip.framework.apollo.spi.ConfigRegistry;
import com.ctrip.framework.apollo.spi.DefaultConfigFactory;
import com.ctrip.framework.apollo.spi.DefaultConfigFactoryManager;
import com.ctrip.framework.apollo.spi.DefaultConfigRegistry;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.ctrip.framework.apollo.util.factory.DefaultPropertiesFactory;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import com.ctrip.framework.apollo.util.http.DefaultHttpClient;
import com.ctrip.framework.apollo.util.http.HttpClient;
import com.ctrip.framework.apollo.util.yaml.YamlParser;
import com.ctrip.framework.foundation.internals.ServiceBootstrap;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Singleton;
import java.util.List;
/**
* Guice injector
* @author Jason Song([email protected])
*/
public class DefaultInjector implements Injector {
private final com.google.inject.Injector m_injector;
private final List<ApolloInjectorCustomizer> m_customizers;
public DefaultInjector() {
try {
m_injector = Guice.createInjector(new ApolloModule());
m_customizers = ServiceBootstrap.loadAllOrdered(ApolloInjectorCustomizer.class);
} catch (Throwable ex) {
ApolloConfigException exception = new ApolloConfigException("Unable to initialize Guice Injector!", ex);
Tracer.logError(exception);
throw exception;
}
}
@Override
public <T> T getInstance(Class<T> clazz) {
try {
for (ApolloInjectorCustomizer customizer : m_customizers) {
T instance = customizer.getInstance(clazz);
if (instance != null) {
return instance;
}
}
return m_injector.getInstance(clazz);
} catch (Throwable ex) {
Tracer.logError(ex);
throw new ApolloConfigException(
String.format("Unable to load instance for %s!", clazz.getName()), ex);
}
}
@Override
public <T> T getInstance(Class<T> clazz, String name) {
try {
for (ApolloInjectorCustomizer customizer : m_customizers) {
T instance = customizer.getInstance(clazz, name);
if (instance != null) {
return instance;
}
}
//Guice does not support get instance by type and name
return null;
} catch (Throwable ex) {
Tracer.logError(ex);
throw new ApolloConfigException(
String.format("Unable to load instance for %s with name %s!", clazz.getName(), name), ex);
}
}
private static class ApolloModule extends AbstractModule {
@Override
protected void configure() {
bind(ConfigManager.class).to(DefaultConfigManager.class).in(Singleton.class);
bind(ConfigFactoryManager.class).to(DefaultConfigFactoryManager.class).in(Singleton.class);
bind(ConfigRegistry.class).to(DefaultConfigRegistry.class).in(Singleton.class);
bind(ConfigFactory.class).to(DefaultConfigFactory.class).in(Singleton.class);
bind(ConfigUtil.class).in(Singleton.class);
bind(HttpClient.class).to(DefaultHttpClient.class).in(Singleton.class);
bind(ConfigServiceLocator.class).in(Singleton.class);
bind(RemoteConfigLongPollService.class).in(Singleton.class);
bind(YamlParser.class).in(Singleton.class);
bind(PropertiesFactory.class).to(DefaultPropertiesFactory.class).in(Singleton.class);
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.exceptions.ApolloConfigException;
import com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer;
import com.ctrip.framework.apollo.spi.ConfigFactory;
import com.ctrip.framework.apollo.spi.ConfigFactoryManager;
import com.ctrip.framework.apollo.spi.ConfigRegistry;
import com.ctrip.framework.apollo.spi.DefaultConfigFactory;
import com.ctrip.framework.apollo.spi.DefaultConfigFactoryManager;
import com.ctrip.framework.apollo.spi.DefaultConfigRegistry;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.ctrip.framework.apollo.util.factory.DefaultPropertiesFactory;
import com.ctrip.framework.apollo.util.factory.PropertiesFactory;
import com.ctrip.framework.apollo.util.http.DefaultHttpClient;
import com.ctrip.framework.apollo.util.http.HttpClient;
import com.ctrip.framework.apollo.util.yaml.YamlParser;
import com.ctrip.framework.foundation.internals.ServiceBootstrap;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Singleton;
import java.util.List;
/**
* Guice injector
* @author Jason Song([email protected])
*/
public class DefaultInjector implements Injector {
private final com.google.inject.Injector m_injector;
private final List<ApolloInjectorCustomizer> m_customizers;
public DefaultInjector() {
try {
m_injector = Guice.createInjector(new ApolloModule());
m_customizers = ServiceBootstrap.loadAllOrdered(ApolloInjectorCustomizer.class);
} catch (Throwable ex) {
ApolloConfigException exception = new ApolloConfigException("Unable to initialize Guice Injector!", ex);
Tracer.logError(exception);
throw exception;
}
}
@Override
public <T> T getInstance(Class<T> clazz) {
try {
for (ApolloInjectorCustomizer customizer : m_customizers) {
T instance = customizer.getInstance(clazz);
if (instance != null) {
return instance;
}
}
return m_injector.getInstance(clazz);
} catch (Throwable ex) {
Tracer.logError(ex);
throw new ApolloConfigException(
String.format("Unable to load instance for %s!", clazz.getName()), ex);
}
}
@Override
public <T> T getInstance(Class<T> clazz, String name) {
try {
for (ApolloInjectorCustomizer customizer : m_customizers) {
T instance = customizer.getInstance(clazz, name);
if (instance != null) {
return instance;
}
}
//Guice does not support get instance by type and name
return null;
} catch (Throwable ex) {
Tracer.logError(ex);
throw new ApolloConfigException(
String.format("Unable to load instance for %s with name %s!", clazz.getName(), name), ex);
}
}
private static class ApolloModule extends AbstractModule {
@Override
protected void configure() {
bind(ConfigManager.class).to(DefaultConfigManager.class).in(Singleton.class);
bind(ConfigFactoryManager.class).to(DefaultConfigFactoryManager.class).in(Singleton.class);
bind(ConfigRegistry.class).to(DefaultConfigRegistry.class).in(Singleton.class);
bind(ConfigFactory.class).to(DefaultConfigFactory.class).in(Singleton.class);
bind(ConfigUtil.class).in(Singleton.class);
bind(HttpClient.class).to(DefaultHttpClient.class).in(Singleton.class);
bind(ConfigServiceLocator.class).in(Singleton.class);
bind(RemoteConfigLongPollService.class).in(Singleton.class);
bind(YamlParser.class).in(Singleton.class);
bind(PropertiesFactory.class).to(DefaultPropertiesFactory.class).in(Singleton.class);
}
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/entity/Namespace.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.entity;
import com.ctrip.framework.apollo.common.entity.BaseEntity;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "Namespace")
@SQLDelete(sql = "Update Namespace set isDeleted = 1 where id = ?")
@Where(clause = "isDeleted = 0")
public class Namespace extends BaseEntity {
@Column(name = "appId", nullable = false)
private String appId;
@Column(name = "ClusterName", nullable = false)
private String clusterName;
@Column(name = "NamespaceName", nullable = false)
private String namespaceName;
public Namespace(){
}
public Namespace(String appId, String clusterName, String namespaceName) {
this.appId = appId;
this.clusterName = clusterName;
this.namespaceName = namespaceName;
}
public String getAppId() {
return appId;
}
public String getClusterName() {
return clusterName;
}
public String getNamespaceName() {
return namespaceName;
}
public void setAppId(String appId) {
this.appId = appId;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public void setNamespaceName(String namespaceName) {
this.namespaceName = namespaceName;
}
public String toString() {
return toStringHelper().add("appId", appId).add("clusterName", clusterName)
.add("namespaceName", namespaceName).toString();
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.entity;
import com.ctrip.framework.apollo.common.entity.BaseEntity;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "Namespace")
@SQLDelete(sql = "Update Namespace set isDeleted = 1 where id = ?")
@Where(clause = "isDeleted = 0")
public class Namespace extends BaseEntity {
@Column(name = "appId", nullable = false)
private String appId;
@Column(name = "ClusterName", nullable = false)
private String clusterName;
@Column(name = "NamespaceName", nullable = false)
private String namespaceName;
public Namespace(){
}
public Namespace(String appId, String clusterName, String namespaceName) {
this.appId = appId;
this.clusterName = clusterName;
this.namespaceName = namespaceName;
}
public String getAppId() {
return appId;
}
public String getClusterName() {
return clusterName;
}
public String getNamespaceName() {
return namespaceName;
}
public void setAppId(String appId) {
this.appId = appId;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public void setNamespaceName(String namespaceName) {
this.namespaceName = namespaceName;
}
public String toString() {
return toStringHelper().add("appId", appId).add("clusterName", clusterName)
.add("namespaceName", namespaceName).toString();
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigRepository.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import java.util.Properties;
/**
* @author Jason Song([email protected])
*/
public interface ConfigRepository {
/**
* Get the config from this repository.
* @return config
*/
Properties getConfig();
/**
* Set the fallback repo for this repository.
* @param upstreamConfigRepository the upstream repo
*/
void setUpstreamRepository(ConfigRepository upstreamConfigRepository);
/**
* Add change listener.
* @param listener the listener to observe the changes
*/
void addChangeListener(RepositoryChangeListener listener);
/**
* Remove change listener.
* @param listener the listener to remove
*/
void removeChangeListener(RepositoryChangeListener listener);
/**
* Return the config's source type, i.e. where is the config loaded from
*
* @return the config's source type
*/
ConfigSourceType getSourceType();
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import java.util.Properties;
/**
* @author Jason Song([email protected])
*/
public interface ConfigRepository {
/**
* Get the config from this repository.
* @return config
*/
Properties getConfig();
/**
* Set the fallback repo for this repository.
* @param upstreamConfigRepository the upstream repo
*/
void setUpstreamRepository(ConfigRepository upstreamConfigRepository);
/**
* Add change listener.
* @param listener the listener to observe the changes
*/
void addChangeListener(RepositoryChangeListener listener);
/**
* Remove change listener.
* @param listener the listener to remove
*/
void removeChangeListener(RepositoryChangeListener listener);
/**
* Return the config's source type, i.e. where is the config loaded from
*
* @return the config's source type
*/
ConfigSourceType getSourceType();
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/webclient/customizer/spi/ApolloClientWebClientCustomizerFactory.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.config.data.extension.webclient.customizer.spi;
import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientProperties;
import com.ctrip.framework.apollo.core.spi.Ordered;
import org.apache.commons.logging.Log;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.web.reactive.function.client.WebClientCustomizer;
import org.springframework.lang.Nullable;
/**
* @author vdisk <[email protected]>
*/
public interface ApolloClientWebClientCustomizerFactory extends Ordered {
/**
* create a WebClientCustomizer instance
*
* @param apolloClientProperties apollo client binded properties
* @param binder properties binder
* @param bindHandler properties binder Handler
* @param log deferred log
* @param bootstrapContext bootstrapContext
* @return WebClientCustomizer instance or null
*/
@Nullable
WebClientCustomizer createWebClientCustomizer(ApolloClientProperties apolloClientProperties,
Binder binder, BindHandler bindHandler, Log log,
ConfigurableBootstrapContext bootstrapContext);
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.config.data.extension.webclient.customizer.spi;
import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientProperties;
import com.ctrip.framework.apollo.core.spi.Ordered;
import org.apache.commons.logging.Log;
import org.springframework.boot.ConfigurableBootstrapContext;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.web.reactive.function.client.WebClientCustomizer;
import org.springframework.lang.Nullable;
/**
* @author vdisk <[email protected]>
*/
public interface ApolloClientWebClientCustomizerFactory extends Ordered {
/**
* create a WebClientCustomizer instance
*
* @param apolloClientProperties apollo client binded properties
* @param binder properties binder
* @param bindHandler properties binder Handler
* @param log deferred log
* @param bootstrapContext bootstrapContext
* @return WebClientCustomizer instance or null
*/
@Nullable
WebClientCustomizer createWebClientCustomizer(ApolloClientProperties apolloClientProperties,
Binder binder, BindHandler bindHandler, Log log,
ConfigurableBootstrapContext bootstrapContext);
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/webclient/injector/ApolloClientCustomHttpClientInjectorCustomizer.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.config.data.extension.webclient.injector;
import com.ctrip.framework.apollo.config.data.extension.webclient.ApolloWebClientHttpClient;
import com.ctrip.framework.apollo.core.spi.Ordered;
import com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer;
import org.springframework.web.reactive.function.client.WebClient;
/**
* @author vdisk <[email protected]>
*/
public class ApolloClientCustomHttpClientInjectorCustomizer implements ApolloInjectorCustomizer {
/**
* the order of the injector customizer
*/
public static final int ORDER = Ordered.LOWEST_PRECEDENCE - 100;
private static ApolloWebClientHttpClient CUSTOM_HTTP_CLIENT;
/**
* set the webClient to use
*
* @param webClient webClient to use
*/
public static void setCustomWebClient(WebClient webClient) {
CUSTOM_HTTP_CLIENT = new ApolloWebClientHttpClient(webClient);
}
@SuppressWarnings("unchecked")
@Override
public <T> T getInstance(Class<T> clazz) {
if (clazz.isInstance(CUSTOM_HTTP_CLIENT)) {
return (T) CUSTOM_HTTP_CLIENT;
}
return null;
}
@Override
public <T> T getInstance(Class<T> clazz, String name) {
return null;
}
@Override
public int getOrder() {
return ORDER;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.config.data.extension.webclient.injector;
import com.ctrip.framework.apollo.config.data.extension.webclient.ApolloWebClientHttpClient;
import com.ctrip.framework.apollo.core.spi.Ordered;
import com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer;
import org.springframework.web.reactive.function.client.WebClient;
/**
* @author vdisk <[email protected]>
*/
public class ApolloClientCustomHttpClientInjectorCustomizer implements ApolloInjectorCustomizer {
/**
* the order of the injector customizer
*/
public static final int ORDER = Ordered.LOWEST_PRECEDENCE - 100;
private static ApolloWebClientHttpClient CUSTOM_HTTP_CLIENT;
/**
* set the webClient to use
*
* @param webClient webClient to use
*/
public static void setCustomWebClient(WebClient webClient) {
CUSTOM_HTTP_CLIENT = new ApolloWebClientHttpClient(webClient);
}
@SuppressWarnings("unchecked")
@Override
public <T> T getInstance(Class<T> clazz) {
if (clazz.isInstance(CUSTOM_HTTP_CLIENT)) {
return (T) CUSTOM_HTTP_CLIENT;
}
return null;
}
@Override
public <T> T getInstance(Class<T> clazz, String name) {
return null;
}
@Override
public int getOrder() {
return ORDER;
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/ctrip/BizLoggingCustomizer.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi.ctrip;
import com.ctrip.framework.apollo.common.customize.LoggingCustomizer;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("ctrip")
public class BizLoggingCustomizer extends LoggingCustomizer {
private final PortalConfig portalConfig;
public BizLoggingCustomizer(final PortalConfig portalConfig) {
this.portalConfig = portalConfig;
}
@Override
protected String cloggingUrl() {
return portalConfig.cloggingUrl();
}
@Override
protected String cloggingPort() {
return portalConfig.cloggingPort();
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi.ctrip;
import com.ctrip.framework.apollo.common.customize.LoggingCustomizer;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Component
@Profile("ctrip")
public class BizLoggingCustomizer extends LoggingCustomizer {
private final PortalConfig portalConfig;
public BizLoggingCustomizer(final PortalConfig portalConfig) {
this.portalConfig = portalConfig;
}
@Override
protected String cloggingUrl() {
return portalConfig.cloggingUrl();
}
@Override
protected String cloggingPort() {
return portalConfig.cloggingPort();
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/ClusterService.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.service;
import com.ctrip.framework.apollo.common.dto.ClusterDTO;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI;
import com.ctrip.framework.apollo.portal.constant.TracerEventType;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.tracer.Tracer;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ClusterService {
private final UserInfoHolder userInfoHolder;
private final AdminServiceAPI.ClusterAPI clusterAPI;
public ClusterService(final UserInfoHolder userInfoHolder, final AdminServiceAPI.ClusterAPI clusterAPI) {
this.userInfoHolder = userInfoHolder;
this.clusterAPI = clusterAPI;
}
public List<ClusterDTO> findClusters(Env env, String appId) {
return clusterAPI.findClustersByApp(appId, env);
}
public ClusterDTO createCluster(Env env, ClusterDTO cluster) {
if (!clusterAPI.isClusterUnique(cluster.getAppId(), env, cluster.getName())) {
throw new BadRequestException(String.format("cluster %s already exists.", cluster.getName()));
}
ClusterDTO clusterDTO = clusterAPI.create(env, cluster);
Tracer.logEvent(TracerEventType.CREATE_CLUSTER, cluster.getAppId(), "0", cluster.getName());
return clusterDTO;
}
public void deleteCluster(Env env, String appId, String clusterName){
clusterAPI.delete(env, appId, clusterName, userInfoHolder.getUser().getUserId());
}
public ClusterDTO loadCluster(String appId, Env env, String clusterName){
return clusterAPI.loadCluster(appId, env, clusterName);
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.service;
import com.ctrip.framework.apollo.common.dto.ClusterDTO;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI;
import com.ctrip.framework.apollo.portal.constant.TracerEventType;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.tracer.Tracer;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ClusterService {
private final UserInfoHolder userInfoHolder;
private final AdminServiceAPI.ClusterAPI clusterAPI;
public ClusterService(final UserInfoHolder userInfoHolder, final AdminServiceAPI.ClusterAPI clusterAPI) {
this.userInfoHolder = userInfoHolder;
this.clusterAPI = clusterAPI;
}
public List<ClusterDTO> findClusters(Env env, String appId) {
return clusterAPI.findClustersByApp(appId, env);
}
public ClusterDTO createCluster(Env env, ClusterDTO cluster) {
if (!clusterAPI.isClusterUnique(cluster.getAppId(), env, cluster.getName())) {
throw new BadRequestException(String.format("cluster %s already exists.", cluster.getName()));
}
ClusterDTO clusterDTO = clusterAPI.create(env, cluster);
Tracer.logEvent(TracerEventType.CREATE_CLUSTER, cluster.getAppId(), "0", cluster.getName());
return clusterDTO;
}
public void deleteCluster(Env env, String appId, String clusterName){
clusterAPI.delete(env, appId, clusterName, userInfoHolder.getUser().getUserId());
}
public ClusterDTO loadCluster(String appId, Env env, String clusterName){
return clusterAPI.loadCluster(appId, env, clusterName);
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenClusterDTO.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.openapi.dto;
public class OpenClusterDTO extends BaseDTO {
private String name;
private String appId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
@Override
public String toString() {
return "OpenClusterDTO{" +
"name='" + name + '\'' +
", appId='" + appId + '\'' +
", dataChangeCreatedBy='" + dataChangeCreatedBy + '\'' +
", dataChangeLastModifiedBy='" + dataChangeLastModifiedBy + '\'' +
", dataChangeCreatedTime=" + dataChangeCreatedTime +
", dataChangeLastModifiedTime=" + dataChangeLastModifiedTime +
'}';
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.openapi.dto;
public class OpenClusterDTO extends BaseDTO {
private String name;
private String appId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
@Override
public String toString() {
return "OpenClusterDTO{" +
"name='" + name + '\'' +
", appId='" + appId + '\'' +
", dataChangeCreatedBy='" + dataChangeCreatedBy + '\'' +
", dataChangeLastModifiedBy='" + dataChangeLastModifiedBy + '\'' +
", dataChangeCreatedTime=" + dataChangeCreatedTime +
", dataChangeLastModifiedTime=" + dataChangeLastModifiedTime +
'}';
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/EmailService.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi;
import com.ctrip.framework.apollo.portal.entity.bo.Email;
public interface EmailService {
void send(Email email);
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi;
import com.ctrip.framework.apollo.portal.entity.bo.Email;
public interface EmailService {
void send(Email email);
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./docs/zh/usage/apollo-open-api-platform.md | ### 一、 什么是开放平台?
Apollo提供了一套的Http REST接口,使第三方应用能够自己管理配置。虽然Apollo系统本身提供了Portal来管理配置,但是在有些情景下,应用需要通过程序去管理配置。
### 二、 第三方应用接入Apollo开放平台
#### 2.1 注册第三方应用
第三方应用负责人需要向Apollo管理员提供一些第三方应用基本信息。
基本信息如下:
* 第三方应用的AppId、应用名、部门
* 第三方应用负责人
Apollo管理员在 http://{portal_address}/open/manage.html 创建第三方应用,创建之前最好先查询此AppId是否已经创建。创建成功之后会生成一个token,如下图所示:

#### 2.2 给已注册的第三方应用授权
第三方应用不应该能操作任何Namespace的配置,所以需要给token绑定可以操作的Namespace。Apollo管理员在 http://{portal_address}/open/manage.html 页面给token赋权。赋权之后,第三方应用就可以通过Apollo提供的Http REST接口来管理已授权的Namespace的配置了。
#### 2.3 第三方应用调用Apollo Open API
##### 2.3.1 调用Http REST接口
任何语言的第三方应用都可以调用Apollo的Open API,在调用接口时,需要设置注意以下两点:
* Http Header中增加一个Authorization字段,字段值为申请的token
* Http Header的Content-Type字段需要设置成application/json;charset=UTF-8
##### 2.3.2 Java应用通过apollo-openapi调用Apollo Open API
从1.1.0版本开始,Apollo提供了[apollo-openapi](https://github.com/ctripcorp/apollo/tree/master/apollo-openapi)客户端,所以Java语言的第三方应用可以更方便地调用Apollo Open API。
首先引入`apollo-openapi`依赖:
```xml
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-openapi</artifactId>
<version>1.7.0</version>
</dependency>
```
在程序中构造`ApolloOpenApiClient`:
```java
String portalUrl = "http://localhost:8070"; // portal url
String token = "e16e5cd903fd0c97a116c873b448544b9d086de9"; // 申请的token
ApolloOpenApiClient client = ApolloOpenApiClient.newBuilder()
.withPortalUrl(portalUrl)
.withToken(token)
.build();
```
后续就可以通过`ApolloOpenApiClient`的接口直接操作Apollo Open API了,接口说明参见下面的Rest接口文档。
##### 2.3.3 .Net core应用调用Apollo Open API
.Net core也提供了open api的客户端,详见https://github.com/ctripcorp/apollo.net/pull/77
### 三、 接口文档
#### 3.1 URL路径参数说明
参数名 | 参数说明
--- | ---
env | 所管理的配置环境
appId | 所管理的配置AppId
clusterName | 所管理的配置集群名, 一般情况下传入 default 即可。如果是特殊集群,传入相应集群的名称即可
namespaceName | 所管理的Namespace的名称,如果是非properties格式,需要加上后缀名,如`sample.yml`
#### 3.2 API接口列表
##### 3.2.1 获取App的环境,集群信息
* **URL** : http://{portal_address}/openapi/v1/apps/{appId}/envclusters
* **Method** : GET
* **Request Params** : 无
* **返回值Sample**:
``` json
[
{
"env":"FAT",
"clusters":[ //集群列表
"default",
"FAT381"
]
},
{
"env":"UAT",
"clusters":[
"default"
]
},
{
"env":"PRO",
"clusters":[
"default",
"SHAOY",
"SHAJQ"
]
}
]
```
##### 3.2.2 获取App信息
* **URL** : http://{portal_address}/openapi/v1/apps
* **Method** : GET
* **Request Params** :
参数名 | 必选 | 类型 | 说明
--- | --- | --- | ---
appIds | false | String | appId列表,以逗号分隔,如果为空则返回所有App信息
* **返回值Sample**:
``` json
[
{
"name":"first_app",
"appId":"100003171",
"orgId":"development",
"orgName":"研发部",
"ownerName":"apollo",
"ownerEmail":"[email protected]",
"dataChangeCreatedBy":"apollo",
"dataChangeLastModifiedBy":"apollo",
"dataChangeCreatedTime":"2019-05-08T09:13:31.000+0800",
"dataChangeLastModifiedTime":"2019-05-08T09:13:31.000+0800"
},
{
"name":"apollo-demo",
"appId":"100004458",
"orgId":"development",
"orgName":"产品研发部",
"ownerName":"apollo",
"ownerEmail":"[email protected]",
"dataChangeCreatedBy":"apollo",
"dataChangeLastModifiedBy":"apollo",
"dataChangeCreatedTime":"2018-12-23T12:35:16.000+0800",
"dataChangeLastModifiedTime":"2019-04-08T13:58:36.000+0800"
}
]
```
##### 3.2.3 获取集群接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}
* **Method** : GET
* **Request Params** :无
* **返回值Sample**:
``` json
{
"name":"default",
"appId":"100004458",
"dataChangeCreatedBy":"apollo",
"dataChangeLastModifiedBy":"apollo",
"dataChangeCreatedTime":"2018-12-23T12:35:16.000+0800",
"dataChangeLastModifiedTime":"2018-12-23T12:35:16.000+0800"
}
```
##### 3.2.4 创建集群接口
可以通过此接口创建集群,调用此接口需要授予第三方APP对目标APP的管理权限。
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters
* **Method** : POST
* **Request Params** :无
* **请求内容(Request Body, JSON格式)** :
参数名 | 必选 | 类型 | 说明
---- | --- | --- | ---
name | true | String | Cluster的名字
appId | true | String | Cluster所属的AppId
dataChangeCreatedBy | true | String | namespace的创建人,格式为域账号,也就是sso系统的User ID
* **返回值 Sample** :
``` json
{
"name":"someClusterName",
"appId":"100004458",
"dataChangeCreatedBy":"apollo",
"dataChangeLastModifiedBy":"apollo",
"dataChangeCreatedTime":"2018-12-23T12:35:16.000+0800",
"dataChangeLastModifiedTime":"2018-12-23T12:35:16.000+0800"
}
```
##### 3.2.5 获取集群下所有Namespace信息接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces
* **Method**: GET
* **Request Params**: 无
* **返回值Sample**:
``` json
[
{
"appId": "100003171",
"clusterName": "default",
"namespaceName": "application",
"comment": "default app namespace",
"format": "properties", //Namespace格式可能取值为:properties、xml、json、yml、yaml
"isPublic": false, //是否为公共的Namespace
"items": [ // Namespace下所有的配置集合
{
"key": "batch",
"value": "100",
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-21T16:03:43.000+0800",
"dataChangeLastModifiedTime": "2016-07-21T16:03:43.000+0800"
}
],
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-20T14:05:58.000+0800",
"dataChangeLastModifiedTime": "2016-07-20T14:05:58.000+0800"
},
{
"appId": "100003171",
"clusterName": "default",
"namespaceName": "FX.apollo",
"comment": "apollo public namespace",
"format": "properties",
"isPublic": true,
"items": [
{
"key": "request.timeout",
"value": "3000",
"comment": "",
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-20T14:08:30.000+0800",
"dataChangeLastModifiedTime": "2016-08-01T13:56:25.000+0800"
},
{
"id": 1116,
"key": "batch",
"value": "3000",
"comment": "",
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-28T15:13:42.000+0800",
"dataChangeLastModifiedTime": "2016-08-01T13:51:00.000+0800"
}
],
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-20T14:08:13.000+0800",
"dataChangeLastModifiedTime": "2016-07-20T14:08:13.000+0800"
}
]
```
##### 3.2.6 获取某个Namespace信息接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}
* **Method** : GET
* **Request Params** :无
* **返回值Sample** :
``` json
{
"appId": "100003171",
"clusterName": "default",
"namespaceName": "application",
"comment": "default app namespace",
"format": "properties", //Namespace格式可能取值为:properties、xml、json、yml、yaml
"isPublic": false, //是否为公共的Namespace
"items": [ // Namespace下所有的配置集合
{
"key": "batch",
"value": "100",
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-21T16:03:43.000+0800",
"dataChangeLastModifiedTime": "2016-07-21T16:03:43.000+0800"
}
],
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-20T14:05:58.000+0800",
"dataChangeLastModifiedTime": "2016-07-20T14:05:58.000+0800"
}
```
##### 3.2.7 创建Namespace
可以通过此接口创建Namespace,调用此接口需要授予第三方APP对目标APP的管理权限。
* **URL** : http://{portal_address}/openapi/v1/apps/{appId}/appnamespaces
* **Method** : POST
* **Request Params** :无
* **请求内容(Request Body, JSON格式)** :
参数名 | 必选 | 类型 | 说明
---- | --- | --- | ---
name | true | String | Namespace的名字
appId | true | String | Namespace所属的AppId
format |true | String | Namespace的格式,**只能是以下类型: properties、xml、json、yml、yaml**
isPublic |true | boolean | 是否是公共文件
comment |false | String | Namespace说明
dataChangeCreatedBy | true | String | namespace的创建人,格式为域账号,也就是sso系统的User ID
* **返回值 Sample** :
``` json
{
"name": "FX.public-0420-11",
"appId": "100003173",
"format": "properties",
"isPublic": true,
"comment": "test",
"dataChangeCreatedBy": "zhanglea",
"dataChangeLastModifiedBy": "zhanglea",
"dataChangeCreatedTime": "2017-04-20T18:25:49.033+0800",
"dataChangeLastModifiedTime": "2017-04-20T18:25:49.033+0800"
}
```
* **返回值说明** :
> 如果是properties文件,name = ${appId所属的部门}.${传入的name值} ,例如调用接口传入的name=xy-z, format=properties,应用的部门为框架(FX),那么name=FX.xy-z
> 如果不是properties文件 name = ${appId所属的部门}.${传入的name值}.${format},例如调用接口传入的name=xy-z, format=json,应用的部门为框架(FX),那么name=FX.xy-z.json
##### 3.2.8 获取某个Namespace当前编辑人接口
Apollo在生产环境(PRO)有限制规则:每次发布只能有一个人编辑配置,且该次发布的人不能是该次发布的编辑人。
也就是说如果一个用户A修改了某个namespace的配置,那么在这个namespace发布前,只能由A修改,其它用户无法修改。同时,该用户A无法发布自己修改的配置,必须找另一个有发布权限的人操作。
这个接口就是用来获取当前namespace是否有人锁定的接口。在非生产环境(FAT、UAT),该接口始终返回没有人锁定。
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/lock
* **Method** : GET
* **Request Params** :无
* **返回值 Sample(未锁定)** :
``` json
{
"namespaceName": "application",
"isLocked": false
}
```
* **返回值Sample(被锁定)** :
``` json
{
"namespaceName": "application",
"isLocked": true,
"lockedBy": "song_s" //锁owner
}
```
##### 3.2.9 读取配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key}
* **Method** : GET
* **Request Params** :无
* **返回值Sample** :
``` json
{
"key": "timeout",
"value": "3000",
"comment": "超时时间",
"dataChangeCreatedBy": "zhanglea",
"dataChangeLastModifiedBy": "zhanglea",
"dataChangeCreatedTime": "2016-08-11T12:06:41.818+0800",
"dataChangeLastModifiedTime": "2016-08-11T12:06:41.818+0800"
}
```
##### 3.2.10 新增配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items
* **Method** : POST
* **Request Params** :无
* **请求内容(Request Body, JSON格式)** :
参数名 | 必选 | 类型 | 说明
---- | --- | --- | ---
key | true | String | 配置的key,长度不能超过128个字符。非properties格式,key固定为`content`
value | true | String | 配置的value,长度不能超过20000个字符,非properties格式,value为文件全部内容
comment | false | String | 配置的备注,长度不能超过1024个字符
dataChangeCreatedBy | true | String | item的创建人,格式为域账号,也就是sso系统的User ID
* **Request body sample** :
``` json
{
"key":"timeout",
"value":"3000",
"comment":"超时时间",
"dataChangeCreatedBy":"zhanglea"
}
```
* **返回值Sample** :
``` json
{
"key": "timeout",
"value": "3000",
"comment": "超时时间",
"dataChangeCreatedBy": "zhanglea",
"dataChangeLastModifiedBy": "zhanglea",
"dataChangeCreatedTime": "2016-08-11T12:06:41.818+0800",
"dataChangeLastModifiedTime": "2016-08-11T12:06:41.818+0800"
}
```
##### 3.2.11 修改配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key}
* **Method** : PUT
* **Request Params** :
参数名 | 必选 | 类型 | 说明
--- | --- | --- | ---
createIfNotExists | false | Boolean | 当配置不存在时是否自动创建
* **请求内容(Request Body, JSON格式)** :
参数名 | 必选 | 类型 | 说明
---- | --- | --- | ---
key | true | String | 配置的key,需和url中的key值一致。非properties格式,key固定为`content`
value | true | String | 配置的value,长度不能超过20000个字符,非properties格式,value为文件全部内容
comment | false | String | 配置的备注,长度不能超过1024个字符
dataChangeLastModifiedBy | true | String | item的修改人,格式为域账号,也就是sso系统的User ID
dataChangeCreatedBy | false | String | 当createIfNotExists为true时必选。item的创建人,格式为域账号,也就是sso系统的User ID
* **Request body sample** :
```json
{
"key":"timeout",
"value":"3000",
"comment":"超时时间",
"dataChangeLastModifiedBy":"zhanglea"
}
```
* **返回值** :无
##### 3.2.12 删除配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key}?operator={operator}
* **Method** : DELETE
* **Request Params** :
参数名 | 必选 | 类型 | 说明
--- | --- | --- | ---
key | true | String | 配置的key。非properties格式,key固定为`content`
operator | true | String | 删除配置的操作者,域账号
* **返回值** : 无
##### 3.2.13 发布配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/releases
* **Method** : POST
* **Request Params** :无
* **Request Body** :
参数名 | 必选 | 类型 | 说明
--- | --- | --- | ---
releaseTitle | true | String | 此次发布的标题,长度不能超过64个字符
releaseComment | false | String | 发布的备注,长度不能超过256个字符
releasedBy | true | String | 发布人,域账号,注意:如果`ApolloConfigDB.ServerConfig`中的`namespace.lock.switch`设置为true的话(默认是false),那么该环境不允许发布人和编辑人为同一人。所以如果编辑人是zhanglea,发布人就不能再是zhanglea。
* **Request Body example** :
```json
{
"releaseTitle":"2016-08-11",
"releaseComment":"修改timeout值",
"releasedBy":"zhanglea"
}
```
* **返回值Sample** :
``` json
{
"appId": "test-0620-01",
"clusterName": "test",
"namespaceName": "application",
"name": "2016-08-11",
"configurations": {
"timeout": "3000",
},
"comment": "修改timeout值",
"dataChangeCreatedBy": "zhanglea",
"dataChangeLastModifiedBy": "zhanglea",
"dataChangeCreatedTime": "2016-08-11T14:03:46.232+0800",
"dataChangeLastModifiedTime": "2016-08-11T14:03:46.235+0800"
}
```
##### 3.2.14 获取某个Namespace当前生效的已发布配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/releases/latest
* **Method** : GET
* **Request Params** :无
* **返回值Sample** :
``` json
{
"appId": "test-0620-01",
"clusterName": "test",
"namespaceName": "application",
"name": "2016-08-11",
"configurations": {
"timeout": "3000",
},
"comment": "修改timeout值",
"dataChangeCreatedBy": "zhanglea",
"dataChangeLastModifiedBy": "zhanglea",
"dataChangeCreatedTime": "2016-08-11T14:03:46.232+0800",
"dataChangeLastModifiedTime": "2016-08-11T14:03:46.235+0800"
}
```
##### 3.2.15 回滚已发布配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/releases/{releaseId}/rollback
* **Method** : PUT
* **Request Params** :
参数名 | 必选 | 类型 | 说明
--- | --- | --- | ---
operator | true | String | 删除配置的操作者,域账号
* **返回值** : 无
### 四、错误码说明
正常情况下,接口返回的Http状态码是200,下面列举了Apollo会返回的非200错误码说明。
#### 4.1 400 - Bad Request
客户端传入参数的错误,如操作人不存在,namespace不存在等等,客户端需要根据提示信息检查对应的参数是否正确。
#### 4.2 401 - Unauthorized
接口传入的token非法或者已过期,客户端需要检查token是否传入正确。
#### 4.3 403 - Forbidden
接口要访问的资源未得到授权,比如只授权了对A应用下Namespace的管理权限,但是却尝试管理B应用下的配置。
#### 4.4 404 - Not Found
接口要访问的资源不存在,一般是URL或URL的参数错误。
#### 4.5 405 - Method Not Allowed
接口访问的Method不正确,比如应该使用POST的接口使用了GET访问等,客户端需要检查接口访问方式是否正确。
#### 4.6 500 - Internal Server Error
其它类型的错误默认都会返回500,对这类错误如果应用无法根据提示信息找到原因的话,可以找Apollo研发团队一起排查问题。
| ### 一、 什么是开放平台?
Apollo提供了一套的Http REST接口,使第三方应用能够自己管理配置。虽然Apollo系统本身提供了Portal来管理配置,但是在有些情景下,应用需要通过程序去管理配置。
### 二、 第三方应用接入Apollo开放平台
#### 2.1 注册第三方应用
第三方应用负责人需要向Apollo管理员提供一些第三方应用基本信息。
基本信息如下:
* 第三方应用的AppId、应用名、部门
* 第三方应用负责人
Apollo管理员在 http://{portal_address}/open/manage.html 创建第三方应用,创建之前最好先查询此AppId是否已经创建。创建成功之后会生成一个token,如下图所示:

#### 2.2 给已注册的第三方应用授权
第三方应用不应该能操作任何Namespace的配置,所以需要给token绑定可以操作的Namespace。Apollo管理员在 http://{portal_address}/open/manage.html 页面给token赋权。赋权之后,第三方应用就可以通过Apollo提供的Http REST接口来管理已授权的Namespace的配置了。
#### 2.3 第三方应用调用Apollo Open API
##### 2.3.1 调用Http REST接口
任何语言的第三方应用都可以调用Apollo的Open API,在调用接口时,需要设置注意以下两点:
* Http Header中增加一个Authorization字段,字段值为申请的token
* Http Header的Content-Type字段需要设置成application/json;charset=UTF-8
##### 2.3.2 Java应用通过apollo-openapi调用Apollo Open API
从1.1.0版本开始,Apollo提供了[apollo-openapi](https://github.com/ctripcorp/apollo/tree/master/apollo-openapi)客户端,所以Java语言的第三方应用可以更方便地调用Apollo Open API。
首先引入`apollo-openapi`依赖:
```xml
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-openapi</artifactId>
<version>1.7.0</version>
</dependency>
```
在程序中构造`ApolloOpenApiClient`:
```java
String portalUrl = "http://localhost:8070"; // portal url
String token = "e16e5cd903fd0c97a116c873b448544b9d086de9"; // 申请的token
ApolloOpenApiClient client = ApolloOpenApiClient.newBuilder()
.withPortalUrl(portalUrl)
.withToken(token)
.build();
```
后续就可以通过`ApolloOpenApiClient`的接口直接操作Apollo Open API了,接口说明参见下面的Rest接口文档。
##### 2.3.3 .Net core应用调用Apollo Open API
.Net core也提供了open api的客户端,详见https://github.com/ctripcorp/apollo.net/pull/77
### 三、 接口文档
#### 3.1 URL路径参数说明
参数名 | 参数说明
--- | ---
env | 所管理的配置环境
appId | 所管理的配置AppId
clusterName | 所管理的配置集群名, 一般情况下传入 default 即可。如果是特殊集群,传入相应集群的名称即可
namespaceName | 所管理的Namespace的名称,如果是非properties格式,需要加上后缀名,如`sample.yml`
#### 3.2 API接口列表
##### 3.2.1 获取App的环境,集群信息
* **URL** : http://{portal_address}/openapi/v1/apps/{appId}/envclusters
* **Method** : GET
* **Request Params** : 无
* **返回值Sample**:
``` json
[
{
"env":"FAT",
"clusters":[ //集群列表
"default",
"FAT381"
]
},
{
"env":"UAT",
"clusters":[
"default"
]
},
{
"env":"PRO",
"clusters":[
"default",
"SHAOY",
"SHAJQ"
]
}
]
```
##### 3.2.2 获取App信息
* **URL** : http://{portal_address}/openapi/v1/apps
* **Method** : GET
* **Request Params** :
参数名 | 必选 | 类型 | 说明
--- | --- | --- | ---
appIds | false | String | appId列表,以逗号分隔,如果为空则返回所有App信息
* **返回值Sample**:
``` json
[
{
"name":"first_app",
"appId":"100003171",
"orgId":"development",
"orgName":"研发部",
"ownerName":"apollo",
"ownerEmail":"[email protected]",
"dataChangeCreatedBy":"apollo",
"dataChangeLastModifiedBy":"apollo",
"dataChangeCreatedTime":"2019-05-08T09:13:31.000+0800",
"dataChangeLastModifiedTime":"2019-05-08T09:13:31.000+0800"
},
{
"name":"apollo-demo",
"appId":"100004458",
"orgId":"development",
"orgName":"产品研发部",
"ownerName":"apollo",
"ownerEmail":"[email protected]",
"dataChangeCreatedBy":"apollo",
"dataChangeLastModifiedBy":"apollo",
"dataChangeCreatedTime":"2018-12-23T12:35:16.000+0800",
"dataChangeLastModifiedTime":"2019-04-08T13:58:36.000+0800"
}
]
```
##### 3.2.3 获取集群接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}
* **Method** : GET
* **Request Params** :无
* **返回值Sample**:
``` json
{
"name":"default",
"appId":"100004458",
"dataChangeCreatedBy":"apollo",
"dataChangeLastModifiedBy":"apollo",
"dataChangeCreatedTime":"2018-12-23T12:35:16.000+0800",
"dataChangeLastModifiedTime":"2018-12-23T12:35:16.000+0800"
}
```
##### 3.2.4 创建集群接口
可以通过此接口创建集群,调用此接口需要授予第三方APP对目标APP的管理权限。
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters
* **Method** : POST
* **Request Params** :无
* **请求内容(Request Body, JSON格式)** :
参数名 | 必选 | 类型 | 说明
---- | --- | --- | ---
name | true | String | Cluster的名字
appId | true | String | Cluster所属的AppId
dataChangeCreatedBy | true | String | namespace的创建人,格式为域账号,也就是sso系统的User ID
* **返回值 Sample** :
``` json
{
"name":"someClusterName",
"appId":"100004458",
"dataChangeCreatedBy":"apollo",
"dataChangeLastModifiedBy":"apollo",
"dataChangeCreatedTime":"2018-12-23T12:35:16.000+0800",
"dataChangeLastModifiedTime":"2018-12-23T12:35:16.000+0800"
}
```
##### 3.2.5 获取集群下所有Namespace信息接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces
* **Method**: GET
* **Request Params**: 无
* **返回值Sample**:
``` json
[
{
"appId": "100003171",
"clusterName": "default",
"namespaceName": "application",
"comment": "default app namespace",
"format": "properties", //Namespace格式可能取值为:properties、xml、json、yml、yaml
"isPublic": false, //是否为公共的Namespace
"items": [ // Namespace下所有的配置集合
{
"key": "batch",
"value": "100",
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-21T16:03:43.000+0800",
"dataChangeLastModifiedTime": "2016-07-21T16:03:43.000+0800"
}
],
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-20T14:05:58.000+0800",
"dataChangeLastModifiedTime": "2016-07-20T14:05:58.000+0800"
},
{
"appId": "100003171",
"clusterName": "default",
"namespaceName": "FX.apollo",
"comment": "apollo public namespace",
"format": "properties",
"isPublic": true,
"items": [
{
"key": "request.timeout",
"value": "3000",
"comment": "",
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-20T14:08:30.000+0800",
"dataChangeLastModifiedTime": "2016-08-01T13:56:25.000+0800"
},
{
"id": 1116,
"key": "batch",
"value": "3000",
"comment": "",
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-28T15:13:42.000+0800",
"dataChangeLastModifiedTime": "2016-08-01T13:51:00.000+0800"
}
],
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-20T14:08:13.000+0800",
"dataChangeLastModifiedTime": "2016-07-20T14:08:13.000+0800"
}
]
```
##### 3.2.6 获取某个Namespace信息接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}
* **Method** : GET
* **Request Params** :无
* **返回值Sample** :
``` json
{
"appId": "100003171",
"clusterName": "default",
"namespaceName": "application",
"comment": "default app namespace",
"format": "properties", //Namespace格式可能取值为:properties、xml、json、yml、yaml
"isPublic": false, //是否为公共的Namespace
"items": [ // Namespace下所有的配置集合
{
"key": "batch",
"value": "100",
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-21T16:03:43.000+0800",
"dataChangeLastModifiedTime": "2016-07-21T16:03:43.000+0800"
}
],
"dataChangeCreatedBy": "song_s",
"dataChangeLastModifiedBy": "song_s",
"dataChangeCreatedTime": "2016-07-20T14:05:58.000+0800",
"dataChangeLastModifiedTime": "2016-07-20T14:05:58.000+0800"
}
```
##### 3.2.7 创建Namespace
可以通过此接口创建Namespace,调用此接口需要授予第三方APP对目标APP的管理权限。
* **URL** : http://{portal_address}/openapi/v1/apps/{appId}/appnamespaces
* **Method** : POST
* **Request Params** :无
* **请求内容(Request Body, JSON格式)** :
参数名 | 必选 | 类型 | 说明
---- | --- | --- | ---
name | true | String | Namespace的名字
appId | true | String | Namespace所属的AppId
format |true | String | Namespace的格式,**只能是以下类型: properties、xml、json、yml、yaml**
isPublic |true | boolean | 是否是公共文件
comment |false | String | Namespace说明
dataChangeCreatedBy | true | String | namespace的创建人,格式为域账号,也就是sso系统的User ID
* **返回值 Sample** :
``` json
{
"name": "FX.public-0420-11",
"appId": "100003173",
"format": "properties",
"isPublic": true,
"comment": "test",
"dataChangeCreatedBy": "zhanglea",
"dataChangeLastModifiedBy": "zhanglea",
"dataChangeCreatedTime": "2017-04-20T18:25:49.033+0800",
"dataChangeLastModifiedTime": "2017-04-20T18:25:49.033+0800"
}
```
* **返回值说明** :
> 如果是properties文件,name = ${appId所属的部门}.${传入的name值} ,例如调用接口传入的name=xy-z, format=properties,应用的部门为框架(FX),那么name=FX.xy-z
> 如果不是properties文件 name = ${appId所属的部门}.${传入的name值}.${format},例如调用接口传入的name=xy-z, format=json,应用的部门为框架(FX),那么name=FX.xy-z.json
##### 3.2.8 获取某个Namespace当前编辑人接口
Apollo在生产环境(PRO)有限制规则:每次发布只能有一个人编辑配置,且该次发布的人不能是该次发布的编辑人。
也就是说如果一个用户A修改了某个namespace的配置,那么在这个namespace发布前,只能由A修改,其它用户无法修改。同时,该用户A无法发布自己修改的配置,必须找另一个有发布权限的人操作。
这个接口就是用来获取当前namespace是否有人锁定的接口。在非生产环境(FAT、UAT),该接口始终返回没有人锁定。
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/lock
* **Method** : GET
* **Request Params** :无
* **返回值 Sample(未锁定)** :
``` json
{
"namespaceName": "application",
"isLocked": false
}
```
* **返回值Sample(被锁定)** :
``` json
{
"namespaceName": "application",
"isLocked": true,
"lockedBy": "song_s" //锁owner
}
```
##### 3.2.9 读取配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key}
* **Method** : GET
* **Request Params** :无
* **返回值Sample** :
``` json
{
"key": "timeout",
"value": "3000",
"comment": "超时时间",
"dataChangeCreatedBy": "zhanglea",
"dataChangeLastModifiedBy": "zhanglea",
"dataChangeCreatedTime": "2016-08-11T12:06:41.818+0800",
"dataChangeLastModifiedTime": "2016-08-11T12:06:41.818+0800"
}
```
##### 3.2.10 新增配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items
* **Method** : POST
* **Request Params** :无
* **请求内容(Request Body, JSON格式)** :
参数名 | 必选 | 类型 | 说明
---- | --- | --- | ---
key | true | String | 配置的key,长度不能超过128个字符。非properties格式,key固定为`content`
value | true | String | 配置的value,长度不能超过20000个字符,非properties格式,value为文件全部内容
comment | false | String | 配置的备注,长度不能超过1024个字符
dataChangeCreatedBy | true | String | item的创建人,格式为域账号,也就是sso系统的User ID
* **Request body sample** :
``` json
{
"key":"timeout",
"value":"3000",
"comment":"超时时间",
"dataChangeCreatedBy":"zhanglea"
}
```
* **返回值Sample** :
``` json
{
"key": "timeout",
"value": "3000",
"comment": "超时时间",
"dataChangeCreatedBy": "zhanglea",
"dataChangeLastModifiedBy": "zhanglea",
"dataChangeCreatedTime": "2016-08-11T12:06:41.818+0800",
"dataChangeLastModifiedTime": "2016-08-11T12:06:41.818+0800"
}
```
##### 3.2.11 修改配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key}
* **Method** : PUT
* **Request Params** :
参数名 | 必选 | 类型 | 说明
--- | --- | --- | ---
createIfNotExists | false | Boolean | 当配置不存在时是否自动创建
* **请求内容(Request Body, JSON格式)** :
参数名 | 必选 | 类型 | 说明
---- | --- | --- | ---
key | true | String | 配置的key,需和url中的key值一致。非properties格式,key固定为`content`
value | true | String | 配置的value,长度不能超过20000个字符,非properties格式,value为文件全部内容
comment | false | String | 配置的备注,长度不能超过1024个字符
dataChangeLastModifiedBy | true | String | item的修改人,格式为域账号,也就是sso系统的User ID
dataChangeCreatedBy | false | String | 当createIfNotExists为true时必选。item的创建人,格式为域账号,也就是sso系统的User ID
* **Request body sample** :
```json
{
"key":"timeout",
"value":"3000",
"comment":"超时时间",
"dataChangeLastModifiedBy":"zhanglea"
}
```
* **返回值** :无
##### 3.2.12 删除配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/items/{key}?operator={operator}
* **Method** : DELETE
* **Request Params** :
参数名 | 必选 | 类型 | 说明
--- | --- | --- | ---
key | true | String | 配置的key。非properties格式,key固定为`content`
operator | true | String | 删除配置的操作者,域账号
* **返回值** : 无
##### 3.2.13 发布配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/releases
* **Method** : POST
* **Request Params** :无
* **Request Body** :
参数名 | 必选 | 类型 | 说明
--- | --- | --- | ---
releaseTitle | true | String | 此次发布的标题,长度不能超过64个字符
releaseComment | false | String | 发布的备注,长度不能超过256个字符
releasedBy | true | String | 发布人,域账号,注意:如果`ApolloConfigDB.ServerConfig`中的`namespace.lock.switch`设置为true的话(默认是false),那么该环境不允许发布人和编辑人为同一人。所以如果编辑人是zhanglea,发布人就不能再是zhanglea。
* **Request Body example** :
```json
{
"releaseTitle":"2016-08-11",
"releaseComment":"修改timeout值",
"releasedBy":"zhanglea"
}
```
* **返回值Sample** :
``` json
{
"appId": "test-0620-01",
"clusterName": "test",
"namespaceName": "application",
"name": "2016-08-11",
"configurations": {
"timeout": "3000",
},
"comment": "修改timeout值",
"dataChangeCreatedBy": "zhanglea",
"dataChangeLastModifiedBy": "zhanglea",
"dataChangeCreatedTime": "2016-08-11T14:03:46.232+0800",
"dataChangeLastModifiedTime": "2016-08-11T14:03:46.235+0800"
}
```
##### 3.2.14 获取某个Namespace当前生效的已发布配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/releases/latest
* **Method** : GET
* **Request Params** :无
* **返回值Sample** :
``` json
{
"appId": "test-0620-01",
"clusterName": "test",
"namespaceName": "application",
"name": "2016-08-11",
"configurations": {
"timeout": "3000",
},
"comment": "修改timeout值",
"dataChangeCreatedBy": "zhanglea",
"dataChangeLastModifiedBy": "zhanglea",
"dataChangeCreatedTime": "2016-08-11T14:03:46.232+0800",
"dataChangeLastModifiedTime": "2016-08-11T14:03:46.235+0800"
}
```
##### 3.2.15 回滚已发布配置接口
* **URL** : http://{portal_address}/openapi/v1/envs/{env}/releases/{releaseId}/rollback
* **Method** : PUT
* **Request Params** :
参数名 | 必选 | 类型 | 说明
--- | --- | --- | ---
operator | true | String | 删除配置的操作者,域账号
* **返回值** : 无
### 四、错误码说明
正常情况下,接口返回的Http状态码是200,下面列举了Apollo会返回的非200错误码说明。
#### 4.1 400 - Bad Request
客户端传入参数的错误,如操作人不存在,namespace不存在等等,客户端需要根据提示信息检查对应的参数是否正确。
#### 4.2 401 - Unauthorized
接口传入的token非法或者已过期,客户端需要检查token是否传入正确。
#### 4.3 403 - Forbidden
接口要访问的资源未得到授权,比如只授权了对A应用下Namespace的管理权限,但是却尝试管理B应用下的配置。
#### 4.4 404 - Not Found
接口要访问的资源不存在,一般是URL或URL的参数错误。
#### 4.5 405 - Method Not Allowed
接口访问的Method不正确,比如应该使用POST的接口使用了GET访问等,客户端需要检查接口访问方式是否正确。
#### 4.6 500 - Internal Server Error
其它类型的错误默认都会返回500,对这类错误如果应用无法根据提示信息找到原因的话,可以找Apollo研发团队一起排查问题。
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/ctrip/WebContextConfiguration.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi.ctrip;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.ctrip.filters.UserAccessFilter;
import com.google.common.base.Strings;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("ctrip")
public class WebContextConfiguration {
private final PortalConfig portalConfig;
private final UserInfoHolder userInfoHolder;
public WebContextConfiguration(final PortalConfig portalConfig, final UserInfoHolder userInfoHolder) {
this.portalConfig = portalConfig;
this.userInfoHolder = userInfoHolder;
}
@Bean
public ServletContextInitializer servletContextInitializer() {
return servletContext -> {
String loggingServerIP = portalConfig.cloggingUrl();
String loggingServerPort = portalConfig.cloggingPort();
String credisServiceUrl = portalConfig.credisServiceUrl();
servletContext.setInitParameter("loggingServerIP",
Strings.isNullOrEmpty(loggingServerIP) ? "" : loggingServerIP);
servletContext.setInitParameter("loggingServerPort",
Strings.isNullOrEmpty(loggingServerPort) ? "" : loggingServerPort);
servletContext.setInitParameter("credisServiceUrl",
Strings.isNullOrEmpty(credisServiceUrl) ? "" : credisServiceUrl);
};
}
@Bean
public FilterRegistrationBean userAccessFilter() {
FilterRegistrationBean filter = new FilterRegistrationBean();
filter.setFilter(new UserAccessFilter(userInfoHolder));
filter.addUrlPatterns("/*");
return filter;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi.ctrip;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.ctrip.filters.UserAccessFilter;
import com.google.common.base.Strings;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
@Profile("ctrip")
public class WebContextConfiguration {
private final PortalConfig portalConfig;
private final UserInfoHolder userInfoHolder;
public WebContextConfiguration(final PortalConfig portalConfig, final UserInfoHolder userInfoHolder) {
this.portalConfig = portalConfig;
this.userInfoHolder = userInfoHolder;
}
@Bean
public ServletContextInitializer servletContextInitializer() {
return servletContext -> {
String loggingServerIP = portalConfig.cloggingUrl();
String loggingServerPort = portalConfig.cloggingPort();
String credisServiceUrl = portalConfig.credisServiceUrl();
servletContext.setInitParameter("loggingServerIP",
Strings.isNullOrEmpty(loggingServerIP) ? "" : loggingServerIP);
servletContext.setInitParameter("loggingServerPort",
Strings.isNullOrEmpty(loggingServerPort) ? "" : loggingServerPort);
servletContext.setInitParameter("credisServiceUrl",
Strings.isNullOrEmpty(credisServiceUrl) ? "" : credisServiceUrl);
};
}
@Bean
public FilterRegistrationBean userAccessFilter() {
FilterRegistrationBean filter = new FilterRegistrationBean();
filter.setFilter(new UserAccessFilter(userInfoHolder));
filter.addUrlPatterns("/*");
return filter;
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-common/src/main/java/com/ctrip/framework/apollo/common/http/RichResponseEntity.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.http;
import org.springframework.http.HttpStatus;
public class RichResponseEntity<T>{
private int code;
private Object message;
private T body;
public static <T> RichResponseEntity<T> ok(T body){
RichResponseEntity<T> richResponseEntity = new RichResponseEntity<>();
richResponseEntity.message = HttpStatus.OK.getReasonPhrase();
richResponseEntity.code = HttpStatus.OK.value();
richResponseEntity.body = body;
return richResponseEntity;
}
public static <T> RichResponseEntity<T> error(HttpStatus httpCode, Object message){
RichResponseEntity<T> richResponseEntity = new RichResponseEntity<>();
richResponseEntity.message = message;
richResponseEntity.code = httpCode.value();
return richResponseEntity;
}
public int getCode() {
return code;
}
public Object getMessage() {
return message;
}
public T getBody() {
return body;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.common.http;
import org.springframework.http.HttpStatus;
public class RichResponseEntity<T>{
private int code;
private Object message;
private T body;
public static <T> RichResponseEntity<T> ok(T body){
RichResponseEntity<T> richResponseEntity = new RichResponseEntity<>();
richResponseEntity.message = HttpStatus.OK.getReasonPhrase();
richResponseEntity.code = HttpStatus.OK.value();
richResponseEntity.body = body;
return richResponseEntity;
}
public static <T> RichResponseEntity<T> error(HttpStatus httpCode, Object message){
RichResponseEntity<T> richResponseEntity = new RichResponseEntity<>();
richResponseEntity.message = message;
richResponseEntity.code = httpCode.value();
return richResponseEntity;
}
public int getCode() {
return code;
}
public Object getMessage() {
return message;
}
public T getBody() {
return body;
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./docs/zh/community/thank-you.md | # 致谢
<hr />
<img src="en/images/community/jetbrains.svg" alt="jetbrains" style="height: 80px; margin-right: 20px">
<img src="en/images/community/intellij-idea.svg" alt="intellij-idea" style="width: 75px" >
Apollo 团队使用 [IntelliJ IDEA](https://www.jetbrains.com/idea/) 开发开源项目,非常感谢 [JetBrains](https://www.jetbrains.com/) 赞助许可证。
<hr />
<img src="en/images/community/docsify.svg" alt="docsify" style="height: 80px">
Apollo 团队使用 [docsify](https://docsify.js.org/) 生成文档站点。 | # 致谢
<hr />
<img src="en/images/community/jetbrains.svg" alt="jetbrains" style="height: 80px; margin-right: 20px">
<img src="en/images/community/intellij-idea.svg" alt="intellij-idea" style="width: 75px" >
Apollo 团队使用 [IntelliJ IDEA](https://www.jetbrains.com/idea/) 开发开源项目,非常感谢 [JetBrains](https://www.jetbrains.com/) 赞助许可证。
<hr />
<img src="en/images/community/docsify.svg" alt="docsify" style="height: 80px">
Apollo 团队使用 [docsify](https://docsify.js.org/) 生成文档站点。 | -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/service/ReleaseHistoryService.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.service;
import com.ctrip.framework.apollo.common.constants.GsonType;
import com.ctrip.framework.apollo.common.dto.PageDTO;
import com.ctrip.framework.apollo.common.dto.ReleaseDTO;
import com.ctrip.framework.apollo.common.dto.ReleaseHistoryDTO;
import com.ctrip.framework.apollo.common.entity.EntityPair;
import com.ctrip.framework.apollo.common.utils.BeanUtils;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI.ReleaseHistoryAPI;
import com.ctrip.framework.apollo.portal.enricher.adapter.BaseDtoUserInfoEnrichedAdapter;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI;
import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO;
import com.ctrip.framework.apollo.portal.util.RelativeDateFormat;
import com.google.gson.Gson;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.util.CollectionUtils;
@Service
public class ReleaseHistoryService {
private final static Gson GSON = new Gson();
private final AdminServiceAPI.ReleaseHistoryAPI releaseHistoryAPI;
private final ReleaseService releaseService;
private final AdditionalUserInfoEnrichService additionalUserInfoEnrichService;
public ReleaseHistoryService(final ReleaseHistoryAPI releaseHistoryAPI,
final ReleaseService releaseService,
AdditionalUserInfoEnrichService additionalUserInfoEnrichService) {
this.releaseHistoryAPI = releaseHistoryAPI;
this.releaseService = releaseService;
this.additionalUserInfoEnrichService = additionalUserInfoEnrichService;
}
public ReleaseHistoryBO findLatestByReleaseIdAndOperation(Env env, long releaseId, int operation){
PageDTO<ReleaseHistoryDTO> pageDTO = releaseHistoryAPI.findByReleaseIdAndOperation(env, releaseId, operation, 0, 1);
if (pageDTO != null && pageDTO.hasContent()){
ReleaseHistoryDTO releaseHistory = pageDTO.getContent().get(0);
ReleaseDTO release = releaseService.findReleaseById(env, releaseHistory.getReleaseId());
return transformReleaseHistoryDTO2BO(releaseHistory, release);
}
return null;
}
public ReleaseHistoryBO findLatestByPreviousReleaseIdAndOperation(Env env, long previousReleaseId, int operation){
PageDTO<ReleaseHistoryDTO> pageDTO = releaseHistoryAPI.findByPreviousReleaseIdAndOperation(env, previousReleaseId, operation, 0, 1);
if (pageDTO != null && pageDTO.hasContent()){
ReleaseHistoryDTO releaseHistory = pageDTO.getContent().get(0);
ReleaseDTO release = releaseService.findReleaseById(env, releaseHistory.getReleaseId());
return transformReleaseHistoryDTO2BO(releaseHistory, release);
}
return null;
}
public List<ReleaseHistoryBO> findNamespaceReleaseHistory(String appId, Env env, String clusterName,
String namespaceName, int page, int size) {
PageDTO<ReleaseHistoryDTO> result = releaseHistoryAPI.findReleaseHistoriesByNamespace(appId, env, clusterName,
namespaceName, page, size);
if (result == null || !result.hasContent()) {
return Collections.emptyList();
}
List<ReleaseHistoryDTO> content = result.getContent();
Set<Long> releaseIds = new HashSet<>();
for (ReleaseHistoryDTO releaseHistoryDTO : content) {
long releaseId = releaseHistoryDTO.getReleaseId();
if (releaseId != 0) {
releaseIds.add(releaseId);
}
}
List<ReleaseDTO> releases = releaseService.findReleaseByIds(env, releaseIds);
return transformReleaseHistoryDTO2BO(content, releases);
}
private List<ReleaseHistoryBO> transformReleaseHistoryDTO2BO(List<ReleaseHistoryDTO> source,
List<ReleaseDTO> releases) {
if (CollectionUtils.isEmpty(source)) {
return Collections.emptyList();
}
this.additionalUserInfoEnrichService.enrichAdditionalUserInfo(source, BaseDtoUserInfoEnrichedAdapter::new);
Map<Long, ReleaseDTO> releasesMap = BeanUtils.mapByKey("id", releases);
List<ReleaseHistoryBO> bos = new ArrayList<>(source.size());
for (ReleaseHistoryDTO dto : source) {
ReleaseDTO release = releasesMap.get(dto.getReleaseId());
bos.add(transformReleaseHistoryDTO2BO(dto, release));
}
return bos;
}
private ReleaseHistoryBO transformReleaseHistoryDTO2BO(ReleaseHistoryDTO dto, ReleaseDTO release){
ReleaseHistoryBO bo = new ReleaseHistoryBO();
bo.setId(dto.getId());
bo.setAppId(dto.getAppId());
bo.setClusterName(dto.getClusterName());
bo.setNamespaceName(dto.getNamespaceName());
bo.setBranchName(dto.getBranchName());
bo.setReleaseId(dto.getReleaseId());
bo.setPreviousReleaseId(dto.getPreviousReleaseId());
bo.setOperator(dto.getDataChangeCreatedBy());
bo.setOperatorDisplayName(dto.getDataChangeCreatedByDisplayName());
bo.setOperation(dto.getOperation());
Date releaseTime = dto.getDataChangeLastModifiedTime();
bo.setReleaseTime(releaseTime);
bo.setReleaseTimeFormatted(RelativeDateFormat.format(releaseTime));
bo.setOperationContext(dto.getOperationContext());
//set release info
setReleaseInfoToReleaseHistoryBO(bo, release);
return bo;
}
private void setReleaseInfoToReleaseHistoryBO(ReleaseHistoryBO bo, ReleaseDTO release) {
if (release != null) {
bo.setReleaseTitle(release.getName());
bo.setReleaseComment(release.getComment());
bo.setReleaseAbandoned(release.isAbandoned());
Map<String, String> configuration = GSON.fromJson(release.getConfigurations(), GsonType.CONFIG);
List<EntityPair<String>> items = new ArrayList<>(configuration.size());
for (Map.Entry<String, String> entry : configuration.entrySet()) {
EntityPair<String> entityPair = new EntityPair<>(entry.getKey(), entry.getValue());
items.add(entityPair);
}
bo.setConfiguration(items);
} else {
bo.setReleaseTitle("no release information");
bo.setConfiguration(null);
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.service;
import com.ctrip.framework.apollo.common.constants.GsonType;
import com.ctrip.framework.apollo.common.dto.PageDTO;
import com.ctrip.framework.apollo.common.dto.ReleaseDTO;
import com.ctrip.framework.apollo.common.dto.ReleaseHistoryDTO;
import com.ctrip.framework.apollo.common.entity.EntityPair;
import com.ctrip.framework.apollo.common.utils.BeanUtils;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI.ReleaseHistoryAPI;
import com.ctrip.framework.apollo.portal.enricher.adapter.BaseDtoUserInfoEnrichedAdapter;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.api.AdminServiceAPI;
import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO;
import com.ctrip.framework.apollo.portal.util.RelativeDateFormat;
import com.google.gson.Gson;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.util.CollectionUtils;
@Service
public class ReleaseHistoryService {
private final static Gson GSON = new Gson();
private final AdminServiceAPI.ReleaseHistoryAPI releaseHistoryAPI;
private final ReleaseService releaseService;
private final AdditionalUserInfoEnrichService additionalUserInfoEnrichService;
public ReleaseHistoryService(final ReleaseHistoryAPI releaseHistoryAPI,
final ReleaseService releaseService,
AdditionalUserInfoEnrichService additionalUserInfoEnrichService) {
this.releaseHistoryAPI = releaseHistoryAPI;
this.releaseService = releaseService;
this.additionalUserInfoEnrichService = additionalUserInfoEnrichService;
}
public ReleaseHistoryBO findLatestByReleaseIdAndOperation(Env env, long releaseId, int operation){
PageDTO<ReleaseHistoryDTO> pageDTO = releaseHistoryAPI.findByReleaseIdAndOperation(env, releaseId, operation, 0, 1);
if (pageDTO != null && pageDTO.hasContent()){
ReleaseHistoryDTO releaseHistory = pageDTO.getContent().get(0);
ReleaseDTO release = releaseService.findReleaseById(env, releaseHistory.getReleaseId());
return transformReleaseHistoryDTO2BO(releaseHistory, release);
}
return null;
}
public ReleaseHistoryBO findLatestByPreviousReleaseIdAndOperation(Env env, long previousReleaseId, int operation){
PageDTO<ReleaseHistoryDTO> pageDTO = releaseHistoryAPI.findByPreviousReleaseIdAndOperation(env, previousReleaseId, operation, 0, 1);
if (pageDTO != null && pageDTO.hasContent()){
ReleaseHistoryDTO releaseHistory = pageDTO.getContent().get(0);
ReleaseDTO release = releaseService.findReleaseById(env, releaseHistory.getReleaseId());
return transformReleaseHistoryDTO2BO(releaseHistory, release);
}
return null;
}
public List<ReleaseHistoryBO> findNamespaceReleaseHistory(String appId, Env env, String clusterName,
String namespaceName, int page, int size) {
PageDTO<ReleaseHistoryDTO> result = releaseHistoryAPI.findReleaseHistoriesByNamespace(appId, env, clusterName,
namespaceName, page, size);
if (result == null || !result.hasContent()) {
return Collections.emptyList();
}
List<ReleaseHistoryDTO> content = result.getContent();
Set<Long> releaseIds = new HashSet<>();
for (ReleaseHistoryDTO releaseHistoryDTO : content) {
long releaseId = releaseHistoryDTO.getReleaseId();
if (releaseId != 0) {
releaseIds.add(releaseId);
}
}
List<ReleaseDTO> releases = releaseService.findReleaseByIds(env, releaseIds);
return transformReleaseHistoryDTO2BO(content, releases);
}
private List<ReleaseHistoryBO> transformReleaseHistoryDTO2BO(List<ReleaseHistoryDTO> source,
List<ReleaseDTO> releases) {
if (CollectionUtils.isEmpty(source)) {
return Collections.emptyList();
}
this.additionalUserInfoEnrichService.enrichAdditionalUserInfo(source, BaseDtoUserInfoEnrichedAdapter::new);
Map<Long, ReleaseDTO> releasesMap = BeanUtils.mapByKey("id", releases);
List<ReleaseHistoryBO> bos = new ArrayList<>(source.size());
for (ReleaseHistoryDTO dto : source) {
ReleaseDTO release = releasesMap.get(dto.getReleaseId());
bos.add(transformReleaseHistoryDTO2BO(dto, release));
}
return bos;
}
private ReleaseHistoryBO transformReleaseHistoryDTO2BO(ReleaseHistoryDTO dto, ReleaseDTO release){
ReleaseHistoryBO bo = new ReleaseHistoryBO();
bo.setId(dto.getId());
bo.setAppId(dto.getAppId());
bo.setClusterName(dto.getClusterName());
bo.setNamespaceName(dto.getNamespaceName());
bo.setBranchName(dto.getBranchName());
bo.setReleaseId(dto.getReleaseId());
bo.setPreviousReleaseId(dto.getPreviousReleaseId());
bo.setOperator(dto.getDataChangeCreatedBy());
bo.setOperatorDisplayName(dto.getDataChangeCreatedByDisplayName());
bo.setOperation(dto.getOperation());
Date releaseTime = dto.getDataChangeLastModifiedTime();
bo.setReleaseTime(releaseTime);
bo.setReleaseTimeFormatted(RelativeDateFormat.format(releaseTime));
bo.setOperationContext(dto.getOperationContext());
//set release info
setReleaseInfoToReleaseHistoryBO(bo, release);
return bo;
}
private void setReleaseInfoToReleaseHistoryBO(ReleaseHistoryBO bo, ReleaseDTO release) {
if (release != null) {
bo.setReleaseTitle(release.getName());
bo.setReleaseComment(release.getComment());
bo.setReleaseAbandoned(release.isAbandoned());
Map<String, String> configuration = GSON.fromJson(release.getConfigurations(), GsonType.CONFIG);
List<EntityPair<String>> items = new ArrayList<>(configuration.size());
for (Map.Entry<String, String> entry : configuration.entrySet()) {
EntityPair<String> entityPair = new EntityPair<>(entry.getKey(), entry.getValue());
items.add(entityPair);
}
bo.setConfiguration(items);
} else {
bo.setReleaseTitle("no release information");
bo.setConfiguration(null);
}
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/configuration/EmailConfiguration.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi.configuration;
import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile;
import com.ctrip.framework.apollo.portal.spi.EmailService;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripEmailService;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripEmailRequestBuilder;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultEmailService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class EmailConfiguration {
/**
* spring.profiles.active = ctrip
*/
@Configuration
@Profile("ctrip")
public static class CtripEmailConfiguration {
@Bean
public EmailService ctripEmailService() {
return new CtripEmailService();
}
@Bean
public CtripEmailRequestBuilder emailRequestBuilder() {
return new CtripEmailRequestBuilder();
}
}
/**
* spring.profiles.active != ctrip
*/
@Configuration
@ConditionalOnMissingProfile({"ctrip"})
public static class DefaultEmailConfiguration {
@Bean
@ConditionalOnMissingBean(EmailService.class)
public EmailService defaultEmailService() {
return new DefaultEmailService();
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi.configuration;
import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile;
import com.ctrip.framework.apollo.portal.spi.EmailService;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripEmailService;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripEmailRequestBuilder;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultEmailService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class EmailConfiguration {
/**
* spring.profiles.active = ctrip
*/
@Configuration
@Profile("ctrip")
public static class CtripEmailConfiguration {
@Bean
public EmailService ctripEmailService() {
return new CtripEmailService();
}
@Bean
public CtripEmailRequestBuilder emailRequestBuilder() {
return new CtripEmailRequestBuilder();
}
}
/**
* spring.profiles.active != ctrip
*/
@Configuration
@ConditionalOnMissingProfile({"ctrip"})
public static class DefaultEmailConfiguration {
@Bean
@ConditionalOnMissingBean(EmailService.class)
public EmailService defaultEmailService() {
return new DefaultEmailService();
}
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-adminservice/src/test/java/com/ctrip/framework/apollo/adminservice/controller/ClusterControllerTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.adminservice.controller;
import com.ctrip.framework.apollo.biz.entity.Cluster;
import com.ctrip.framework.apollo.biz.service.ClusterService;
import com.ctrip.framework.apollo.common.dto.ClusterDTO;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.common.utils.InputValidator;
import com.ctrip.framework.apollo.core.ConfigConsts;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.Mockito.*;
public class ClusterControllerTest extends AbstractControllerTest {
private ClusterController clusterController;
@Mock
private ClusterService clusterService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
clusterController = new ClusterController(clusterService);
}
@Test(expected = BadRequestException.class)
public void testDeleteDefaultFail() {
Cluster cluster = new Cluster();
cluster.setName(ConfigConsts.CLUSTER_NAME_DEFAULT);
when(clusterService.findOne(any(String.class), any(String.class))).thenReturn(cluster);
clusterController.delete("1", "2", "d");
}
@Test
public void testDeleteSuccess() {
Cluster cluster = new Cluster();
when(clusterService.findOne(any(String.class), any(String.class))).thenReturn(cluster);
clusterController.delete("1", "2", "d");
verify(clusterService, times(1)).findOne("1", "2");
}
@Test
public void shouldFailWhenRequestBodyInvalid() {
ClusterDTO cluster = new ClusterDTO();
cluster.setAppId("valid");
cluster.setName("notBlank");
ResponseEntity<ClusterDTO> response =
restTemplate.postForEntity(baseUrl() + "/apps/{appId}/clusters", cluster, ClusterDTO.class, cluster.getAppId());
ClusterDTO createdCluster = response.getBody();
Assert.assertNotNull(createdCluster);
Assert.assertEquals(cluster.getAppId(), createdCluster.getAppId());
Assert.assertEquals(cluster.getName(), createdCluster.getName());
cluster.setName("invalid app name");
try {
restTemplate.postForEntity(baseUrl() + "/apps/{appId}/clusters", cluster, ClusterDTO.class, cluster.getAppId());
Assert.fail("Should throw");
} catch (HttpClientErrorException e) {
Assert.assertThat(new String(e.getResponseBodyAsByteArray()), containsString(InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE));
}
}
private String baseUrl() {
return "http://localhost:" + port;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.adminservice.controller;
import com.ctrip.framework.apollo.biz.entity.Cluster;
import com.ctrip.framework.apollo.biz.service.ClusterService;
import com.ctrip.framework.apollo.common.dto.ClusterDTO;
import com.ctrip.framework.apollo.common.exception.BadRequestException;
import com.ctrip.framework.apollo.common.utils.InputValidator;
import com.ctrip.framework.apollo.core.ConfigConsts;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.HttpClientErrorException;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.Mockito.*;
public class ClusterControllerTest extends AbstractControllerTest {
private ClusterController clusterController;
@Mock
private ClusterService clusterService;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
clusterController = new ClusterController(clusterService);
}
@Test(expected = BadRequestException.class)
public void testDeleteDefaultFail() {
Cluster cluster = new Cluster();
cluster.setName(ConfigConsts.CLUSTER_NAME_DEFAULT);
when(clusterService.findOne(any(String.class), any(String.class))).thenReturn(cluster);
clusterController.delete("1", "2", "d");
}
@Test
public void testDeleteSuccess() {
Cluster cluster = new Cluster();
when(clusterService.findOne(any(String.class), any(String.class))).thenReturn(cluster);
clusterController.delete("1", "2", "d");
verify(clusterService, times(1)).findOne("1", "2");
}
@Test
public void shouldFailWhenRequestBodyInvalid() {
ClusterDTO cluster = new ClusterDTO();
cluster.setAppId("valid");
cluster.setName("notBlank");
ResponseEntity<ClusterDTO> response =
restTemplate.postForEntity(baseUrl() + "/apps/{appId}/clusters", cluster, ClusterDTO.class, cluster.getAppId());
ClusterDTO createdCluster = response.getBody();
Assert.assertNotNull(createdCluster);
Assert.assertEquals(cluster.getAppId(), createdCluster.getAppId());
Assert.assertEquals(cluster.getName(), createdCluster.getName());
cluster.setName("invalid app name");
try {
restTemplate.postForEntity(baseUrl() + "/apps/{appId}/clusters", cluster, ClusterDTO.class, cluster.getAppId());
Assert.fail("Should throw");
} catch (HttpClientErrorException e) {
Assert.assertThat(new String(e.getResponseBodyAsByteArray()), containsString(InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE));
}
}
private String baseUrl() {
return "http://localhost:" + port;
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-configservice/src/main/java/com/ctrip/framework/apollo/configservice/filter/ClientAuthenticationFilter.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.filter;
import com.ctrip.framework.apollo.configservice.util.AccessKeyUtil;
import com.ctrip.framework.apollo.core.signature.Signature;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.google.common.net.HttpHeaders;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
/**
* @author nisiyong
*/
public class ClientAuthenticationFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(ClientAuthenticationFilter.class);
private static final Long TIMESTAMP_INTERVAL = 60 * 1000L;
private final AccessKeyUtil accessKeyUtil;
public ClientAuthenticationFilter(AccessKeyUtil accessKeyUtil) {
this.accessKeyUtil = accessKeyUtil;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//nothing
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String appId = accessKeyUtil.extractAppIdFromRequest(request);
if (StringUtils.isBlank(appId)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidAppId");
return;
}
List<String> availableSecrets = accessKeyUtil.findAvailableSecret(appId);
if (!CollectionUtils.isEmpty(availableSecrets)) {
String timestamp = request.getHeader(Signature.HTTP_HEADER_TIMESTAMP);
String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
// check timestamp, valid within 1 minute
if (!checkTimestamp(timestamp)) {
logger.warn("Invalid timestamp. appId={},timestamp={}", appId, timestamp);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "RequestTimeTooSkewed");
return;
}
// check signature
String uri = request.getRequestURI();
String query = request.getQueryString();
if (!checkAuthorization(authorization, availableSecrets, timestamp, uri, query)) {
logger.warn("Invalid authorization. appId={},authorization={}", appId, authorization);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
return;
}
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
//nothing
}
private boolean checkTimestamp(String timestamp) {
long requestTimeMillis = 0L;
try {
requestTimeMillis = Long.parseLong(timestamp);
} catch (NumberFormatException e) {
// nothing to do
}
long x = System.currentTimeMillis() - requestTimeMillis;
return x >= -TIMESTAMP_INTERVAL && x <= TIMESTAMP_INTERVAL;
}
private boolean checkAuthorization(String authorization, List<String> availableSecrets,
String timestamp, String path, String query) {
String signature = null;
if (authorization != null) {
String[] split = authorization.split(":");
if (split.length > 1) {
signature = split[1];
}
}
for (String secret : availableSecrets) {
String availableSignature = accessKeyUtil.buildSignature(path, query, timestamp, secret);
if (Objects.equals(signature, availableSignature)) {
return true;
}
}
return false;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.filter;
import com.ctrip.framework.apollo.configservice.util.AccessKeyUtil;
import com.ctrip.framework.apollo.core.signature.Signature;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.google.common.net.HttpHeaders;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
/**
* @author nisiyong
*/
public class ClientAuthenticationFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(ClientAuthenticationFilter.class);
private static final Long TIMESTAMP_INTERVAL = 60 * 1000L;
private final AccessKeyUtil accessKeyUtil;
public ClientAuthenticationFilter(AccessKeyUtil accessKeyUtil) {
this.accessKeyUtil = accessKeyUtil;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//nothing
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String appId = accessKeyUtil.extractAppIdFromRequest(request);
if (StringUtils.isBlank(appId)) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "InvalidAppId");
return;
}
List<String> availableSecrets = accessKeyUtil.findAvailableSecret(appId);
if (!CollectionUtils.isEmpty(availableSecrets)) {
String timestamp = request.getHeader(Signature.HTTP_HEADER_TIMESTAMP);
String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
// check timestamp, valid within 1 minute
if (!checkTimestamp(timestamp)) {
logger.warn("Invalid timestamp. appId={},timestamp={}", appId, timestamp);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "RequestTimeTooSkewed");
return;
}
// check signature
String uri = request.getRequestURI();
String query = request.getQueryString();
if (!checkAuthorization(authorization, availableSecrets, timestamp, uri, query)) {
logger.warn("Invalid authorization. appId={},authorization={}", appId, authorization);
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
return;
}
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
//nothing
}
private boolean checkTimestamp(String timestamp) {
long requestTimeMillis = 0L;
try {
requestTimeMillis = Long.parseLong(timestamp);
} catch (NumberFormatException e) {
// nothing to do
}
long x = System.currentTimeMillis() - requestTimeMillis;
return x >= -TIMESTAMP_INTERVAL && x <= TIMESTAMP_INTERVAL;
}
private boolean checkAuthorization(String authorization, List<String> availableSecrets,
String timestamp, String path, String query) {
String signature = null;
if (authorization != null) {
String[] split = authorization.split(":");
if (split.length > 1) {
signature = split[1];
}
}
for (String secret : availableSecrets) {
String availableSignature = accessKeyUtil.buildSignature(path, query, timestamp, secret);
if (Objects.equals(signature, availableSignature)) {
return true;
}
}
return false;
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-configservice/src/main/java/com/ctrip/framework/apollo/configservice/service/AccessKeyServiceWithCache.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.service;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import com.ctrip.framework.apollo.biz.entity.AccessKey;
import com.ctrip.framework.apollo.biz.repository.AccessKeyRepository;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.MultimapBuilder.ListMultimapBuilder;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
/**
* @author nisiyong
*/
@Service
public class AccessKeyServiceWithCache implements InitializingBean {
private static Logger logger = LoggerFactory.getLogger(AccessKeyServiceWithCache.class);
private final AccessKeyRepository accessKeyRepository;
private final BizConfig bizConfig;
private int scanInterval;
private TimeUnit scanIntervalTimeUnit;
private int rebuildInterval;
private TimeUnit rebuildIntervalTimeUnit;
private ScheduledExecutorService scheduledExecutorService;
private Date lastTimeScanned;
private ListMultimap<String, AccessKey> accessKeyCache;
private ConcurrentMap<Long, AccessKey> accessKeyIdCache;
@Autowired
public AccessKeyServiceWithCache(AccessKeyRepository accessKeyRepository, BizConfig bizConfig) {
this.accessKeyRepository = accessKeyRepository;
this.bizConfig = bizConfig;
initialize();
}
private void initialize() {
scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
ApolloThreadFactory.create("AccessKeyServiceWithCache", true));
lastTimeScanned = new Date(0L);
ListMultimap<String, AccessKey> multimap = ListMultimapBuilder.treeKeys(String.CASE_INSENSITIVE_ORDER)
.arrayListValues().build();
accessKeyCache = Multimaps.synchronizedListMultimap(multimap);
accessKeyIdCache = Maps.newConcurrentMap();
}
public List<String> getAvailableSecrets(String appId) {
List<AccessKey> accessKeys = accessKeyCache.get(appId);
if (CollectionUtils.isEmpty(accessKeys)) {
return Collections.emptyList();
}
return accessKeys.stream()
.filter(AccessKey::isEnabled)
.map(AccessKey::getSecret)
.collect(Collectors.toList());
}
@Override
public void afterPropertiesSet() throws Exception {
populateDataBaseInterval();
scanNewAndUpdatedAccessKeys(); //block the startup process until load finished
scheduledExecutorService.scheduleWithFixedDelay(this::scanNewAndUpdatedAccessKeys,
scanInterval, scanInterval, scanIntervalTimeUnit);
scheduledExecutorService.scheduleAtFixedRate(this::rebuildAccessKeyCache,
rebuildInterval, rebuildInterval, rebuildIntervalTimeUnit);
}
private void scanNewAndUpdatedAccessKeys() {
Transaction transaction = Tracer.newTransaction("Apollo.AccessKeyServiceWithCache",
"scanNewAndUpdatedAccessKeys");
try {
loadNewAndUpdatedAccessKeys();
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
logger.error("Load new/updated app access keys failed", ex);
} finally {
transaction.complete();
}
}
private void rebuildAccessKeyCache() {
Transaction transaction = Tracer.newTransaction("Apollo.AccessKeyServiceWithCache",
"rebuildCache");
try {
deleteAccessKeyCache();
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
logger.error("Rebuild cache failed", ex);
} finally {
transaction.complete();
}
}
private void loadNewAndUpdatedAccessKeys() {
boolean hasMore = true;
while (hasMore && !Thread.currentThread().isInterrupted()) {
//current batch is 500
List<AccessKey> accessKeys = accessKeyRepository
.findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(lastTimeScanned);
if (CollectionUtils.isEmpty(accessKeys)) {
break;
}
int scanned = accessKeys.size();
mergeAccessKeys(accessKeys);
logger.info("Loaded {} new/updated Accesskey from startTime {}", scanned, lastTimeScanned);
hasMore = scanned == 500;
lastTimeScanned = accessKeys.get(scanned - 1).getDataChangeLastModifiedTime();
// In order to avoid missing some records at the last time, we need to scan records at this time individually
if (hasMore) {
List<AccessKey> lastModifiedTimeAccessKeys = accessKeyRepository.findByDataChangeLastModifiedTime(lastTimeScanned);
mergeAccessKeys(lastModifiedTimeAccessKeys);
logger.info("Loaded {} new/updated Accesskey at lastModifiedTime {}", scanned, lastTimeScanned);
}
}
}
private void mergeAccessKeys(List<AccessKey> accessKeys) {
for (AccessKey accessKey : accessKeys) {
AccessKey thatInCache = accessKeyIdCache.get(accessKey.getId());
accessKeyIdCache.put(accessKey.getId(), accessKey);
accessKeyCache.put(accessKey.getAppId(), accessKey);
if (thatInCache != null && accessKey.getDataChangeLastModifiedTime()
.after(thatInCache.getDataChangeLastModifiedTime())) {
accessKeyCache.remove(accessKey.getAppId(), thatInCache);
logger.info("Found Accesskey changes, old: {}, new: {}", thatInCache, accessKey);
}
}
}
private void deleteAccessKeyCache() {
List<Long> ids = Lists.newArrayList(accessKeyIdCache.keySet());
if (CollectionUtils.isEmpty(ids)) {
return;
}
List<List<Long>> partitionIds = Lists.partition(ids, 500);
for (List<Long> toRebuildIds : partitionIds) {
Iterable<AccessKey> accessKeys = accessKeyRepository.findAllById(toRebuildIds);
Set<Long> foundIds = Sets.newHashSet();
for (AccessKey accessKey : accessKeys) {
foundIds.add(accessKey.getId());
}
//handle deleted
SetView<Long> deletedIds = Sets.difference(Sets.newHashSet(toRebuildIds), foundIds);
handleDeletedAccessKeys(deletedIds);
}
}
private void handleDeletedAccessKeys(Set<Long> deletedIds) {
if (CollectionUtils.isEmpty(deletedIds)) {
return;
}
for (Long deletedId : deletedIds) {
AccessKey deleted = accessKeyIdCache.remove(deletedId);
if (deleted == null) {
continue;
}
accessKeyCache.remove(deleted.getAppId(), deleted);
logger.info("Found AccessKey deleted, {}", deleted);
}
}
private void populateDataBaseInterval() {
scanInterval = bizConfig.accessKeyCacheScanInterval();
scanIntervalTimeUnit = bizConfig.accessKeyCacheScanIntervalTimeUnit();
rebuildInterval = bizConfig.accessKeyCacheRebuildInterval();
rebuildIntervalTimeUnit = bizConfig.accessKeyCacheRebuildIntervalTimeUnit();
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.service;
import com.ctrip.framework.apollo.biz.config.BizConfig;
import com.ctrip.framework.apollo.biz.entity.AccessKey;
import com.ctrip.framework.apollo.biz.repository.AccessKeyRepository;
import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.ctrip.framework.apollo.tracer.spi.Transaction;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.MultimapBuilder.ListMultimapBuilder;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
/**
* @author nisiyong
*/
@Service
public class AccessKeyServiceWithCache implements InitializingBean {
private static Logger logger = LoggerFactory.getLogger(AccessKeyServiceWithCache.class);
private final AccessKeyRepository accessKeyRepository;
private final BizConfig bizConfig;
private int scanInterval;
private TimeUnit scanIntervalTimeUnit;
private int rebuildInterval;
private TimeUnit rebuildIntervalTimeUnit;
private ScheduledExecutorService scheduledExecutorService;
private Date lastTimeScanned;
private ListMultimap<String, AccessKey> accessKeyCache;
private ConcurrentMap<Long, AccessKey> accessKeyIdCache;
@Autowired
public AccessKeyServiceWithCache(AccessKeyRepository accessKeyRepository, BizConfig bizConfig) {
this.accessKeyRepository = accessKeyRepository;
this.bizConfig = bizConfig;
initialize();
}
private void initialize() {
scheduledExecutorService = new ScheduledThreadPoolExecutor(1,
ApolloThreadFactory.create("AccessKeyServiceWithCache", true));
lastTimeScanned = new Date(0L);
ListMultimap<String, AccessKey> multimap = ListMultimapBuilder.treeKeys(String.CASE_INSENSITIVE_ORDER)
.arrayListValues().build();
accessKeyCache = Multimaps.synchronizedListMultimap(multimap);
accessKeyIdCache = Maps.newConcurrentMap();
}
public List<String> getAvailableSecrets(String appId) {
List<AccessKey> accessKeys = accessKeyCache.get(appId);
if (CollectionUtils.isEmpty(accessKeys)) {
return Collections.emptyList();
}
return accessKeys.stream()
.filter(AccessKey::isEnabled)
.map(AccessKey::getSecret)
.collect(Collectors.toList());
}
@Override
public void afterPropertiesSet() throws Exception {
populateDataBaseInterval();
scanNewAndUpdatedAccessKeys(); //block the startup process until load finished
scheduledExecutorService.scheduleWithFixedDelay(this::scanNewAndUpdatedAccessKeys,
scanInterval, scanInterval, scanIntervalTimeUnit);
scheduledExecutorService.scheduleAtFixedRate(this::rebuildAccessKeyCache,
rebuildInterval, rebuildInterval, rebuildIntervalTimeUnit);
}
private void scanNewAndUpdatedAccessKeys() {
Transaction transaction = Tracer.newTransaction("Apollo.AccessKeyServiceWithCache",
"scanNewAndUpdatedAccessKeys");
try {
loadNewAndUpdatedAccessKeys();
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
logger.error("Load new/updated app access keys failed", ex);
} finally {
transaction.complete();
}
}
private void rebuildAccessKeyCache() {
Transaction transaction = Tracer.newTransaction("Apollo.AccessKeyServiceWithCache",
"rebuildCache");
try {
deleteAccessKeyCache();
transaction.setStatus(Transaction.SUCCESS);
} catch (Throwable ex) {
transaction.setStatus(ex);
logger.error("Rebuild cache failed", ex);
} finally {
transaction.complete();
}
}
private void loadNewAndUpdatedAccessKeys() {
boolean hasMore = true;
while (hasMore && !Thread.currentThread().isInterrupted()) {
//current batch is 500
List<AccessKey> accessKeys = accessKeyRepository
.findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(lastTimeScanned);
if (CollectionUtils.isEmpty(accessKeys)) {
break;
}
int scanned = accessKeys.size();
mergeAccessKeys(accessKeys);
logger.info("Loaded {} new/updated Accesskey from startTime {}", scanned, lastTimeScanned);
hasMore = scanned == 500;
lastTimeScanned = accessKeys.get(scanned - 1).getDataChangeLastModifiedTime();
// In order to avoid missing some records at the last time, we need to scan records at this time individually
if (hasMore) {
List<AccessKey> lastModifiedTimeAccessKeys = accessKeyRepository.findByDataChangeLastModifiedTime(lastTimeScanned);
mergeAccessKeys(lastModifiedTimeAccessKeys);
logger.info("Loaded {} new/updated Accesskey at lastModifiedTime {}", scanned, lastTimeScanned);
}
}
}
private void mergeAccessKeys(List<AccessKey> accessKeys) {
for (AccessKey accessKey : accessKeys) {
AccessKey thatInCache = accessKeyIdCache.get(accessKey.getId());
accessKeyIdCache.put(accessKey.getId(), accessKey);
accessKeyCache.put(accessKey.getAppId(), accessKey);
if (thatInCache != null && accessKey.getDataChangeLastModifiedTime()
.after(thatInCache.getDataChangeLastModifiedTime())) {
accessKeyCache.remove(accessKey.getAppId(), thatInCache);
logger.info("Found Accesskey changes, old: {}, new: {}", thatInCache, accessKey);
}
}
}
private void deleteAccessKeyCache() {
List<Long> ids = Lists.newArrayList(accessKeyIdCache.keySet());
if (CollectionUtils.isEmpty(ids)) {
return;
}
List<List<Long>> partitionIds = Lists.partition(ids, 500);
for (List<Long> toRebuildIds : partitionIds) {
Iterable<AccessKey> accessKeys = accessKeyRepository.findAllById(toRebuildIds);
Set<Long> foundIds = Sets.newHashSet();
for (AccessKey accessKey : accessKeys) {
foundIds.add(accessKey.getId());
}
//handle deleted
SetView<Long> deletedIds = Sets.difference(Sets.newHashSet(toRebuildIds), foundIds);
handleDeletedAccessKeys(deletedIds);
}
}
private void handleDeletedAccessKeys(Set<Long> deletedIds) {
if (CollectionUtils.isEmpty(deletedIds)) {
return;
}
for (Long deletedId : deletedIds) {
AccessKey deleted = accessKeyIdCache.remove(deletedId);
if (deleted == null) {
continue;
}
accessKeyCache.remove(deleted.getAppId(), deleted);
logger.info("Found AccessKey deleted, {}", deleted);
}
}
private void populateDataBaseInterval() {
scanInterval = bizConfig.accessKeyCacheScanInterval();
scanIntervalTimeUnit = bizConfig.accessKeyCacheScanIntervalTimeUnit();
rebuildInterval = bizConfig.accessKeyCacheRebuildInterval();
rebuildIntervalTimeUnit = bizConfig.accessKeyCacheRebuildIntervalTimeUnit();
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./docs/zh/community/team.md | # Apollo 团队
Apollo 团队由 Member 和 Contributor 组成。Member 可以直接访问 Apollo 项目的源代码并基于代码库积极演进。Contributor 通过向 Member 提交补丁和建议来改善项目,项目的贡献者数量是没有限制的。无论是进行小规模的清理,提交新的功能或其它形式的贡献,都将受到极大的赞赏。
有关社区治理模型的更多信息,请参考[GOVERNANCE.md](https://github.com/ctripcorp/apollo/blob/master/GOVERNANCE.md)。
## Member
Member 包括 PMC 成员和 Committer,该列表按字母顺序排列。
### Project Management Committee(PMC)
| Github ID | Name | Organization |
| ---------- | ---------- | ------------ |
| JaredTan95 | Jared Tan | DaoCloud |
| kezhenxu94 | Zhenxu Ke | Tetrate |
| nobodyiam | Jason Song | Ant Group |
| zouyx | Joe Zou | Shein |
### Committer
| Github ID | Name | Organization |
| ----------- | ------------- | ------------ |
| Anilople | Xiaoquan Wang | Some Bank |
| klboke | Kailing Chen | TapTap |
| lepdou | Le Zhang | Ant Group |
| nisiyong | Stephen Ni | Qihoo 360 |
| pengweiqhca | Wei Peng | Tuhu |
| vdisk-group | Lvqiu Ye | Hundsun |
## Contributor
### Apollo 主仓库
<a href="https://github.com/ctripcorp/apollo/graphs/contributors"><img src="https://opencollective.com/apollo/contributors.svg?width=880&button=false" /></a>
### apollo.net
<a href="https://github.com/ctripcorp/apollo.net/graphs/contributors"><img src="https://opencollective.com/apollonet/contributors.svg?width=880&button=false" /></a>
## **如何成为提交者**
请参考 [How to become a Committer](https://github.com/ctripcorp/apollo/blob/master/GOVERNANCE.md#how-to-become-a-committer).
| # Apollo 团队
Apollo 团队由 Member 和 Contributor 组成。Member 可以直接访问 Apollo 项目的源代码并基于代码库积极演进。Contributor 通过向 Member 提交补丁和建议来改善项目,项目的贡献者数量是没有限制的。无论是进行小规模的清理,提交新的功能或其它形式的贡献,都将受到极大的赞赏。
有关社区治理模型的更多信息,请参考[GOVERNANCE.md](https://github.com/ctripcorp/apollo/blob/master/GOVERNANCE.md)。
## Member
Member 包括 PMC 成员和 Committer,该列表按字母顺序排列。
### Project Management Committee(PMC)
| Github ID | Name | Organization |
| ---------- | ---------- | ------------ |
| JaredTan95 | Jared Tan | DaoCloud |
| kezhenxu94 | Zhenxu Ke | Tetrate |
| nobodyiam | Jason Song | Ant Group |
| zouyx | Joe Zou | Shein |
### Committer
| Github ID | Name | Organization |
| ----------- | ------------- | ------------ |
| Anilople | Xiaoquan Wang | Some Bank |
| klboke | Kailing Chen | TapTap |
| lepdou | Le Zhang | Ant Group |
| nisiyong | Stephen Ni | Qihoo 360 |
| pengweiqhca | Wei Peng | Tuhu |
| vdisk-group | Lvqiu Ye | Hundsun |
## Contributor
### Apollo 主仓库
<a href="https://github.com/ctripcorp/apollo/graphs/contributors"><img src="https://opencollective.com/apollo/contributors.svg?width=880&button=false" /></a>
### apollo.net
<a href="https://github.com/ctripcorp/apollo.net/graphs/contributors"><img src="https://opencollective.com/apollonet/contributors.svg?width=880&button=false" /></a>
## **如何成为提交者**
请参考 [How to become a Committer](https://github.com/ctripcorp/apollo/blob/master/GOVERNANCE.md#how-to-become-a-committer).
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./docs/zh/development/portal-how-to-implement-user-login-function.md | Apollo是配置管理系统,会提供权限管理(Authorization),理论上是不负责用户登录认证功能的实现(Authentication)。
所以Apollo定义了一些SPI用来解耦,Apollo接入登录的关键就是实现这些SPI。
## 实现方式一:使用Apollo提供的Spring Security简单认证
可能很多公司并没有统一的登录认证系统,如果自己实现一套会比较麻烦。Apollo针对这种情况,从0.9.0开始提供了利用Spring Security实现的Http Basic简单认证版本。
使用步骤如下:
### 1. 安装0.9.0以上版本
>如果之前是0.8.0版本,需要导入[apolloportaldb-v080-v090.sql](https://github.com/ctripcorp/apollo/blob/master/scripts/sql/delta/v080-v090/apolloportaldb-v080-v090.sql)
查看ApolloPortalDB,应该已经存在`Users`表,并有一条初始记录。初始用户名是apollo,密码是admin。
|Id|Username|Password|Email|Enabled|
|-|-|-|-|-|
|1|apollo|$2a$10$7r20uS.BQ9uBpf3Baj3uQOZvMVvB1RN3PYoKE94gtz2.WAOuiiwXS|[email protected]|1|
### 2. 重启Portal
如果是IDE启动的话,确保`-Dapollo_profile=github,auth`
### 3. 添加用户
超级管理员登录系统后打开`管理员工具 - 用户管理`即可添加用户。
### 4. 修改用户密码
超级管理员登录系统后打开`管理员工具 - 用户管理`,输入用户名和密码后即可修改用户密码,建议同时修改超级管理员apollo的密码。
## 实现方式二: 接入LDAP
从1.2.0版本开始,Apollo支持了ldap协议的登录,按照如下方式配置即可。
> 如果采用helm chart部署方式,建议通过配置方式实现,不用修改镜像,可以参考[启用 LDAP 支持](zh/deployment/distributed-deployment-guide#_241449-启用-ldap-支持)
### 1. OpenLDAP接入方式
#### 1.1 配置`application-ldap.yml`
解压`apollo-portal-x.x.x-github.zip`后,在`config`目录下创建`application-ldap.yml`,内容参考如下([样例](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/config/application-ldap-openldap-sample.yml)),相关的内容需要按照具体情况调整:
```yml
spring:
ldap:
base: "dc=example,dc=org"
username: "cn=admin,dc=example,dc=org" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(uid={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://localhost:389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "inetOrgPerson" # ldap 用户 objectClass 配置
loginId: "uid" # ldap 用户惟一 id,用来作为登录的 id
userDisplayName: "cn" # ldap 用户名,用来作为显示名
email: "mail" # ldap 邮箱属性
```
##### 1.1.1 基于memberOf过滤用户
OpenLDAP[开启memberOf特性](https://myanbin.github.io/post/enable-memberof-in-openldap.html)后,可以配置filter从而缩小用户搜索的范围:
```yml
spring:
ldap:
base: "dc=example,dc=org"
username: "cn=admin,dc=example,dc=org" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(uid={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://localhost:389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "inetOrgPerson" # ldap 用户 objectClass 配置
loginId: "uid" # ldap 用户惟一 id,用来作为登录的 id
userDisplayName: "cn" # ldap 用户名,用来作为显示名
email: "mail" # ldap 邮箱属性
filter: # 配置过滤,目前只支持 memberOf
memberOf: "cn=ServiceDEV,ou=DEV,dc=example,dc=org|cn=WebDEV,ou=DEV,dc=example,dc=org" # 只允许 memberOf 属性为 ServiceDEV 和 WebDEV 的用户访问
```
##### 1.1.2 基于Group过滤用户
从1.3.0版本开始支持基于Group过滤用户,从而可以控制只有特定Group的用户可以登录和使用apollo:
```yml
spring:
ldap:
base: "dc=example,dc=org"
username: "cn=admin,dc=example,dc=org" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(uid={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://localhost:389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "inetOrgPerson" # ldap 用户 objectClass 配置
loginId: "uid" # ldap 用户惟一 id,用来作为登录的 id
rdnKey: "uid" # ldap rdn key
userDisplayName: "cn" # ldap 用户名,用来作为显示名
email: "mail" # ldap 邮箱属性
group: # 启用group search,启用后只有特定group的用户可以登录apollo
objectClass: "posixGroup" # 配置groupClassName
groupBase: "ou=group" # group search base
groupSearch: "(&(cn=dev))" # group filter
groupMembership: "memberUid" # group memberShip eg. member or memberUid
```
#### 1.2 配置`startup.sh`
修改`scripts/startup.sh`,指定`spring.profiles.active`为`github,ldap`。
```bash
SERVICE_NAME=apollo-portal
## Adjust log dir if necessary
LOG_DIR=/opt/logs/100003173
## Adjust server port if necessary
SERVER_PORT=8070
export JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=github,ldap"
```
### 2. Active Directory接入方式
#### 2.1 配置`application-ldap.yml`
解压`apollo-portal-x.x.x-github.zip`后,在`config`目录下创建`application-ldap.yml`,内容参考如下([样例](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/config/application-ldap-activedirectory-sample.yml)),相关的内容需要按照具体情况调整:
```yml
spring:
ldap:
base: "dc=example,dc=com"
username: "admin" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(sAMAccountName={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://1.1.1.1:389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "user" # ldap 用户 objectClass 配置
loginId: "sAMAccountName" # ldap 用户惟一 id,用来作为登录的 id
userDisplayName: "cn" # ldap 用户名,用来作为显示名
email: "userPrincipalName" # ldap 邮箱属性
filter: # 可选项,配置过滤,目前只支持 memberOf
memberOf: "CN=ServiceDEV,OU=test,DC=example,DC=com|CN=WebDEV,OU=test,DC=example,DC=com" # 只允许 memberOf 属性为 ServiceDEV 和 WebDEV 的用户访问
```
#### 2.2 配置`startup.sh`
修改`scripts/startup.sh`,指定`spring.profiles.active`为`github,ldap`。
```bash
SERVICE_NAME=apollo-portal
## Adjust log dir if necessary
LOG_DIR=/opt/logs/100003173
## Adjust server port if necessary
SERVER_PORT=8070
export JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=github,ldap"
```
### 3. ApacheDS接入方式
#### 3.1 配置`application-ldap.yml`
解压`apollo-portal-x.x.x-github.zip`后,在`config`目录下创建`application-ldap.yml`,内容参考如下([样例](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/config/application-ldap-apacheds-sample.yml)),相关的内容需要按照具体情况调整:
```yml
spring:
ldap:
base: "dc=example,dc=com"
username: "uid=admin,ou=system" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(uid={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://localhost:10389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "inetOrgPerson" # ldap 用户 objectClass 配置
loginId: "uid" # ldap 用户惟一 id,用来作为登录的 id
userDisplayName: "displayName" # ldap 用户名,用来作为显示名
email: "mail" # ldap 邮箱属性
```
##### 3.1.1 基于Group过滤用户
从1.3.0版本开始支持基于Group过滤用户,从而可以控制只有特定Group的用户可以登录和使用apollo:
```yml
spring:
ldap:
base: "dc=example,dc=com"
username: "uid=admin,ou=system" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(uid={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://localhost:10389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "inetOrgPerson" # ldap 用户 objectClass 配置
loginId: "uid" # ldap 用户惟一 id,用来作为登录的 id
rdnKey: "cn" # ldap rdn key
userDisplayName: "displayName" # ldap 用户名,用来作为显示名
email: "mail" # ldap 邮箱属性
group: # 配置ldap group,启用后只有特定group的用户可以登录apollo
objectClass: "groupOfNames" # 配置groupClassName
groupBase: "ou=group" # group search base
groupSearch: "(&(cn=dev))" # group filter
groupMembership: "member" # group memberShip eg. member or memberUid
```
#### 3.2 配置`startup.sh`
修改`scripts/startup.sh`,指定`spring.profiles.active`为`github,ldap`。
```bash
SERVICE_NAME=apollo-portal
## Adjust log dir if necessary
LOG_DIR=/opt/logs/100003173
## Adjust server port if necessary
SERVER_PORT=8070
export JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=github,ldap"
```
## 实现方式三: 接入OIDC
从 1.8.0 版本开始支持 OpenID Connect 登录, 这种实现方式的前提是已经部署了 OpenID Connect 登录服务
配置前需要准备:
* OpenID Connect 的提供者配置端点(符合 RFC 8414 标准的 issuer-uri), 需要是 **https** 的, 例如 https://host:port/auth/realms/apollo/.well-known/openid-configuration
* 在 OpenID Connect 服务里创建一个 client, idToken 的签名算法必须设置为 **RS256**, 获取 client-id 以及对应的 client-secret
### 1. 配置 `application-oidc.yml`
解压`apollo-portal-x.x.x-github.zip`后,在`config`目录下创建`application-oidc.yml`,内容参考如下([样例](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/config/application-oidc-sample.yml)),相关的内容需要按照具体情况调整:
#### 1.1 最小配置
```yml
spring:
security:
oauth2:
client:
provider:
# provider-name 是 oidc 提供者的名称, 任意字符均可, registration 的配置需要用到这个名称
provider-name:
# 必须是 https, oidc 的 issuer-uri
# 例如 你的 issuer-uri 是 https://host:port/auth/realms/apollo/.well-known/openid-configuration, 那么此处只需要配置 https://host:port/auth/realms/apollo 即可, spring boot 处理的时候会加上 /.well-known/openid-configuration 的后缀
issuer-uri: https://host:port/auth/realms/apollo
registration:
# registration-name 是 oidc 客户端的名称, 任意字符均可, oidc 登录必须配置一个 authorization_code 类型的 registration
registration-name:
# oidc 登录必须配置一个 authorization_code 类型的 registration
authorization-grant-type: authorization_code
client-authentication-method: basic
# client-id 是在 oidc 提供者处配置的客户端ID, 用于登录 provider
client-id: apollo-portal
# provider 的名称, 需要和上面配置的 provider 名称保持一致
provider: provider-name
# openid 为 oidc 登录的必须 scope, 此处可以添加其它自定义的 scope
scope:
- openid
# client-secret 是在 oidc 提供者处配置的客户端密码, 用于登录 provider
# 从安全角度考虑更推荐使用环境变量来配置, 环境变量的命名规则为: 将配置项的 key 当中的 点(.)、横杠(-)替换为下划线(_), 然后将所有字母改为大写, spring boot 会自动处理符合此规则的环境变量
# 例如 spring.security.oauth2.client.registration.registration-name.client-secret -> SPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_NAME_VDISK_CLIENT_SECRET (REGISTRATION_NAME 可以替换为自定义的 oidc 客户端的名称)
client-secret: d43c91c0-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
#### 1.2 扩展配置
* 如果 OpenID Connect 登录服务支持 client_credentials 模式, 还可以再配置一个 client_credentials 类型的 registration, 用于 apollo-portal 作为客户端请求其它被 oidc 保护的资源
* 如果 OpenID Connect 登录服务支持 jwt, 还可以配置 ${spring.security.oauth2.resourceserver.jwt.issuer-uri}, 以支持通过 jwt 访问 apollo-portal
```yml
spring:
security:
oauth2:
client:
provider:
# provider-name 是 oidc 提供者的名称, 任意字符均可, registration 的配置需要用到这个名称
provider-name:
# 必须是 https, oidc 的 issuer-uri, 和 jwt 的 issuer-uri 一致的话直接引用即可, 也可以单独设置
issuer-uri: ${spring.security.oauth2.resourceserver.jwt.issuer-uri}
registration:
# registration-name 是 oidc 客户端的名称, 任意字符均可, oidc 登录必须配置一个 authorization_code 类型的 registration
registration-name:
# oidc 登录必须配置一个 authorization_code 类型的 registration
authorization-grant-type: authorization_code
client-authentication-method: basic
# client-id 是在 oidc 提供者处配置的客户端ID, 用于登录 provider
client-id: apollo-portal
# provider 的名称, 需要和上面配置的 provider 名称保持一致
provider: provider-name
# openid 为 oidc 登录的必须 scope, 此处可以添加其它自定义的 scope
scope:
- openid
# client-secret 是在 oidc 提供者处配置的客户端密码, 用于登录 provider
# 从安全角度考虑更推荐使用环境变量来配置, 环境变量的命名规则为: 将配置项的 key 当中的 点(.)、横杠(-)替换为下划线(_), 然后将所有字母改为大写, spring boot 会自动处理符合此规则的环境变量
# 例如 spring.security.oauth2.client.registration.registration-name.client-secret -> SPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_NAME_VDISK_CLIENT_SECRET (REGISTRATION_NAME 可以替换为自定义的 oidc 客户端的名称)
client-secret: d43c91c0-xxxx-xxxx-xxxx-xxxxxxxxxxxx
# registration-name-client 是 oidc 客户端的名称, 任意字符均可, client_credentials 类型的 registration 为选填项, 可以不配置
registration-name-client:
# client_credentials 类型的 registration 为选填项, 用于 apollo-portal 作为客户端请求其它被 oidc 保护的资源, 可以不配置
authorization-grant-type: client_credentials
client-authentication-method: basic
# client-id 是在 oidc 提供者处配置的客户端ID, 用于登录 provider
client-id: apollo-portal
# provider 的名称, 需要和上面配置的 provider 名称保持一致
provider: provider-name
# openid 为 oidc 登录的必须 scope, 此处可以添加其它自定义的 scope
scope:
- openid
# client-secret 是在 oidc 提供者处配置的客户端密码, 用于登录 provider, 多个 registration 的密码如果一致可以直接引用
client-secret: ${spring.security.oauth2.client.registration.registration-name.client-secret}
resourceserver:
jwt:
# 必须是 https, jwt 的 issuer-uri
# 例如 你的 issuer-uri 是 https://host:port/auth/realms/apollo/.well-known/openid-configuration, 那么此处只需要配置 https://host:port/auth/realms/apollo 即可, spring boot 处理的时候会自动加上 /.well-known/openid-configuration 的后缀
issuer-uri: https://host:port/auth/realms/apollo
```
### 2. 配置 `startup.sh`
修改`scripts/startup.sh`,指定`spring.profiles.active`为`github,oidc`。
```bash
SERVICE_NAME=apollo-portal
## Adjust log dir if necessary
LOG_DIR=/opt/logs/100003173
## Adjust server port if necessary
SERVER_PORT=8070
export JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=github,oidc"
```
## 实现方式四: 接入公司的统一登录认证系统
这种实现方式的前提是公司已经有统一的登录认证系统,最常见的比如SSO、LDAP等。接入时,实现以下SPI。其中UserService和UserInfoHolder是必须要实现的。
接口说明如下:
* UserService(Required):用户服务,用来给Portal提供用户搜索相关功能
* UserInfoHolder(Required):获取当前登录用户信息,SSO一般都是把当前登录用户信息放在线程ThreadLocal上
* LogoutHandler(Optional):用来实现登出功能
* SsoHeartbeatHandler(Optional):Portal页面如果长时间不刷新,登录信息会过期。通过此接口来刷新登录信息
可以参考apollo-portal下的[com.ctrip.framework.apollo.portal.spi](https://github.com/ctripcorp/apollo/tree/master/apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi)这个包下面的四个实现:
1. defaultimpl:默认实现,全局只有apollo一个账号
2. ctrip:ctrip实现,接入了SSO并实现用户搜索、查询接口
3. springsecurity: spring security实现,可以新增用户,修改用户密码等
4. ldap: [@pandalin](https://github.com/pandalin)和[codepiano](https://github.com/codepiano)贡献的ldap实现
实现了相关接口后,可以通过[com.ctrip.framework.apollo.portal.configuration.AuthConfiguration](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/configuration/AuthConfiguration.java)在运行时替换默认的实现。
接入SSO的思路如下:
1. SSO会提供一个jar包,需要配置一个filter
2. filter会拦截所有请求,检查是否已经登录
3. 如果没有登录,那么就会跳转到SSO的登录页面
4. 在SSO登录页面登录成功后,会跳转回apollo的页面,带上认证的信息
5. 再次进入SSO的filter,校验认证信息,把用户的信息保存下来,并且把用户凭证写入cookie或分布式session,以免下次还要重新登录
6. 进入Apollo的代码,Apollo的代码会调用UserInfoHolder.getUser获取当前登录用户
注意,以上1-5这几步都是SSO的代码,不是Apollo的代码,Apollo的代码只需要你实现第6步。
>注:运行时使用不同的实现是通过[Profiles](http://docs.spring.io/autorepo/docs/spring-boot/current/reference/html/boot-features-profiles.html)实现的,比如你自己的sso实现是在`custom` profile中的话,在打包脚本中可以指定-Dapollo_profile=github,custom。其中`github`是Apollo必须的一个profile,用于数据库的配置,`custom`是你自己实现的profile。同时需要注意在[AuthConfiguration](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/configuration/AuthConfiguration.java)中修改默认实现的条件
,从`@ConditionalOnMissingProfile({"ctrip", "auth", "ldap"})`改为`@ConditionalOnMissingProfile({"ctrip", "auth", "ldap", "custom"})`。
| Apollo是配置管理系统,会提供权限管理(Authorization),理论上是不负责用户登录认证功能的实现(Authentication)。
所以Apollo定义了一些SPI用来解耦,Apollo接入登录的关键就是实现这些SPI。
## 实现方式一:使用Apollo提供的Spring Security简单认证
可能很多公司并没有统一的登录认证系统,如果自己实现一套会比较麻烦。Apollo针对这种情况,从0.9.0开始提供了利用Spring Security实现的Http Basic简单认证版本。
使用步骤如下:
### 1. 安装0.9.0以上版本
>如果之前是0.8.0版本,需要导入[apolloportaldb-v080-v090.sql](https://github.com/ctripcorp/apollo/blob/master/scripts/sql/delta/v080-v090/apolloportaldb-v080-v090.sql)
查看ApolloPortalDB,应该已经存在`Users`表,并有一条初始记录。初始用户名是apollo,密码是admin。
|Id|Username|Password|Email|Enabled|
|-|-|-|-|-|
|1|apollo|$2a$10$7r20uS.BQ9uBpf3Baj3uQOZvMVvB1RN3PYoKE94gtz2.WAOuiiwXS|[email protected]|1|
### 2. 重启Portal
如果是IDE启动的话,确保`-Dapollo_profile=github,auth`
### 3. 添加用户
超级管理员登录系统后打开`管理员工具 - 用户管理`即可添加用户。
### 4. 修改用户密码
超级管理员登录系统后打开`管理员工具 - 用户管理`,输入用户名和密码后即可修改用户密码,建议同时修改超级管理员apollo的密码。
## 实现方式二: 接入LDAP
从1.2.0版本开始,Apollo支持了ldap协议的登录,按照如下方式配置即可。
> 如果采用helm chart部署方式,建议通过配置方式实现,不用修改镜像,可以参考[启用 LDAP 支持](zh/deployment/distributed-deployment-guide#_241449-启用-ldap-支持)
### 1. OpenLDAP接入方式
#### 1.1 配置`application-ldap.yml`
解压`apollo-portal-x.x.x-github.zip`后,在`config`目录下创建`application-ldap.yml`,内容参考如下([样例](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/config/application-ldap-openldap-sample.yml)),相关的内容需要按照具体情况调整:
```yml
spring:
ldap:
base: "dc=example,dc=org"
username: "cn=admin,dc=example,dc=org" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(uid={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://localhost:389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "inetOrgPerson" # ldap 用户 objectClass 配置
loginId: "uid" # ldap 用户惟一 id,用来作为登录的 id
userDisplayName: "cn" # ldap 用户名,用来作为显示名
email: "mail" # ldap 邮箱属性
```
##### 1.1.1 基于memberOf过滤用户
OpenLDAP[开启memberOf特性](https://myanbin.github.io/post/enable-memberof-in-openldap.html)后,可以配置filter从而缩小用户搜索的范围:
```yml
spring:
ldap:
base: "dc=example,dc=org"
username: "cn=admin,dc=example,dc=org" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(uid={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://localhost:389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "inetOrgPerson" # ldap 用户 objectClass 配置
loginId: "uid" # ldap 用户惟一 id,用来作为登录的 id
userDisplayName: "cn" # ldap 用户名,用来作为显示名
email: "mail" # ldap 邮箱属性
filter: # 配置过滤,目前只支持 memberOf
memberOf: "cn=ServiceDEV,ou=DEV,dc=example,dc=org|cn=WebDEV,ou=DEV,dc=example,dc=org" # 只允许 memberOf 属性为 ServiceDEV 和 WebDEV 的用户访问
```
##### 1.1.2 基于Group过滤用户
从1.3.0版本开始支持基于Group过滤用户,从而可以控制只有特定Group的用户可以登录和使用apollo:
```yml
spring:
ldap:
base: "dc=example,dc=org"
username: "cn=admin,dc=example,dc=org" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(uid={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://localhost:389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "inetOrgPerson" # ldap 用户 objectClass 配置
loginId: "uid" # ldap 用户惟一 id,用来作为登录的 id
rdnKey: "uid" # ldap rdn key
userDisplayName: "cn" # ldap 用户名,用来作为显示名
email: "mail" # ldap 邮箱属性
group: # 启用group search,启用后只有特定group的用户可以登录apollo
objectClass: "posixGroup" # 配置groupClassName
groupBase: "ou=group" # group search base
groupSearch: "(&(cn=dev))" # group filter
groupMembership: "memberUid" # group memberShip eg. member or memberUid
```
#### 1.2 配置`startup.sh`
修改`scripts/startup.sh`,指定`spring.profiles.active`为`github,ldap`。
```bash
SERVICE_NAME=apollo-portal
## Adjust log dir if necessary
LOG_DIR=/opt/logs/100003173
## Adjust server port if necessary
SERVER_PORT=8070
export JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=github,ldap"
```
### 2. Active Directory接入方式
#### 2.1 配置`application-ldap.yml`
解压`apollo-portal-x.x.x-github.zip`后,在`config`目录下创建`application-ldap.yml`,内容参考如下([样例](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/config/application-ldap-activedirectory-sample.yml)),相关的内容需要按照具体情况调整:
```yml
spring:
ldap:
base: "dc=example,dc=com"
username: "admin" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(sAMAccountName={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://1.1.1.1:389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "user" # ldap 用户 objectClass 配置
loginId: "sAMAccountName" # ldap 用户惟一 id,用来作为登录的 id
userDisplayName: "cn" # ldap 用户名,用来作为显示名
email: "userPrincipalName" # ldap 邮箱属性
filter: # 可选项,配置过滤,目前只支持 memberOf
memberOf: "CN=ServiceDEV,OU=test,DC=example,DC=com|CN=WebDEV,OU=test,DC=example,DC=com" # 只允许 memberOf 属性为 ServiceDEV 和 WebDEV 的用户访问
```
#### 2.2 配置`startup.sh`
修改`scripts/startup.sh`,指定`spring.profiles.active`为`github,ldap`。
```bash
SERVICE_NAME=apollo-portal
## Adjust log dir if necessary
LOG_DIR=/opt/logs/100003173
## Adjust server port if necessary
SERVER_PORT=8070
export JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=github,ldap"
```
### 3. ApacheDS接入方式
#### 3.1 配置`application-ldap.yml`
解压`apollo-portal-x.x.x-github.zip`后,在`config`目录下创建`application-ldap.yml`,内容参考如下([样例](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/config/application-ldap-apacheds-sample.yml)),相关的内容需要按照具体情况调整:
```yml
spring:
ldap:
base: "dc=example,dc=com"
username: "uid=admin,ou=system" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(uid={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://localhost:10389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "inetOrgPerson" # ldap 用户 objectClass 配置
loginId: "uid" # ldap 用户惟一 id,用来作为登录的 id
userDisplayName: "displayName" # ldap 用户名,用来作为显示名
email: "mail" # ldap 邮箱属性
```
##### 3.1.1 基于Group过滤用户
从1.3.0版本开始支持基于Group过滤用户,从而可以控制只有特定Group的用户可以登录和使用apollo:
```yml
spring:
ldap:
base: "dc=example,dc=com"
username: "uid=admin,ou=system" # 配置管理员账号,用于搜索、匹配用户
password: "password"
searchFilter: "(uid={0})" # 用户过滤器,登录的时候用这个过滤器来搜索用户
urls:
- "ldap://localhost:10389"
ldap:
mapping: # 配置 ldap 属性
objectClass: "inetOrgPerson" # ldap 用户 objectClass 配置
loginId: "uid" # ldap 用户惟一 id,用来作为登录的 id
rdnKey: "cn" # ldap rdn key
userDisplayName: "displayName" # ldap 用户名,用来作为显示名
email: "mail" # ldap 邮箱属性
group: # 配置ldap group,启用后只有特定group的用户可以登录apollo
objectClass: "groupOfNames" # 配置groupClassName
groupBase: "ou=group" # group search base
groupSearch: "(&(cn=dev))" # group filter
groupMembership: "member" # group memberShip eg. member or memberUid
```
#### 3.2 配置`startup.sh`
修改`scripts/startup.sh`,指定`spring.profiles.active`为`github,ldap`。
```bash
SERVICE_NAME=apollo-portal
## Adjust log dir if necessary
LOG_DIR=/opt/logs/100003173
## Adjust server port if necessary
SERVER_PORT=8070
export JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=github,ldap"
```
## 实现方式三: 接入OIDC
从 1.8.0 版本开始支持 OpenID Connect 登录, 这种实现方式的前提是已经部署了 OpenID Connect 登录服务
配置前需要准备:
* OpenID Connect 的提供者配置端点(符合 RFC 8414 标准的 issuer-uri), 需要是 **https** 的, 例如 https://host:port/auth/realms/apollo/.well-known/openid-configuration
* 在 OpenID Connect 服务里创建一个 client, idToken 的签名算法必须设置为 **RS256**, 获取 client-id 以及对应的 client-secret
### 1. 配置 `application-oidc.yml`
解压`apollo-portal-x.x.x-github.zip`后,在`config`目录下创建`application-oidc.yml`,内容参考如下([样例](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/config/application-oidc-sample.yml)),相关的内容需要按照具体情况调整:
#### 1.1 最小配置
```yml
spring:
security:
oauth2:
client:
provider:
# provider-name 是 oidc 提供者的名称, 任意字符均可, registration 的配置需要用到这个名称
provider-name:
# 必须是 https, oidc 的 issuer-uri
# 例如 你的 issuer-uri 是 https://host:port/auth/realms/apollo/.well-known/openid-configuration, 那么此处只需要配置 https://host:port/auth/realms/apollo 即可, spring boot 处理的时候会加上 /.well-known/openid-configuration 的后缀
issuer-uri: https://host:port/auth/realms/apollo
registration:
# registration-name 是 oidc 客户端的名称, 任意字符均可, oidc 登录必须配置一个 authorization_code 类型的 registration
registration-name:
# oidc 登录必须配置一个 authorization_code 类型的 registration
authorization-grant-type: authorization_code
client-authentication-method: basic
# client-id 是在 oidc 提供者处配置的客户端ID, 用于登录 provider
client-id: apollo-portal
# provider 的名称, 需要和上面配置的 provider 名称保持一致
provider: provider-name
# openid 为 oidc 登录的必须 scope, 此处可以添加其它自定义的 scope
scope:
- openid
# client-secret 是在 oidc 提供者处配置的客户端密码, 用于登录 provider
# 从安全角度考虑更推荐使用环境变量来配置, 环境变量的命名规则为: 将配置项的 key 当中的 点(.)、横杠(-)替换为下划线(_), 然后将所有字母改为大写, spring boot 会自动处理符合此规则的环境变量
# 例如 spring.security.oauth2.client.registration.registration-name.client-secret -> SPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_NAME_VDISK_CLIENT_SECRET (REGISTRATION_NAME 可以替换为自定义的 oidc 客户端的名称)
client-secret: d43c91c0-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
#### 1.2 扩展配置
* 如果 OpenID Connect 登录服务支持 client_credentials 模式, 还可以再配置一个 client_credentials 类型的 registration, 用于 apollo-portal 作为客户端请求其它被 oidc 保护的资源
* 如果 OpenID Connect 登录服务支持 jwt, 还可以配置 ${spring.security.oauth2.resourceserver.jwt.issuer-uri}, 以支持通过 jwt 访问 apollo-portal
```yml
spring:
security:
oauth2:
client:
provider:
# provider-name 是 oidc 提供者的名称, 任意字符均可, registration 的配置需要用到这个名称
provider-name:
# 必须是 https, oidc 的 issuer-uri, 和 jwt 的 issuer-uri 一致的话直接引用即可, 也可以单独设置
issuer-uri: ${spring.security.oauth2.resourceserver.jwt.issuer-uri}
registration:
# registration-name 是 oidc 客户端的名称, 任意字符均可, oidc 登录必须配置一个 authorization_code 类型的 registration
registration-name:
# oidc 登录必须配置一个 authorization_code 类型的 registration
authorization-grant-type: authorization_code
client-authentication-method: basic
# client-id 是在 oidc 提供者处配置的客户端ID, 用于登录 provider
client-id: apollo-portal
# provider 的名称, 需要和上面配置的 provider 名称保持一致
provider: provider-name
# openid 为 oidc 登录的必须 scope, 此处可以添加其它自定义的 scope
scope:
- openid
# client-secret 是在 oidc 提供者处配置的客户端密码, 用于登录 provider
# 从安全角度考虑更推荐使用环境变量来配置, 环境变量的命名规则为: 将配置项的 key 当中的 点(.)、横杠(-)替换为下划线(_), 然后将所有字母改为大写, spring boot 会自动处理符合此规则的环境变量
# 例如 spring.security.oauth2.client.registration.registration-name.client-secret -> SPRING_SECURITY_OAUTH2_CLIENT_REGISTRATION_NAME_VDISK_CLIENT_SECRET (REGISTRATION_NAME 可以替换为自定义的 oidc 客户端的名称)
client-secret: d43c91c0-xxxx-xxxx-xxxx-xxxxxxxxxxxx
# registration-name-client 是 oidc 客户端的名称, 任意字符均可, client_credentials 类型的 registration 为选填项, 可以不配置
registration-name-client:
# client_credentials 类型的 registration 为选填项, 用于 apollo-portal 作为客户端请求其它被 oidc 保护的资源, 可以不配置
authorization-grant-type: client_credentials
client-authentication-method: basic
# client-id 是在 oidc 提供者处配置的客户端ID, 用于登录 provider
client-id: apollo-portal
# provider 的名称, 需要和上面配置的 provider 名称保持一致
provider: provider-name
# openid 为 oidc 登录的必须 scope, 此处可以添加其它自定义的 scope
scope:
- openid
# client-secret 是在 oidc 提供者处配置的客户端密码, 用于登录 provider, 多个 registration 的密码如果一致可以直接引用
client-secret: ${spring.security.oauth2.client.registration.registration-name.client-secret}
resourceserver:
jwt:
# 必须是 https, jwt 的 issuer-uri
# 例如 你的 issuer-uri 是 https://host:port/auth/realms/apollo/.well-known/openid-configuration, 那么此处只需要配置 https://host:port/auth/realms/apollo 即可, spring boot 处理的时候会自动加上 /.well-known/openid-configuration 的后缀
issuer-uri: https://host:port/auth/realms/apollo
```
### 2. 配置 `startup.sh`
修改`scripts/startup.sh`,指定`spring.profiles.active`为`github,oidc`。
```bash
SERVICE_NAME=apollo-portal
## Adjust log dir if necessary
LOG_DIR=/opt/logs/100003173
## Adjust server port if necessary
SERVER_PORT=8070
export JAVA_OPTS="$JAVA_OPTS -Dspring.profiles.active=github,oidc"
```
## 实现方式四: 接入公司的统一登录认证系统
这种实现方式的前提是公司已经有统一的登录认证系统,最常见的比如SSO、LDAP等。接入时,实现以下SPI。其中UserService和UserInfoHolder是必须要实现的。
接口说明如下:
* UserService(Required):用户服务,用来给Portal提供用户搜索相关功能
* UserInfoHolder(Required):获取当前登录用户信息,SSO一般都是把当前登录用户信息放在线程ThreadLocal上
* LogoutHandler(Optional):用来实现登出功能
* SsoHeartbeatHandler(Optional):Portal页面如果长时间不刷新,登录信息会过期。通过此接口来刷新登录信息
可以参考apollo-portal下的[com.ctrip.framework.apollo.portal.spi](https://github.com/ctripcorp/apollo/tree/master/apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi)这个包下面的四个实现:
1. defaultimpl:默认实现,全局只有apollo一个账号
2. ctrip:ctrip实现,接入了SSO并实现用户搜索、查询接口
3. springsecurity: spring security实现,可以新增用户,修改用户密码等
4. ldap: [@pandalin](https://github.com/pandalin)和[codepiano](https://github.com/codepiano)贡献的ldap实现
实现了相关接口后,可以通过[com.ctrip.framework.apollo.portal.configuration.AuthConfiguration](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/configuration/AuthConfiguration.java)在运行时替换默认的实现。
接入SSO的思路如下:
1. SSO会提供一个jar包,需要配置一个filter
2. filter会拦截所有请求,检查是否已经登录
3. 如果没有登录,那么就会跳转到SSO的登录页面
4. 在SSO登录页面登录成功后,会跳转回apollo的页面,带上认证的信息
5. 再次进入SSO的filter,校验认证信息,把用户的信息保存下来,并且把用户凭证写入cookie或分布式session,以免下次还要重新登录
6. 进入Apollo的代码,Apollo的代码会调用UserInfoHolder.getUser获取当前登录用户
注意,以上1-5这几步都是SSO的代码,不是Apollo的代码,Apollo的代码只需要你实现第6步。
>注:运行时使用不同的实现是通过[Profiles](http://docs.spring.io/autorepo/docs/spring-boot/current/reference/html/boot-features-profiles.html)实现的,比如你自己的sso实现是在`custom` profile中的话,在打包脚本中可以指定-Dapollo_profile=github,custom。其中`github`是Apollo必须的一个profile,用于数据库的配置,`custom`是你自己实现的profile。同时需要注意在[AuthConfiguration](https://github.com/ctripcorp/apollo/blob/master/apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/configuration/AuthConfiguration.java)中修改默认实现的条件
,从`@ConditionalOnMissingProfile({"ctrip", "auth", "ldap"})`改为`@ConditionalOnMissingProfile({"ctrip", "auth", "ldap", "custom"})`。
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloProcessor.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.util.ReflectionUtils;
/**
* Create by zhangzheng on 2018/2/6
*/
public abstract class ApolloProcessor implements BeanPostProcessor, PriorityOrdered {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
Class clazz = bean.getClass();
for (Field field : findAllField(clazz)) {
processField(bean, beanName, field);
}
for (Method method : findAllMethod(clazz)) {
processMethod(bean, beanName, method);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* subclass should implement this method to process field
*/
protected abstract void processField(Object bean, String beanName, Field field);
/**
* subclass should implement this method to process method
*/
protected abstract void processMethod(Object bean, String beanName, Method method);
@Override
public int getOrder() {
//make it as late as possible
return Ordered.LOWEST_PRECEDENCE;
}
private List<Field> findAllField(Class clazz) {
final List<Field> res = new LinkedList<>();
ReflectionUtils.doWithFields(clazz, new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
res.add(field);
}
});
return res;
}
private List<Method> findAllMethod(Class clazz) {
final List<Method> res = new LinkedList<>();
ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
res.add(method);
}
});
return res;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.util.ReflectionUtils;
/**
* Create by zhangzheng on 2018/2/6
*/
public abstract class ApolloProcessor implements BeanPostProcessor, PriorityOrdered {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
Class clazz = bean.getClass();
for (Field field : findAllField(clazz)) {
processField(bean, beanName, field);
}
for (Method method : findAllMethod(clazz)) {
processMethod(bean, beanName, method);
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
/**
* subclass should implement this method to process field
*/
protected abstract void processField(Object bean, String beanName, Field field);
/**
* subclass should implement this method to process method
*/
protected abstract void processMethod(Object bean, String beanName, Method method);
@Override
public int getOrder() {
//make it as late as possible
return Ordered.LOWEST_PRECEDENCE;
}
private List<Field> findAllField(Class clazz) {
final List<Field> res = new LinkedList<>();
ReflectionUtils.doWithFields(clazz, new ReflectionUtils.FieldCallback() {
@Override
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
res.add(field);
}
});
return res;
}
private List<Method> findAllMethod(Class clazz) {
final List<Method> res = new LinkedList<>();
ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
res.add(method);
}
});
return res;
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloConfig.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ctrip.framework.apollo.core.ConfigConsts;
/**
* Use this annotation to inject Apollo Config Instance.
*
* <p>Usage example:</p>
* <pre class="code">
* //Inject the config for "someNamespace"
* @ApolloConfig("someNamespace")
* private Config config;
* </pre>
*
* <p>Usage example with placeholder:</p>
* <pre class="code">
* // The namespace could also be specified as a placeholder, e.g. ${redis.namespace:xxx},
* // which will use the value of the key "redis.namespace" or "xxx" if this key is not configured.
* @ApolloConfig("${redis.namespace:xxx}")
* private Config config;
* </pre>
*
*
* @author Jason Song([email protected])
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface ApolloConfig {
/**
* Apollo namespace for the config, if not specified then default to application
*/
String value() default ConfigConsts.NAMESPACE_APPLICATION;
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.ctrip.framework.apollo.core.ConfigConsts;
/**
* Use this annotation to inject Apollo Config Instance.
*
* <p>Usage example:</p>
* <pre class="code">
* //Inject the config for "someNamespace"
* @ApolloConfig("someNamespace")
* private Config config;
* </pre>
*
* <p>Usage example with placeholder:</p>
* <pre class="code">
* // The namespace could also be specified as a placeholder, e.g. ${redis.namespace:xxx},
* // which will use the value of the key "redis.namespace" or "xxx" if this key is not configured.
* @ApolloConfig("${redis.namespace:xxx}")
* private Config config;
* </pre>
*
*
* @author Jason Song([email protected])
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface ApolloConfig {
/**
* Apollo namespace for the config, if not specified then default to application
*/
String value() default ConfigConsts.NAMESPACE_APPLICATION;
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-adminservice/src/main/java/com/ctrip/framework/apollo/adminservice/aop/PreAcquireNamespaceLock.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.adminservice.aop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 标识方法需要获取到namespace的lock才能执行
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PreAcquireNamespaceLock {
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.adminservice.aop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 标识方法需要获取到namespace的lock才能执行
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PreAcquireNamespaceLock {
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-configservice/src/test/java/com/ctrip/framework/apollo/configservice/controller/ConfigFileControllerTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.controller;
import com.ctrip.framework.apollo.biz.entity.ReleaseMessage;
import com.ctrip.framework.apollo.biz.grayReleaseRule.GrayReleaseRulesHolder;
import com.ctrip.framework.apollo.biz.message.Topics;
import com.ctrip.framework.apollo.configservice.util.NamespaceUtil;
import com.ctrip.framework.apollo.configservice.util.WatchKeysUtil;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.google.common.cache.Cache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Jason Song([email protected])
*/
@RunWith(MockitoJUnitRunner.class)
public class ConfigFileControllerTest {
@Mock
private ConfigController configController;
@Mock
private WatchKeysUtil watchKeysUtil;
@Mock
private NamespaceUtil namespaceUtil;
@Mock
private GrayReleaseRulesHolder grayReleaseRulesHolder;
private ConfigFileController configFileController;
private String someAppId;
private String someClusterName;
private String someNamespace;
private String someDataCenter;
private String someClientIp;
@Mock
private HttpServletResponse someResponse;
@Mock
private HttpServletRequest someRequest;
Multimap<String, String> watchedKeys2CacheKey;
Multimap<String, String> cacheKey2WatchedKeys;
private static final Gson GSON = new Gson();
@Before
public void setUp() throws Exception {
configFileController = new ConfigFileController(
configController, namespaceUtil, watchKeysUtil, grayReleaseRulesHolder
);
someAppId = "someAppId";
someClusterName = "someClusterName";
someNamespace = "someNamespace";
someDataCenter = "someDataCenter";
someClientIp = "10.1.1.1";
when(namespaceUtil.filterNamespaceName(someNamespace)).thenReturn(someNamespace);
when(namespaceUtil.normalizeNamespace(someAppId, someNamespace)).thenReturn(someNamespace);
when(grayReleaseRulesHolder.hasGrayReleaseRule(anyString(), anyString(), anyString()))
.thenReturn(false);
watchedKeys2CacheKey =
(Multimap<String, String>) ReflectionTestUtils
.getField(configFileController, "watchedKeys2CacheKey");
cacheKey2WatchedKeys =
(Multimap<String, String>) ReflectionTestUtils
.getField(configFileController, "cacheKey2WatchedKeys");
}
@Test
public void testQueryConfigAsProperties() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
String anotherKey = "anotherKey";
String anotherValue = "anotherValue";
String someWatchKey = "someWatchKey";
String anotherWatchKey = "anotherWatchKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey, anotherWatchKey);
String cacheKey =
configFileController
.assembleCacheKey(ConfigFileController.ConfigFileOutputFormat.PROPERTIES, someAppId, someClusterName, someNamespace, someDataCenter);
Map<String, String> configurations =
ImmutableMap.of(someKey, someValue, anotherKey, anotherValue);
ApolloConfig someApolloConfig = mock(ApolloConfig.class);
when(someApolloConfig.getConfigurations()).thenReturn(configurations);
when(configController
.queryConfig(someAppId, someClusterName, someNamespace, someDataCenter, "-1", someClientIp, null,
someRequest, someResponse)).thenReturn(someApolloConfig);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someClusterName, someNamespace, someDataCenter))
.thenReturn(watchKeys);
ResponseEntity<String> response =
configFileController
.queryConfigAsProperties(someAppId, someClusterName, someNamespace, someDataCenter,
someClientIp, someRequest, someResponse);
assertEquals(2, watchedKeys2CacheKey.size());
assertEquals(2, cacheKey2WatchedKeys.size());
assertTrue(watchedKeys2CacheKey.containsEntry(someWatchKey, cacheKey));
assertTrue(watchedKeys2CacheKey.containsEntry(anotherWatchKey, cacheKey));
assertTrue(cacheKey2WatchedKeys.containsEntry(cacheKey, someWatchKey));
assertTrue(cacheKey2WatchedKeys.containsEntry(cacheKey, anotherWatchKey));
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(response.getBody().contains(String.format("%s=%s", someKey, someValue)));
assertTrue(response.getBody().contains(String.format("%s=%s", anotherKey, anotherValue)));
ResponseEntity<String> anotherResponse =
configFileController
.queryConfigAsProperties(someAppId, someClusterName, someNamespace, someDataCenter,
someClientIp, someRequest, someResponse);
assertEquals(response, anotherResponse);
verify(configController, times(1))
.queryConfig(someAppId, someClusterName, someNamespace, someDataCenter, "-1", someClientIp, null,
someRequest, someResponse);
}
@Test
public void testQueryConfigAsJson() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
Type responseType = new TypeToken<Map<String, String>>(){}.getType();
String someWatchKey = "someWatchKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey);
Map<String, String> configurations =
ImmutableMap.of(someKey, someValue);
ApolloConfig someApolloConfig = mock(ApolloConfig.class);
when(configController
.queryConfig(someAppId, someClusterName, someNamespace, someDataCenter, "-1", someClientIp, null,
someRequest, someResponse)).thenReturn(someApolloConfig);
when(someApolloConfig.getConfigurations()).thenReturn(configurations);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someClusterName, someNamespace, someDataCenter))
.thenReturn(watchKeys);
ResponseEntity<String> response =
configFileController
.queryConfigAsJson(someAppId, someClusterName, someNamespace, someDataCenter,
someClientIp, someRequest, someResponse);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(configurations, GSON.fromJson(response.getBody(), responseType));
}
@Test
public void testQueryConfigWithGrayRelease() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
Type responseType = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> configurations =
ImmutableMap.of(someKey, someValue);
when(grayReleaseRulesHolder.hasGrayReleaseRule(someAppId, someClientIp, someNamespace))
.thenReturn(true);
ApolloConfig someApolloConfig = mock(ApolloConfig.class);
when(someApolloConfig.getConfigurations()).thenReturn(configurations);
when(configController
.queryConfig(someAppId, someClusterName, someNamespace, someDataCenter, "-1", someClientIp, null,
someRequest, someResponse)).thenReturn(someApolloConfig);
ResponseEntity<String> response =
configFileController
.queryConfigAsJson(someAppId, someClusterName, someNamespace, someDataCenter,
someClientIp, someRequest, someResponse);
ResponseEntity<String> anotherResponse =
configFileController
.queryConfigAsJson(someAppId, someClusterName, someNamespace, someDataCenter,
someClientIp, someRequest, someResponse);
verify(configController, times(2))
.queryConfig(someAppId, someClusterName, someNamespace, someDataCenter, "-1", someClientIp, null,
someRequest, someResponse);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(configurations, GSON.fromJson(response.getBody(), responseType));
assertTrue(watchedKeys2CacheKey.isEmpty());
assertTrue(cacheKey2WatchedKeys.isEmpty());
}
@Test
public void testHandleMessage() throws Exception {
String someWatchKey = "someWatchKey";
String anotherWatchKey = "anotherWatchKey";
String someCacheKey = "someCacheKey";
String anotherCacheKey = "anotherCacheKey";
String someValue = "someValue";
ReleaseMessage someReleaseMessage = mock(ReleaseMessage.class);
when(someReleaseMessage.getMessage()).thenReturn(someWatchKey);
Cache<String, String> cache =
(Cache<String, String>) ReflectionTestUtils.getField(configFileController, "localCache");
cache.put(someCacheKey, someValue);
cache.put(anotherCacheKey, someValue);
watchedKeys2CacheKey.putAll(someWatchKey, Lists.newArrayList(someCacheKey, anotherCacheKey));
watchedKeys2CacheKey.putAll(anotherWatchKey, Lists.newArrayList(someCacheKey, anotherCacheKey));
cacheKey2WatchedKeys.putAll(someCacheKey, Lists.newArrayList(someWatchKey, anotherWatchKey));
cacheKey2WatchedKeys.putAll(anotherCacheKey, Lists.newArrayList(someWatchKey, anotherWatchKey));
configFileController.handleMessage(someReleaseMessage, Topics.APOLLO_RELEASE_TOPIC);
assertTrue(watchedKeys2CacheKey.isEmpty());
assertTrue(cacheKey2WatchedKeys.isEmpty());
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.controller;
import com.ctrip.framework.apollo.biz.entity.ReleaseMessage;
import com.ctrip.framework.apollo.biz.grayReleaseRule.GrayReleaseRulesHolder;
import com.ctrip.framework.apollo.biz.message.Topics;
import com.ctrip.framework.apollo.configservice.util.NamespaceUtil;
import com.ctrip.framework.apollo.configservice.util.WatchKeysUtil;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.google.common.cache.Cache;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Sets;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.util.ReflectionTestUtils;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* @author Jason Song([email protected])
*/
@RunWith(MockitoJUnitRunner.class)
public class ConfigFileControllerTest {
@Mock
private ConfigController configController;
@Mock
private WatchKeysUtil watchKeysUtil;
@Mock
private NamespaceUtil namespaceUtil;
@Mock
private GrayReleaseRulesHolder grayReleaseRulesHolder;
private ConfigFileController configFileController;
private String someAppId;
private String someClusterName;
private String someNamespace;
private String someDataCenter;
private String someClientIp;
@Mock
private HttpServletResponse someResponse;
@Mock
private HttpServletRequest someRequest;
Multimap<String, String> watchedKeys2CacheKey;
Multimap<String, String> cacheKey2WatchedKeys;
private static final Gson GSON = new Gson();
@Before
public void setUp() throws Exception {
configFileController = new ConfigFileController(
configController, namespaceUtil, watchKeysUtil, grayReleaseRulesHolder
);
someAppId = "someAppId";
someClusterName = "someClusterName";
someNamespace = "someNamespace";
someDataCenter = "someDataCenter";
someClientIp = "10.1.1.1";
when(namespaceUtil.filterNamespaceName(someNamespace)).thenReturn(someNamespace);
when(namespaceUtil.normalizeNamespace(someAppId, someNamespace)).thenReturn(someNamespace);
when(grayReleaseRulesHolder.hasGrayReleaseRule(anyString(), anyString(), anyString()))
.thenReturn(false);
watchedKeys2CacheKey =
(Multimap<String, String>) ReflectionTestUtils
.getField(configFileController, "watchedKeys2CacheKey");
cacheKey2WatchedKeys =
(Multimap<String, String>) ReflectionTestUtils
.getField(configFileController, "cacheKey2WatchedKeys");
}
@Test
public void testQueryConfigAsProperties() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
String anotherKey = "anotherKey";
String anotherValue = "anotherValue";
String someWatchKey = "someWatchKey";
String anotherWatchKey = "anotherWatchKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey, anotherWatchKey);
String cacheKey =
configFileController
.assembleCacheKey(ConfigFileController.ConfigFileOutputFormat.PROPERTIES, someAppId, someClusterName, someNamespace, someDataCenter);
Map<String, String> configurations =
ImmutableMap.of(someKey, someValue, anotherKey, anotherValue);
ApolloConfig someApolloConfig = mock(ApolloConfig.class);
when(someApolloConfig.getConfigurations()).thenReturn(configurations);
when(configController
.queryConfig(someAppId, someClusterName, someNamespace, someDataCenter, "-1", someClientIp, null,
someRequest, someResponse)).thenReturn(someApolloConfig);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someClusterName, someNamespace, someDataCenter))
.thenReturn(watchKeys);
ResponseEntity<String> response =
configFileController
.queryConfigAsProperties(someAppId, someClusterName, someNamespace, someDataCenter,
someClientIp, someRequest, someResponse);
assertEquals(2, watchedKeys2CacheKey.size());
assertEquals(2, cacheKey2WatchedKeys.size());
assertTrue(watchedKeys2CacheKey.containsEntry(someWatchKey, cacheKey));
assertTrue(watchedKeys2CacheKey.containsEntry(anotherWatchKey, cacheKey));
assertTrue(cacheKey2WatchedKeys.containsEntry(cacheKey, someWatchKey));
assertTrue(cacheKey2WatchedKeys.containsEntry(cacheKey, anotherWatchKey));
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(response.getBody().contains(String.format("%s=%s", someKey, someValue)));
assertTrue(response.getBody().contains(String.format("%s=%s", anotherKey, anotherValue)));
ResponseEntity<String> anotherResponse =
configFileController
.queryConfigAsProperties(someAppId, someClusterName, someNamespace, someDataCenter,
someClientIp, someRequest, someResponse);
assertEquals(response, anotherResponse);
verify(configController, times(1))
.queryConfig(someAppId, someClusterName, someNamespace, someDataCenter, "-1", someClientIp, null,
someRequest, someResponse);
}
@Test
public void testQueryConfigAsJson() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
Type responseType = new TypeToken<Map<String, String>>(){}.getType();
String someWatchKey = "someWatchKey";
Set<String> watchKeys = Sets.newHashSet(someWatchKey);
Map<String, String> configurations =
ImmutableMap.of(someKey, someValue);
ApolloConfig someApolloConfig = mock(ApolloConfig.class);
when(configController
.queryConfig(someAppId, someClusterName, someNamespace, someDataCenter, "-1", someClientIp, null,
someRequest, someResponse)).thenReturn(someApolloConfig);
when(someApolloConfig.getConfigurations()).thenReturn(configurations);
when(watchKeysUtil
.assembleAllWatchKeys(someAppId, someClusterName, someNamespace, someDataCenter))
.thenReturn(watchKeys);
ResponseEntity<String> response =
configFileController
.queryConfigAsJson(someAppId, someClusterName, someNamespace, someDataCenter,
someClientIp, someRequest, someResponse);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(configurations, GSON.fromJson(response.getBody(), responseType));
}
@Test
public void testQueryConfigWithGrayRelease() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
Type responseType = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> configurations =
ImmutableMap.of(someKey, someValue);
when(grayReleaseRulesHolder.hasGrayReleaseRule(someAppId, someClientIp, someNamespace))
.thenReturn(true);
ApolloConfig someApolloConfig = mock(ApolloConfig.class);
when(someApolloConfig.getConfigurations()).thenReturn(configurations);
when(configController
.queryConfig(someAppId, someClusterName, someNamespace, someDataCenter, "-1", someClientIp, null,
someRequest, someResponse)).thenReturn(someApolloConfig);
ResponseEntity<String> response =
configFileController
.queryConfigAsJson(someAppId, someClusterName, someNamespace, someDataCenter,
someClientIp, someRequest, someResponse);
ResponseEntity<String> anotherResponse =
configFileController
.queryConfigAsJson(someAppId, someClusterName, someNamespace, someDataCenter,
someClientIp, someRequest, someResponse);
verify(configController, times(2))
.queryConfig(someAppId, someClusterName, someNamespace, someDataCenter, "-1", someClientIp, null,
someRequest, someResponse);
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(configurations, GSON.fromJson(response.getBody(), responseType));
assertTrue(watchedKeys2CacheKey.isEmpty());
assertTrue(cacheKey2WatchedKeys.isEmpty());
}
@Test
public void testHandleMessage() throws Exception {
String someWatchKey = "someWatchKey";
String anotherWatchKey = "anotherWatchKey";
String someCacheKey = "someCacheKey";
String anotherCacheKey = "anotherCacheKey";
String someValue = "someValue";
ReleaseMessage someReleaseMessage = mock(ReleaseMessage.class);
when(someReleaseMessage.getMessage()).thenReturn(someWatchKey);
Cache<String, String> cache =
(Cache<String, String>) ReflectionTestUtils.getField(configFileController, "localCache");
cache.put(someCacheKey, someValue);
cache.put(anotherCacheKey, someValue);
watchedKeys2CacheKey.putAll(someWatchKey, Lists.newArrayList(someCacheKey, anotherCacheKey));
watchedKeys2CacheKey.putAll(anotherWatchKey, Lists.newArrayList(someCacheKey, anotherCacheKey));
cacheKey2WatchedKeys.putAll(someCacheKey, Lists.newArrayList(someWatchKey, anotherWatchKey));
cacheKey2WatchedKeys.putAll(anotherCacheKey, Lists.newArrayList(someWatchKey, anotherWatchKey));
configFileController.handleMessage(someReleaseMessage, Topics.APOLLO_RELEASE_TOPIC);
assertTrue(watchedKeys2CacheKey.isEmpty());
assertTrue(cacheKey2WatchedKeys.isEmpty());
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/PlaceholderHelper.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.property;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import java.util.Set;
import java.util.Stack;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.util.StringUtils;
/**
* Placeholder helper functions.
*/
public class PlaceholderHelper {
private static final String PLACEHOLDER_PREFIX = "${";
private static final String PLACEHOLDER_SUFFIX = "}";
private static final String VALUE_SEPARATOR = ":";
private static final String SIMPLE_PLACEHOLDER_PREFIX = "{";
private static final String EXPRESSION_PREFIX = "#{";
private static final String EXPRESSION_SUFFIX = "}";
/**
* Resolve placeholder property values, e.g.
* <br />
* <br />
* "${somePropertyValue}" -> "the actual property value"
*/
public Object resolvePropertyValue(ConfigurableBeanFactory beanFactory, String beanName, String placeholder) {
// resolve string value
String strVal = beanFactory.resolveEmbeddedValue(placeholder);
BeanDefinition bd = (beanFactory.containsBean(beanName) ? beanFactory
.getMergedBeanDefinition(beanName) : null);
// resolve expressions like "#{systemProperties.myProp}"
return evaluateBeanDefinitionString(beanFactory, strVal, bd);
}
private Object evaluateBeanDefinitionString(ConfigurableBeanFactory beanFactory, String value,
BeanDefinition beanDefinition) {
if (beanFactory.getBeanExpressionResolver() == null) {
return value;
}
Scope scope = (beanDefinition != null ? beanFactory
.getRegisteredScope(beanDefinition.getScope()) : null);
return beanFactory.getBeanExpressionResolver()
.evaluate(value, new BeanExpressionContext(beanFactory, scope));
}
/**
* Extract keys from placeholder, e.g.
* <ul>
* <li>${some.key} => "some.key"</li>
* <li>${some.key:${some.other.key:100}} => "some.key", "some.other.key"</li>
* <li>${${some.key}} => "some.key"</li>
* <li>${${some.key:other.key}} => "some.key"</li>
* <li>${${some.key}:${another.key}} => "some.key", "another.key"</li>
* <li>#{new java.text.SimpleDateFormat('${some.key}').parse('${another.key}')} => "some.key", "another.key"</li>
* </ul>
*/
public Set<String> extractPlaceholderKeys(String propertyString) {
Set<String> placeholderKeys = Sets.newHashSet();
if (Strings.isNullOrEmpty(propertyString) || (!isNormalizedPlaceholder(propertyString) && !isExpressionWithPlaceholder(propertyString))) {
return placeholderKeys;
}
Stack<String> stack = new Stack<>();
stack.push(propertyString);
while (!stack.isEmpty()) {
String strVal = stack.pop();
int startIndex = strVal.indexOf(PLACEHOLDER_PREFIX);
if (startIndex == -1) {
placeholderKeys.add(strVal);
continue;
}
int endIndex = findPlaceholderEndIndex(strVal, startIndex);
if (endIndex == -1) {
// invalid placeholder?
continue;
}
String placeholderCandidate = strVal.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex);
// ${some.key:other.key}
if (placeholderCandidate.startsWith(PLACEHOLDER_PREFIX)) {
stack.push(placeholderCandidate);
} else {
// some.key:${some.other.key:100}
int separatorIndex = placeholderCandidate.indexOf(VALUE_SEPARATOR);
if (separatorIndex == -1) {
stack.push(placeholderCandidate);
} else {
stack.push(placeholderCandidate.substring(0, separatorIndex));
String defaultValuePart =
normalizeToPlaceholder(placeholderCandidate.substring(separatorIndex + VALUE_SEPARATOR.length()));
if (!Strings.isNullOrEmpty(defaultValuePart)) {
stack.push(defaultValuePart);
}
}
}
// has remaining part, e.g. ${a}.${b}
if (endIndex + PLACEHOLDER_SUFFIX.length() < strVal.length() - 1) {
String remainingPart = normalizeToPlaceholder(strVal.substring(endIndex + PLACEHOLDER_SUFFIX.length()));
if (!Strings.isNullOrEmpty(remainingPart)) {
stack.push(remainingPart);
}
}
}
return placeholderKeys;
}
private boolean isNormalizedPlaceholder(String propertyString) {
return propertyString.startsWith(PLACEHOLDER_PREFIX) && propertyString.contains(PLACEHOLDER_SUFFIX);
}
private boolean isExpressionWithPlaceholder(String propertyString) {
return propertyString.startsWith(EXPRESSION_PREFIX) && propertyString.contains(EXPRESSION_SUFFIX)
&& propertyString.contains(PLACEHOLDER_PREFIX) && propertyString.contains(PLACEHOLDER_SUFFIX);
}
private String normalizeToPlaceholder(String strVal) {
int startIndex = strVal.indexOf(PLACEHOLDER_PREFIX);
if (startIndex == -1) {
return null;
}
int endIndex = strVal.lastIndexOf(PLACEHOLDER_SUFFIX);
if (endIndex == -1) {
return null;
}
return strVal.substring(startIndex, endIndex + PLACEHOLDER_SUFFIX.length());
}
private int findPlaceholderEndIndex(CharSequence buf, int startIndex) {
int index = startIndex + PLACEHOLDER_PREFIX.length();
int withinNestedPlaceholder = 0;
while (index < buf.length()) {
if (StringUtils.substringMatch(buf, index, PLACEHOLDER_SUFFIX)) {
if (withinNestedPlaceholder > 0) {
withinNestedPlaceholder--;
index = index + PLACEHOLDER_SUFFIX.length();
} else {
return index;
}
} else if (StringUtils.substringMatch(buf, index, SIMPLE_PLACEHOLDER_PREFIX)) {
withinNestedPlaceholder++;
index = index + SIMPLE_PLACEHOLDER_PREFIX.length();
} else {
index++;
}
}
return -1;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.spring.property;
import com.google.common.base.Strings;
import com.google.common.collect.Sets;
import java.util.Set;
import java.util.Stack;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.util.StringUtils;
/**
* Placeholder helper functions.
*/
public class PlaceholderHelper {
private static final String PLACEHOLDER_PREFIX = "${";
private static final String PLACEHOLDER_SUFFIX = "}";
private static final String VALUE_SEPARATOR = ":";
private static final String SIMPLE_PLACEHOLDER_PREFIX = "{";
private static final String EXPRESSION_PREFIX = "#{";
private static final String EXPRESSION_SUFFIX = "}";
/**
* Resolve placeholder property values, e.g.
* <br />
* <br />
* "${somePropertyValue}" -> "the actual property value"
*/
public Object resolvePropertyValue(ConfigurableBeanFactory beanFactory, String beanName, String placeholder) {
// resolve string value
String strVal = beanFactory.resolveEmbeddedValue(placeholder);
BeanDefinition bd = (beanFactory.containsBean(beanName) ? beanFactory
.getMergedBeanDefinition(beanName) : null);
// resolve expressions like "#{systemProperties.myProp}"
return evaluateBeanDefinitionString(beanFactory, strVal, bd);
}
private Object evaluateBeanDefinitionString(ConfigurableBeanFactory beanFactory, String value,
BeanDefinition beanDefinition) {
if (beanFactory.getBeanExpressionResolver() == null) {
return value;
}
Scope scope = (beanDefinition != null ? beanFactory
.getRegisteredScope(beanDefinition.getScope()) : null);
return beanFactory.getBeanExpressionResolver()
.evaluate(value, new BeanExpressionContext(beanFactory, scope));
}
/**
* Extract keys from placeholder, e.g.
* <ul>
* <li>${some.key} => "some.key"</li>
* <li>${some.key:${some.other.key:100}} => "some.key", "some.other.key"</li>
* <li>${${some.key}} => "some.key"</li>
* <li>${${some.key:other.key}} => "some.key"</li>
* <li>${${some.key}:${another.key}} => "some.key", "another.key"</li>
* <li>#{new java.text.SimpleDateFormat('${some.key}').parse('${another.key}')} => "some.key", "another.key"</li>
* </ul>
*/
public Set<String> extractPlaceholderKeys(String propertyString) {
Set<String> placeholderKeys = Sets.newHashSet();
if (Strings.isNullOrEmpty(propertyString) || (!isNormalizedPlaceholder(propertyString) && !isExpressionWithPlaceholder(propertyString))) {
return placeholderKeys;
}
Stack<String> stack = new Stack<>();
stack.push(propertyString);
while (!stack.isEmpty()) {
String strVal = stack.pop();
int startIndex = strVal.indexOf(PLACEHOLDER_PREFIX);
if (startIndex == -1) {
placeholderKeys.add(strVal);
continue;
}
int endIndex = findPlaceholderEndIndex(strVal, startIndex);
if (endIndex == -1) {
// invalid placeholder?
continue;
}
String placeholderCandidate = strVal.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex);
// ${some.key:other.key}
if (placeholderCandidate.startsWith(PLACEHOLDER_PREFIX)) {
stack.push(placeholderCandidate);
} else {
// some.key:${some.other.key:100}
int separatorIndex = placeholderCandidate.indexOf(VALUE_SEPARATOR);
if (separatorIndex == -1) {
stack.push(placeholderCandidate);
} else {
stack.push(placeholderCandidate.substring(0, separatorIndex));
String defaultValuePart =
normalizeToPlaceholder(placeholderCandidate.substring(separatorIndex + VALUE_SEPARATOR.length()));
if (!Strings.isNullOrEmpty(defaultValuePart)) {
stack.push(defaultValuePart);
}
}
}
// has remaining part, e.g. ${a}.${b}
if (endIndex + PLACEHOLDER_SUFFIX.length() < strVal.length() - 1) {
String remainingPart = normalizeToPlaceholder(strVal.substring(endIndex + PLACEHOLDER_SUFFIX.length()));
if (!Strings.isNullOrEmpty(remainingPart)) {
stack.push(remainingPart);
}
}
}
return placeholderKeys;
}
private boolean isNormalizedPlaceholder(String propertyString) {
return propertyString.startsWith(PLACEHOLDER_PREFIX) && propertyString.contains(PLACEHOLDER_SUFFIX);
}
private boolean isExpressionWithPlaceholder(String propertyString) {
return propertyString.startsWith(EXPRESSION_PREFIX) && propertyString.contains(EXPRESSION_SUFFIX)
&& propertyString.contains(PLACEHOLDER_PREFIX) && propertyString.contains(PLACEHOLDER_SUFFIX);
}
private String normalizeToPlaceholder(String strVal) {
int startIndex = strVal.indexOf(PLACEHOLDER_PREFIX);
if (startIndex == -1) {
return null;
}
int endIndex = strVal.lastIndexOf(PLACEHOLDER_SUFFIX);
if (endIndex == -1) {
return null;
}
return strVal.substring(startIndex, endIndex + PLACEHOLDER_SUFFIX.length());
}
private int findPlaceholderEndIndex(CharSequence buf, int startIndex) {
int index = startIndex + PLACEHOLDER_PREFIX.length();
int withinNestedPlaceholder = 0;
while (index < buf.length()) {
if (StringUtils.substringMatch(buf, index, PLACEHOLDER_SUFFIX)) {
if (withinNestedPlaceholder > 0) {
withinNestedPlaceholder--;
index = index + PLACEHOLDER_SUFFIX.length();
} else {
return index;
}
} else if (StringUtils.substringMatch(buf, index, SIMPLE_PLACEHOLDER_PREFIX)) {
withinNestedPlaceholder++;
index = index + SIMPLE_PLACEHOLDER_PREFIX.length();
} else {
index++;
}
}
return -1;
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-client/src/test/java/com/ctrip/framework/apollo/integration/ConfigIntegrationTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.integration;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.ctrip.framework.apollo.util.OrderedProperties;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
import com.ctrip.framework.apollo.BaseIntegrationTest;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification;
import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil;
import com.ctrip.framework.apollo.internals.RemoteConfigLongPollService;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.SettableFuture;
/**
* @author Jason Song([email protected])
*/
public class ConfigIntegrationTest extends BaseIntegrationTest {
private String someReleaseKey;
private File configDir;
private String defaultNamespace;
private String someOtherNamespace;
private RemoteConfigLongPollService remoteConfigLongPollService;
@Before
public void setUp() throws Exception {
super.setUp();
defaultNamespace = ConfigConsts.NAMESPACE_APPLICATION;
someOtherNamespace = "someOtherNamespace";
someReleaseKey = "1";
configDir = new File(ClassLoaderUtil.getClassPath() + "config-cache");
if (configDir.exists()) {
configDir.delete();
}
configDir.mkdirs();
remoteConfigLongPollService = ApolloInjector.getInstance(RemoteConfigLongPollService.class);
}
@Override
@After
public void tearDown() throws Exception {
ReflectionTestUtils.invokeMethod(remoteConfigLongPollService, "stopLongPollingRefresh");
recursiveDelete(configDir);
super.tearDown();
}
private void recursiveDelete(File file) {
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
for (File f : file.listFiles()) {
recursiveDelete(f);
}
}
try {
Files.deleteIfExists(file.toPath());
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testGetConfigWithNoLocalFileButWithRemoteConfig() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
String someNonExistedKey = "someNonExistedKey";
String someDefaultValue = "someDefaultValue";
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.of(someKey, someValue));
ContextHandler handler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
assertEquals(someValue, config.getProperty(someKey, null));
assertEquals(someDefaultValue, config.getProperty(someNonExistedKey, someDefaultValue));
}
@Test
public void testOrderGetConfigWithNoLocalFileButWithRemoteConfig() throws Exception {
setPropertiesOrderEnabled(true);
String someKey1 = "someKey1";
String someValue1 = "someValue1";
String someKey2 = "someKey2";
String someValue2 = "someValue2";
Map<String, String> configurations = new LinkedHashMap<>();
configurations.put(someKey1, someValue1);
configurations.put(someKey2, someValue2);
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.copyOf(configurations));
ContextHandler handler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
Set<String> propertyNames = config.getPropertyNames();
Iterator<String> it = propertyNames.iterator();
assertEquals(someKey1, it.next());
assertEquals(someKey2, it.next());
}
@Test
public void testGetConfigWithLocalFileAndWithRemoteConfig() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
String anotherValue = "anotherValue";
Properties properties = new Properties();
properties.put(someKey, someValue);
createLocalCachePropertyFile(properties);
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.of(someKey, anotherValue));
ContextHandler handler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
assertEquals(anotherValue, config.getProperty(someKey, null));
}
@Test
public void testOrderGetConfigWithLocalFileAndWithRemoteConfig() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
String anotherValue = "anotherValue";
String someKey1 = "someKey1";
String someValue1 = "someValue1";
String anotherValue1 = "anotherValue1";
String someKey2 = "someKey2";
String someValue2 = "someValue2";
setPropertiesOrderEnabled(true);
Properties properties = new OrderedProperties();
properties.put(someKey, someValue);
properties.put(someKey1, someValue1);
properties.put(someKey2, someValue2);
createLocalCachePropertyFile(properties);
Map<String, String> configurations = new LinkedHashMap<>();
configurations.put(someKey, anotherValue);
configurations.put(someKey1, anotherValue1);
configurations.put(someKey2, someValue2);
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.copyOf(configurations));
ContextHandler handler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
assertEquals(anotherValue, config.getProperty(someKey, null));
Set<String> propertyNames = config.getPropertyNames();
Iterator<String> it = propertyNames.iterator();
assertEquals(someKey, it.next());
assertEquals(someKey1, it.next());
assertEquals(someKey2, it.next());
assertEquals(anotherValue1, config.getProperty(someKey1, ""));
}
@Test
public void testGetConfigWithNoLocalFileAndRemoteConfigError() throws Exception {
ContextHandler handler =
mockConfigServerHandler(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
String someKey = "someKey";
String someDefaultValue = "defaultValue" + Math.random();
assertEquals(someDefaultValue, config.getProperty(someKey, someDefaultValue));
}
@Test
public void testGetConfigWithLocalFileAndRemoteConfigError() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
Properties properties = new Properties();
properties.put(someKey, someValue);
createLocalCachePropertyFile(properties);
ContextHandler handler =
mockConfigServerHandler(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
assertEquals(someValue, config.getProperty(someKey, null));
}
@Test
public void testOrderGetConfigWithLocalFileAndRemoteConfigError() throws Exception {
String someKey1 = "someKey1";
String someValue1 = "someValue1";
String someKey2 = "someKey2";
String someValue2 = "someValue2";
setPropertiesOrderEnabled(true);
Properties properties = new OrderedProperties();
properties.put(someKey1, someValue1);
properties.put(someKey2, someValue2);
createLocalCachePropertyFile(properties);
ContextHandler handler =
mockConfigServerHandler(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
assertEquals(someValue1, config.getProperty(someKey1, null));
assertEquals(someValue2, config.getProperty(someKey2, null));
Set<String> propertyNames = config.getPropertyNames();
Iterator<String> it = propertyNames.iterator();
assertEquals(someKey1, it.next());
assertEquals(someKey2, it.next());
}
@Test
public void testGetConfigWithNoLocalFileAndRemoteMetaServiceRetry() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.of(someKey, someValue));
ContextHandler configHandler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
boolean failAtFirstTime = true;
ContextHandler metaServerHandler = mockMetaServerHandler(failAtFirstTime);
startServerWithHandlers(metaServerHandler, configHandler);
Config config = ConfigService.getAppConfig();
assertEquals(someValue, config.getProperty(someKey, null));
}
@Test
public void testGetConfigWithNoLocalFileAndRemoteConfigServiceRetry() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.of(someKey, someValue));
boolean failedAtFirstTime = true;
ContextHandler handler =
mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig, failedAtFirstTime);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
assertEquals(someValue, config.getProperty(someKey, null));
}
@Test
public void testRefreshConfig() throws Exception {
final String someKey = "someKey";
final String someValue = "someValue";
final String anotherValue = "anotherValue";
int someRefreshInterval = 500;
TimeUnit someRefreshTimeUnit = TimeUnit.MILLISECONDS;
setRefreshInterval(someRefreshInterval);
setRefreshTimeUnit(someRefreshTimeUnit);
Map<String, String> configurations = Maps.newHashMap();
configurations.put(someKey, someValue);
ApolloConfig apolloConfig = assembleApolloConfig(configurations);
ContextHandler handler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
final List<ConfigChangeEvent> changeEvents = Lists.newArrayList();
final SettableFuture<Boolean> refreshFinished = SettableFuture.create();
config.addChangeListener(new ConfigChangeListener() {
AtomicInteger counter = new AtomicInteger(0);
@Override
public void onChange(ConfigChangeEvent changeEvent) {
//only need to assert once
if (counter.incrementAndGet() > 1) {
return;
}
assertEquals(1, changeEvent.changedKeys().size());
assertTrue(changeEvent.isChanged(someKey));
assertEquals(someValue, changeEvent.getChange(someKey).getOldValue());
assertEquals(anotherValue, changeEvent.getChange(someKey).getNewValue());
// if there is any assertion failed above, this line won't be executed
changeEvents.add(changeEvent);
refreshFinished.set(true);
}
});
apolloConfig.getConfigurations().put(someKey, anotherValue);
refreshFinished.get(someRefreshInterval * 5, someRefreshTimeUnit);
assertThat(
"Change event's size should equal to one or there must be some assertion failed in change listener",
1, equalTo(changeEvents.size()));
assertEquals(anotherValue, config.getProperty(someKey, null));
}
@Test
public void testLongPollRefresh() throws Exception {
final String someKey = "someKey";
final String someValue = "someValue";
final String anotherValue = "anotherValue";
long someNotificationId = 1;
long pollTimeoutInMS = 50;
Map<String, String> configurations = Maps.newHashMap();
configurations.put(someKey, someValue);
ApolloConfig apolloConfig = assembleApolloConfig(configurations);
ContextHandler configHandler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
ContextHandler pollHandler =
mockPollNotificationHandler(pollTimeoutInMS, HttpServletResponse.SC_OK,
Lists.newArrayList(
new ApolloConfigNotification(apolloConfig.getNamespaceName(), someNotificationId)),
false);
startServerWithHandlers(configHandler, pollHandler);
Config config = ConfigService.getAppConfig();
assertEquals(someValue, config.getProperty(someKey, null));
final SettableFuture<Boolean> longPollFinished = SettableFuture.create();
config.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
longPollFinished.set(true);
}
});
apolloConfig.getConfigurations().put(someKey, anotherValue);
longPollFinished.get(pollTimeoutInMS * 20, TimeUnit.MILLISECONDS);
assertEquals(anotherValue, config.getProperty(someKey, null));
}
@Test
public void testLongPollRefreshWithMultipleNamespacesAndOnlyOneNamespaceNotified()
throws Exception {
final String someKey = "someKey";
final String someValue = "someValue";
final String anotherValue = "anotherValue";
long someNotificationId = 1;
long pollTimeoutInMS = 50;
Map<String, String> configurations = Maps.newHashMap();
configurations.put(someKey, someValue);
ApolloConfig apolloConfig = assembleApolloConfig(configurations);
ContextHandler configHandler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
ContextHandler pollHandler =
mockPollNotificationHandler(pollTimeoutInMS, HttpServletResponse.SC_OK,
Lists.newArrayList(
new ApolloConfigNotification(apolloConfig.getNamespaceName(), someNotificationId)),
false);
startServerWithHandlers(configHandler, pollHandler);
Config someOtherConfig = ConfigService.getConfig(someOtherNamespace);
Config config = ConfigService.getAppConfig();
assertEquals(someValue, config.getProperty(someKey, null));
assertEquals(someValue, someOtherConfig.getProperty(someKey, null));
final SettableFuture<Boolean> longPollFinished = SettableFuture.create();
config.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
longPollFinished.set(true);
}
});
apolloConfig.getConfigurations().put(someKey, anotherValue);
longPollFinished.get(5000, TimeUnit.MILLISECONDS);
assertEquals(anotherValue, config.getProperty(someKey, null));
TimeUnit.MILLISECONDS.sleep(pollTimeoutInMS * 10);
assertEquals(someValue, someOtherConfig.getProperty(someKey, null));
}
@Test
public void testLongPollRefreshWithMultipleNamespacesAndMultipleNamespaceNotified()
throws Exception {
final String someKey = "someKey";
final String someValue = "someValue";
final String anotherValue = "anotherValue";
long someNotificationId = 1;
long pollTimeoutInMS = 50;
Map<String, String> configurations = Maps.newHashMap();
configurations.put(someKey, someValue);
ApolloConfig apolloConfig = assembleApolloConfig(configurations);
ContextHandler configHandler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
ContextHandler pollHandler =
mockPollNotificationHandler(pollTimeoutInMS, HttpServletResponse.SC_OK,
Lists.newArrayList(
new ApolloConfigNotification(apolloConfig.getNamespaceName(), someNotificationId),
new ApolloConfigNotification(someOtherNamespace, someNotificationId)),
false);
startServerWithHandlers(configHandler, pollHandler);
Config config = ConfigService.getAppConfig();
Config someOtherConfig = ConfigService.getConfig(someOtherNamespace);
assertEquals(someValue, config.getProperty(someKey, null));
assertEquals(someValue, someOtherConfig.getProperty(someKey, null));
final SettableFuture<Boolean> longPollFinished = SettableFuture.create();
final SettableFuture<Boolean> someOtherNamespacelongPollFinished = SettableFuture.create();
config.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
longPollFinished.set(true);
}
});
someOtherConfig.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
someOtherNamespacelongPollFinished.set(true);
}
});
apolloConfig.getConfigurations().put(someKey, anotherValue);
longPollFinished.get(5000, TimeUnit.MILLISECONDS);
someOtherNamespacelongPollFinished.get(5000, TimeUnit.MILLISECONDS);
assertEquals(anotherValue, config.getProperty(someKey, null));
assertEquals(anotherValue, someOtherConfig.getProperty(someKey, null));
}
private ContextHandler mockPollNotificationHandler(final long pollResultTimeOutInMS,
final int statusCode,
final List<ApolloConfigNotification> result,
final boolean failedAtFirstTime) {
ContextHandler context = new ContextHandler("/notifications/v2");
context.setHandler(new AbstractHandler() {
AtomicInteger counter = new AtomicInteger(0);
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
if (failedAtFirstTime && counter.incrementAndGet() == 1) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
baseRequest.setHandled(true);
return;
}
try {
TimeUnit.MILLISECONDS.sleep(pollResultTimeOutInMS);
} catch (InterruptedException e) {
}
response.setContentType("application/json;charset=UTF-8");
response.setStatus(statusCode);
response.getWriter().println(gson.toJson(result));
baseRequest.setHandled(true);
}
});
return context;
}
private ContextHandler mockConfigServerHandler(final int statusCode, final ApolloConfig result,
final boolean failedAtFirstTime) {
ContextHandler context = new ContextHandler("/configs/*");
context.setHandler(new AbstractHandler() {
AtomicInteger counter = new AtomicInteger(0);
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
if (failedAtFirstTime && counter.incrementAndGet() == 1) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
baseRequest.setHandled(true);
return;
}
response.setContentType("application/json;charset=UTF-8");
response.setStatus(statusCode);
response.getWriter().println(gson.toJson(result));
baseRequest.setHandled(true);
}
});
return context;
}
private ContextHandler mockConfigServerHandler(int statusCode, ApolloConfig result) {
return mockConfigServerHandler(statusCode, result, false);
}
private ApolloConfig assembleApolloConfig(Map<String, String> configurations) {
ApolloConfig apolloConfig =
new ApolloConfig(someAppId, someClusterName, defaultNamespace, someReleaseKey);
apolloConfig.setConfigurations(configurations);
return apolloConfig;
}
private File createLocalCachePropertyFile(Properties properties) throws IOException {
File file = new File(configDir, assembleLocalCacheFileName());
try (FileOutputStream in = new FileOutputStream(file)) {
properties.store(in, "Persisted by ConfigIntegrationTest");
}
return file;
}
private String assembleLocalCacheFileName() {
return String.format("%s.properties", Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR)
.join(someAppId, someClusterName, defaultNamespace));
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.integration;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import com.ctrip.framework.apollo.util.OrderedProperties;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;
import com.ctrip.framework.apollo.BaseIntegrationTest;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification;
import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil;
import com.ctrip.framework.apollo.internals.RemoteConfigLongPollService;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.SettableFuture;
/**
* @author Jason Song([email protected])
*/
public class ConfigIntegrationTest extends BaseIntegrationTest {
private String someReleaseKey;
private File configDir;
private String defaultNamespace;
private String someOtherNamespace;
private RemoteConfigLongPollService remoteConfigLongPollService;
@Before
public void setUp() throws Exception {
super.setUp();
defaultNamespace = ConfigConsts.NAMESPACE_APPLICATION;
someOtherNamespace = "someOtherNamespace";
someReleaseKey = "1";
configDir = new File(ClassLoaderUtil.getClassPath() + "config-cache");
if (configDir.exists()) {
configDir.delete();
}
configDir.mkdirs();
remoteConfigLongPollService = ApolloInjector.getInstance(RemoteConfigLongPollService.class);
}
@Override
@After
public void tearDown() throws Exception {
ReflectionTestUtils.invokeMethod(remoteConfigLongPollService, "stopLongPollingRefresh");
recursiveDelete(configDir);
super.tearDown();
}
private void recursiveDelete(File file) {
if (!file.exists()) {
return;
}
if (file.isDirectory()) {
for (File f : file.listFiles()) {
recursiveDelete(f);
}
}
try {
Files.deleteIfExists(file.toPath());
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testGetConfigWithNoLocalFileButWithRemoteConfig() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
String someNonExistedKey = "someNonExistedKey";
String someDefaultValue = "someDefaultValue";
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.of(someKey, someValue));
ContextHandler handler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
assertEquals(someValue, config.getProperty(someKey, null));
assertEquals(someDefaultValue, config.getProperty(someNonExistedKey, someDefaultValue));
}
@Test
public void testOrderGetConfigWithNoLocalFileButWithRemoteConfig() throws Exception {
setPropertiesOrderEnabled(true);
String someKey1 = "someKey1";
String someValue1 = "someValue1";
String someKey2 = "someKey2";
String someValue2 = "someValue2";
Map<String, String> configurations = new LinkedHashMap<>();
configurations.put(someKey1, someValue1);
configurations.put(someKey2, someValue2);
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.copyOf(configurations));
ContextHandler handler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
Set<String> propertyNames = config.getPropertyNames();
Iterator<String> it = propertyNames.iterator();
assertEquals(someKey1, it.next());
assertEquals(someKey2, it.next());
}
@Test
public void testGetConfigWithLocalFileAndWithRemoteConfig() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
String anotherValue = "anotherValue";
Properties properties = new Properties();
properties.put(someKey, someValue);
createLocalCachePropertyFile(properties);
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.of(someKey, anotherValue));
ContextHandler handler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
assertEquals(anotherValue, config.getProperty(someKey, null));
}
@Test
public void testOrderGetConfigWithLocalFileAndWithRemoteConfig() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
String anotherValue = "anotherValue";
String someKey1 = "someKey1";
String someValue1 = "someValue1";
String anotherValue1 = "anotherValue1";
String someKey2 = "someKey2";
String someValue2 = "someValue2";
setPropertiesOrderEnabled(true);
Properties properties = new OrderedProperties();
properties.put(someKey, someValue);
properties.put(someKey1, someValue1);
properties.put(someKey2, someValue2);
createLocalCachePropertyFile(properties);
Map<String, String> configurations = new LinkedHashMap<>();
configurations.put(someKey, anotherValue);
configurations.put(someKey1, anotherValue1);
configurations.put(someKey2, someValue2);
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.copyOf(configurations));
ContextHandler handler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
assertEquals(anotherValue, config.getProperty(someKey, null));
Set<String> propertyNames = config.getPropertyNames();
Iterator<String> it = propertyNames.iterator();
assertEquals(someKey, it.next());
assertEquals(someKey1, it.next());
assertEquals(someKey2, it.next());
assertEquals(anotherValue1, config.getProperty(someKey1, ""));
}
@Test
public void testGetConfigWithNoLocalFileAndRemoteConfigError() throws Exception {
ContextHandler handler =
mockConfigServerHandler(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
String someKey = "someKey";
String someDefaultValue = "defaultValue" + Math.random();
assertEquals(someDefaultValue, config.getProperty(someKey, someDefaultValue));
}
@Test
public void testGetConfigWithLocalFileAndRemoteConfigError() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
Properties properties = new Properties();
properties.put(someKey, someValue);
createLocalCachePropertyFile(properties);
ContextHandler handler =
mockConfigServerHandler(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
assertEquals(someValue, config.getProperty(someKey, null));
}
@Test
public void testOrderGetConfigWithLocalFileAndRemoteConfigError() throws Exception {
String someKey1 = "someKey1";
String someValue1 = "someValue1";
String someKey2 = "someKey2";
String someValue2 = "someValue2";
setPropertiesOrderEnabled(true);
Properties properties = new OrderedProperties();
properties.put(someKey1, someValue1);
properties.put(someKey2, someValue2);
createLocalCachePropertyFile(properties);
ContextHandler handler =
mockConfigServerHandler(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
assertEquals(someValue1, config.getProperty(someKey1, null));
assertEquals(someValue2, config.getProperty(someKey2, null));
Set<String> propertyNames = config.getPropertyNames();
Iterator<String> it = propertyNames.iterator();
assertEquals(someKey1, it.next());
assertEquals(someKey2, it.next());
}
@Test
public void testGetConfigWithNoLocalFileAndRemoteMetaServiceRetry() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.of(someKey, someValue));
ContextHandler configHandler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
boolean failAtFirstTime = true;
ContextHandler metaServerHandler = mockMetaServerHandler(failAtFirstTime);
startServerWithHandlers(metaServerHandler, configHandler);
Config config = ConfigService.getAppConfig();
assertEquals(someValue, config.getProperty(someKey, null));
}
@Test
public void testGetConfigWithNoLocalFileAndRemoteConfigServiceRetry() throws Exception {
String someKey = "someKey";
String someValue = "someValue";
ApolloConfig apolloConfig = assembleApolloConfig(ImmutableMap.of(someKey, someValue));
boolean failedAtFirstTime = true;
ContextHandler handler =
mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig, failedAtFirstTime);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
assertEquals(someValue, config.getProperty(someKey, null));
}
@Test
public void testRefreshConfig() throws Exception {
final String someKey = "someKey";
final String someValue = "someValue";
final String anotherValue = "anotherValue";
int someRefreshInterval = 500;
TimeUnit someRefreshTimeUnit = TimeUnit.MILLISECONDS;
setRefreshInterval(someRefreshInterval);
setRefreshTimeUnit(someRefreshTimeUnit);
Map<String, String> configurations = Maps.newHashMap();
configurations.put(someKey, someValue);
ApolloConfig apolloConfig = assembleApolloConfig(configurations);
ContextHandler handler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
startServerWithHandlers(handler);
Config config = ConfigService.getAppConfig();
final List<ConfigChangeEvent> changeEvents = Lists.newArrayList();
final SettableFuture<Boolean> refreshFinished = SettableFuture.create();
config.addChangeListener(new ConfigChangeListener() {
AtomicInteger counter = new AtomicInteger(0);
@Override
public void onChange(ConfigChangeEvent changeEvent) {
//only need to assert once
if (counter.incrementAndGet() > 1) {
return;
}
assertEquals(1, changeEvent.changedKeys().size());
assertTrue(changeEvent.isChanged(someKey));
assertEquals(someValue, changeEvent.getChange(someKey).getOldValue());
assertEquals(anotherValue, changeEvent.getChange(someKey).getNewValue());
// if there is any assertion failed above, this line won't be executed
changeEvents.add(changeEvent);
refreshFinished.set(true);
}
});
apolloConfig.getConfigurations().put(someKey, anotherValue);
refreshFinished.get(someRefreshInterval * 5, someRefreshTimeUnit);
assertThat(
"Change event's size should equal to one or there must be some assertion failed in change listener",
1, equalTo(changeEvents.size()));
assertEquals(anotherValue, config.getProperty(someKey, null));
}
@Test
public void testLongPollRefresh() throws Exception {
final String someKey = "someKey";
final String someValue = "someValue";
final String anotherValue = "anotherValue";
long someNotificationId = 1;
long pollTimeoutInMS = 50;
Map<String, String> configurations = Maps.newHashMap();
configurations.put(someKey, someValue);
ApolloConfig apolloConfig = assembleApolloConfig(configurations);
ContextHandler configHandler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
ContextHandler pollHandler =
mockPollNotificationHandler(pollTimeoutInMS, HttpServletResponse.SC_OK,
Lists.newArrayList(
new ApolloConfigNotification(apolloConfig.getNamespaceName(), someNotificationId)),
false);
startServerWithHandlers(configHandler, pollHandler);
Config config = ConfigService.getAppConfig();
assertEquals(someValue, config.getProperty(someKey, null));
final SettableFuture<Boolean> longPollFinished = SettableFuture.create();
config.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
longPollFinished.set(true);
}
});
apolloConfig.getConfigurations().put(someKey, anotherValue);
longPollFinished.get(pollTimeoutInMS * 20, TimeUnit.MILLISECONDS);
assertEquals(anotherValue, config.getProperty(someKey, null));
}
@Test
public void testLongPollRefreshWithMultipleNamespacesAndOnlyOneNamespaceNotified()
throws Exception {
final String someKey = "someKey";
final String someValue = "someValue";
final String anotherValue = "anotherValue";
long someNotificationId = 1;
long pollTimeoutInMS = 50;
Map<String, String> configurations = Maps.newHashMap();
configurations.put(someKey, someValue);
ApolloConfig apolloConfig = assembleApolloConfig(configurations);
ContextHandler configHandler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
ContextHandler pollHandler =
mockPollNotificationHandler(pollTimeoutInMS, HttpServletResponse.SC_OK,
Lists.newArrayList(
new ApolloConfigNotification(apolloConfig.getNamespaceName(), someNotificationId)),
false);
startServerWithHandlers(configHandler, pollHandler);
Config someOtherConfig = ConfigService.getConfig(someOtherNamespace);
Config config = ConfigService.getAppConfig();
assertEquals(someValue, config.getProperty(someKey, null));
assertEquals(someValue, someOtherConfig.getProperty(someKey, null));
final SettableFuture<Boolean> longPollFinished = SettableFuture.create();
config.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
longPollFinished.set(true);
}
});
apolloConfig.getConfigurations().put(someKey, anotherValue);
longPollFinished.get(5000, TimeUnit.MILLISECONDS);
assertEquals(anotherValue, config.getProperty(someKey, null));
TimeUnit.MILLISECONDS.sleep(pollTimeoutInMS * 10);
assertEquals(someValue, someOtherConfig.getProperty(someKey, null));
}
@Test
public void testLongPollRefreshWithMultipleNamespacesAndMultipleNamespaceNotified()
throws Exception {
final String someKey = "someKey";
final String someValue = "someValue";
final String anotherValue = "anotherValue";
long someNotificationId = 1;
long pollTimeoutInMS = 50;
Map<String, String> configurations = Maps.newHashMap();
configurations.put(someKey, someValue);
ApolloConfig apolloConfig = assembleApolloConfig(configurations);
ContextHandler configHandler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
ContextHandler pollHandler =
mockPollNotificationHandler(pollTimeoutInMS, HttpServletResponse.SC_OK,
Lists.newArrayList(
new ApolloConfigNotification(apolloConfig.getNamespaceName(), someNotificationId),
new ApolloConfigNotification(someOtherNamespace, someNotificationId)),
false);
startServerWithHandlers(configHandler, pollHandler);
Config config = ConfigService.getAppConfig();
Config someOtherConfig = ConfigService.getConfig(someOtherNamespace);
assertEquals(someValue, config.getProperty(someKey, null));
assertEquals(someValue, someOtherConfig.getProperty(someKey, null));
final SettableFuture<Boolean> longPollFinished = SettableFuture.create();
final SettableFuture<Boolean> someOtherNamespacelongPollFinished = SettableFuture.create();
config.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
longPollFinished.set(true);
}
});
someOtherConfig.addChangeListener(new ConfigChangeListener() {
@Override
public void onChange(ConfigChangeEvent changeEvent) {
someOtherNamespacelongPollFinished.set(true);
}
});
apolloConfig.getConfigurations().put(someKey, anotherValue);
longPollFinished.get(5000, TimeUnit.MILLISECONDS);
someOtherNamespacelongPollFinished.get(5000, TimeUnit.MILLISECONDS);
assertEquals(anotherValue, config.getProperty(someKey, null));
assertEquals(anotherValue, someOtherConfig.getProperty(someKey, null));
}
private ContextHandler mockPollNotificationHandler(final long pollResultTimeOutInMS,
final int statusCode,
final List<ApolloConfigNotification> result,
final boolean failedAtFirstTime) {
ContextHandler context = new ContextHandler("/notifications/v2");
context.setHandler(new AbstractHandler() {
AtomicInteger counter = new AtomicInteger(0);
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
if (failedAtFirstTime && counter.incrementAndGet() == 1) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
baseRequest.setHandled(true);
return;
}
try {
TimeUnit.MILLISECONDS.sleep(pollResultTimeOutInMS);
} catch (InterruptedException e) {
}
response.setContentType("application/json;charset=UTF-8");
response.setStatus(statusCode);
response.getWriter().println(gson.toJson(result));
baseRequest.setHandled(true);
}
});
return context;
}
private ContextHandler mockConfigServerHandler(final int statusCode, final ApolloConfig result,
final boolean failedAtFirstTime) {
ContextHandler context = new ContextHandler("/configs/*");
context.setHandler(new AbstractHandler() {
AtomicInteger counter = new AtomicInteger(0);
@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
if (failedAtFirstTime && counter.incrementAndGet() == 1) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
baseRequest.setHandled(true);
return;
}
response.setContentType("application/json;charset=UTF-8");
response.setStatus(statusCode);
response.getWriter().println(gson.toJson(result));
baseRequest.setHandled(true);
}
});
return context;
}
private ContextHandler mockConfigServerHandler(int statusCode, ApolloConfig result) {
return mockConfigServerHandler(statusCode, result, false);
}
private ApolloConfig assembleApolloConfig(Map<String, String> configurations) {
ApolloConfig apolloConfig =
new ApolloConfig(someAppId, someClusterName, defaultNamespace, someReleaseKey);
apolloConfig.setConfigurations(configurations);
return apolloConfig;
}
private File createLocalCachePropertyFile(Properties properties) throws IOException {
File file = new File(configDir, assembleLocalCacheFileName());
try (FileOutputStream in = new FileOutputStream(file)) {
properties.store(in, "Persisted by ConfigIntegrationTest");
}
return file;
}
private String assembleLocalCacheFileName() {
return String.format("%s.properties", Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR)
.join(someAppId, someClusterName, defaultNamespace));
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-client/src/main/resources/META-INF/apollo-1.0.0.xsd | <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<xsd:schema xmlns="http://www.ctrip.com/schema/apollo"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.ctrip.com/schema/apollo"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xsd:annotation>
<xsd:documentation><![CDATA[ Namespace support for Ctrip Apollo Configuration Center. ]]></xsd:documentation>
</xsd:annotation>
<xsd:element name="config">
<xsd:annotation>
<xsd:documentation>
<![CDATA[ Apollo configuration section to integrate with Spring.]]>
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:attribute name="namespaces" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:documentation>
<![CDATA[
The comma-separated list of namespace names to integrate with Spring property sources.
If not specified, then default to application namespace.
]]>
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="order" type="xsd:int" use="optional">
<xsd:annotation>
<xsd:documentation>
<![CDATA[
The order of the config, default to Ordered.LOWEST_PRECEDENCE, which is Integer.MAX_VALUE.
If there are properties with the same name in different apollo configs, the config with smaller order wins.
]]>
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
</xsd:complexType>
</xsd:element>
</xsd:schema> | <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<xsd:schema xmlns="http://www.ctrip.com/schema/apollo"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.ctrip.com/schema/apollo"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xsd:annotation>
<xsd:documentation><![CDATA[ Namespace support for Ctrip Apollo Configuration Center. ]]></xsd:documentation>
</xsd:annotation>
<xsd:element name="config">
<xsd:annotation>
<xsd:documentation>
<![CDATA[ Apollo configuration section to integrate with Spring.]]>
</xsd:documentation>
</xsd:annotation>
<xsd:complexType>
<xsd:attribute name="namespaces" type="xsd:string" use="optional">
<xsd:annotation>
<xsd:documentation>
<![CDATA[
The comma-separated list of namespace names to integrate with Spring property sources.
If not specified, then default to application namespace.
]]>
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
<xsd:attribute name="order" type="xsd:int" use="optional">
<xsd:annotation>
<xsd:documentation>
<![CDATA[
The order of the config, default to Ordered.LOWEST_PRECEDENCE, which is Integer.MAX_VALUE.
If there are properties with the same name in different apollo configs, the config with smaller order wins.
]]>
</xsd:documentation>
</xsd:annotation>
</xsd:attribute>
</xsd:complexType>
</xsd:element>
</xsd:schema> | -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-portal/src/main/resources/logback.xml | <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<property name="LOG_FILE"
value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}apollo-portal.log}" />
<include resource="org/springframework/boot/logging/logback/file-appender.xml" />
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<root level="INFO">
<if condition='isDefined("LOG_APPENDERS")'>
<then>
<if condition='property("LOG_APPENDERS").contains("CONSOLE")'>
<then>
<appender-ref ref="CONSOLE"/>
</then>
</if>
<if condition='property("LOG_APPENDERS").contains("FILE")'>
<then>
<appender-ref ref="FILE"/>
</then>
</if>
</then>
<else>
<appender-ref ref="FILE" />
<appender-ref ref="CONSOLE" />
</else>
</if>
</root>
</configuration>
| <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<property name="LOG_FILE"
value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}apollo-portal.log}" />
<include resource="org/springframework/boot/logging/logback/file-appender.xml" />
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<root level="INFO">
<if condition='isDefined("LOG_APPENDERS")'>
<then>
<if condition='property("LOG_APPENDERS").contains("CONSOLE")'>
<then>
<appender-ref ref="CONSOLE"/>
</then>
</if>
<if condition='property("LOG_APPENDERS").contains("FILE")'>
<then>
<appender-ref ref="FILE"/>
</then>
</if>
</then>
<else>
<appender-ref ref="FILE" />
<appender-ref ref="CONSOLE" />
</else>
</if>
</root>
</configuration>
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-configservice/src/test/java/com/ctrip/framework/apollo/metaservice/service/NacosDiscoveryServiceTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.metaservice.service;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author kl (http://kailing.pub)
* @since 2020/12/21
*/
@RunWith(MockitoJUnitRunner.class)
public class NacosDiscoveryServiceTest {
private NacosDiscoveryService nacosDiscoveryService;
@Mock
private NamingService nacosNamingService;
private String someServiceId;
@Before
public void setUp() throws Exception {
nacosDiscoveryService = new NacosDiscoveryService();
nacosDiscoveryService.setNamingService(nacosNamingService);
someServiceId = "someServiceId";
}
@Test
public void testGetServiceInstancesWithEmptyInstances() throws Exception {
assertTrue(nacosNamingService.selectInstances(someServiceId, true).isEmpty());
}
@Test
public void testGetServiceInstancesWithInvalidServiceId() {
assertTrue(nacosDiscoveryService.getServiceInstances(someServiceId).isEmpty());
}
@Test
public void testGetServiceInstances() throws Exception {
String someIp = "1.2.3.4";
int somePort = 8080;
String someInstanceId = "someInstanceId";
Instance someServiceInstance = mockServiceInstance(someInstanceId, someIp, somePort);
when(nacosNamingService.selectInstances(someServiceId, true)).thenReturn(
Lists.newArrayList(someServiceInstance));
List<ServiceDTO> serviceDTOList = nacosDiscoveryService.getServiceInstances(someServiceId);
ServiceDTO serviceDTO = serviceDTOList.get(0);
assertEquals(1, serviceDTOList.size());
assertEquals(someServiceId, serviceDTO.getAppName());
assertEquals("http://1.2.3.4:8080/", serviceDTO.getHomepageUrl());
}
private Instance mockServiceInstance(String instanceId, String ip, int port) {
Instance serviceInstance = mock(Instance.class);
when(serviceInstance.getInstanceId()).thenReturn(instanceId);
when(serviceInstance.getIp()).thenReturn(ip);
when(serviceInstance.getPort()).thenReturn(port);
return serviceInstance;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.metaservice.service;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.ctrip.framework.apollo.core.dto.ServiceDTO;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author kl (http://kailing.pub)
* @since 2020/12/21
*/
@RunWith(MockitoJUnitRunner.class)
public class NacosDiscoveryServiceTest {
private NacosDiscoveryService nacosDiscoveryService;
@Mock
private NamingService nacosNamingService;
private String someServiceId;
@Before
public void setUp() throws Exception {
nacosDiscoveryService = new NacosDiscoveryService();
nacosDiscoveryService.setNamingService(nacosNamingService);
someServiceId = "someServiceId";
}
@Test
public void testGetServiceInstancesWithEmptyInstances() throws Exception {
assertTrue(nacosNamingService.selectInstances(someServiceId, true).isEmpty());
}
@Test
public void testGetServiceInstancesWithInvalidServiceId() {
assertTrue(nacosDiscoveryService.getServiceInstances(someServiceId).isEmpty());
}
@Test
public void testGetServiceInstances() throws Exception {
String someIp = "1.2.3.4";
int somePort = 8080;
String someInstanceId = "someInstanceId";
Instance someServiceInstance = mockServiceInstance(someInstanceId, someIp, somePort);
when(nacosNamingService.selectInstances(someServiceId, true)).thenReturn(
Lists.newArrayList(someServiceInstance));
List<ServiceDTO> serviceDTOList = nacosDiscoveryService.getServiceInstances(someServiceId);
ServiceDTO serviceDTO = serviceDTOList.get(0);
assertEquals(1, serviceDTOList.size());
assertEquals(someServiceId, serviceDTO.getAppName());
assertEquals("http://1.2.3.4:8080/", serviceDTO.getHomepageUrl());
}
private Instance mockServiceInstance(String instanceId, String ip, int port) {
Instance serviceInstance = mock(Instance.class);
when(serviceInstance.getInstanceId()).thenReturn(instanceId);
when(serviceInstance.getIp()).thenReturn(ip);
when(serviceInstance.getPort()).thenReturn(port);
return serviceInstance;
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./.git/hooks/pre-receive.sample | #!/bin/sh
#
# An example hook script to make use of push options.
# The example simply echoes all push options that start with 'echoback='
# and rejects all pushes when the "reject" push option is used.
#
# To enable this hook, rename this file to "pre-receive".
if test -n "$GIT_PUSH_OPTION_COUNT"
then
i=0
while test "$i" -lt "$GIT_PUSH_OPTION_COUNT"
do
eval "value=\$GIT_PUSH_OPTION_$i"
case "$value" in
echoback=*)
echo "echo from the pre-receive-hook: ${value#*=}" >&2
;;
reject)
exit 1
esac
i=$((i + 1))
done
fi
| #!/bin/sh
#
# An example hook script to make use of push options.
# The example simply echoes all push options that start with 'echoback='
# and rejects all pushes when the "reject" push option is used.
#
# To enable this hook, rename this file to "pre-receive".
if test -n "$GIT_PUSH_OPTION_COUNT"
then
i=0
while test "$i" -lt "$GIT_PUSH_OPTION_COUNT"
do
eval "value=\$GIT_PUSH_OPTION_$i"
case "$value" in
echoback=*)
echo "echo from the pre-receive-hook: ${value#*=}" >&2
;;
reject)
exit 1
esac
i=$((i + 1))
done
fi
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-adminservice/src/test/java/com/ctrip/framework/apollo/adminservice/filter/AdminServiceAuthenticationIntegrationTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.adminservice.filter;
import com.ctrip.framework.apollo.adminservice.controller.AbstractControllerTest;
import com.ctrip.framework.apollo.common.config.RefreshablePropertySource;
import com.ctrip.framework.apollo.common.dto.AppDTO;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.Sql.ExecutionPhase;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.client.HttpClientErrorException;
@DirtiesContext
public class AdminServiceAuthenticationIntegrationTest extends AbstractControllerTest {
@Autowired
private List<RefreshablePropertySource> propertySources;
@Before
public void setUp() throws Exception {
doRefresh(propertySources);
}
@Test
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/filter/test-access-control-disabled.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testWithAccessControlDisabledExplicitly() {
String appId = "someAppId";
AppDTO app = restTemplate
.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class);
Assert.assertEquals("someAppId", app.getAppId());
}
@Test
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/filter/test-access-control-disabled.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testWithAccessControlDisabledExplicitlyWithAccessToken() {
String appId = "someAppId";
String someToken = "someToken";
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, someToken);
HttpEntity<Void> entity = new HttpEntity<>(headers);
AppDTO app = restTemplate
.exchange("http://localhost:" + port + "/apps/" + appId, HttpMethod.GET, entity,
AppDTO.class).getBody();
Assert.assertEquals("someAppId", app.getAppId());
}
@Test
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/filter/test-access-control-enabled.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testWithAccessControlEnabledWithValidAccessToken() {
String appId = "someAppId";
String someValidToken = "someToken";
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, someValidToken);
HttpEntity<Void> entity = new HttpEntity<>(headers);
AppDTO app = restTemplate
.exchange("http://localhost:" + port + "/apps/" + appId, HttpMethod.GET, entity,
AppDTO.class).getBody();
Assert.assertEquals("someAppId", app.getAppId());
}
@Test(expected = HttpClientErrorException.class)
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/filter/test-access-control-enabled.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testWithAccessControlEnabledWithNoAccessToken() {
String appId = "someAppId";
AppDTO app = restTemplate
.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class);
}
@Test(expected = HttpClientErrorException.class)
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/filter/test-access-control-enabled.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testWithAccessControlEnabledWithInValidAccessToken() {
String appId = "someAppId";
String someValidToken = "someInvalidToken";
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, someValidToken);
HttpEntity<Void> entity = new HttpEntity<>(headers);
AppDTO app = restTemplate
.exchange("http://localhost:" + port + "/apps/" + appId, HttpMethod.GET, entity,
AppDTO.class).getBody();
}
@Test
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/filter/test-access-control-enabled-no-token.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testWithAccessControlEnabledWithNoTokenSpecified() {
String appId = "someAppId";
String someToken = "someToken";
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, someToken);
HttpEntity<Void> entity = new HttpEntity<>(headers);
AppDTO app = restTemplate
.exchange("http://localhost:" + port + "/apps/" + appId, HttpMethod.GET, entity,
AppDTO.class).getBody();
Assert.assertEquals("someAppId", app.getAppId());
}
private void doRefresh(List<RefreshablePropertySource> propertySources) {
propertySources.forEach(refreshablePropertySource -> ReflectionTestUtils
.invokeMethod(refreshablePropertySource, "refresh"));
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.adminservice.filter;
import com.ctrip.framework.apollo.adminservice.controller.AbstractControllerTest;
import com.ctrip.framework.apollo.common.config.RefreshablePropertySource;
import com.ctrip.framework.apollo.common.dto.AppDTO;
import java.util.List;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.Sql.ExecutionPhase;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.client.HttpClientErrorException;
@DirtiesContext
public class AdminServiceAuthenticationIntegrationTest extends AbstractControllerTest {
@Autowired
private List<RefreshablePropertySource> propertySources;
@Before
public void setUp() throws Exception {
doRefresh(propertySources);
}
@Test
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/filter/test-access-control-disabled.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testWithAccessControlDisabledExplicitly() {
String appId = "someAppId";
AppDTO app = restTemplate
.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class);
Assert.assertEquals("someAppId", app.getAppId());
}
@Test
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/filter/test-access-control-disabled.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testWithAccessControlDisabledExplicitlyWithAccessToken() {
String appId = "someAppId";
String someToken = "someToken";
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, someToken);
HttpEntity<Void> entity = new HttpEntity<>(headers);
AppDTO app = restTemplate
.exchange("http://localhost:" + port + "/apps/" + appId, HttpMethod.GET, entity,
AppDTO.class).getBody();
Assert.assertEquals("someAppId", app.getAppId());
}
@Test
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/filter/test-access-control-enabled.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testWithAccessControlEnabledWithValidAccessToken() {
String appId = "someAppId";
String someValidToken = "someToken";
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, someValidToken);
HttpEntity<Void> entity = new HttpEntity<>(headers);
AppDTO app = restTemplate
.exchange("http://localhost:" + port + "/apps/" + appId, HttpMethod.GET, entity,
AppDTO.class).getBody();
Assert.assertEquals("someAppId", app.getAppId());
}
@Test(expected = HttpClientErrorException.class)
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/filter/test-access-control-enabled.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testWithAccessControlEnabledWithNoAccessToken() {
String appId = "someAppId";
AppDTO app = restTemplate
.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class);
}
@Test(expected = HttpClientErrorException.class)
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/filter/test-access-control-enabled.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testWithAccessControlEnabledWithInValidAccessToken() {
String appId = "someAppId";
String someValidToken = "someInvalidToken";
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, someValidToken);
HttpEntity<Void> entity = new HttpEntity<>(headers);
AppDTO app = restTemplate
.exchange("http://localhost:" + port + "/apps/" + appId, HttpMethod.GET, entity,
AppDTO.class).getBody();
}
@Test
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/filter/test-access-control-enabled-no-token.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testWithAccessControlEnabledWithNoTokenSpecified() {
String appId = "someAppId";
String someToken = "someToken";
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, someToken);
HttpEntity<Void> entity = new HttpEntity<>(headers);
AppDTO app = restTemplate
.exchange("http://localhost:" + port + "/apps/" + appId, HttpMethod.GET, entity,
AppDTO.class).getBody();
Assert.assertEquals("someAppId", app.getAppId());
}
private void doRefresh(List<RefreshablePropertySource> propertySources) {
propertySources.forEach(refreshablePropertySource -> ReflectionTestUtils
.invokeMethod(refreshablePropertySource, "refresh"));
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./scripts/apollo-on-kubernetes/kubernetes/apollo-env-dev/service-apollo-admin-server-dev.yaml | #
# Copyright 2021 Apollo 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.
#
---
# configmap for apollo-admin-server-dev
kind: ConfigMap
apiVersion: v1
metadata:
namespace: sre
name: configmap-apollo-admin-server-dev
data:
application-github.properties: |
spring.datasource.url = jdbc:mysql://service-mysql-for-apollo-dev-env.sre:3306/DevApolloConfigDB?characterEncoding=utf8
spring.datasource.username = FillInCorrectUser
spring.datasource.password = FillInCorrectPassword
eureka.service.url = http://statefulset-apollo-config-server-dev-0.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-1.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-2.service-apollo-meta-server-dev:8080/eureka/
---
kind: Service
apiVersion: v1
metadata:
namespace: sre
name: service-apollo-admin-server-dev
labels:
app: service-apollo-admin-server-dev
spec:
ports:
- protocol: TCP
port: 8090
targetPort: 8090
selector:
app: pod-apollo-admin-server-dev
type: ClusterIP
sessionAffinity: ClientIP
---
kind: Deployment
apiVersion: apps/v1
metadata:
namespace: sre
name: deployment-apollo-admin-server-dev
labels:
app: deployment-apollo-admin-server-dev
spec:
replicas: 3
selector:
matchLabels:
app: pod-apollo-admin-server-dev
strategy:
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
type: RollingUpdate
template:
metadata:
labels:
app: pod-apollo-admin-server-dev
spec:
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app
operator: In
values:
- pod-apollo-admin-server-dev
topologyKey: kubernetes.io/hostname
volumes:
- name: volume-configmap-apollo-admin-server-dev
configMap:
name: configmap-apollo-admin-server-dev
items:
- key: application-github.properties
path: application-github.properties
initContainers:
- image: alpine-bash:3.8
name: check-service-apollo-config-server-dev
command: ['bash', '-c', "curl --connect-timeout 2 --max-time 5 --retry 60 --retry-delay 1 --retry-max-time 120 service-apollo-config-server-dev.sre:8080"]
containers:
- image: apollo-admin-server:v1.0.0
securityContext:
privileged: true
imagePullPolicy: IfNotPresent
name: container-apollo-admin-server-dev
ports:
- protocol: TCP
containerPort: 8090
volumeMounts:
- name: volume-configmap-apollo-admin-server-dev
mountPath: /apollo-admin-server/config/application-github.properties
subPath: application-github.properties
env:
- name: APOLLO_ADMIN_SERVICE_NAME
value: "service-apollo-admin-server-dev.sre"
readinessProbe:
tcpSocket:
port: 8090
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
tcpSocket:
port: 8090
initialDelaySeconds: 120
periodSeconds: 10
dnsPolicy: ClusterFirst
restartPolicy: Always | #
# Copyright 2021 Apollo 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.
#
---
# configmap for apollo-admin-server-dev
kind: ConfigMap
apiVersion: v1
metadata:
namespace: sre
name: configmap-apollo-admin-server-dev
data:
application-github.properties: |
spring.datasource.url = jdbc:mysql://service-mysql-for-apollo-dev-env.sre:3306/DevApolloConfigDB?characterEncoding=utf8
spring.datasource.username = FillInCorrectUser
spring.datasource.password = FillInCorrectPassword
eureka.service.url = http://statefulset-apollo-config-server-dev-0.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-1.service-apollo-meta-server-dev:8080/eureka/,http://statefulset-apollo-config-server-dev-2.service-apollo-meta-server-dev:8080/eureka/
---
kind: Service
apiVersion: v1
metadata:
namespace: sre
name: service-apollo-admin-server-dev
labels:
app: service-apollo-admin-server-dev
spec:
ports:
- protocol: TCP
port: 8090
targetPort: 8090
selector:
app: pod-apollo-admin-server-dev
type: ClusterIP
sessionAffinity: ClientIP
---
kind: Deployment
apiVersion: apps/v1
metadata:
namespace: sre
name: deployment-apollo-admin-server-dev
labels:
app: deployment-apollo-admin-server-dev
spec:
replicas: 3
selector:
matchLabels:
app: pod-apollo-admin-server-dev
strategy:
rollingUpdate:
maxSurge: 1
maxUnavailable: 1
type: RollingUpdate
template:
metadata:
labels:
app: pod-apollo-admin-server-dev
spec:
affinity:
podAntiAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
labelSelector:
matchExpressions:
- key: app
operator: In
values:
- pod-apollo-admin-server-dev
topologyKey: kubernetes.io/hostname
volumes:
- name: volume-configmap-apollo-admin-server-dev
configMap:
name: configmap-apollo-admin-server-dev
items:
- key: application-github.properties
path: application-github.properties
initContainers:
- image: alpine-bash:3.8
name: check-service-apollo-config-server-dev
command: ['bash', '-c', "curl --connect-timeout 2 --max-time 5 --retry 60 --retry-delay 1 --retry-max-time 120 service-apollo-config-server-dev.sre:8080"]
containers:
- image: apollo-admin-server:v1.0.0
securityContext:
privileged: true
imagePullPolicy: IfNotPresent
name: container-apollo-admin-server-dev
ports:
- protocol: TCP
containerPort: 8090
volumeMounts:
- name: volume-configmap-apollo-admin-server-dev
mountPath: /apollo-admin-server/config/application-github.properties
subPath: application-github.properties
env:
- name: APOLLO_ADMIN_SERVICE_NAME
value: "service-apollo-admin-server-dev.sre"
readinessProbe:
tcpSocket:
port: 8090
initialDelaySeconds: 10
periodSeconds: 5
livenessProbe:
tcpSocket:
port: 8090
initialDelaySeconds: 120
periodSeconds: 10
dnsPolicy: ClusterFirst
restartPolicy: Always | -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-core/src/main/java/com/ctrip/framework/apollo/core/dto/ApolloConfigNotification.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.core.dto;
/**
* @author Jason Song([email protected])
*/
public class ApolloConfigNotification {
private String namespaceName;
private long notificationId;
private volatile ApolloNotificationMessages messages;
//for json converter
public ApolloConfigNotification() {
}
public ApolloConfigNotification(String namespaceName, long notificationId) {
this.namespaceName = namespaceName;
this.notificationId = notificationId;
}
public String getNamespaceName() {
return namespaceName;
}
public long getNotificationId() {
return notificationId;
}
public void setNamespaceName(String namespaceName) {
this.namespaceName = namespaceName;
}
public ApolloNotificationMessages getMessages() {
return messages;
}
public void setMessages(ApolloNotificationMessages messages) {
this.messages = messages;
}
public void addMessage(String key, long notificationId) {
if (this.messages == null) {
synchronized (this) {
if (this.messages == null) {
this.messages = new ApolloNotificationMessages();
}
}
}
this.messages.put(key, notificationId);
}
@Override
public String toString() {
return "ApolloConfigNotification{" +
"namespaceName='" + namespaceName + '\'' +
", notificationId=" + notificationId +
'}';
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.core.dto;
/**
* @author Jason Song([email protected])
*/
public class ApolloConfigNotification {
private String namespaceName;
private long notificationId;
private volatile ApolloNotificationMessages messages;
//for json converter
public ApolloConfigNotification() {
}
public ApolloConfigNotification(String namespaceName, long notificationId) {
this.namespaceName = namespaceName;
this.notificationId = notificationId;
}
public String getNamespaceName() {
return namespaceName;
}
public long getNotificationId() {
return notificationId;
}
public void setNamespaceName(String namespaceName) {
this.namespaceName = namespaceName;
}
public ApolloNotificationMessages getMessages() {
return messages;
}
public void setMessages(ApolloNotificationMessages messages) {
this.messages = messages;
}
public void addMessage(String key, long notificationId) {
if (this.messages == null) {
synchronized (this) {
if (this.messages == null) {
this.messages = new ApolloNotificationMessages();
}
}
}
this.messages.put(key, notificationId);
}
@Override
public String toString() {
return "ApolloConfigNotification{" +
"namespaceName='" + namespaceName + '\'' +
", notificationId=" + notificationId +
'}';
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/constant/ApolloOpenApiConstants.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.openapi.client.constant;
public interface ApolloOpenApiConstants {
int DEFAULT_CONNECT_TIMEOUT = 1000; //1 second
int DEFAULT_READ_TIMEOUT = 5000; //5 seconds
String OPEN_API_V1_PREFIX = "/openapi/v1";
String JSON_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.openapi.client.constant;
public interface ApolloOpenApiConstants {
int DEFAULT_CONNECT_TIMEOUT = 1000; //1 second
int DEFAULT_READ_TIMEOUT = 5000; //5 seconds
String OPEN_API_V1_PREFIX = "/openapi/v1";
String JSON_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/spi/configuration/AuthConfiguration.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi.configuration;
import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.repository.UserRepository;
import com.ctrip.framework.apollo.portal.spi.LogoutHandler;
import com.ctrip.framework.apollo.portal.spi.SsoHeartbeatHandler;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.UserService;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripLogoutHandler;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripSsoHeartbeatHandler;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripUserService;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultLogoutHandler;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultSsoHeartbeatHandler;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultUserService;
import com.ctrip.framework.apollo.portal.spi.ldap.ApolloLdapAuthenticationProvider;
import com.ctrip.framework.apollo.portal.spi.ldap.FilterLdapByGroupUserSearch;
import com.ctrip.framework.apollo.portal.spi.ldap.LdapUserService;
import com.ctrip.framework.apollo.portal.spi.oidc.ExcludeClientCredentialsClientRegistrationRepository;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcAuthenticationSuccessEventListener;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcLocalUserService;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcLocalUserServiceImpl;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcLogoutHandler;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.springsecurity.SpringSecurityUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.springsecurity.SpringSecurityUserService;
import com.google.common.collect.Maps;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.LdapOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.ldap.authentication.BindAuthenticator;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
import org.springframework.security.ldap.search.FilterBasedLdapUserSearch;
import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.Collections;
import java.util.EventListener;
import java.util.Map;
@Configuration
public class AuthConfiguration {
private static final String[] BY_PASS_URLS = {"/prometheus/**", "/metrics/**", "/openapi/**",
"/vendor/**", "/styles/**", "/scripts/**", "/views/**", "/img/**", "/i18n/**", "/prefix-path",
"/health"};
/**
* spring.profiles.active = ctrip
*/
@Configuration
@Profile("ctrip")
static class CtripAuthAutoConfiguration {
private final PortalConfig portalConfig;
public CtripAuthAutoConfiguration(final PortalConfig portalConfig) {
this.portalConfig = portalConfig;
}
@Bean
public ServletListenerRegistrationBean redisAppSettingListner() {
ServletListenerRegistrationBean redisAppSettingListener = new ServletListenerRegistrationBean();
redisAppSettingListener
.setListener(listener("org.jasig.cas.client.credis.CRedisAppSettingListner"));
return redisAppSettingListener;
}
@Bean
public ServletListenerRegistrationBean singleSignOutHttpSessionListener() {
ServletListenerRegistrationBean singleSignOutHttpSessionListener = new ServletListenerRegistrationBean();
singleSignOutHttpSessionListener
.setListener(listener("org.jasig.cas.client.session.SingleSignOutHttpSessionListener"));
return singleSignOutHttpSessionListener;
}
@Bean
public FilterRegistrationBean casFilter() {
FilterRegistrationBean singleSignOutFilter = new FilterRegistrationBean();
singleSignOutFilter.setFilter(filter("org.jasig.cas.client.session.SingleSignOutFilter"));
singleSignOutFilter.addUrlPatterns("/*");
singleSignOutFilter.setOrder(1);
return singleSignOutFilter;
}
@Bean
public FilterRegistrationBean authenticationFilter() {
FilterRegistrationBean casFilter = new FilterRegistrationBean();
Map<String, String> filterInitParam = Maps.newHashMap();
filterInitParam.put("redisClusterName", "casClientPrincipal");
filterInitParam.put("serverName", portalConfig.portalServerName());
filterInitParam.put("casServerLoginUrl", portalConfig.casServerLoginUrl());
//we don't want to use session to store login information, since we will be deployed to a cluster, not a single instance
filterInitParam.put("useSession", "false");
filterInitParam.put("/openapi.*", "exclude");
casFilter.setInitParameters(filterInitParam);
casFilter
.setFilter(filter("com.ctrip.framework.apollo.sso.filter.ApolloAuthenticationFilter"));
casFilter.addUrlPatterns("/*");
casFilter.setOrder(2);
return casFilter;
}
@Bean
public FilterRegistrationBean casValidationFilter() {
FilterRegistrationBean casValidationFilter = new FilterRegistrationBean();
Map<String, String> filterInitParam = Maps.newHashMap();
filterInitParam.put("casServerUrlPrefix", portalConfig.casServerUrlPrefix());
filterInitParam.put("serverName", portalConfig.portalServerName());
filterInitParam.put("encoding", "UTF-8");
//we don't want to use session to store login information, since we will be deployed to a cluster, not a single instance
filterInitParam.put("useSession", "false");
filterInitParam.put("useRedis", "true");
filterInitParam.put("redisClusterName", "casClientPrincipal");
casValidationFilter
.setFilter(
filter("org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter"));
casValidationFilter.setInitParameters(filterInitParam);
casValidationFilter.addUrlPatterns("/*");
casValidationFilter.setOrder(3);
return casValidationFilter;
}
@Bean
public FilterRegistrationBean assertionHolder() {
FilterRegistrationBean assertionHolderFilter = new FilterRegistrationBean();
Map<String, String> filterInitParam = Maps.newHashMap();
filterInitParam.put("/openapi.*", "exclude");
assertionHolderFilter.setInitParameters(filterInitParam);
assertionHolderFilter.setFilter(
filter("com.ctrip.framework.apollo.sso.filter.ApolloAssertionThreadLocalFilter"));
assertionHolderFilter.addUrlPatterns("/*");
assertionHolderFilter.setOrder(4);
return assertionHolderFilter;
}
@Bean
public CtripUserInfoHolder ctripUserInfoHolder() {
return new CtripUserInfoHolder();
}
@Bean
public CtripLogoutHandler logoutHandler() {
return new CtripLogoutHandler();
}
private Filter filter(String className) {
Class clazz = null;
try {
clazz = Class.forName(className);
Object obj = clazz.newInstance();
return (Filter) obj;
} catch (Exception e) {
throw new RuntimeException("instance filter fail", e);
}
}
private EventListener listener(String className) {
Class clazz = null;
try {
clazz = Class.forName(className);
Object obj = clazz.newInstance();
return (EventListener) obj;
} catch (Exception e) {
throw new RuntimeException("instance listener fail", e);
}
}
@Bean
public UserService ctripUserService(PortalConfig portalConfig) {
return new CtripUserService(portalConfig);
}
@Bean
public SsoHeartbeatHandler ctripSsoHeartbeatHandler() {
return new CtripSsoHeartbeatHandler();
}
}
/**
* spring.profiles.active = auth
*/
@Configuration
@Profile("auth")
static class SpringSecurityAuthAutoConfiguration {
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public UserInfoHolder springSecurityUserInfoHolder(UserService userService) {
return new SpringSecurityUserInfoHolder(userService);
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public LogoutHandler logoutHandler() {
return new DefaultLogoutHandler();
}
@Bean
public JdbcUserDetailsManager jdbcUserDetailsManager(AuthenticationManagerBuilder auth,
DataSource datasource) throws Exception {
JdbcUserDetailsManager jdbcUserDetailsManager = auth.jdbcAuthentication()
.passwordEncoder(new BCryptPasswordEncoder()).dataSource(datasource)
.usersByUsernameQuery("select Username,Password,Enabled from `Users` where Username = ?")
.authoritiesByUsernameQuery(
"select Username,Authority from `Authorities` where Username = ?")
.getUserDetailsService();
jdbcUserDetailsManager.setUserExistsSql("select Username from `Users` where Username = ?");
jdbcUserDetailsManager
.setCreateUserSql("insert into `Users` (Username, Password, Enabled) values (?,?,?)");
jdbcUserDetailsManager
.setUpdateUserSql("update `Users` set Password = ?, Enabled = ? where id = (select u.id from (select id from `Users` where Username = ?) as u)");
jdbcUserDetailsManager.setDeleteUserSql("delete from `Users` where id = (select u.id from (select id from `Users` where Username = ?) as u)");
jdbcUserDetailsManager
.setCreateAuthoritySql("insert into `Authorities` (Username, Authority) values (?,?)");
jdbcUserDetailsManager
.setDeleteUserAuthoritiesSql("delete from `Authorities` where id in (select a.id from (select id from `Authorities` where Username = ?) as a)");
jdbcUserDetailsManager
.setChangePasswordSql("update `Users` set Password = ? where id = (select u.id from (select id from `Users` where Username = ?) as u)");
return jdbcUserDetailsManager;
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService springSecurityUserService() {
return new SpringSecurityUserService();
}
}
@Order(99)
@Profile("auth")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter {
public static final String USER_ROLE = "user";
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
http.authorizeRequests()
.antMatchers(BY_PASS_URLS).permitAll()
.antMatchers("/**").hasAnyRole(USER_ROLE);
http.formLogin().loginPage("/signin").defaultSuccessUrl("/", true).permitAll().failureUrl("/signin?#/error").and()
.httpBasic();
http.logout().logoutUrl("/user/logout").invalidateHttpSession(true).clearAuthentication(true)
.logoutSuccessUrl("/signin?#/logout");
http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/signin"));
}
}
/**
* spring.profiles.active = ldap
*/
@Configuration
@Profile("ldap")
@EnableConfigurationProperties({LdapProperties.class,LdapExtendProperties.class})
static class SpringSecurityLDAPAuthAutoConfiguration {
private final LdapProperties properties;
private final Environment environment;
public SpringSecurityLDAPAuthAutoConfiguration(final LdapProperties properties, final Environment environment) {
this.properties = properties;
this.environment = environment;
}
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public UserInfoHolder springSecurityUserInfoHolder(UserService userService) {
return new SpringSecurityUserInfoHolder(userService);
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public LogoutHandler logoutHandler() {
return new DefaultLogoutHandler();
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService springSecurityUserService() {
return new LdapUserService();
}
@Bean
@ConditionalOnMissingBean
public ContextSource ldapContextSource() {
LdapContextSource source = new LdapContextSource();
source.setUserDn(this.properties.getUsername());
source.setPassword(this.properties.getPassword());
source.setAnonymousReadOnly(this.properties.getAnonymousReadOnly());
source.setBase(this.properties.getBase());
source.setUrls(this.properties.determineUrls(this.environment));
source.setBaseEnvironmentProperties(
Collections.unmodifiableMap(this.properties.getBaseEnvironment()));
return source;
}
@Bean
@ConditionalOnMissingBean(LdapOperations.class)
public LdapTemplate ldapTemplate(ContextSource contextSource) {
LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
ldapTemplate.setIgnorePartialResultException(true);
return ldapTemplate;
}
}
@Order(99)
@Profile("ldap")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class SpringSecurityLDAPConfigurer extends WebSecurityConfigurerAdapter {
private final LdapProperties ldapProperties;
private final LdapContextSource ldapContextSource;
private final LdapExtendProperties ldapExtendProperties;
public SpringSecurityLDAPConfigurer(final LdapProperties ldapProperties,
final LdapContextSource ldapContextSource,
final LdapExtendProperties ldapExtendProperties) {
this.ldapProperties = ldapProperties;
this.ldapContextSource = ldapContextSource;
this.ldapExtendProperties = ldapExtendProperties;
}
@Bean
public FilterBasedLdapUserSearch userSearch() {
if (ldapExtendProperties.getGroup() == null || StringUtils
.isBlank(ldapExtendProperties.getGroup().getGroupSearch())) {
FilterBasedLdapUserSearch filterBasedLdapUserSearch = new FilterBasedLdapUserSearch("",
ldapProperties.getSearchFilter(), ldapContextSource);
filterBasedLdapUserSearch.setSearchSubtree(true);
return filterBasedLdapUserSearch;
}
FilterLdapByGroupUserSearch filterLdapByGroupUserSearch = new FilterLdapByGroupUserSearch(
ldapProperties.getBase(), ldapProperties.getSearchFilter(), ldapExtendProperties.getGroup().getGroupBase(),
ldapContextSource, ldapExtendProperties.getGroup().getGroupSearch(),
ldapExtendProperties.getMapping().getRdnKey(),
ldapExtendProperties.getGroup().getGroupMembership(),ldapExtendProperties.getMapping().getLoginId());
filterLdapByGroupUserSearch.setSearchSubtree(true);
return filterLdapByGroupUserSearch;
}
@Bean
public LdapAuthenticationProvider ldapAuthProvider() {
BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
bindAuthenticator.setUserSearch(userSearch());
DefaultLdapAuthoritiesPopulator defaultAuthAutoConfiguration = new DefaultLdapAuthoritiesPopulator(
ldapContextSource, null);
defaultAuthAutoConfiguration.setIgnorePartialResultException(true);
defaultAuthAutoConfiguration.setSearchSubtree(true);
// Rewrite the logic of LdapAuthenticationProvider with ApolloLdapAuthenticationProvider,
// use userId in LDAP system instead of userId input by user.
return new ApolloLdapAuthenticationProvider(
bindAuthenticator, defaultAuthAutoConfiguration, ldapExtendProperties);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
http.authorizeRequests()
.antMatchers(BY_PASS_URLS).permitAll()
.antMatchers("/**").authenticated();
http.formLogin().loginPage("/signin").defaultSuccessUrl("/", true).permitAll().failureUrl("/signin?#/error").and()
.httpBasic();
http.logout().logoutUrl("/user/logout").invalidateHttpSession(true).clearAuthentication(true)
.logoutSuccessUrl("/signin?#/logout");
http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/signin"));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(ldapAuthProvider());
}
}
@Profile("oidc")
@EnableConfigurationProperties({OAuth2ClientProperties.class, OAuth2ResourceServerProperties.class})
@Configuration
static class OidcAuthAutoConfiguration {
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public UserInfoHolder oidcUserInfoHolder(UserService userService) {
return new OidcUserInfoHolder(userService);
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public LogoutHandler oidcLogoutHandler() {
return new OidcLogoutHandler();
}
@Bean
@ConditionalOnMissingBean(JdbcUserDetailsManager.class)
public JdbcUserDetailsManager jdbcUserDetailsManager(AuthenticationManagerBuilder auth,
DataSource datasource) throws Exception {
return new SpringSecurityAuthAutoConfiguration().jdbcUserDetailsManager(auth, datasource);
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public OidcLocalUserService oidcLocalUserService(JdbcUserDetailsManager userDetailsManager,
UserRepository userRepository) {
return new OidcLocalUserServiceImpl(userDetailsManager, userRepository);
}
@Bean
public OidcAuthenticationSuccessEventListener oidcAuthenticationSuccessEventListener(OidcLocalUserService oidcLocalUserService) {
return new OidcAuthenticationSuccessEventListener(oidcLocalUserService);
}
}
@Profile("oidc")
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
static class OidcWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
private final InMemoryClientRegistrationRepository clientRegistrationRepository;
private final OAuth2ResourceServerProperties oauth2ResourceServerProperties;
public OidcWebSecurityConfigurerAdapter(
InMemoryClientRegistrationRepository clientRegistrationRepository,
OAuth2ResourceServerProperties oauth2ResourceServerProperties) {
this.clientRegistrationRepository = clientRegistrationRepository;
this.oauth2ResourceServerProperties = oauth2ResourceServerProperties;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests(requests -> requests.antMatchers(BY_PASS_URLS).permitAll());
http.authorizeRequests(requests -> requests.anyRequest().authenticated());
http.oauth2Login(configure ->
configure.clientRegistrationRepository(
new ExcludeClientCredentialsClientRegistrationRepository(
this.clientRegistrationRepository)));
http.oauth2Client();
http.logout(configure -> {
OidcClientInitiatedLogoutSuccessHandler logoutSuccessHandler = new OidcClientInitiatedLogoutSuccessHandler(
this.clientRegistrationRepository);
logoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}");
configure.logoutSuccessHandler(logoutSuccessHandler);
});
// make jwt optional
String jwtIssuerUri = this.oauth2ResourceServerProperties.getJwt().getIssuerUri();
if (!StringUtils.isBlank(jwtIssuerUri)) {
http.oauth2ResourceServer().jwt();
}
}
}
/**
* default profile
*/
@Configuration
@ConditionalOnMissingProfile({"ctrip", "auth", "ldap", "oidc"})
static class DefaultAuthAutoConfiguration {
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public DefaultUserInfoHolder defaultUserInfoHolder() {
return new DefaultUserInfoHolder();
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public DefaultLogoutHandler logoutHandler() {
return new DefaultLogoutHandler();
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService defaultUserService() {
return new DefaultUserService();
}
}
@ConditionalOnMissingProfile({"auth", "ldap", "oidc"})
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class DefaultWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.spi.configuration;
import com.ctrip.framework.apollo.common.condition.ConditionalOnMissingProfile;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.repository.UserRepository;
import com.ctrip.framework.apollo.portal.spi.LogoutHandler;
import com.ctrip.framework.apollo.portal.spi.SsoHeartbeatHandler;
import com.ctrip.framework.apollo.portal.spi.UserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.UserService;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripLogoutHandler;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripSsoHeartbeatHandler;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.ctrip.CtripUserService;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultLogoutHandler;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultSsoHeartbeatHandler;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.defaultimpl.DefaultUserService;
import com.ctrip.framework.apollo.portal.spi.ldap.ApolloLdapAuthenticationProvider;
import com.ctrip.framework.apollo.portal.spi.ldap.FilterLdapByGroupUserSearch;
import com.ctrip.framework.apollo.portal.spi.ldap.LdapUserService;
import com.ctrip.framework.apollo.portal.spi.oidc.ExcludeClientCredentialsClientRegistrationRepository;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcAuthenticationSuccessEventListener;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcLocalUserService;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcLocalUserServiceImpl;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcLogoutHandler;
import com.ctrip.framework.apollo.portal.spi.oidc.OidcUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.springsecurity.SpringSecurityUserInfoHolder;
import com.ctrip.framework.apollo.portal.spi.springsecurity.SpringSecurityUserService;
import com.google.common.collect.Maps;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.LdapOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.ldap.authentication.BindAuthenticator;
import org.springframework.security.ldap.authentication.LdapAuthenticationProvider;
import org.springframework.security.ldap.search.FilterBasedLdapUserSearch;
import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator;
import org.springframework.security.oauth2.client.oidc.web.logout.OidcClientInitiatedLogoutSuccessHandler;
import org.springframework.security.oauth2.client.registration.InMemoryClientRegistrationRepository;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import javax.servlet.Filter;
import javax.sql.DataSource;
import java.util.Collections;
import java.util.EventListener;
import java.util.Map;
@Configuration
public class AuthConfiguration {
private static final String[] BY_PASS_URLS = {"/prometheus/**", "/metrics/**", "/openapi/**",
"/vendor/**", "/styles/**", "/scripts/**", "/views/**", "/img/**", "/i18n/**", "/prefix-path",
"/health"};
/**
* spring.profiles.active = ctrip
*/
@Configuration
@Profile("ctrip")
static class CtripAuthAutoConfiguration {
private final PortalConfig portalConfig;
public CtripAuthAutoConfiguration(final PortalConfig portalConfig) {
this.portalConfig = portalConfig;
}
@Bean
public ServletListenerRegistrationBean redisAppSettingListner() {
ServletListenerRegistrationBean redisAppSettingListener = new ServletListenerRegistrationBean();
redisAppSettingListener
.setListener(listener("org.jasig.cas.client.credis.CRedisAppSettingListner"));
return redisAppSettingListener;
}
@Bean
public ServletListenerRegistrationBean singleSignOutHttpSessionListener() {
ServletListenerRegistrationBean singleSignOutHttpSessionListener = new ServletListenerRegistrationBean();
singleSignOutHttpSessionListener
.setListener(listener("org.jasig.cas.client.session.SingleSignOutHttpSessionListener"));
return singleSignOutHttpSessionListener;
}
@Bean
public FilterRegistrationBean casFilter() {
FilterRegistrationBean singleSignOutFilter = new FilterRegistrationBean();
singleSignOutFilter.setFilter(filter("org.jasig.cas.client.session.SingleSignOutFilter"));
singleSignOutFilter.addUrlPatterns("/*");
singleSignOutFilter.setOrder(1);
return singleSignOutFilter;
}
@Bean
public FilterRegistrationBean authenticationFilter() {
FilterRegistrationBean casFilter = new FilterRegistrationBean();
Map<String, String> filterInitParam = Maps.newHashMap();
filterInitParam.put("redisClusterName", "casClientPrincipal");
filterInitParam.put("serverName", portalConfig.portalServerName());
filterInitParam.put("casServerLoginUrl", portalConfig.casServerLoginUrl());
//we don't want to use session to store login information, since we will be deployed to a cluster, not a single instance
filterInitParam.put("useSession", "false");
filterInitParam.put("/openapi.*", "exclude");
casFilter.setInitParameters(filterInitParam);
casFilter
.setFilter(filter("com.ctrip.framework.apollo.sso.filter.ApolloAuthenticationFilter"));
casFilter.addUrlPatterns("/*");
casFilter.setOrder(2);
return casFilter;
}
@Bean
public FilterRegistrationBean casValidationFilter() {
FilterRegistrationBean casValidationFilter = new FilterRegistrationBean();
Map<String, String> filterInitParam = Maps.newHashMap();
filterInitParam.put("casServerUrlPrefix", portalConfig.casServerUrlPrefix());
filterInitParam.put("serverName", portalConfig.portalServerName());
filterInitParam.put("encoding", "UTF-8");
//we don't want to use session to store login information, since we will be deployed to a cluster, not a single instance
filterInitParam.put("useSession", "false");
filterInitParam.put("useRedis", "true");
filterInitParam.put("redisClusterName", "casClientPrincipal");
casValidationFilter
.setFilter(
filter("org.jasig.cas.client.validation.Cas20ProxyReceivingTicketValidationFilter"));
casValidationFilter.setInitParameters(filterInitParam);
casValidationFilter.addUrlPatterns("/*");
casValidationFilter.setOrder(3);
return casValidationFilter;
}
@Bean
public FilterRegistrationBean assertionHolder() {
FilterRegistrationBean assertionHolderFilter = new FilterRegistrationBean();
Map<String, String> filterInitParam = Maps.newHashMap();
filterInitParam.put("/openapi.*", "exclude");
assertionHolderFilter.setInitParameters(filterInitParam);
assertionHolderFilter.setFilter(
filter("com.ctrip.framework.apollo.sso.filter.ApolloAssertionThreadLocalFilter"));
assertionHolderFilter.addUrlPatterns("/*");
assertionHolderFilter.setOrder(4);
return assertionHolderFilter;
}
@Bean
public CtripUserInfoHolder ctripUserInfoHolder() {
return new CtripUserInfoHolder();
}
@Bean
public CtripLogoutHandler logoutHandler() {
return new CtripLogoutHandler();
}
private Filter filter(String className) {
Class clazz = null;
try {
clazz = Class.forName(className);
Object obj = clazz.newInstance();
return (Filter) obj;
} catch (Exception e) {
throw new RuntimeException("instance filter fail", e);
}
}
private EventListener listener(String className) {
Class clazz = null;
try {
clazz = Class.forName(className);
Object obj = clazz.newInstance();
return (EventListener) obj;
} catch (Exception e) {
throw new RuntimeException("instance listener fail", e);
}
}
@Bean
public UserService ctripUserService(PortalConfig portalConfig) {
return new CtripUserService(portalConfig);
}
@Bean
public SsoHeartbeatHandler ctripSsoHeartbeatHandler() {
return new CtripSsoHeartbeatHandler();
}
}
/**
* spring.profiles.active = auth
*/
@Configuration
@Profile("auth")
static class SpringSecurityAuthAutoConfiguration {
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public UserInfoHolder springSecurityUserInfoHolder(UserService userService) {
return new SpringSecurityUserInfoHolder(userService);
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public LogoutHandler logoutHandler() {
return new DefaultLogoutHandler();
}
@Bean
public JdbcUserDetailsManager jdbcUserDetailsManager(AuthenticationManagerBuilder auth,
DataSource datasource) throws Exception {
JdbcUserDetailsManager jdbcUserDetailsManager = auth.jdbcAuthentication()
.passwordEncoder(new BCryptPasswordEncoder()).dataSource(datasource)
.usersByUsernameQuery("select Username,Password,Enabled from `Users` where Username = ?")
.authoritiesByUsernameQuery(
"select Username,Authority from `Authorities` where Username = ?")
.getUserDetailsService();
jdbcUserDetailsManager.setUserExistsSql("select Username from `Users` where Username = ?");
jdbcUserDetailsManager
.setCreateUserSql("insert into `Users` (Username, Password, Enabled) values (?,?,?)");
jdbcUserDetailsManager
.setUpdateUserSql("update `Users` set Password = ?, Enabled = ? where id = (select u.id from (select id from `Users` where Username = ?) as u)");
jdbcUserDetailsManager.setDeleteUserSql("delete from `Users` where id = (select u.id from (select id from `Users` where Username = ?) as u)");
jdbcUserDetailsManager
.setCreateAuthoritySql("insert into `Authorities` (Username, Authority) values (?,?)");
jdbcUserDetailsManager
.setDeleteUserAuthoritiesSql("delete from `Authorities` where id in (select a.id from (select id from `Authorities` where Username = ?) as a)");
jdbcUserDetailsManager
.setChangePasswordSql("update `Users` set Password = ? where id = (select u.id from (select id from `Users` where Username = ?) as u)");
return jdbcUserDetailsManager;
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService springSecurityUserService() {
return new SpringSecurityUserService();
}
}
@Order(99)
@Profile("auth")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class SpringSecurityConfigurer extends WebSecurityConfigurerAdapter {
public static final String USER_ROLE = "user";
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
http.authorizeRequests()
.antMatchers(BY_PASS_URLS).permitAll()
.antMatchers("/**").hasAnyRole(USER_ROLE);
http.formLogin().loginPage("/signin").defaultSuccessUrl("/", true).permitAll().failureUrl("/signin?#/error").and()
.httpBasic();
http.logout().logoutUrl("/user/logout").invalidateHttpSession(true).clearAuthentication(true)
.logoutSuccessUrl("/signin?#/logout");
http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/signin"));
}
}
/**
* spring.profiles.active = ldap
*/
@Configuration
@Profile("ldap")
@EnableConfigurationProperties({LdapProperties.class,LdapExtendProperties.class})
static class SpringSecurityLDAPAuthAutoConfiguration {
private final LdapProperties properties;
private final Environment environment;
public SpringSecurityLDAPAuthAutoConfiguration(final LdapProperties properties, final Environment environment) {
this.properties = properties;
this.environment = environment;
}
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public UserInfoHolder springSecurityUserInfoHolder(UserService userService) {
return new SpringSecurityUserInfoHolder(userService);
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public LogoutHandler logoutHandler() {
return new DefaultLogoutHandler();
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService springSecurityUserService() {
return new LdapUserService();
}
@Bean
@ConditionalOnMissingBean
public ContextSource ldapContextSource() {
LdapContextSource source = new LdapContextSource();
source.setUserDn(this.properties.getUsername());
source.setPassword(this.properties.getPassword());
source.setAnonymousReadOnly(this.properties.getAnonymousReadOnly());
source.setBase(this.properties.getBase());
source.setUrls(this.properties.determineUrls(this.environment));
source.setBaseEnvironmentProperties(
Collections.unmodifiableMap(this.properties.getBaseEnvironment()));
return source;
}
@Bean
@ConditionalOnMissingBean(LdapOperations.class)
public LdapTemplate ldapTemplate(ContextSource contextSource) {
LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
ldapTemplate.setIgnorePartialResultException(true);
return ldapTemplate;
}
}
@Order(99)
@Profile("ldap")
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class SpringSecurityLDAPConfigurer extends WebSecurityConfigurerAdapter {
private final LdapProperties ldapProperties;
private final LdapContextSource ldapContextSource;
private final LdapExtendProperties ldapExtendProperties;
public SpringSecurityLDAPConfigurer(final LdapProperties ldapProperties,
final LdapContextSource ldapContextSource,
final LdapExtendProperties ldapExtendProperties) {
this.ldapProperties = ldapProperties;
this.ldapContextSource = ldapContextSource;
this.ldapExtendProperties = ldapExtendProperties;
}
@Bean
public FilterBasedLdapUserSearch userSearch() {
if (ldapExtendProperties.getGroup() == null || StringUtils
.isBlank(ldapExtendProperties.getGroup().getGroupSearch())) {
FilterBasedLdapUserSearch filterBasedLdapUserSearch = new FilterBasedLdapUserSearch("",
ldapProperties.getSearchFilter(), ldapContextSource);
filterBasedLdapUserSearch.setSearchSubtree(true);
return filterBasedLdapUserSearch;
}
FilterLdapByGroupUserSearch filterLdapByGroupUserSearch = new FilterLdapByGroupUserSearch(
ldapProperties.getBase(), ldapProperties.getSearchFilter(), ldapExtendProperties.getGroup().getGroupBase(),
ldapContextSource, ldapExtendProperties.getGroup().getGroupSearch(),
ldapExtendProperties.getMapping().getRdnKey(),
ldapExtendProperties.getGroup().getGroupMembership(),ldapExtendProperties.getMapping().getLoginId());
filterLdapByGroupUserSearch.setSearchSubtree(true);
return filterLdapByGroupUserSearch;
}
@Bean
public LdapAuthenticationProvider ldapAuthProvider() {
BindAuthenticator bindAuthenticator = new BindAuthenticator(ldapContextSource);
bindAuthenticator.setUserSearch(userSearch());
DefaultLdapAuthoritiesPopulator defaultAuthAutoConfiguration = new DefaultLdapAuthoritiesPopulator(
ldapContextSource, null);
defaultAuthAutoConfiguration.setIgnorePartialResultException(true);
defaultAuthAutoConfiguration.setSearchSubtree(true);
// Rewrite the logic of LdapAuthenticationProvider with ApolloLdapAuthenticationProvider,
// use userId in LDAP system instead of userId input by user.
return new ApolloLdapAuthenticationProvider(
bindAuthenticator, defaultAuthAutoConfiguration, ldapExtendProperties);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
http.authorizeRequests()
.antMatchers(BY_PASS_URLS).permitAll()
.antMatchers("/**").authenticated();
http.formLogin().loginPage("/signin").defaultSuccessUrl("/", true).permitAll().failureUrl("/signin?#/error").and()
.httpBasic();
http.logout().logoutUrl("/user/logout").invalidateHttpSession(true).clearAuthentication(true)
.logoutSuccessUrl("/signin?#/logout");
http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/signin"));
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(ldapAuthProvider());
}
}
@Profile("oidc")
@EnableConfigurationProperties({OAuth2ClientProperties.class, OAuth2ResourceServerProperties.class})
@Configuration
static class OidcAuthAutoConfiguration {
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public UserInfoHolder oidcUserInfoHolder(UserService userService) {
return new OidcUserInfoHolder(userService);
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public LogoutHandler oidcLogoutHandler() {
return new OidcLogoutHandler();
}
@Bean
@ConditionalOnMissingBean(JdbcUserDetailsManager.class)
public JdbcUserDetailsManager jdbcUserDetailsManager(AuthenticationManagerBuilder auth,
DataSource datasource) throws Exception {
return new SpringSecurityAuthAutoConfiguration().jdbcUserDetailsManager(auth, datasource);
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public OidcLocalUserService oidcLocalUserService(JdbcUserDetailsManager userDetailsManager,
UserRepository userRepository) {
return new OidcLocalUserServiceImpl(userDetailsManager, userRepository);
}
@Bean
public OidcAuthenticationSuccessEventListener oidcAuthenticationSuccessEventListener(OidcLocalUserService oidcLocalUserService) {
return new OidcAuthenticationSuccessEventListener(oidcLocalUserService);
}
}
@Profile("oidc")
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
static class OidcWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
private final InMemoryClientRegistrationRepository clientRegistrationRepository;
private final OAuth2ResourceServerProperties oauth2ResourceServerProperties;
public OidcWebSecurityConfigurerAdapter(
InMemoryClientRegistrationRepository clientRegistrationRepository,
OAuth2ResourceServerProperties oauth2ResourceServerProperties) {
this.clientRegistrationRepository = clientRegistrationRepository;
this.oauth2ResourceServerProperties = oauth2ResourceServerProperties;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests(requests -> requests.antMatchers(BY_PASS_URLS).permitAll());
http.authorizeRequests(requests -> requests.anyRequest().authenticated());
http.oauth2Login(configure ->
configure.clientRegistrationRepository(
new ExcludeClientCredentialsClientRegistrationRepository(
this.clientRegistrationRepository)));
http.oauth2Client();
http.logout(configure -> {
OidcClientInitiatedLogoutSuccessHandler logoutSuccessHandler = new OidcClientInitiatedLogoutSuccessHandler(
this.clientRegistrationRepository);
logoutSuccessHandler.setPostLogoutRedirectUri("{baseUrl}");
configure.logoutSuccessHandler(logoutSuccessHandler);
});
// make jwt optional
String jwtIssuerUri = this.oauth2ResourceServerProperties.getJwt().getIssuerUri();
if (!StringUtils.isBlank(jwtIssuerUri)) {
http.oauth2ResourceServer().jwt();
}
}
}
/**
* default profile
*/
@Configuration
@ConditionalOnMissingProfile({"ctrip", "auth", "ldap", "oidc"})
static class DefaultAuthAutoConfiguration {
@Bean
@ConditionalOnMissingBean(SsoHeartbeatHandler.class)
public SsoHeartbeatHandler defaultSsoHeartbeatHandler() {
return new DefaultSsoHeartbeatHandler();
}
@Bean
@ConditionalOnMissingBean(UserInfoHolder.class)
public DefaultUserInfoHolder defaultUserInfoHolder() {
return new DefaultUserInfoHolder();
}
@Bean
@ConditionalOnMissingBean(LogoutHandler.class)
public DefaultLogoutHandler logoutHandler() {
return new DefaultLogoutHandler();
}
@Bean
@ConditionalOnMissingBean(UserService.class)
public UserService defaultUserService() {
return new DefaultUserService();
}
}
@ConditionalOnMissingProfile({"auth", "ldap", "oidc"})
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
static class DefaultWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.headers().frameOptions().sameOrigin();
}
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./docs/zh/usage/third-party-sdks-user-guide.md | ## 1. Go
### Apollo Go 客户端 1
项目地址:[zouyx/agollo](https://github.com/zouyx/agollo)
> 非常感谢[@zouyx](https://github.com/zouyx)提供Go Apollo客户端的支持
### Apollo Go 客户端 2
项目地址:[philchia/agollo](https://github.com/philchia/agollo)
> 非常感谢[@philchia](https://github.com/philchia)提供Go Apollo客户端的支持
### Apollo Go 客户端 3
项目地址:[shima-park/agollo](https://github.com/shima-park/agollo)
> 非常感谢[@shima-park](https://github.com/shima-park)提供Go Apollo客户端的支持
### Apollo Go 客户端 4
项目地址:[go-microservices/php_conf_agent](https://github.com/go-microservices/php_conf_agent)
> 非常感谢[@GanymedeNil](https://github.com/GanymedeNil)提供Go Apollo客户端的支持
### Apollo Go 客户端 5
项目地址:[hyperjiang/lunar](https://github.com/hyperjiang/lunar)
> 非常感谢[@hyperjiang](https://github.com/hyperjiang)提供Go Apollo客户端的支持
### Apollo Go 客户端 6
项目地址:[tagconfig/tagconfig](https://github.com/tagconfig/tagconfig)
> 非常感谢[@n0trace](https://github.com/n0trace)提供Go Apollo客户端的支持
### Apollo Go 客户端 7
项目地址:[go-chassis/go-archaius](https://github.com/go-chassis/go-archaius/tree/master/examples/apollo)
> 非常感谢[@tianxiaoliang](https://github.com/tianxiaoliang) 和 [@Shonminh](https://github.com/Shonminh)提供Go Apollo客户端的支持
### Apollo Go 客户端 8
项目地址:[xhrg-product/apollo-client-golang](https://github.com/xhrg-product/apollo-client-golang)
> 非常感谢[@xhrg](https://github.com/xhrg)提供Go Apollo客户端的支持
## 2. Python
### Apollo Python 客户端 1
项目地址:[pyapollo](https://github.com/filamoon/pyapollo)
> 非常感谢[@filamoon](https://github.com/filamoon)提供Python Apollo客户端的支持
### Apollo Python 客户端 2
项目地址:[BruceWW-pyapollo](https://github.com/BruceWW/pyapollo)
> 非常感谢[@BruceWW](https://github.com/BruceWW)提供Python Apollo客户端的支持
### Apollo Python 客户端 3
项目地址:[xhrg-product/apollo-client-python](https://github.com/xhrg-product/apollo-client-python)
> 非常感谢[@xhrg-product](https://github.com/xhrg-product)提供Python Apollo客户端的支持
## 3. NodeJS
### Apollo NodeJS 客户端 1
项目地址:[node-apollo](https://github.com/Quinton/node-apollo)
> 非常感谢[@Quinton](https://github.com/Quinton)提供NodeJS Apollo客户端的支持
### Apollo NodeJS 客户端 2
项目地址:[ctrip-apollo](https://github.com/kaelzhang/ctrip-apollo)
> 非常感谢[@kaelzhang](https://github.com/kaelzhang)提供NodeJS Apollo客户端的支持
### Apollo NodeJS 客户端 3
项目地址:[node-apollo-client](https://github.com/shinux/node-apollo-client)
> 非常感谢[@shinux](https://github.com/shinux)提供NodeJS Apollo客户端的支持
### Apollo NodeJS 客户端 4
项目地址:[ctrip-apollo-client](https://github.com/lvgithub/ctrip-apollo-client)
> 非常感谢[@lvgithub](https://github.com/lvgithub)提供NodeJS Apollo客户端的支持
### Apollo NodeJS 客户端 5
项目地址:[apollo-node](https://github.com/lengyuxuan/apollo-node)
> 非常感谢[@lengyuxuan](https://github.com/lengyuxuan)提供NodeJS Apollo客户端的支持
### Apollo NodeJS 客户端 6
项目地址:[egg-apollo-client](https://github.com/xuezier/egg-apollo-client)
> 非常感谢[@xuezier](https://github.com/xuezier)提供NodeJS Apollo客户端的支持
### Apollo NodeJS 客户端 7
项目地址:[apollo-node-client](https://github.com/zhangxh1023/apollo-node-client)
> 非常感谢[@zhangxh1023](https://github.com/zhangxh1023)提供NodeJS Apollo客户端的支持
## 4. PHP
### Apollo PHP 客户端 1
项目地址:[apollo-php-client](https://github.com/multilinguals/apollo-php-client)
> 非常感谢[@t04041143](https://github.com/t04041143)提供PHP Apollo客户端的支持
### Apollo PHP 客户端 2
项目地址:[apollo-sdk-config](https://github.com/fengzhibin/apollo-sdk-config)
项目地址:[apollo-sdk-clientd](https://github.com/fengzhibin/apollo-sdk-clientd)
> 非常感谢[@fengzhibin](https://github.com/fengzhibin)提供PHP Apollo客户端的支持
## 5. C
### Apollo C 客户端
项目地址:[apollo-c-client](https://github.com/lzeqian/apollo)
> 非常感谢[@lzeqian](https://github.com/lzeqian)提供C Apollo客户端的支持
| ## 1. Go
### Apollo Go 客户端 1
项目地址:[zouyx/agollo](https://github.com/zouyx/agollo)
> 非常感谢[@zouyx](https://github.com/zouyx)提供Go Apollo客户端的支持
### Apollo Go 客户端 2
项目地址:[philchia/agollo](https://github.com/philchia/agollo)
> 非常感谢[@philchia](https://github.com/philchia)提供Go Apollo客户端的支持
### Apollo Go 客户端 3
项目地址:[shima-park/agollo](https://github.com/shima-park/agollo)
> 非常感谢[@shima-park](https://github.com/shima-park)提供Go Apollo客户端的支持
### Apollo Go 客户端 4
项目地址:[go-microservices/php_conf_agent](https://github.com/go-microservices/php_conf_agent)
> 非常感谢[@GanymedeNil](https://github.com/GanymedeNil)提供Go Apollo客户端的支持
### Apollo Go 客户端 5
项目地址:[hyperjiang/lunar](https://github.com/hyperjiang/lunar)
> 非常感谢[@hyperjiang](https://github.com/hyperjiang)提供Go Apollo客户端的支持
### Apollo Go 客户端 6
项目地址:[tagconfig/tagconfig](https://github.com/tagconfig/tagconfig)
> 非常感谢[@n0trace](https://github.com/n0trace)提供Go Apollo客户端的支持
### Apollo Go 客户端 7
项目地址:[go-chassis/go-archaius](https://github.com/go-chassis/go-archaius/tree/master/examples/apollo)
> 非常感谢[@tianxiaoliang](https://github.com/tianxiaoliang) 和 [@Shonminh](https://github.com/Shonminh)提供Go Apollo客户端的支持
### Apollo Go 客户端 8
项目地址:[xhrg-product/apollo-client-golang](https://github.com/xhrg-product/apollo-client-golang)
> 非常感谢[@xhrg](https://github.com/xhrg)提供Go Apollo客户端的支持
## 2. Python
### Apollo Python 客户端 1
项目地址:[pyapollo](https://github.com/filamoon/pyapollo)
> 非常感谢[@filamoon](https://github.com/filamoon)提供Python Apollo客户端的支持
### Apollo Python 客户端 2
项目地址:[BruceWW-pyapollo](https://github.com/BruceWW/pyapollo)
> 非常感谢[@BruceWW](https://github.com/BruceWW)提供Python Apollo客户端的支持
### Apollo Python 客户端 3
项目地址:[xhrg-product/apollo-client-python](https://github.com/xhrg-product/apollo-client-python)
> 非常感谢[@xhrg-product](https://github.com/xhrg-product)提供Python Apollo客户端的支持
## 3. NodeJS
### Apollo NodeJS 客户端 1
项目地址:[node-apollo](https://github.com/Quinton/node-apollo)
> 非常感谢[@Quinton](https://github.com/Quinton)提供NodeJS Apollo客户端的支持
### Apollo NodeJS 客户端 2
项目地址:[ctrip-apollo](https://github.com/kaelzhang/ctrip-apollo)
> 非常感谢[@kaelzhang](https://github.com/kaelzhang)提供NodeJS Apollo客户端的支持
### Apollo NodeJS 客户端 3
项目地址:[node-apollo-client](https://github.com/shinux/node-apollo-client)
> 非常感谢[@shinux](https://github.com/shinux)提供NodeJS Apollo客户端的支持
### Apollo NodeJS 客户端 4
项目地址:[ctrip-apollo-client](https://github.com/lvgithub/ctrip-apollo-client)
> 非常感谢[@lvgithub](https://github.com/lvgithub)提供NodeJS Apollo客户端的支持
### Apollo NodeJS 客户端 5
项目地址:[apollo-node](https://github.com/lengyuxuan/apollo-node)
> 非常感谢[@lengyuxuan](https://github.com/lengyuxuan)提供NodeJS Apollo客户端的支持
### Apollo NodeJS 客户端 6
项目地址:[egg-apollo-client](https://github.com/xuezier/egg-apollo-client)
> 非常感谢[@xuezier](https://github.com/xuezier)提供NodeJS Apollo客户端的支持
### Apollo NodeJS 客户端 7
项目地址:[apollo-node-client](https://github.com/zhangxh1023/apollo-node-client)
> 非常感谢[@zhangxh1023](https://github.com/zhangxh1023)提供NodeJS Apollo客户端的支持
## 4. PHP
### Apollo PHP 客户端 1
项目地址:[apollo-php-client](https://github.com/multilinguals/apollo-php-client)
> 非常感谢[@t04041143](https://github.com/t04041143)提供PHP Apollo客户端的支持
### Apollo PHP 客户端 2
项目地址:[apollo-sdk-config](https://github.com/fengzhibin/apollo-sdk-config)
项目地址:[apollo-sdk-clientd](https://github.com/fengzhibin/apollo-sdk-clientd)
> 非常感谢[@fengzhibin](https://github.com/fengzhibin)提供PHP Apollo客户端的支持
## 5. C
### Apollo C 客户端
项目地址:[apollo-c-client](https://github.com/lzeqian/apollo)
> 非常感谢[@lzeqian](https://github.com/lzeqian)提供C Apollo客户端的支持
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.spring.spi.ConfigPropertySourcesProcessorHelper | com.ctrip.framework.apollo.spring.spi.TestProcessorHelper
| com.ctrip.framework.apollo.spring.spi.TestProcessorHelper
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/component/emailbuilder/ConfigPublishEmailBuilder.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.component.emailbuilder;
import com.google.common.collect.Lists;
import com.ctrip.framework.apollo.common.constants.ReleaseOperation;
import com.ctrip.framework.apollo.common.constants.ReleaseOperationContext;
import com.ctrip.framework.apollo.common.dto.ReleaseDTO;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.constant.RoleType;
import com.ctrip.framework.apollo.portal.entity.bo.Email;
import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import com.ctrip.framework.apollo.portal.entity.vo.Change;
import com.ctrip.framework.apollo.portal.entity.vo.ReleaseCompareResult;
import com.ctrip.framework.apollo.portal.service.AppNamespaceService;
import com.ctrip.framework.apollo.portal.service.ReleaseService;
import com.ctrip.framework.apollo.portal.service.RolePermissionService;
import com.ctrip.framework.apollo.portal.spi.UserService;
import com.ctrip.framework.apollo.portal.util.RoleUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
public abstract class ConfigPublishEmailBuilder {
private static final String EMERGENCY_PUBLISH_TAG = "<span style='color:red'>(紧急发布)</span>";
//email content common field placeholder
private static final String EMAIL_CONTENT_FIELD_APPID = "#\\{appId\\}";
private static final String EMAIL_CONTENT_FIELD_ENV = "#\\{env}";
private static final String EMAIL_CONTENT_FIELD_CLUSTER = "#\\{clusterName}";
private static final String EMAIL_CONTENT_FIELD_NAMESPACE = "#\\{namespaceName}";
private static final String EMAIL_CONTENT_FIELD_OPERATOR = "#\\{operator}";
private static final String EMAIL_CONTENT_FIELD_RELEASE_TIME = "#\\{releaseTime}";
private static final String EMAIL_CONTENT_FIELD_RELEASE_ID = "#\\{releaseId}";
private static final String EMAIL_CONTENT_FIELD_RELEASE_HISTORY_ID = "#\\{releaseHistoryId}";
private static final String EMAIL_CONTENT_FIELD_RELEASE_TITLE = "#\\{releaseTitle}";
private static final String EMAIL_CONTENT_FIELD_RELEASE_COMMENT = "#\\{releaseComment}";
private static final String EMAIL_CONTENT_FIELD_APOLLO_SERVER_ADDRESS = "#\\{apollo.portal.address}";
private static final String EMAIL_CONTENT_FIELD_DIFF_CONTENT = "#\\{diffContent}";
private static final String EMAIL_CONTENT_FIELD_EMERGENCY_PUBLISH = "#\\{emergencyPublish}";
private static final String EMAIL_CONTENT_DIFF_MODULE = "#\\{diffModule}";
protected static final String EMAIL_CONTENT_GRAY_RULES_MODULE = "#\\{rulesModule}";
//email content special field placeholder
protected static final String EMAIL_CONTENT_GRAY_RULES_CONTENT = "#\\{rulesContent}";
//set config's value max length to protect email.
protected static final int VALUE_MAX_LENGTH = 100;
protected FastDateFormat dateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
@Autowired
private RolePermissionService rolePermissionService;
@Autowired
private ReleaseService releaseService;
@Autowired
private AppNamespaceService appNamespaceService;
@Autowired
private UserService userService;
@Autowired
protected PortalConfig portalConfig;
/**
* email subject
*/
protected abstract String subject();
/**
* email body content
*/
protected abstract String emailContent(Env env, ReleaseHistoryBO releaseHistory);
/**
* email body template framework
*/
protected abstract String getTemplateFramework();
/**
* email body diff module template
*/
protected abstract String getDiffModuleTemplate();
public Email build(Env env, ReleaseHistoryBO releaseHistory) {
Email email = new Email();
email.setSubject(subject());
email.setSenderEmailAddress(portalConfig.emailSender());
email.setRecipients(recipients(releaseHistory.getAppId(), releaseHistory.getNamespaceName(), env.toString()));
String emailBody = emailContent(env, releaseHistory);
//clear not used module
emailBody = emailBody.replaceAll(EMAIL_CONTENT_DIFF_MODULE, "");
emailBody = emailBody.replaceAll(EMAIL_CONTENT_GRAY_RULES_MODULE, "");
email.setBody(emailBody);
return email;
}
protected String renderEmailCommonContent(Env env, ReleaseHistoryBO releaseHistory) {
String template = getTemplateFramework();
String renderResult = renderReleaseBasicInfo(template, env, releaseHistory);
renderResult = renderDiffModule(renderResult, env, releaseHistory);
return renderResult;
}
private String renderReleaseBasicInfo(String template, Env env, ReleaseHistoryBO releaseHistory) {
String renderResult = template;
Map<String, Object> operationContext = releaseHistory.getOperationContext();
boolean isEmergencyPublish = operationContext.containsKey(ReleaseOperationContext.IS_EMERGENCY_PUBLISH) &&
(boolean) operationContext.get(ReleaseOperationContext.IS_EMERGENCY_PUBLISH);
if (isEmergencyPublish) {
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_EMERGENCY_PUBLISH, Matcher.quoteReplacement(EMERGENCY_PUBLISH_TAG));
} else {
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_EMERGENCY_PUBLISH, "");
}
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_APPID, Matcher.quoteReplacement(releaseHistory.getAppId()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_ENV, Matcher.quoteReplacement(env.toString()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_CLUSTER, Matcher.quoteReplacement(releaseHistory.getClusterName()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_NAMESPACE, Matcher.quoteReplacement(releaseHistory.getNamespaceName()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_OPERATOR, Matcher.quoteReplacement(releaseHistory.getOperator()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_RELEASE_TITLE, Matcher.quoteReplacement(releaseHistory.getReleaseTitle()));
renderResult =
renderResult.replaceAll(EMAIL_CONTENT_FIELD_RELEASE_ID, String.valueOf(releaseHistory.getReleaseId()));
renderResult =
renderResult.replaceAll(EMAIL_CONTENT_FIELD_RELEASE_HISTORY_ID, String.valueOf(releaseHistory.getId()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_RELEASE_COMMENT, Matcher.quoteReplacement(releaseHistory.getReleaseComment() == null ? "" : releaseHistory.getReleaseComment()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_APOLLO_SERVER_ADDRESS, getApolloPortalAddress());
return renderResult
.replaceAll(EMAIL_CONTENT_FIELD_RELEASE_TIME, dateFormat.format(releaseHistory.getReleaseTime()));
}
private String renderDiffModule(String bodyTemplate, Env env, ReleaseHistoryBO releaseHistory) {
String appId = releaseHistory.getAppId();
String namespaceName = releaseHistory.getNamespaceName();
AppNamespace appNamespace = appNamespaceService.findByAppIdAndName(appId, namespaceName);
if (appNamespace == null) {
appNamespace = appNamespaceService.findPublicAppNamespace(namespaceName);
}
//don't show diff content if namespace's format is file
if (appNamespace == null ||
!appNamespace.getFormat().equals(ConfigFileFormat.Properties.getValue())) {
return bodyTemplate.replaceAll(EMAIL_CONTENT_DIFF_MODULE, "<br><h4>变更内容请点击链接到Apollo上查看</h4>");
}
ReleaseCompareResult result = getReleaseCompareResult(env, releaseHistory);
if (!result.hasContent()) {
return bodyTemplate.replaceAll(EMAIL_CONTENT_DIFF_MODULE, "<br><h4>无配置变更</h4>");
}
List<Change> changes = result.getChanges();
StringBuilder changesHtmlBuilder = new StringBuilder();
for (Change change : changes) {
String key = change.getEntity().getFirstEntity().getKey();
String oldValue = change.getEntity().getFirstEntity().getValue();
String newValue = change.getEntity().getSecondEntity().getValue();
newValue = newValue == null ? "" : newValue;
changesHtmlBuilder.append("<tr>");
changesHtmlBuilder.append("<td width=\"10%\">").append(change.getType().toString()).append("</td>");
changesHtmlBuilder.append("<td width=\"20%\">").append(cutOffString(key)).append("</td>");
changesHtmlBuilder.append("<td width=\"35%\">").append(cutOffString(oldValue)).append("</td>");
changesHtmlBuilder.append("<td width=\"35%\">").append(cutOffString(newValue)).append("</td>");
changesHtmlBuilder.append("</tr>");
}
String diffContent = Matcher.quoteReplacement(changesHtmlBuilder.toString());
String diffModuleTemplate = getDiffModuleTemplate();
String diffModuleRenderResult = diffModuleTemplate.replaceAll(EMAIL_CONTENT_FIELD_DIFF_CONTENT, diffContent);
return bodyTemplate.replaceAll(EMAIL_CONTENT_DIFF_MODULE, diffModuleRenderResult);
}
private ReleaseCompareResult getReleaseCompareResult(Env env, ReleaseHistoryBO releaseHistory) {
if (releaseHistory.getOperation() == ReleaseOperation.GRAY_RELEASE
&& releaseHistory.getPreviousReleaseId() == 0) {
ReleaseDTO masterLatestActiveRelease = releaseService.loadLatestRelease(
releaseHistory.getAppId(), env, releaseHistory.getClusterName(), releaseHistory.getNamespaceName());
ReleaseDTO branchLatestActiveRelease = releaseService.findReleaseById(env, releaseHistory.getReleaseId());
return releaseService.compare(masterLatestActiveRelease, branchLatestActiveRelease);
}
return releaseService.compare(env, releaseHistory.getPreviousReleaseId(), releaseHistory.getReleaseId());
}
private List<String> recipients(String appId, String namespaceName, String env) {
Set<UserInfo> modifyRoleUsers =
rolePermissionService
.queryUsersWithRole(RoleUtils.buildNamespaceRoleName(appId, namespaceName, RoleType.MODIFY_NAMESPACE));
Set<UserInfo> envModifyRoleUsers =
rolePermissionService
.queryUsersWithRole(RoleUtils.buildNamespaceRoleName(appId, namespaceName, RoleType.MODIFY_NAMESPACE, env));
Set<UserInfo> releaseRoleUsers =
rolePermissionService
.queryUsersWithRole(RoleUtils.buildNamespaceRoleName(appId, namespaceName, RoleType.RELEASE_NAMESPACE));
Set<UserInfo> envReleaseRoleUsers =
rolePermissionService
.queryUsersWithRole(RoleUtils.buildNamespaceRoleName(appId, namespaceName, RoleType.RELEASE_NAMESPACE, env));
Set<UserInfo> owners = rolePermissionService.queryUsersWithRole(RoleUtils.buildAppMasterRoleName(appId));
Set<String> userIds = new HashSet<>(modifyRoleUsers.size() + releaseRoleUsers.size() + owners.size());
for (UserInfo userInfo : modifyRoleUsers) {
userIds.add(userInfo.getUserId());
}
for (UserInfo userInfo : envModifyRoleUsers) {
userIds.add(userInfo.getUserId());
}
for (UserInfo userInfo : releaseRoleUsers) {
userIds.add(userInfo.getUserId());
}
for (UserInfo userInfo : envReleaseRoleUsers) {
userIds.add(userInfo.getUserId());
}
for (UserInfo userInfo : owners) {
userIds.add(userInfo.getUserId());
}
List<UserInfo> userInfos = userService.findByUserIds(Lists.newArrayList(userIds));
if (CollectionUtils.isEmpty(userInfos)) {
return Collections.emptyList();
}
List<String> recipients = new ArrayList<>(userInfos.size());
for (UserInfo userInfo : userInfos) {
recipients.add(userInfo.getEmail());
}
return recipients;
}
protected String getApolloPortalAddress() {
return portalConfig.portalAddress();
}
private String cutOffString(String source) {
if (source.length() > VALUE_MAX_LENGTH) {
return source.substring(0, VALUE_MAX_LENGTH) + "...";
}
return source;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.component.emailbuilder;
import com.google.common.collect.Lists;
import com.ctrip.framework.apollo.common.constants.ReleaseOperation;
import com.ctrip.framework.apollo.common.constants.ReleaseOperationContext;
import com.ctrip.framework.apollo.common.dto.ReleaseDTO;
import com.ctrip.framework.apollo.common.entity.AppNamespace;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.portal.environment.Env;
import com.ctrip.framework.apollo.portal.component.config.PortalConfig;
import com.ctrip.framework.apollo.portal.constant.RoleType;
import com.ctrip.framework.apollo.portal.entity.bo.Email;
import com.ctrip.framework.apollo.portal.entity.bo.ReleaseHistoryBO;
import com.ctrip.framework.apollo.portal.entity.bo.UserInfo;
import com.ctrip.framework.apollo.portal.entity.vo.Change;
import com.ctrip.framework.apollo.portal.entity.vo.ReleaseCompareResult;
import com.ctrip.framework.apollo.portal.service.AppNamespaceService;
import com.ctrip.framework.apollo.portal.service.ReleaseService;
import com.ctrip.framework.apollo.portal.service.RolePermissionService;
import com.ctrip.framework.apollo.portal.spi.UserService;
import com.ctrip.framework.apollo.portal.util.RoleUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
public abstract class ConfigPublishEmailBuilder {
private static final String EMERGENCY_PUBLISH_TAG = "<span style='color:red'>(紧急发布)</span>";
//email content common field placeholder
private static final String EMAIL_CONTENT_FIELD_APPID = "#\\{appId\\}";
private static final String EMAIL_CONTENT_FIELD_ENV = "#\\{env}";
private static final String EMAIL_CONTENT_FIELD_CLUSTER = "#\\{clusterName}";
private static final String EMAIL_CONTENT_FIELD_NAMESPACE = "#\\{namespaceName}";
private static final String EMAIL_CONTENT_FIELD_OPERATOR = "#\\{operator}";
private static final String EMAIL_CONTENT_FIELD_RELEASE_TIME = "#\\{releaseTime}";
private static final String EMAIL_CONTENT_FIELD_RELEASE_ID = "#\\{releaseId}";
private static final String EMAIL_CONTENT_FIELD_RELEASE_HISTORY_ID = "#\\{releaseHistoryId}";
private static final String EMAIL_CONTENT_FIELD_RELEASE_TITLE = "#\\{releaseTitle}";
private static final String EMAIL_CONTENT_FIELD_RELEASE_COMMENT = "#\\{releaseComment}";
private static final String EMAIL_CONTENT_FIELD_APOLLO_SERVER_ADDRESS = "#\\{apollo.portal.address}";
private static final String EMAIL_CONTENT_FIELD_DIFF_CONTENT = "#\\{diffContent}";
private static final String EMAIL_CONTENT_FIELD_EMERGENCY_PUBLISH = "#\\{emergencyPublish}";
private static final String EMAIL_CONTENT_DIFF_MODULE = "#\\{diffModule}";
protected static final String EMAIL_CONTENT_GRAY_RULES_MODULE = "#\\{rulesModule}";
//email content special field placeholder
protected static final String EMAIL_CONTENT_GRAY_RULES_CONTENT = "#\\{rulesContent}";
//set config's value max length to protect email.
protected static final int VALUE_MAX_LENGTH = 100;
protected FastDateFormat dateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
@Autowired
private RolePermissionService rolePermissionService;
@Autowired
private ReleaseService releaseService;
@Autowired
private AppNamespaceService appNamespaceService;
@Autowired
private UserService userService;
@Autowired
protected PortalConfig portalConfig;
/**
* email subject
*/
protected abstract String subject();
/**
* email body content
*/
protected abstract String emailContent(Env env, ReleaseHistoryBO releaseHistory);
/**
* email body template framework
*/
protected abstract String getTemplateFramework();
/**
* email body diff module template
*/
protected abstract String getDiffModuleTemplate();
public Email build(Env env, ReleaseHistoryBO releaseHistory) {
Email email = new Email();
email.setSubject(subject());
email.setSenderEmailAddress(portalConfig.emailSender());
email.setRecipients(recipients(releaseHistory.getAppId(), releaseHistory.getNamespaceName(), env.toString()));
String emailBody = emailContent(env, releaseHistory);
//clear not used module
emailBody = emailBody.replaceAll(EMAIL_CONTENT_DIFF_MODULE, "");
emailBody = emailBody.replaceAll(EMAIL_CONTENT_GRAY_RULES_MODULE, "");
email.setBody(emailBody);
return email;
}
protected String renderEmailCommonContent(Env env, ReleaseHistoryBO releaseHistory) {
String template = getTemplateFramework();
String renderResult = renderReleaseBasicInfo(template, env, releaseHistory);
renderResult = renderDiffModule(renderResult, env, releaseHistory);
return renderResult;
}
private String renderReleaseBasicInfo(String template, Env env, ReleaseHistoryBO releaseHistory) {
String renderResult = template;
Map<String, Object> operationContext = releaseHistory.getOperationContext();
boolean isEmergencyPublish = operationContext.containsKey(ReleaseOperationContext.IS_EMERGENCY_PUBLISH) &&
(boolean) operationContext.get(ReleaseOperationContext.IS_EMERGENCY_PUBLISH);
if (isEmergencyPublish) {
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_EMERGENCY_PUBLISH, Matcher.quoteReplacement(EMERGENCY_PUBLISH_TAG));
} else {
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_EMERGENCY_PUBLISH, "");
}
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_APPID, Matcher.quoteReplacement(releaseHistory.getAppId()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_ENV, Matcher.quoteReplacement(env.toString()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_CLUSTER, Matcher.quoteReplacement(releaseHistory.getClusterName()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_NAMESPACE, Matcher.quoteReplacement(releaseHistory.getNamespaceName()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_OPERATOR, Matcher.quoteReplacement(releaseHistory.getOperator()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_RELEASE_TITLE, Matcher.quoteReplacement(releaseHistory.getReleaseTitle()));
renderResult =
renderResult.replaceAll(EMAIL_CONTENT_FIELD_RELEASE_ID, String.valueOf(releaseHistory.getReleaseId()));
renderResult =
renderResult.replaceAll(EMAIL_CONTENT_FIELD_RELEASE_HISTORY_ID, String.valueOf(releaseHistory.getId()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_RELEASE_COMMENT, Matcher.quoteReplacement(releaseHistory.getReleaseComment() == null ? "" : releaseHistory.getReleaseComment()));
renderResult = renderResult.replaceAll(EMAIL_CONTENT_FIELD_APOLLO_SERVER_ADDRESS, getApolloPortalAddress());
return renderResult
.replaceAll(EMAIL_CONTENT_FIELD_RELEASE_TIME, dateFormat.format(releaseHistory.getReleaseTime()));
}
private String renderDiffModule(String bodyTemplate, Env env, ReleaseHistoryBO releaseHistory) {
String appId = releaseHistory.getAppId();
String namespaceName = releaseHistory.getNamespaceName();
AppNamespace appNamespace = appNamespaceService.findByAppIdAndName(appId, namespaceName);
if (appNamespace == null) {
appNamespace = appNamespaceService.findPublicAppNamespace(namespaceName);
}
//don't show diff content if namespace's format is file
if (appNamespace == null ||
!appNamespace.getFormat().equals(ConfigFileFormat.Properties.getValue())) {
return bodyTemplate.replaceAll(EMAIL_CONTENT_DIFF_MODULE, "<br><h4>变更内容请点击链接到Apollo上查看</h4>");
}
ReleaseCompareResult result = getReleaseCompareResult(env, releaseHistory);
if (!result.hasContent()) {
return bodyTemplate.replaceAll(EMAIL_CONTENT_DIFF_MODULE, "<br><h4>无配置变更</h4>");
}
List<Change> changes = result.getChanges();
StringBuilder changesHtmlBuilder = new StringBuilder();
for (Change change : changes) {
String key = change.getEntity().getFirstEntity().getKey();
String oldValue = change.getEntity().getFirstEntity().getValue();
String newValue = change.getEntity().getSecondEntity().getValue();
newValue = newValue == null ? "" : newValue;
changesHtmlBuilder.append("<tr>");
changesHtmlBuilder.append("<td width=\"10%\">").append(change.getType().toString()).append("</td>");
changesHtmlBuilder.append("<td width=\"20%\">").append(cutOffString(key)).append("</td>");
changesHtmlBuilder.append("<td width=\"35%\">").append(cutOffString(oldValue)).append("</td>");
changesHtmlBuilder.append("<td width=\"35%\">").append(cutOffString(newValue)).append("</td>");
changesHtmlBuilder.append("</tr>");
}
String diffContent = Matcher.quoteReplacement(changesHtmlBuilder.toString());
String diffModuleTemplate = getDiffModuleTemplate();
String diffModuleRenderResult = diffModuleTemplate.replaceAll(EMAIL_CONTENT_FIELD_DIFF_CONTENT, diffContent);
return bodyTemplate.replaceAll(EMAIL_CONTENT_DIFF_MODULE, diffModuleRenderResult);
}
private ReleaseCompareResult getReleaseCompareResult(Env env, ReleaseHistoryBO releaseHistory) {
if (releaseHistory.getOperation() == ReleaseOperation.GRAY_RELEASE
&& releaseHistory.getPreviousReleaseId() == 0) {
ReleaseDTO masterLatestActiveRelease = releaseService.loadLatestRelease(
releaseHistory.getAppId(), env, releaseHistory.getClusterName(), releaseHistory.getNamespaceName());
ReleaseDTO branchLatestActiveRelease = releaseService.findReleaseById(env, releaseHistory.getReleaseId());
return releaseService.compare(masterLatestActiveRelease, branchLatestActiveRelease);
}
return releaseService.compare(env, releaseHistory.getPreviousReleaseId(), releaseHistory.getReleaseId());
}
private List<String> recipients(String appId, String namespaceName, String env) {
Set<UserInfo> modifyRoleUsers =
rolePermissionService
.queryUsersWithRole(RoleUtils.buildNamespaceRoleName(appId, namespaceName, RoleType.MODIFY_NAMESPACE));
Set<UserInfo> envModifyRoleUsers =
rolePermissionService
.queryUsersWithRole(RoleUtils.buildNamespaceRoleName(appId, namespaceName, RoleType.MODIFY_NAMESPACE, env));
Set<UserInfo> releaseRoleUsers =
rolePermissionService
.queryUsersWithRole(RoleUtils.buildNamespaceRoleName(appId, namespaceName, RoleType.RELEASE_NAMESPACE));
Set<UserInfo> envReleaseRoleUsers =
rolePermissionService
.queryUsersWithRole(RoleUtils.buildNamespaceRoleName(appId, namespaceName, RoleType.RELEASE_NAMESPACE, env));
Set<UserInfo> owners = rolePermissionService.queryUsersWithRole(RoleUtils.buildAppMasterRoleName(appId));
Set<String> userIds = new HashSet<>(modifyRoleUsers.size() + releaseRoleUsers.size() + owners.size());
for (UserInfo userInfo : modifyRoleUsers) {
userIds.add(userInfo.getUserId());
}
for (UserInfo userInfo : envModifyRoleUsers) {
userIds.add(userInfo.getUserId());
}
for (UserInfo userInfo : releaseRoleUsers) {
userIds.add(userInfo.getUserId());
}
for (UserInfo userInfo : envReleaseRoleUsers) {
userIds.add(userInfo.getUserId());
}
for (UserInfo userInfo : owners) {
userIds.add(userInfo.getUserId());
}
List<UserInfo> userInfos = userService.findByUserIds(Lists.newArrayList(userIds));
if (CollectionUtils.isEmpty(userInfos)) {
return Collections.emptyList();
}
List<String> recipients = new ArrayList<>(userInfos.size());
for (UserInfo userInfo : userInfos) {
recipients.add(userInfo.getEmail());
}
return recipients;
}
protected String getApolloPortalAddress() {
return portalConfig.portalAddress();
}
private String cutOffString(String source) {
if (source.length() > VALUE_MAX_LENGTH) {
return source.substring(0, VALUE_MAX_LENGTH) + "...";
}
return source;
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-client/src/test/java/com/ctrip/framework/apollo/internals/DefaultConfigManagerTest.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import java.util.Properties;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.spi.ConfigFactory;
import com.ctrip.framework.apollo.spi.ConfigFactoryManager;
import com.ctrip.framework.apollo.util.ConfigUtil;
/**
* @author Jason Song([email protected])
*/
public class DefaultConfigManagerTest {
private DefaultConfigManager defaultConfigManager;
private static String someConfigContent;
@Before
public void setUp() throws Exception {
MockInjector.setInstance(ConfigFactoryManager.class, new MockConfigFactoryManager());
MockInjector.setInstance(ConfigUtil.class, new ConfigUtil());
defaultConfigManager = new DefaultConfigManager();
someConfigContent = "someContent";
}
@After
public void tearDown() throws Exception {
MockInjector.reset();
}
@Test
public void testGetConfig() throws Exception {
String someNamespace = "someName";
String anotherNamespace = "anotherName";
String someKey = "someKey";
Config config = defaultConfigManager.getConfig(someNamespace);
Config anotherConfig = defaultConfigManager.getConfig(anotherNamespace);
assertEquals(someNamespace + ":" + someKey, config.getProperty(someKey, null));
assertEquals(anotherNamespace + ":" + someKey, anotherConfig.getProperty(someKey, null));
}
@Test
public void testGetConfigMultipleTimesWithSameNamespace() throws Exception {
String someNamespace = "someName";
Config config = defaultConfigManager.getConfig(someNamespace);
Config anotherConfig = defaultConfigManager.getConfig(someNamespace);
assertThat(
"Get config multiple times with the same namespace should return the same config instance",
config, equalTo(anotherConfig));
}
@Test
public void testGetConfigFile() throws Exception {
String someNamespace = "someName";
ConfigFileFormat someConfigFileFormat = ConfigFileFormat.Properties;
ConfigFile configFile =
defaultConfigManager.getConfigFile(someNamespace, someConfigFileFormat);
assertEquals(someConfigFileFormat, configFile.getConfigFileFormat());
assertEquals(someConfigContent, configFile.getContent());
}
@Test
public void testGetConfigFileMultipleTimesWithSameNamespace() throws Exception {
String someNamespace = "someName";
ConfigFileFormat someConfigFileFormat = ConfigFileFormat.Properties;
ConfigFile someConfigFile =
defaultConfigManager.getConfigFile(someNamespace, someConfigFileFormat);
ConfigFile anotherConfigFile =
defaultConfigManager.getConfigFile(someNamespace, someConfigFileFormat);
assertThat(
"Get config file multiple times with the same namespace should return the same config file instance",
someConfigFile, equalTo(anotherConfigFile));
}
public static class MockConfigFactoryManager implements ConfigFactoryManager {
@Override
public ConfigFactory getFactory(String namespace) {
return new ConfigFactory() {
@Override
public Config create(final String namespace) {
return new AbstractConfig() {
@Override
public String getProperty(String key, String defaultValue) {
return namespace + ":" + key;
}
@Override
public Set<String> getPropertyNames() {
return null;
}
@Override
public ConfigSourceType getSourceType() {
return null;
}
};
}
@Override
public ConfigFile createConfigFile(String namespace, final ConfigFileFormat configFileFormat) {
ConfigRepository someConfigRepository = mock(ConfigRepository.class);
return new AbstractConfigFile(namespace, someConfigRepository) {
@Override
protected void update(Properties newProperties) {
}
@Override
public String getContent() {
return someConfigContent;
}
@Override
public boolean hasContent() {
return true;
}
@Override
public ConfigFileFormat getConfigFileFormat() {
return configFileFormat;
}
};
}
};
}
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.internals;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import java.util.Properties;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.build.MockInjector;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.spi.ConfigFactory;
import com.ctrip.framework.apollo.spi.ConfigFactoryManager;
import com.ctrip.framework.apollo.util.ConfigUtil;
/**
* @author Jason Song([email protected])
*/
public class DefaultConfigManagerTest {
private DefaultConfigManager defaultConfigManager;
private static String someConfigContent;
@Before
public void setUp() throws Exception {
MockInjector.setInstance(ConfigFactoryManager.class, new MockConfigFactoryManager());
MockInjector.setInstance(ConfigUtil.class, new ConfigUtil());
defaultConfigManager = new DefaultConfigManager();
someConfigContent = "someContent";
}
@After
public void tearDown() throws Exception {
MockInjector.reset();
}
@Test
public void testGetConfig() throws Exception {
String someNamespace = "someName";
String anotherNamespace = "anotherName";
String someKey = "someKey";
Config config = defaultConfigManager.getConfig(someNamespace);
Config anotherConfig = defaultConfigManager.getConfig(anotherNamespace);
assertEquals(someNamespace + ":" + someKey, config.getProperty(someKey, null));
assertEquals(anotherNamespace + ":" + someKey, anotherConfig.getProperty(someKey, null));
}
@Test
public void testGetConfigMultipleTimesWithSameNamespace() throws Exception {
String someNamespace = "someName";
Config config = defaultConfigManager.getConfig(someNamespace);
Config anotherConfig = defaultConfigManager.getConfig(someNamespace);
assertThat(
"Get config multiple times with the same namespace should return the same config instance",
config, equalTo(anotherConfig));
}
@Test
public void testGetConfigFile() throws Exception {
String someNamespace = "someName";
ConfigFileFormat someConfigFileFormat = ConfigFileFormat.Properties;
ConfigFile configFile =
defaultConfigManager.getConfigFile(someNamespace, someConfigFileFormat);
assertEquals(someConfigFileFormat, configFile.getConfigFileFormat());
assertEquals(someConfigContent, configFile.getContent());
}
@Test
public void testGetConfigFileMultipleTimesWithSameNamespace() throws Exception {
String someNamespace = "someName";
ConfigFileFormat someConfigFileFormat = ConfigFileFormat.Properties;
ConfigFile someConfigFile =
defaultConfigManager.getConfigFile(someNamespace, someConfigFileFormat);
ConfigFile anotherConfigFile =
defaultConfigManager.getConfigFile(someNamespace, someConfigFileFormat);
assertThat(
"Get config file multiple times with the same namespace should return the same config file instance",
someConfigFile, equalTo(anotherConfigFile));
}
public static class MockConfigFactoryManager implements ConfigFactoryManager {
@Override
public ConfigFactory getFactory(String namespace) {
return new ConfigFactory() {
@Override
public Config create(final String namespace) {
return new AbstractConfig() {
@Override
public String getProperty(String key, String defaultValue) {
return namespace + ":" + key;
}
@Override
public Set<String> getPropertyNames() {
return null;
}
@Override
public ConfigSourceType getSourceType() {
return null;
}
};
}
@Override
public ConfigFile createConfigFile(String namespace, final ConfigFileFormat configFileFormat) {
ConfigRepository someConfigRepository = mock(ConfigRepository.class);
return new AbstractConfigFile(namespace, someConfigRepository) {
@Override
protected void update(Properties newProperties) {
}
@Override
public String getContent() {
return someConfigContent;
}
@Override
public boolean hasContent() {
return true;
}
@Override
public ConfigFileFormat getConfigFileFormat() {
return configFileFormat;
}
};
}
};
}
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-biz/src/main/java/com/ctrip/framework/apollo/biz/repository/InstanceConfigRepository.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.biz.entity.InstanceConfig;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.Date;
import java.util.List;
import java.util.Set;
public interface InstanceConfigRepository extends PagingAndSortingRepository<InstanceConfig, Long> {
InstanceConfig findByInstanceIdAndConfigAppIdAndConfigNamespaceName(long instanceId, String
configAppId, String configNamespaceName);
Page<InstanceConfig> findByReleaseKeyAndDataChangeLastModifiedTimeAfter(String releaseKey, Date
validDate, Pageable pageable);
Page<InstanceConfig> findByConfigAppIdAndConfigClusterNameAndConfigNamespaceNameAndDataChangeLastModifiedTimeAfter(
String appId, String clusterName, String namespaceName, Date validDate, Pageable pageable);
List<InstanceConfig> findByConfigAppIdAndConfigClusterNameAndConfigNamespaceNameAndDataChangeLastModifiedTimeAfterAndReleaseKeyNotIn(
String appId, String clusterName, String namespaceName, Date validDate, Set<String> releaseKey);
@Modifying
@Query("delete from InstanceConfig where ConfigAppId=?1 and ConfigClusterName=?2 and ConfigNamespaceName = ?3")
int batchDelete(String appId, String clusterName, String namespaceName);
@Query(
value = "select b.Id from `InstanceConfig` a inner join `Instance` b on b.Id =" +
" a.`InstanceId` where a.`ConfigAppId` = :configAppId and a.`ConfigClusterName` = " +
":clusterName and a.`ConfigNamespaceName` = :namespaceName and a.`DataChange_LastTime` " +
"> :validDate and b.`AppId` = :instanceAppId",
countQuery = "select count(1) from `InstanceConfig` a inner join `Instance` b on b.id =" +
" a.`InstanceId` where a.`ConfigAppId` = :configAppId and a.`ConfigClusterName` = " +
":clusterName and a.`ConfigNamespaceName` = :namespaceName and a.`DataChange_LastTime` " +
"> :validDate and b.`AppId` = :instanceAppId",
nativeQuery = true)
Page<Object> findInstanceIdsByNamespaceAndInstanceAppId(
@Param("instanceAppId") String instanceAppId, @Param("configAppId") String configAppId,
@Param("clusterName") String clusterName, @Param("namespaceName") String namespaceName,
@Param("validDate") Date validDate, Pageable pageable);
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.biz.repository;
import com.ctrip.framework.apollo.biz.entity.InstanceConfig;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.util.Date;
import java.util.List;
import java.util.Set;
public interface InstanceConfigRepository extends PagingAndSortingRepository<InstanceConfig, Long> {
InstanceConfig findByInstanceIdAndConfigAppIdAndConfigNamespaceName(long instanceId, String
configAppId, String configNamespaceName);
Page<InstanceConfig> findByReleaseKeyAndDataChangeLastModifiedTimeAfter(String releaseKey, Date
validDate, Pageable pageable);
Page<InstanceConfig> findByConfigAppIdAndConfigClusterNameAndConfigNamespaceNameAndDataChangeLastModifiedTimeAfter(
String appId, String clusterName, String namespaceName, Date validDate, Pageable pageable);
List<InstanceConfig> findByConfigAppIdAndConfigClusterNameAndConfigNamespaceNameAndDataChangeLastModifiedTimeAfterAndReleaseKeyNotIn(
String appId, String clusterName, String namespaceName, Date validDate, Set<String> releaseKey);
@Modifying
@Query("delete from InstanceConfig where ConfigAppId=?1 and ConfigClusterName=?2 and ConfigNamespaceName = ?3")
int batchDelete(String appId, String clusterName, String namespaceName);
@Query(
value = "select b.Id from `InstanceConfig` a inner join `Instance` b on b.Id =" +
" a.`InstanceId` where a.`ConfigAppId` = :configAppId and a.`ConfigClusterName` = " +
":clusterName and a.`ConfigNamespaceName` = :namespaceName and a.`DataChange_LastTime` " +
"> :validDate and b.`AppId` = :instanceAppId",
countQuery = "select count(1) from `InstanceConfig` a inner join `Instance` b on b.id =" +
" a.`InstanceId` where a.`ConfigAppId` = :configAppId and a.`ConfigClusterName` = " +
":clusterName and a.`ConfigNamespaceName` = :namespaceName and a.`DataChange_LastTime` " +
"> :validDate and b.`AppId` = :instanceAppId",
nativeQuery = true)
Page<Object> findInstanceIdsByNamespaceAndInstanceAppId(
@Param("instanceAppId") String instanceAppId, @Param("configAppId") String configAppId,
@Param("clusterName") String clusterName, @Param("namespaceName") String namespaceName,
@Param("validDate") Date validDate, Pageable pageable);
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-configservice/src/main/java/com/ctrip/framework/apollo/configservice/controller/ConfigFileController.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.controller;
import com.ctrip.framework.apollo.biz.entity.ReleaseMessage;
import com.ctrip.framework.apollo.biz.grayReleaseRule.GrayReleaseRulesHolder;
import com.ctrip.framework.apollo.biz.message.ReleaseMessageListener;
import com.ctrip.framework.apollo.biz.message.Topics;
import com.ctrip.framework.apollo.configservice.util.NamespaceUtil;
import com.ctrip.framework.apollo.configservice.util.WatchKeysUtil;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.ctrip.framework.apollo.core.utils.PropertiesUtil;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.Weigher;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author Jason Song([email protected])
*/
@RestController
@RequestMapping("/configfiles")
public class ConfigFileController implements ReleaseMessageListener {
private static final Logger logger = LoggerFactory.getLogger(ConfigFileController.class);
private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR);
private static final Splitter X_FORWARDED_FOR_SPLITTER = Splitter.on(",").omitEmptyStrings()
.trimResults();
private static final long MAX_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
private static final long EXPIRE_AFTER_WRITE = 30;
private final HttpHeaders propertiesResponseHeaders;
private final HttpHeaders jsonResponseHeaders;
private final ResponseEntity<String> NOT_FOUND_RESPONSE;
private Cache<String, String> localCache;
private final Multimap<String, String>
watchedKeys2CacheKey = Multimaps.synchronizedSetMultimap(HashMultimap.create());
private final Multimap<String, String>
cacheKey2WatchedKeys = Multimaps.synchronizedSetMultimap(HashMultimap.create());
private static final Gson GSON = new Gson();
private final ConfigController configController;
private final NamespaceUtil namespaceUtil;
private final WatchKeysUtil watchKeysUtil;
private final GrayReleaseRulesHolder grayReleaseRulesHolder;
public ConfigFileController(
final ConfigController configController,
final NamespaceUtil namespaceUtil,
final WatchKeysUtil watchKeysUtil,
final GrayReleaseRulesHolder grayReleaseRulesHolder) {
localCache = CacheBuilder.newBuilder()
.expireAfterWrite(EXPIRE_AFTER_WRITE, TimeUnit.MINUTES)
.weigher((Weigher<String, String>) (key, value) -> value == null ? 0 : value.length())
.maximumWeight(MAX_CACHE_SIZE)
.removalListener(notification -> {
String cacheKey = notification.getKey();
logger.debug("removing cache key: {}", cacheKey);
if (!cacheKey2WatchedKeys.containsKey(cacheKey)) {
return;
}
//create a new list to avoid ConcurrentModificationException
List<String> watchedKeys = new ArrayList<>(cacheKey2WatchedKeys.get(cacheKey));
for (String watchedKey : watchedKeys) {
watchedKeys2CacheKey.remove(watchedKey, cacheKey);
}
cacheKey2WatchedKeys.removeAll(cacheKey);
logger.debug("removed cache key: {}", cacheKey);
})
.build();
propertiesResponseHeaders = new HttpHeaders();
propertiesResponseHeaders.add("Content-Type", "text/plain;charset=UTF-8");
jsonResponseHeaders = new HttpHeaders();
jsonResponseHeaders.add("Content-Type", "application/json;charset=UTF-8");
NOT_FOUND_RESPONSE = new ResponseEntity<>(HttpStatus.NOT_FOUND);
this.configController = configController;
this.namespaceUtil = namespaceUtil;
this.watchKeysUtil = watchKeysUtil;
this.grayReleaseRulesHolder = grayReleaseRulesHolder;
}
@GetMapping(value = "/{appId}/{clusterName}/{namespace:.+}")
public ResponseEntity<String> queryConfigAsProperties(@PathVariable String appId,
@PathVariable String clusterName,
@PathVariable String namespace,
@RequestParam(value = "dataCenter", required = false) String dataCenter,
@RequestParam(value = "ip", required = false) String clientIp,
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
String result =
queryConfig(ConfigFileOutputFormat.PROPERTIES, appId, clusterName, namespace, dataCenter,
clientIp, request, response);
if (result == null) {
return NOT_FOUND_RESPONSE;
}
return new ResponseEntity<>(result, propertiesResponseHeaders, HttpStatus.OK);
}
@GetMapping(value = "/json/{appId}/{clusterName}/{namespace:.+}")
public ResponseEntity<String> queryConfigAsJson(@PathVariable String appId,
@PathVariable String clusterName,
@PathVariable String namespace,
@RequestParam(value = "dataCenter", required = false) String dataCenter,
@RequestParam(value = "ip", required = false) String clientIp,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
String result =
queryConfig(ConfigFileOutputFormat.JSON, appId, clusterName, namespace, dataCenter,
clientIp, request, response);
if (result == null) {
return NOT_FOUND_RESPONSE;
}
return new ResponseEntity<>(result, jsonResponseHeaders, HttpStatus.OK);
}
String queryConfig(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
String namespace, String dataCenter, String clientIp,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
//strip out .properties suffix
namespace = namespaceUtil.filterNamespaceName(namespace);
//fix the character case issue, such as FX.apollo <-> fx.apollo
namespace = namespaceUtil.normalizeNamespace(appId, namespace);
if (Strings.isNullOrEmpty(clientIp)) {
clientIp = tryToGetClientIp(request);
}
//1. check whether this client has gray release rules
boolean hasGrayReleaseRule = grayReleaseRulesHolder.hasGrayReleaseRule(appId, clientIp,
namespace);
String cacheKey = assembleCacheKey(outputFormat, appId, clusterName, namespace, dataCenter);
//2. try to load gray release and return
if (hasGrayReleaseRule) {
Tracer.logEvent("ConfigFile.Cache.GrayRelease", cacheKey);
return loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
request, response);
}
//3. if not gray release, check weather cache exists, if exists, return
String result = localCache.getIfPresent(cacheKey);
//4. if not exists, load from ConfigController
if (Strings.isNullOrEmpty(result)) {
Tracer.logEvent("ConfigFile.Cache.Miss", cacheKey);
result = loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
request, response);
if (result == null) {
return null;
}
//5. Double check if this client needs to load gray release, if yes, load from db again
//This step is mainly to avoid cache pollution
if (grayReleaseRulesHolder.hasGrayReleaseRule(appId, clientIp, namespace)) {
Tracer.logEvent("ConfigFile.Cache.GrayReleaseConflict", cacheKey);
return loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
request, response);
}
localCache.put(cacheKey, result);
logger.debug("adding cache for key: {}", cacheKey);
Set<String> watchedKeys =
watchKeysUtil.assembleAllWatchKeys(appId, clusterName, namespace, dataCenter);
for (String watchedKey : watchedKeys) {
watchedKeys2CacheKey.put(watchedKey, cacheKey);
}
cacheKey2WatchedKeys.putAll(cacheKey, watchedKeys);
logger.debug("added cache for key: {}", cacheKey);
} else {
Tracer.logEvent("ConfigFile.Cache.Hit", cacheKey);
}
return result;
}
private String loadConfig(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
String namespace, String dataCenter, String clientIp,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
ApolloConfig apolloConfig = configController.queryConfig(appId, clusterName, namespace,
dataCenter, "-1", clientIp, null, request, response);
if (apolloConfig == null || apolloConfig.getConfigurations() == null) {
return null;
}
String result = null;
switch (outputFormat) {
case PROPERTIES:
Properties properties = new Properties();
properties.putAll(apolloConfig.getConfigurations());
result = PropertiesUtil.toString(properties);
break;
case JSON:
result = GSON.toJson(apolloConfig.getConfigurations());
break;
}
return result;
}
String assembleCacheKey(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
String namespace,
String dataCenter) {
List<String> keyParts =
Lists.newArrayList(outputFormat.getValue(), appId, clusterName, namespace);
if (!Strings.isNullOrEmpty(dataCenter)) {
keyParts.add(dataCenter);
}
return STRING_JOINER.join(keyParts);
}
@Override
public void handleMessage(ReleaseMessage message, String channel) {
logger.info("message received - channel: {}, message: {}", channel, message);
String content = message.getMessage();
if (!Topics.APOLLO_RELEASE_TOPIC.equals(channel) || Strings.isNullOrEmpty(content)) {
return;
}
if (!watchedKeys2CacheKey.containsKey(content)) {
return;
}
//create a new list to avoid ConcurrentModificationException
List<String> cacheKeys = new ArrayList<>(watchedKeys2CacheKey.get(content));
for (String cacheKey : cacheKeys) {
logger.debug("invalidate cache key: {}", cacheKey);
localCache.invalidate(cacheKey);
}
}
enum ConfigFileOutputFormat {
PROPERTIES("properties"), JSON("json");
private String value;
ConfigFileOutputFormat(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
private String tryToGetClientIp(HttpServletRequest request) {
String forwardedFor = request.getHeader("X-FORWARDED-FOR");
if (!Strings.isNullOrEmpty(forwardedFor)) {
return X_FORWARDED_FOR_SPLITTER.splitToList(forwardedFor).get(0);
}
return request.getRemoteAddr();
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.configservice.controller;
import com.ctrip.framework.apollo.biz.entity.ReleaseMessage;
import com.ctrip.framework.apollo.biz.grayReleaseRule.GrayReleaseRulesHolder;
import com.ctrip.framework.apollo.biz.message.ReleaseMessageListener;
import com.ctrip.framework.apollo.biz.message.Topics;
import com.ctrip.framework.apollo.configservice.util.NamespaceUtil;
import com.ctrip.framework.apollo.configservice.util.WatchKeysUtil;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.ctrip.framework.apollo.core.utils.PropertiesUtil;
import com.ctrip.framework.apollo.tracer.Tracer;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.Weigher;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author Jason Song([email protected])
*/
@RestController
@RequestMapping("/configfiles")
public class ConfigFileController implements ReleaseMessageListener {
private static final Logger logger = LoggerFactory.getLogger(ConfigFileController.class);
private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR);
private static final Splitter X_FORWARDED_FOR_SPLITTER = Splitter.on(",").omitEmptyStrings()
.trimResults();
private static final long MAX_CACHE_SIZE = 50 * 1024 * 1024; // 50MB
private static final long EXPIRE_AFTER_WRITE = 30;
private final HttpHeaders propertiesResponseHeaders;
private final HttpHeaders jsonResponseHeaders;
private final ResponseEntity<String> NOT_FOUND_RESPONSE;
private Cache<String, String> localCache;
private final Multimap<String, String>
watchedKeys2CacheKey = Multimaps.synchronizedSetMultimap(HashMultimap.create());
private final Multimap<String, String>
cacheKey2WatchedKeys = Multimaps.synchronizedSetMultimap(HashMultimap.create());
private static final Gson GSON = new Gson();
private final ConfigController configController;
private final NamespaceUtil namespaceUtil;
private final WatchKeysUtil watchKeysUtil;
private final GrayReleaseRulesHolder grayReleaseRulesHolder;
public ConfigFileController(
final ConfigController configController,
final NamespaceUtil namespaceUtil,
final WatchKeysUtil watchKeysUtil,
final GrayReleaseRulesHolder grayReleaseRulesHolder) {
localCache = CacheBuilder.newBuilder()
.expireAfterWrite(EXPIRE_AFTER_WRITE, TimeUnit.MINUTES)
.weigher((Weigher<String, String>) (key, value) -> value == null ? 0 : value.length())
.maximumWeight(MAX_CACHE_SIZE)
.removalListener(notification -> {
String cacheKey = notification.getKey();
logger.debug("removing cache key: {}", cacheKey);
if (!cacheKey2WatchedKeys.containsKey(cacheKey)) {
return;
}
//create a new list to avoid ConcurrentModificationException
List<String> watchedKeys = new ArrayList<>(cacheKey2WatchedKeys.get(cacheKey));
for (String watchedKey : watchedKeys) {
watchedKeys2CacheKey.remove(watchedKey, cacheKey);
}
cacheKey2WatchedKeys.removeAll(cacheKey);
logger.debug("removed cache key: {}", cacheKey);
})
.build();
propertiesResponseHeaders = new HttpHeaders();
propertiesResponseHeaders.add("Content-Type", "text/plain;charset=UTF-8");
jsonResponseHeaders = new HttpHeaders();
jsonResponseHeaders.add("Content-Type", "application/json;charset=UTF-8");
NOT_FOUND_RESPONSE = new ResponseEntity<>(HttpStatus.NOT_FOUND);
this.configController = configController;
this.namespaceUtil = namespaceUtil;
this.watchKeysUtil = watchKeysUtil;
this.grayReleaseRulesHolder = grayReleaseRulesHolder;
}
@GetMapping(value = "/{appId}/{clusterName}/{namespace:.+}")
public ResponseEntity<String> queryConfigAsProperties(@PathVariable String appId,
@PathVariable String clusterName,
@PathVariable String namespace,
@RequestParam(value = "dataCenter", required = false) String dataCenter,
@RequestParam(value = "ip", required = false) String clientIp,
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
String result =
queryConfig(ConfigFileOutputFormat.PROPERTIES, appId, clusterName, namespace, dataCenter,
clientIp, request, response);
if (result == null) {
return NOT_FOUND_RESPONSE;
}
return new ResponseEntity<>(result, propertiesResponseHeaders, HttpStatus.OK);
}
@GetMapping(value = "/json/{appId}/{clusterName}/{namespace:.+}")
public ResponseEntity<String> queryConfigAsJson(@PathVariable String appId,
@PathVariable String clusterName,
@PathVariable String namespace,
@RequestParam(value = "dataCenter", required = false) String dataCenter,
@RequestParam(value = "ip", required = false) String clientIp,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
String result =
queryConfig(ConfigFileOutputFormat.JSON, appId, clusterName, namespace, dataCenter,
clientIp, request, response);
if (result == null) {
return NOT_FOUND_RESPONSE;
}
return new ResponseEntity<>(result, jsonResponseHeaders, HttpStatus.OK);
}
String queryConfig(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
String namespace, String dataCenter, String clientIp,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
//strip out .properties suffix
namespace = namespaceUtil.filterNamespaceName(namespace);
//fix the character case issue, such as FX.apollo <-> fx.apollo
namespace = namespaceUtil.normalizeNamespace(appId, namespace);
if (Strings.isNullOrEmpty(clientIp)) {
clientIp = tryToGetClientIp(request);
}
//1. check whether this client has gray release rules
boolean hasGrayReleaseRule = grayReleaseRulesHolder.hasGrayReleaseRule(appId, clientIp,
namespace);
String cacheKey = assembleCacheKey(outputFormat, appId, clusterName, namespace, dataCenter);
//2. try to load gray release and return
if (hasGrayReleaseRule) {
Tracer.logEvent("ConfigFile.Cache.GrayRelease", cacheKey);
return loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
request, response);
}
//3. if not gray release, check weather cache exists, if exists, return
String result = localCache.getIfPresent(cacheKey);
//4. if not exists, load from ConfigController
if (Strings.isNullOrEmpty(result)) {
Tracer.logEvent("ConfigFile.Cache.Miss", cacheKey);
result = loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
request, response);
if (result == null) {
return null;
}
//5. Double check if this client needs to load gray release, if yes, load from db again
//This step is mainly to avoid cache pollution
if (grayReleaseRulesHolder.hasGrayReleaseRule(appId, clientIp, namespace)) {
Tracer.logEvent("ConfigFile.Cache.GrayReleaseConflict", cacheKey);
return loadConfig(outputFormat, appId, clusterName, namespace, dataCenter, clientIp,
request, response);
}
localCache.put(cacheKey, result);
logger.debug("adding cache for key: {}", cacheKey);
Set<String> watchedKeys =
watchKeysUtil.assembleAllWatchKeys(appId, clusterName, namespace, dataCenter);
for (String watchedKey : watchedKeys) {
watchedKeys2CacheKey.put(watchedKey, cacheKey);
}
cacheKey2WatchedKeys.putAll(cacheKey, watchedKeys);
logger.debug("added cache for key: {}", cacheKey);
} else {
Tracer.logEvent("ConfigFile.Cache.Hit", cacheKey);
}
return result;
}
private String loadConfig(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
String namespace, String dataCenter, String clientIp,
HttpServletRequest request,
HttpServletResponse response) throws IOException {
ApolloConfig apolloConfig = configController.queryConfig(appId, clusterName, namespace,
dataCenter, "-1", clientIp, null, request, response);
if (apolloConfig == null || apolloConfig.getConfigurations() == null) {
return null;
}
String result = null;
switch (outputFormat) {
case PROPERTIES:
Properties properties = new Properties();
properties.putAll(apolloConfig.getConfigurations());
result = PropertiesUtil.toString(properties);
break;
case JSON:
result = GSON.toJson(apolloConfig.getConfigurations());
break;
}
return result;
}
String assembleCacheKey(ConfigFileOutputFormat outputFormat, String appId, String clusterName,
String namespace,
String dataCenter) {
List<String> keyParts =
Lists.newArrayList(outputFormat.getValue(), appId, clusterName, namespace);
if (!Strings.isNullOrEmpty(dataCenter)) {
keyParts.add(dataCenter);
}
return STRING_JOINER.join(keyParts);
}
@Override
public void handleMessage(ReleaseMessage message, String channel) {
logger.info("message received - channel: {}, message: {}", channel, message);
String content = message.getMessage();
if (!Topics.APOLLO_RELEASE_TOPIC.equals(channel) || Strings.isNullOrEmpty(content)) {
return;
}
if (!watchedKeys2CacheKey.containsKey(content)) {
return;
}
//create a new list to avoid ConcurrentModificationException
List<String> cacheKeys = new ArrayList<>(watchedKeys2CacheKey.get(content));
for (String cacheKey : cacheKeys) {
logger.debug("invalidate cache key: {}", cacheKey);
localCache.invalidate(cacheKey);
}
}
enum ConfigFileOutputFormat {
PROPERTIES("properties"), JSON("json");
private String value;
ConfigFileOutputFormat(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
private String tryToGetClientIp(HttpServletRequest request) {
String forwardedFor = request.getHeader("X-FORWARDED-FOR");
if (!Strings.isNullOrEmpty(forwardedFor)) {
return X_FORWARDED_FOR_SPLITTER.splitToList(forwardedFor).get(0);
}
return request.getRemoteAddr();
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./.github/ISSUE_TEMPLATE/bug_report_en.md | ---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
<!-- The content in here will not be show。To forbid duplication,easier search in the feature,before you create an issue,please check the following. If your question is a newer/beginner's,recommand to https://github.com/ctripcorp/apollo/discussions to ask it. -->
- [ ] I have checked the [discussions](https://github.com/ctripcorp/apollo/discussions)
- [ ] I have searched the [issues](https://github.com/ctripcorp/apollo/issues) of this repository and believe that this is not a duplicate.
- [ ] I have checked the [FAQ](https://www.apolloconfig.com/#/zh/faq/common-issues-in-deployment-and-development-phase) of this repository and believe that this is not a duplicate.
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1.
2.
3.
4.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
### Additional Details & Logs
- Version
- Error logs
- Configuration
- Platform and Operating System
| ---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
<!-- The content in here will not be show。To forbid duplication,easier search in the feature,before you create an issue,please check the following. If your question is a newer/beginner's,recommand to https://github.com/ctripcorp/apollo/discussions to ask it. -->
- [ ] I have checked the [discussions](https://github.com/ctripcorp/apollo/discussions)
- [ ] I have searched the [issues](https://github.com/ctripcorp/apollo/issues) of this repository and believe that this is not a duplicate.
- [ ] I have checked the [FAQ](https://www.apolloconfig.com/#/zh/faq/common-issues-in-deployment-and-development-phase) of this repository and believe that this is not a duplicate.
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1.
2.
3.
4.
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
### Additional Details & Logs
- Version
- Error logs
- Configuration
- Platform and Operating System
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-core/src/test/resources/log4j2.xml | <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<configuration monitorInterval="60">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="[apollo-client][%t]%d %-5p [%c] %m%n"/>
</Console>
<Async name="Async" includeLocation="true">
<AppenderRef ref="Console"/>
</Async>
</appenders>
<loggers>
<logger name="com.ctrip.framework.apollo" additivity="false" level="trace">
<AppenderRef ref="Async" level="WARN"/>
</logger>
<root level="debug">
<AppenderRef ref="Async"/>
</root>
</loggers>
</configuration>
| <?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright 2021 Apollo 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.
~
-->
<configuration monitorInterval="60">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="[apollo-client][%t]%d %-5p [%c] %m%n"/>
</Console>
<Async name="Async" includeLocation="true">
<AppenderRef ref="Console"/>
</Async>
</appenders>
<loggers>
<logger name="com.ctrip.framework.apollo" additivity="false" level="trace">
<AppenderRef ref="Async" level="WARN"/>
</logger>
<root level="debug">
<AppenderRef ref="Async"/>
</root>
</loggers>
</configuration>
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-core/src/main/java/com/ctrip/framework/foundation/internals/io/IOUtils.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.foundation.internals.io;
public class IOUtils {
public static final int EOF = -1;
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.foundation.internals.io;
public class IOUtils {
public static final int EOF = -1;
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./apollo-portal/src/main/java/com/ctrip/framework/apollo/portal/entity/bo/UserInfo.java | /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.entity.bo;
public class UserInfo {
private String userId;
private String name;
private String email;
public UserInfo() {
}
public UserInfo(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public boolean equals(Object o) {
if (o instanceof UserInfo) {
if (o == this){
return true;
}
UserInfo anotherUser = (UserInfo) o;
return userId.equals(anotherUser.userId);
}
return false;
}
}
| /*
* Copyright 2021 Apollo 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.ctrip.framework.apollo.portal.entity.bo;
public class UserInfo {
private String userId;
private String name;
private String email;
public UserInfo() {
}
public UserInfo(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public boolean equals(Object o) {
if (o instanceof UserInfo) {
if (o == this){
return true;
}
UserInfo anotherUser = (UserInfo) o;
return userId.equals(anotherUser.userId);
}
return false;
}
}
| -1 |
apolloconfig/apollo | 3,647 | feat(open-api): get authorized apps | ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| Anilople | 2021-04-24T06:40:38Z | 2021-06-26T13:21:02Z | 9a6f8e277f678fa583a23f551ed1648d5e13bdfa | f1eca02f4033d050bd71ede288d1707954d3dea4 | feat(open-api): get authorized apps. ## What's the purpose of this PR
Let open api know that which applications it can operate.
## Which issue(s) this PR fixes:
Relate to #3607
## Brief changelog
Add a new controller in portal
Add a new method in ApolloOpenApiClient
Follow this checklist to help us incorporate your contribution quickly and easily:
- [x] Read the [Contributing Guide](https://github.com/ctripcorp/apollo/blob/master/CONTRIBUTING.md) before making this pull request.
- [x] Write a pull request description that is detailed enough to understand what the pull request does, how, and why.
- [x] Write necessary unit tests to verify the code.
- [x] Run `mvn clean test` to make sure this pull request doesn't break anything.
| ./doc/images/cluster-created.png | PNG
IHDR z IDATxUyl,^$B!ԅzf[[++c'q߉ۉmEQzG
@HB@De{}{.{;|.sf<ΜPQQ " " " " " " 5GE@D@D@D@D@D@D@D@D@D@D@D@D@ZB@%GD@D@D@D@D@D@H
,-X" " " " " " tx " " 괾\GdB!xcPKh_4$.ܪ*+GD@DCYZZZ%%%EuǬ=z[(qp*i#ЦJbIIzԉD@D U[YY[NefZgu&''7ƈ8" " "p dԶY]233% |" "pF TVVZQQѱC,==;qZ=ǚ" " @H挔XMu222:HUXD@D!4w,55-nYF{D@D@D@ǔۊ2Ζxߔ@-tTOm$ kҹ'ZD@D= `d^|uUe{Fy36ǖiע9Z^D@ +f@y3" " @OUC@4**" " " " " F@)tUQ85OE@D@D@D@D@D0M<5~J-" " " " " dijUTD@D@D@D@D@NSj0$ ;LS" " " " " "pj$ OR@! aZS#rjc;uMMMZjjj~G4&%%Y(j;Ƃ/99(/" " " " " qA adAA=䓆`"9r]pn;w/~.Z@4wygoqM ~駶pB|M
h>GЦZc~OeeVD@ړ@
Hmۜڵb5֭[mvwZnnc\ZZʊʽmȐ!ܳgmڴF ϗxl@G;D@D@ <W}YgYϞ=]u:Xy233mn5K7ߴpf͚e}|" "p$䡆UK묎^@n= {饗[ouH#^{mFAI=V\iyo>㓖f{nԼSD@D@ ?v垙.ģņ?X";w잃<;t`_=zE]V^mGq&L0KX2肂EO?m}sI>|K^z,ݎ3 H,%%%֩Sp\=z
0@0}HVn|k
p'|b|(n' Hfdun5k%= s }6ƍsȚ5knmK%#ޕg&.ysD!s`~|S`˩" "p& $)@Ab= ++Vp~?[,XYLE8p6nhÆ
sљccҥ
:4@~ _'0%HԚ(O6}<>%G`.z-^}E<5o{7Wv0*K"}wµ`ݻ[n"<g}]ֹ^|n?<HD@D@D S*++sgǻt#
ѿ7Goҥn !`F
&wٲe˃&O<-Zd{5!8uTݻw<e? %C,ZX)[eaM2P@/g&MrW Y`[/"i)9$?~Ç<#Æ
ܳΔ0`M| I3vX>peDrn)ZFEE@Dt!P"qڴiF }q|@Lrg5:#y`a9i+" "q ~^{5BA7c>};gsnqG̺ulnq<gep3bs<Ba"q_~s9xnyۮ<D
>kh>l9^/Rc6Xc`ܹvaW~_g,3sLǏz,^>>Yg6w' aFۉO|@io1ǒoC+B!Mrlr>mE@DL@Bncd%bFyygdԘ|FF{$8;ޅ߇7oςl%,>Xyn!:HqPlB]uUMqɋ<[>bBgq2e,ģl>><ãx^@a{SGHsVGNHHOyC+qYұ?ȟ<Ysh2
c?QO}Woa>ϧm`Y Ncy0%`E$RXwn aIsF.qea$9
" " " |Yds!.yqVq'.XXnclU>Als7Z0yS^]y
.^Q.D6
\y2Sĉ;Du8g,H݂W<R:G)+e ^,?.M6xwQ^_F,
ُM-wh o9ÇQMP4p?|UfOQO A#.ȹ8X*^veN ,8ن8pRLDl+nq<Ě멾טI+7.^;'qXُe(i`/+;7\>2_zٳ[잋fn'~W^ye|[176G䋫1#>G}Y0}
V3M $J"nf=7g^D}'oSOEA(cp>V[
W{V lB{֬Y.
BE}C0!(<;Dnt
gӦMQ"+ܗ3<n&{衇xH<gpԖI^l! :"ᅅu",9]y<;|ԫŭ4()?bc˂h& uG|0a*5 + y0DwrqCWÉ~P@In2<D@D@D H 3gg_U+7yD8 `R<<p1YX@U}\:,!H9Eۚ-PBWx_eX)I$찴=ȎG
4LB#".-XN2-ߋGVD@b@
HF|$l.<#]A~Lvo*|<D@D@D 7x
io@3|!`{-yP>VF-mcDqnt#lL8x1ɶƞeqO>Z]
" "OV@rե5U$ZX5D@D@D1鱐V'U0= 5/ˋȴA_+8C+2hq|BmwC}(7[,iw)##p~"mI{(@<HXOt
++mG̰KcГBDΗp8B-hCʋhMji>_402<.cUU ݸUdE%}XyH4KmPD6PD :VF !H;ͧطo<pD,">} _V]<^H!e3ge|ӷ;b2y1tdAܹoۉ5"ԑ/˖.BQQHz4-
@p\0]}nkumi+" Jwx-" " 1B "W?rA
oED4ypx2#<+DGŋ=ydVBV>'d^&v\ϫ2
hx+Vh MSeE4"Z $Pɼ,¸R`YYUAD@,Ғ@8I^LJ&1H!py%- !A9ǎh>cѢENGxgãUao~zSį_dz y{gl}+y-^ؽn٩S6!궈sXKYuq֗9`6adtPD@N# [Xl
il_{zBыHA-pH ~
#8phY˻zF|.zn'/[_AY__vQL|WdJ(3SV%>o3'
zӱ%nAA6' sƻ,y#yR0ȓ(?n1heeVD@╀\XTn# ={D|G b\:KG^^[gd@@!|7"-(ꪫu$8Z,@B wyӓD6X`?Ɩ4>`띨"K(q;e[nqOwuxݔ)S\q8;WZOmƍs+R& c=sǽx=nhB;?<?⒧
Y c%T'Ș5k
!X18}t'R"8 "qe.#d|3 ?oAEt;-~9%?vˇy3fC^`8q+#X)7F8i0_Î:+p~ذb+%Ǖח-h
իW;G=9 k* z>7tdUv$/ʍȤ+4\ffmB _@|¢Â'Y"nn1^QdvJ&" "byݬU'JJlAaw(# PAdND's*D=ǂ3<ُkY+Bqb
I@x|D˧a-eGRv6(yԃ4''4[Y)\O\J'" @@Y
*@#hB[DĶUy}>X& ڂݩGʌu5ښ(́SyE@D@D@D@D@D<CuZ8UmaA;2(@" ֎ު@s+w>
!s*@LTMD@D@ w}n,Ꞽb4+&8BUOD@D H@"@%E <Э[O%4cj-" " " " " & jdJ " " " " " dlwZD@D@D@D@D@ZM@Ȕ@D@D@D@D@D@:&6]Dܪ;&IZD@DI'ʉ&3ANd(d? E@D@@JJZV%h@d]][<##ICD@D@dR" " "L@!==$ B"
+k+" " "p":Y>Mӈ Ц_8M$ OhFD@D@D@D@D@❀d/" " " " " iӈ@TE@D@D@D@D@D4<Muwނ*& N#" " " " " N@2[PD@4iD@D@D@D@D@D {T~huufu " " "& F/" " "p BH@`@ ݘjII
}R,R =4]D@D@G)@C@6dS{cv#FXnnn۷o5kXJJ͘1222Zyf̴ZR"c" " " " "\j=cN|~m{5ɛo>{GW_*u|ͦW# dC>߿ߊl̘1vWZ^^^֔Zrr[Ɩ-[ԩS---MϧD@D@D@D@D@< 3JPQQs
G,~t?\[U7ݻ[YPP`@t}hv"4]D@D@D@D@D@d)bopB' i}us#ۖ-[7ߴ{:x5j]z֩S'{l.ʕ+{~7ܼb' IkѣC|ngeƍmܹy嗇ߍFٶmf/</*@[lm<nСC/Kh0{yᇭĆ
f]vunѢENxvmN".M)!qg;v˖>Sz;K"4;;ۉSR۽{r[/|;BVAD@D@D@D@D H@@{n:|'/b={eX7Dq[}뭷xˌܹ?8"G# x g\Z,Ŀl ;vƜIeswc`DTq_ڹ~_BwHZ5v!ҥsL8ѹ"t<^qNX2CqAH >@~Ϛ5˾N·)}<!"jerE@@CJ^}[iyu mx,ë="o&l`d#鐗"xSSiE@D@D@D@D@bd@0qaLիW=WZź- >qsݰaӹb;DKRo_[z@&2"7Q,//J[:xd^#XoJlJ^ 5֭ƫ@JFE#.E9\W["91^=zpb<r}GN0R#͑n IDATUVOrX}|ꭓv^zYOIt#8̟dQ{ȗ|wbŊy[TT<" " " " " B@hH,,psϹ,ê C! 8Μ9Ӟ~i7om߾Y#ysvYg&,2q[C>uY$,b1[w7ϝGq $y#Vc0Vwsa+<
" " " " " C G?˟jueΊQh=>}8 ía7` 4i?2!HasW_Grv1|pc!M+lqk|JVx%V~E@$qsssK.qc1Vpz:j('XquWAD@<Pgd'wܶʪ*q\@" " g@씟XfA(<\GYk4yA!qo2%tBy_!B^(v+$ Ӓt#"HJJܼnVWwlX-+"8pPVVGD@D@ M7a5Ήplm"|D@D@D@D@D@I6UD@D@D@D@D@D]H@Ve*" " " " " G@2T5v! .X$ kSHD@D@D@D@D@څd`U" " " " " "x$ MU#hU@L6UD@D@D@D@D@D]H@Ve*" " " " " G@2T5v! .X$ kSHD@D@ڝ@EEUWW<///oJJJ©ѣGO-kjjT&4/2j g]VZ[Q@JW@8|M;t}_my۷ou],[^~eh999G\~<`Æ
k]ׯGyս{Zaa%%շ BPI9nzF_6m45k`K<dffZJJӒz6hР"_CbUh6mjƍmŊvYgE$8:w\/ݻr3XQQmu9NǻgϞ2d?G?fR4~߰aUVV6IGxlѢE`$|222w=ھolܹ
v[/3f4+1߶gϞzCFZ_~]z|'ݮ]S$ c9Th=ʪj[zY֍9YZj9y'9rĞ|Iv&lTݻE}t:L~+_i DZ2.\h=z?$;wڜ9s\>2{tb_:uj 8d B{E5|lҥv!(Puvޒ?ƍmۜE"Bk_@~smɆ{y11bywݽ<IKWPַ~
:? w_$
ULW~d
6&%5ƏjyWmQ~ecI'pٟ'IH'7;;jڵn#.YxI*8_6a劧WǞ{/ܳ=\Ucsυx衇Wcꫯs=lbX+n\bic@r<nֵkWǔwBk ;0O,Z'8lϜpzD0o&<hC"jǏ_/Og]X/:
:4|o@pQg3@S_}N@
<Tl+͝%'SV-EtVzj'htIS:}1y҉ʖ@bU$ *$/=''vҊKĉ]x#VZVC l3CuMmmU@pOb5BHATkh#6پ}k7ȋTY\\<>}"nw;d>=oyꩧƪ;b
֭[w{1y`d#qM?+폴#f#We6Z8>pg?oYG~Ϯ~Od(dGh/!" " FNrMM%'ZFJ݀ƭ;2ӬƒB$21MvE)DС+}tnjCnnOSg?soK,3{.y9vZ=ֵQqiB۵&'γ1#8<ziȇ3^x
Kssb0wO@֭s9vw6;*l=V`ھmmݦ6lP_wIc7[uڑmE"~WWi*c/vg?"AD#s@Sq<>縯o/?mh3
=EvcRD@D@N ]R-=Pjdedشsƹ۞}m#6bH-1zmٶjsdn??68Uy\X;
tf"r`}j뿆W]uL__Z~~~Sձ.n{%'ۇKWَ,)5fL=.ynz1~ҵa=ozEs(^}U7Bܺ+Ҟ}Y1+}bLP\Rf~Y{BsCf5וkH@zNw??n:oey`ϵ..=z":Q>b=Z\E&?sM3gl0PuK[5ԧ6 oS(oZӟ,y
(TD@@u_kyz>uZ]_⻖l}^YI
DI[CtPy-DТw: ~`ND-Ǜn),fxSQj<عO>n^$)u]נC.\|7jM<xX"ņ54XF5ȑ(`nh3:>`裏u%+"L}QW\q%[ecϽaٸ-)Kډ"Kl㖝v̲;eZNDh;v8PXmnYF9_00ޅN:!ٳ8epUkks9]krL4ɹrK)nˑVknŤ#? p?`û:SQhz{|h3IS̉T +PiE@D >Q~Q;ce*F,\t4Ho)X;Hj>nݺuHXIwB k"x,;ġI>,C,X`g`
#M'rAꪫ8ʃᄑZ6_.Z;ڡ.%bŇX믻<meknه@d;h.8eq֮BH
?dVPp^}~:.1%ߍ@9>z+"2ϵGGn\3.2NoDT?:>Oҳ8kqGF
Z(?57@DZ&}:m@
DR@s,)9ml=uͱ
1%9X!4VI","9cDLF[R̙# u]n3,,!XIsV+4N 7|F,?">
5X]s{d `Nݷ-7/D$NnN'7}^[fcƏbC{XNNP3K/y~'.0]D+`]5X SLq.X66 #Kla{Hdā91Y6H@&V{6" " J[q?x+l֝aA .8tқR˗/^#@g+^%K:""5k9x9X),k+Ubi%L\֘;^:jVd_//N.X',ī H
?oɋ7y'BK_RX@4,glE6R`ɪ H
OwdzMWϲ.ޥTfUrLj'?87O,|ovK.1^55
u2폑/l9bp?>609OZ
J۶@ @'{.}u^}=7Y=HtKlC7=m<zN^!
w">nW2L'k ygQQ|Ϊ@g1U1W< .bUI0B1<Jڀjva0cN^Ǐ}cgwkGG_7\^cy9ԯMk/b-p=묳я~`st˵`J,B2zj
L{eee;*A0p-2Ǒvs9q3;G ZtPXRstTߧ57./Ḳ5<8:aaEed0*sby?@%DKNB 9H"կk_9@m̂,AEx⢌щ#"X^E]),x~st0fzfEㆥylʵ6e.dON"5Wk'b6vrI`@m83N}\7}>W#}iC5h0X-#!,wiNY,{bLvT-D@D@:(:sEK-5%Ֆ\cG
[]6*Yq%^-HGƵ^:,ҁt>:*sx%$-tqSh$ta B3_YwcP@.<.y, h%KJ{Vd؋vPM4̞ni,@4E*+eZY%p/:#8lD(ɇE凵9
uG1ȃ[^wѤ\g1%ifp1bYxرaj|SE@D@:8V\-*.__FZKOKJ *r|(F5bC
$ dជ+\?wmK疎1p`A::
+a"q1%b K5;bTwߵڹzAwWDB~%s+}X>;JJMw[eC֫G7;Z^^Mqg?hABs9mI
687oV5j}uD<2+qD9}笄X(7]N0bWVra+~Gzp`UaX?2ynPaĈn->$
ULzww,55z=/[]D'%)~˶le,}!TV~$aD_YB,<w8t><@G7Kދ\H/ { :VrBS
#10m4f̼5\R˧}hD֙{
)u
Z ̽gؐ~vճlȡ"oxu
~_v'EC
B0"h'^ׁ*57n~^2ݰv"*Y!S,̵`Vi_|Sv^o2(
oϹĒWBĥ|z9sHD6?$ 㧭TRh@%0ٳ{WKOK\
vdFb͢#H`#N2H,#X)"Ё.e,$@/>ѿ#B;eMI
X3G+ %Koo羺m^1mpEnuu3.]:X&`ua=~#_|pƒQ':a>k#+puŐp-e1$Ή%KN<ن
Ζ_x.Xfx+'@9HÇX^K}U *,*kL/,OvVi&tյf=;bY]tb겲++-9X)[c嘷`{ڋI?>*ս[T$n=͚1~+06v.?5O͵#VYYe~);g(߷vW\<f;Nԭ"PXTle9/23[VE+" "Pf_p8tɹZrr(Wuun͜j_}-ĒBI6a̰Exg
%Y.iuY@$ g" " "wx]9kU2*G6dTgnծy-^M2fQrsK*4 v@%7
+
," " " " " "pFH@:Xve
y,I!KIUWT[13VӋ%GIXM噒YUͱ(tHNY>" " " " " C@2ڪ׆Ayqie[O[YϬκfY;PTi5N( Sl@nuVK{ɇ6EaWъ }n%?6sUؾ9uu6g%ܻ/{8C};1dX'
ȱIsYV_CvZQyuJO`ؼ5wX-BĂ9sdάVPZi7wm;Xz|~NT;ܒ ʹ]4_ Wc~N}6i@u![w؞^
˪eH{faiyGzLՙA4KKIr0" "$ ce؟_5z9{KHim=-?;~&Ûw^uNi΅6:$랓jI<\bo=r#+*K*4
.YU.ZMauIEն`,wNm3_jeUQ]nND@D FK
I*+\gR)";$ c-,dG;XTVmzw}c#zfcم#ڨ{mRc$o#q;%\b'ʱ!;]ַK
eo.<>z#焚:_YZjxG*spLEdb,aI=UD@:>Yc啬wV IDATnW.:sN<tt~Z5Z~:ʝE'ډ5Je{ֹI;zea]-+-ɶ*#nun
8G'1K˷نVVU-Eӗ797V"z5*z[U E8#ph}m59Rgu$'=
*1@1Eh3Ǯoo*tद$٦e6Znf-vԭSWVbk]nke6eP;m`L|\MkivE<̹|lm|%Ċ!L
9w7>;`^Ϲa*#" ">ٺv.Ԕ&-Kx1Rb]4zHH TU[g˶8]TɜaҶ,%[
lR[[VFeXf<#-ʈ3t0gml\aټ`Dg{f^HmkU^ֱ?ŕ`qJ%m?\ΗdFoEIIm3kP[h.y$ZR۸#" H@FrǷ9{X^f>$l9Pj.k<xx=rӌOKllwEzV,vzg9ܕkB42o,qYPReVo)[QiUTYZJcN78XК܁ڴ(ݸ6\ QmfJ:@G& Yw؋+s켡]O^peߥmOaU.Ŷxs1Ç'uu='&?Z**o2E/tʹ/ZmfiKXl6KdKcXq@WXXh)))֖دJ(@UUWhٜ#tl7sB{ka:cۜ7/ܖG{9~`l8{=YQSkb3I>bf;W),#->z9c}!+!tjIVZUd$o,,r#ϫ" "wn:iXmKڒΝ;-55zٖ*/H8gIX=:bҒ^l>`XBq_}kM#XNF[|pKC&+`Nz7[l{K&٩6kdWýWdmc@`?}%vnnaGwg̴c'.o_fjII!]PaEL@ppT48$ O7zJ*jhdW[{݂8٩3尊O[klX,sԔcwC~o uJO#FʲZ˱d'")Cu(de3E_Cy9kvrNqn)$3Q|\.\h*.*) yOհ]wn˦
l?y-ZhVZJ#{sZUUq̧̏*lg
!%Wm{+,?;uL.Yily܊kw<x 5Ѧ۰vݳ"HI]ͫҦʬc" " " " " G@2KXƪOh5u#|IsCzJ[ұ.x_#!qܶ,sVQ;;YLX'}@>nw=zɘnmN)͙onCUz hnf;k`]>&tp˫jlŶnUnEZNfs 4h5Y
VU]kٿSP
gXVT[{n{g]ŶvO]96wʹZ|w~;O/k˷%AnN&$mtlkZ_726c " " " " "2-!m(oXYSk5Dž#Xԁw88/kJ}°S&''ٲͅAOâ<,2fKqXỶW܉zWl=Pf|t"J~!lKm:PʽqYڊ6 j_R_ |p/xqWPCqW;62$cX-#ţΞzl8vx>" " " " " C@2F;lMYi%=R D@D@D@D@D@ZKJ,M" " " " " " dkrUXD@D@D@D@D@NqS*p$ ;\" " " " " "pr$ OR@# \#x7a;w5kָƎ.mqq-Yjjjmƌq0$}G{Ň~h%%%nm|gk.B֧O7n\~ٳHG
#FDS$ c9T qF{7ڦNOڵkitMU" K ~zw_a)( +++m
a7u7Ď;lyn@k̙q! 5֢U$x"biiiκwBEE=䓮1##nf;% qUV8l:s-55;oeee8p<Hdw~EdVRE@D@D@N =n:CPg]/_Z?s۶mK:.t&{it ۲eLdeeـ" O Ν;[AAzz!ׯ{Fi{͛}{
֤Xrڵ;ѣGyѣGWs۴i~uqKI@5Q'" " "3zsڊ+h?[nI&+'_|Ѿtz-m :&yN>ݮ{pcyN" qMѣGۢEhc@ AX[[kQF}Z}~=nݺmfώO=W٫Ecp{.K/^p(êɽ8^x<'O.'KND@D@D@b );~Nnⱪu°PÊ:p,AG.lt۹sFGrȐ!1@ Dq"2裏{k`ffGp/Y`O>/:qra-_)}V>~[l% ۂYt1:`a֭Ƈb^{?v#k! ZkOVbTHL.]qνڻwo'pAE02uW<<?'"}%Z \fY؇Wb?Œ-[VOpF˫ą5
%[d[[H\ufi!HIvM% c"1>C><^A\?ߑd`D 1:cA
,
" I9x& Ə*>yd7!ɽW^qoJ =y6,s>enqoBHR
m' SmR{YuY#ض*U5u6gwJ8)(B:sr:Kjwy`xu脱T?Naa Vp5%9N+ڲ(z@"` by! {hRj')"!q*
m& Sӳl\rxXXa5u[D@:}RlΨLai0g #cƌqjK/t*W:#>/fC:C:bgVEܷo81H֩E4 QVK7*^
~
D1Žu
.]ԹAK%"=F~xˋɖxm" )tZZeeeۭuNWcA}\t\D@D 0&=R!ֿse=mNXrHsq;F!̙*c3cсIJqpUHl2=t7k}ʭwq17rna萦X/ C5ܣHKD,;1~s_BRgXF2@<3+ǒS삡%vW,!;\9VnjKe,?RI㑀ѱb16:be:t*ѢƢC~n#뮻.6qD灥rĈMv
}\mE@ WŋkVY9=;8WVETܷcժU֩S']?aЊEXgΝ9z
,qpg)X9fҟ =#R2{H~mE@D@:V-OܗxX gtѱC7SvY'o|v%s#YLy0OgwM2g t˾3ED a ʠ{F:+k$a ~ewH߫_#s)}[yg$sP27#Y5z.6$jN6j$e#" J[~*wc1G@\\"`u,((p4`^/.B#FD@:\Sg=K_0̚5CG,uguht7w{,7pWqGb]D{^NJ e@ui=D@D@ +.>&.<:?{RV5|7ؤ#x]w& |