diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index d8f071e045b..00000000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,48 +0,0 @@ -# -# Copyright 2022 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. -# -# This workflow will build a Java project with Maven -# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven - -name: publish sdks - -on: - workflow_dispatch: - inputs: - repository: - description: 'Maven Repository(snapshots or releases)' - required: true - default: 'snapshots' - -jobs: - publish: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: Set up Maven Central Repository - uses: actions/setup-java@v1 - with: - java-version: 8 - server-id: ${{ github.event.inputs.repository }} - server-username: MAVEN_USERNAME - server-password: MAVEN_CENTRAL_TOKEN - gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} - gpg-passphrase: MAVEN_GPG_PASSPHRASE - - name: Publish to Apache Maven Central - run: mvn clean deploy -pl apollo-client,apollo-mockserver,apollo-openapi,apollo-client-config-data -am -DskipTests=true -Prelease "-Dreleases.repo=https://oss.sonatype.org/service/local/staging/deploy/maven2" "-Dsnapshots.repo=https://oss.sonatype.org/content/repositories/snapshots" - env: - MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} - MAVEN_CENTRAL_TOKEN: ${{ secrets.MAVEN_CENTRAL_TOKEN }} - MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} \ No newline at end of file diff --git a/CHANGES.md b/CHANGES.md index 34cc988ac48..c724a90626a 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -5,10 +5,6 @@ Release Notes. Apollo 2.1.0 ------------------ -* [Add a config adjust the property source overriden behavior](https://github.com/apolloconfig/apollo/pull/4409) -* [feat(apollo-client): the spi of config service load balancer client](https://github.com/apolloconfig/apollo/pull/4394) -* [add cat-client as optional dependency](https://github.com/apolloconfig/apollo/pull/4414) -* [refactor Functions class with lambda](https://github.com/apolloconfig/apollo/pull/4419) * [fix:occur a 400 error request when openapi key's parameter contain "a[0]"](https://github.com/apolloconfig/apollo/pull/4424) * [Upgrade mysql-connector-java version to fix possible transaction rollback failure issue](https://github.com/apolloconfig/apollo/pull/4425) * [Remove database migration tool Flyway](https://github.com/apolloconfig/apollo/pull/4361) @@ -21,7 +17,7 @@ Apollo 2.1.0 * [Optimize performance of '/apps/{appId}/envs/{env}/clusters/{clusterName}/namespaces' interface queries](https://github.com/apolloconfig/apollo/pull/4473) * [Add a new API to load items with pagination](https://github.com/apolloconfig/apollo/pull/4468) * [fix(#4474):'openjdk:8-jre-alpine' potentially causing wrong number of cpu cores](https://github.com/apolloconfig/apollo/pull/4475) -* [Switching spring-session serialization mode to json for compatibility with spring-security version updates]() +* [Switching spring-session serialization mode to json for compatibility with spring-security version updates](https://github.com/apolloconfig/apollo/pull/4484) * [fix(#4483):Fixed overwrite JSON type configuration being empty](https://github.com/apolloconfig/apollo/pull/4486) * [Allow users to delete AppNamespace](https://github.com/apolloconfig/apollo/pull/4499) * [fix the deleted at timestamp issue](https://github.com/apolloconfig/apollo/pull/4493) @@ -33,8 +29,8 @@ Apollo 2.1.0 * [fix openapi item with url illegalKey 400 error](https://github.com/apolloconfig/apollo/pull/4549) * [fix the exception occurred when publish/rollback namespaces with grayrelease](https://github.com/apolloconfig/apollo/pull/4564) * [fix create namespace with single dot 500 error](https://github.com/apolloconfig/apollo/pull/4568) -* [Add overloaded shortcut method to register BeanDefinition](https://github.com/apolloconfig/apollo/pull/4574) * [Add nodejs client sdk and fix doc](https://github.com/apolloconfig/apollo/pull/4590) +* [Move apollo-core, apollo-client, apollo-mockserver, apollo-openapi and apollo-client-config-data to apollo-java repo](https://github.com/apolloconfig/apollo/pull/4594) ------------------ All issues and pull requests are [here](https://github.com/apolloconfig/apollo/milestone/11?closed=1) \ No newline at end of file diff --git a/apollo-client-config-data/pom.xml b/apollo-client-config-data/pom.xml deleted file mode 100644 index c162ce28d5c..00000000000 --- a/apollo-client-config-data/pom.xml +++ /dev/null @@ -1,77 +0,0 @@ - - - - - com.ctrip.framework.apollo - apollo - ${revision} - ../pom.xml - - 4.0.0 - apollo-client-config-data - Apollo Client Config Data - - ${project.artifactId} - - - - com.ctrip.framework.apollo - apollo-client - - - org.springframework.boot - spring-boot-autoconfigure - provided - - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - org.springframework - spring-webflux - true - - - - org.springframework.boot - spring-boot-starter-log4j2 - test - - - com.github.stefanbirkner - system-lambda - test - - - org.springframework.boot - spring-boot-starter - test - - - org.springframework.boot - spring-boot-starter-logging - - - - - diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/ApolloClientConfigDataAutoConfiguration.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/ApolloClientConfigDataAutoConfiguration.java deleted file mode 100644 index 15779366d9c..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/ApolloClientConfigDataAutoConfiguration.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.config.data.extension.initialize.ApolloClientPropertiesFactory; -import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientProperties; -import com.ctrip.framework.apollo.spring.config.ConfigPropertySourcesProcessor; -import com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author vdisk - */ -@Configuration(proxyBeanMethods = false) -public class ApolloClientConfigDataAutoConfiguration { - - @ConditionalOnMissingBean(ApolloClientProperties.class) - @ConfigurationProperties(ApolloClientPropertiesFactory.PROPERTIES_PREFIX) - @Bean - public static ApolloClientProperties apolloWebClientSecurityProperties() { - return new ApolloClientProperties(); - } - - @ConditionalOnMissingBean(PropertySourcesProcessor.class) - @Bean - public static ConfigPropertySourcesProcessor configPropertySourcesProcessor() { - return new ConfigPropertySourcesProcessor(); - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/enums/ApolloClientMessagingType.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/enums/ApolloClientMessagingType.java deleted file mode 100644 index 4b77bc7433f..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/enums/ApolloClientMessagingType.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2022 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.enums; - -/** - * @author vdisk - */ -public enum ApolloClientMessagingType { - - /** - * long polling - */ - LONG_POLLING, - - /** - * websocket - */ - WEBSOCKET, - ; -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/initialize/ApolloClientExtensionInitializeFactory.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/initialize/ApolloClientExtensionInitializeFactory.java deleted file mode 100644 index f6f86a1c951..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/initialize/ApolloClientExtensionInitializeFactory.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright 2022 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.initialize; - -import com.ctrip.framework.apollo.config.data.extension.enums.ApolloClientMessagingType; -import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientExtensionProperties; -import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientProperties; -import com.ctrip.framework.apollo.config.data.extension.webclient.ApolloClientLongPollingExtensionInitializer; -import com.ctrip.framework.apollo.config.data.extension.websocket.ApolloClientWebsocketExtensionInitializer; -import com.ctrip.framework.apollo.config.data.util.Slf4jLogMessageFormatter; -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; - -/** - * @author vdisk - */ -public class ApolloClientExtensionInitializeFactory { - - private final Log log; - - private final ApolloClientPropertiesFactory apolloClientPropertiesFactory; - - private final ApolloClientLongPollingExtensionInitializer apolloClientLongPollingExtensionInitializer; - - private final ApolloClientWebsocketExtensionInitializer apolloClientWebsocketExtensionInitializer; - - public ApolloClientExtensionInitializeFactory(Log log, - ConfigurableBootstrapContext bootstrapContext) { - this.log = log; - this.apolloClientPropertiesFactory = new ApolloClientPropertiesFactory(); - this.apolloClientLongPollingExtensionInitializer = new ApolloClientLongPollingExtensionInitializer(log, - bootstrapContext); - this.apolloClientWebsocketExtensionInitializer = new ApolloClientWebsocketExtensionInitializer(log, - bootstrapContext); - } - - /** - * initialize extension - * - * @param binder properties binder - * @param bindHandler properties bind handler - */ - public void initializeExtension(Binder binder, BindHandler bindHandler) { - ApolloClientProperties apolloClientProperties = this.apolloClientPropertiesFactory - .createApolloClientProperties(binder, bindHandler); - if (apolloClientProperties == null || apolloClientProperties.getExtension() == null) { - this.log.info("apollo client extension is not configured, default to disabled"); - return; - } - ApolloClientExtensionProperties extension = apolloClientProperties.getExtension(); - if (!extension.getEnabled()) { - this.log.info("apollo client extension disabled"); - return; - } - ApolloClientMessagingType messagingType = extension.getMessagingType(); - log.debug(Slf4jLogMessageFormatter - .format("apollo client extension messaging type: {}", messagingType)); - switch (messagingType) { - case LONG_POLLING: - this.apolloClientLongPollingExtensionInitializer - .initialize(apolloClientProperties, binder, bindHandler); - return; - case WEBSOCKET: - this.apolloClientWebsocketExtensionInitializer - .initialize(apolloClientProperties, binder, bindHandler); - return; - default: - throw new IllegalStateException("Unexpected value: " + messagingType); - } - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/initialize/ApolloClientExtensionInitializer.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/initialize/ApolloClientExtensionInitializer.java deleted file mode 100644 index cb9d0c6d013..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/initialize/ApolloClientExtensionInitializer.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2022 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.initialize; - -import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientProperties; -import org.springframework.boot.context.properties.bind.BindHandler; -import org.springframework.boot.context.properties.bind.Binder; - -/** - * @author vdisk - */ -public interface ApolloClientExtensionInitializer { - - /** - * initialize extension - * - * @param apolloClientProperties apollo client extension properties - * @param binder properties binder - * @param bindHandler properties bind handler - */ - void initialize(ApolloClientProperties apolloClientProperties, Binder binder, - BindHandler bindHandler); -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/initialize/ApolloClientPropertiesFactory.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/initialize/ApolloClientPropertiesFactory.java deleted file mode 100644 index cb008ae7d47..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/initialize/ApolloClientPropertiesFactory.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2022 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.initialize; - -import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientProperties; -import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties; -import org.springframework.boot.context.properties.bind.BindHandler; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; - -/** - * @author vdisk - */ -public class ApolloClientPropertiesFactory { - - public static final String PROPERTIES_PREFIX = "apollo.client"; - - public ApolloClientProperties createApolloClientProperties( - Binder binder, - BindHandler bindHandler) { - return binder.bind(PROPERTIES_PREFIX, - Bindable.of(ApolloClientProperties.class), bindHandler).orElse(null); - } - - public OAuth2ClientProperties createOauth2ClientProperties(Binder binder, - BindHandler bindHandler) { - return binder.bind("spring.security.oauth2.client", Bindable.of(OAuth2ClientProperties.class), - bindHandler).orElse(null); - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/properties/ApolloClientExtensionProperties.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/properties/ApolloClientExtensionProperties.java deleted file mode 100644 index f8732a29432..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/properties/ApolloClientExtensionProperties.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2022 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.properties; - -import com.ctrip.framework.apollo.config.data.extension.enums.ApolloClientMessagingType; - -/** - * @author vdisk - */ -public class ApolloClientExtensionProperties { - - /** - * enable apollo client extension(webclient/websocket and authentication) - */ - private Boolean enabled = false; - - /** - * apollo client listening type - */ - private ApolloClientMessagingType messagingType = ApolloClientMessagingType.LONG_POLLING; - - public Boolean getEnabled() { - return enabled; - } - - public void setEnabled(Boolean enabled) { - this.enabled = enabled; - } - - public ApolloClientMessagingType getMessagingType() { - return messagingType; - } - - public void setMessagingType( - ApolloClientMessagingType messagingType) { - this.messagingType = messagingType; - } - - @Override - public String toString() { - return "ApolloClientExtensionProperties{" + - "enabled=" + enabled + - ", messagingType=" + messagingType + - '}'; - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/properties/ApolloClientProperties.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/properties/ApolloClientProperties.java deleted file mode 100644 index 2b085f07aad..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/properties/ApolloClientProperties.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2022 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.properties; - -import org.springframework.boot.context.properties.NestedConfigurationProperty; - -/** - * @author vdisk - */ -public class ApolloClientProperties { - - /** - * extension configuration - */ - @NestedConfigurationProperty - private ApolloClientExtensionProperties extension; - - public ApolloClientExtensionProperties getExtension() { - return extension; - } - - public void setExtension( - ApolloClientExtensionProperties extension) { - this.extension = extension; - } - - @Override - public String toString() { - return "ApolloClientProperties{" + - "extension=" + extension + - '}'; - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/webclient/ApolloClientLongPollingExtensionInitializer.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/webclient/ApolloClientLongPollingExtensionInitializer.java deleted file mode 100644 index 07fc8eefcdb..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/webclient/ApolloClientLongPollingExtensionInitializer.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.config.data.extension.initialize.ApolloClientExtensionInitializer; -import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientProperties; -import com.ctrip.framework.apollo.config.data.extension.webclient.customizer.spi.ApolloClientWebClientCustomizerFactory; -import com.ctrip.framework.apollo.config.data.injector.ApolloConfigDataInjectorCustomizer; -import com.ctrip.framework.apollo.util.http.HttpClient; -import com.ctrip.framework.foundation.internals.ServiceBootstrap; -import java.util.List; -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.util.CollectionUtils; -import org.springframework.web.reactive.function.client.WebClient; - -/** - * @author vdisk - */ -public class ApolloClientLongPollingExtensionInitializer implements - ApolloClientExtensionInitializer { - - private final Log log; - - private final ConfigurableBootstrapContext bootstrapContext; - - public ApolloClientLongPollingExtensionInitializer(Log log, - ConfigurableBootstrapContext bootstrapContext) { - this.log = log; - this.bootstrapContext = bootstrapContext; - } - - @Override - public void initialize(ApolloClientProperties apolloClientProperties, Binder binder, - BindHandler bindHandler) { - WebClient.Builder webClientBuilder = WebClient.builder(); - List factories = ServiceBootstrap - .loadAllOrdered(ApolloClientWebClientCustomizerFactory.class); - if (!CollectionUtils.isEmpty(factories)) { - for (ApolloClientWebClientCustomizerFactory factory : factories) { - WebClientCustomizer webClientCustomizer = factory - .createWebClientCustomizer(apolloClientProperties, binder, bindHandler, this.log, - this.bootstrapContext); - if (webClientCustomizer != null) { - webClientCustomizer.customize(webClientBuilder); - } - } - } - HttpClient httpClient = new ApolloWebClientHttpClient(webClientBuilder.build()); - ApolloConfigDataInjectorCustomizer.registerIfAbsent(HttpClient.class, () -> httpClient); - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/webclient/ApolloWebClientHttpClient.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/webclient/ApolloWebClientHttpClient.java deleted file mode 100644 index f36bcca4c59..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/webclient/ApolloWebClientHttpClient.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException; -import com.ctrip.framework.apollo.util.http.HttpClient; -import com.ctrip.framework.apollo.util.http.HttpRequest; -import com.ctrip.framework.apollo.util.http.HttpResponse; -import com.google.gson.Gson; -import java.lang.reflect.Type; -import java.net.URI; -import java.util.Map; -import org.springframework.http.HttpStatus; -import org.springframework.util.CollectionUtils; -import org.springframework.web.reactive.function.client.WebClient; -import reactor.core.publisher.Mono; - -/** - * @author vdisk - */ -public class ApolloWebClientHttpClient implements HttpClient { - - private final WebClient webClient; - - private final Gson gson; - - public ApolloWebClientHttpClient(WebClient webClient) { - this(webClient, new Gson()); - } - - public ApolloWebClientHttpClient(WebClient webClient, Gson gson) { - this.webClient = webClient; - this.gson = gson; - } - - @Override - public HttpResponse doGet(HttpRequest httpRequest, Class responseType) - throws ApolloConfigException { - return this.doGetInternal(httpRequest, responseType); - } - - private HttpResponse doGetInternal(HttpRequest httpRequest, Type responseType) - throws ApolloConfigException { - WebClient.RequestHeadersSpec requestHeadersSpec = this.webClient.get() - .uri(URI.create(httpRequest.getUrl())); - if (!CollectionUtils.isEmpty(httpRequest.getHeaders())) { - for (Map.Entry entry : httpRequest.getHeaders().entrySet()) { - requestHeadersSpec.header(entry.getKey(), entry.getValue()); - } - } - return requestHeadersSpec.exchangeToMono(clientResponse -> { - if (HttpStatus.OK.equals(clientResponse.statusCode())) { - return clientResponse.bodyToMono(String.class) - .map(body -> new HttpResponse(HttpStatus.OK.value(), - gson.fromJson(body, responseType))); - } - if (HttpStatus.NOT_MODIFIED.equals(clientResponse.statusCode())) { - return Mono.just(new HttpResponse(HttpStatus.NOT_MODIFIED.value(), null)); - } - return Mono.error(new ApolloConfigStatusCodeException(clientResponse.rawStatusCode(), - String.format("Get operation failed for %s", httpRequest.getUrl()))); - }).block(); - } - - @Override - public HttpResponse doGet(HttpRequest httpRequest, Type responseType) - throws ApolloConfigException { - return this.doGetInternal(httpRequest, responseType); - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/webclient/customizer/spi/ApolloClientWebClientCustomizerFactory.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/webclient/customizer/spi/ApolloClientWebClientCustomizerFactory.java deleted file mode 100644 index 8e3448ede6a..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/webclient/customizer/spi/ApolloClientWebClientCustomizerFactory.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2022 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 - */ -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); -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/websocket/ApolloClientWebsocketExtensionInitializer.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/websocket/ApolloClientWebsocketExtensionInitializer.java deleted file mode 100644 index 88342fdcde9..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/extension/websocket/ApolloClientWebsocketExtensionInitializer.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2022 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.websocket; - -import com.ctrip.framework.apollo.config.data.extension.initialize.ApolloClientExtensionInitializer; -import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientProperties; -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; - -/** - * @author vdisk - */ -public class ApolloClientWebsocketExtensionInitializer implements ApolloClientExtensionInitializer { - - private final Log log; - - private final ConfigurableBootstrapContext bootstrapContext; - - public ApolloClientWebsocketExtensionInitializer(Log log, - ConfigurableBootstrapContext bootstrapContext) { - this.log = log; - this.bootstrapContext = bootstrapContext; - } - - @Override - public void initialize(ApolloClientProperties apolloClientProperties, Binder binder, - BindHandler bindHandler) { - throw new UnsupportedOperationException("apollo client websocket support is not complete yet."); - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataLoader.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataLoader.java deleted file mode 100644 index 2cb09a6540e..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataLoader.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2022 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.importer; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigService; -import com.ctrip.framework.apollo.config.data.util.Slf4jLogMessageFormatter; -import com.ctrip.framework.apollo.spring.config.ConfigPropertySource; -import com.ctrip.framework.apollo.spring.config.ConfigPropertySourceFactory; -import com.ctrip.framework.apollo.spring.util.SpringInjector; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import org.apache.commons.logging.Log; -import org.springframework.boot.BootstrapRegistry.InstanceSupplier; -import org.springframework.boot.ConfigurableBootstrapContext; -import org.springframework.boot.context.config.ConfigData; -import org.springframework.boot.context.config.ConfigDataLoader; -import org.springframework.boot.context.config.ConfigDataLoaderContext; -import org.springframework.boot.context.config.ConfigDataResourceNotFoundException; -import org.springframework.boot.context.properties.bind.BindHandler; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.core.Ordered; -import org.springframework.core.env.PropertySource; - -/** - * @author vdisk - */ -public class ApolloConfigDataLoader implements ConfigDataLoader, Ordered { - - private final Log log; - - public ApolloConfigDataLoader(Log log) { - this.log = log; - } - - @Override - public ConfigData load(ConfigDataLoaderContext context, ApolloConfigDataResource resource) - throws IOException, ConfigDataResourceNotFoundException { - ConfigurableBootstrapContext bootstrapContext = context.getBootstrapContext(); - Binder binder = bootstrapContext.get(Binder.class); - BindHandler bindHandler = this.getBindHandler(context); - bootstrapContext.registerIfAbsent(ApolloConfigDataLoaderInitializer.class, InstanceSupplier - .from(() -> new ApolloConfigDataLoaderInitializer(this.log, binder, bindHandler, - bootstrapContext))); - ApolloConfigDataLoaderInitializer apolloConfigDataLoaderInitializer = bootstrapContext - .get(ApolloConfigDataLoaderInitializer.class); - // init apollo client - List> initialPropertySourceList = apolloConfigDataLoaderInitializer - .initApolloClient(); - // load config - bootstrapContext.registerIfAbsent(ConfigPropertySourceFactory.class, - InstanceSupplier.from(() -> SpringInjector.getInstance(ConfigPropertySourceFactory.class))); - ConfigPropertySourceFactory configPropertySourceFactory = bootstrapContext - .get(ConfigPropertySourceFactory.class); - String namespace = resource.getNamespace(); - Config config = ConfigService.getConfig(namespace); - ConfigPropertySource configPropertySource = configPropertySourceFactory - .getConfigPropertySource(namespace, config); - List> propertySourceList = new ArrayList<>(); - propertySourceList.add(configPropertySource); - propertySourceList.addAll(initialPropertySourceList); - log.debug(Slf4jLogMessageFormatter.format("apollo client loaded namespace [{}]", namespace)); - return new ConfigData(propertySourceList); - } - - private BindHandler getBindHandler(ConfigDataLoaderContext context) { - return context.getBootstrapContext().getOrElse(BindHandler.class, null); - } - - @Override - public int getOrder() { - return Ordered.HIGHEST_PRECEDENCE + 100; - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataLoaderInitializer.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataLoaderInitializer.java deleted file mode 100644 index ef36192492f..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataLoaderInitializer.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright 2022 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.importer; - -import com.ctrip.framework.apollo.config.data.extension.initialize.ApolloClientExtensionInitializeFactory; -import com.ctrip.framework.apollo.config.data.injector.ApolloConfigDataInjectorCustomizer; -import com.ctrip.framework.apollo.config.data.internals.PureApolloConfigFactory; -import com.ctrip.framework.apollo.config.data.system.ApolloClientSystemPropertyInitializer; -import com.ctrip.framework.apollo.config.data.util.Slf4jLogMessageFormatter; -import com.ctrip.framework.apollo.core.utils.DeferredLogger; -import com.ctrip.framework.apollo.spi.ConfigFactory; -import com.ctrip.framework.apollo.spring.config.PropertySourcesConstants; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -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.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.boot.context.properties.source.ConfigurationPropertyName; -import org.springframework.core.env.MapPropertySource; -import org.springframework.core.env.PropertySource; - -/** - * @author vdisk - */ -class ApolloConfigDataLoaderInitializer { - - private static volatile boolean INITIALIZED = false; - - private final Log log; - - private final Binder binder; - - private final BindHandler bindHandler; - - private final ConfigurableBootstrapContext bootstrapContext; - - public ApolloConfigDataLoaderInitializer(Log log, - Binder binder, BindHandler bindHandler, - ConfigurableBootstrapContext bootstrapContext) { - this.log = log; - this.binder = binder; - this.bindHandler = bindHandler; - this.bootstrapContext = bootstrapContext; - } - - /** - * init apollo client (only once) - * - * @return initial sources as placeholders or empty list if already initialized - */ - public List> initApolloClient() { - if (INITIALIZED) { - return Collections.emptyList(); - } - synchronized (ApolloConfigDataLoaderInitializer.class) { - if (INITIALIZED) { - return Collections.emptyList(); - } - this.initApolloClientInternal(); - INITIALIZED = true; - if (this.forceDisableApolloBootstrap()) { - // force disable apollo bootstrap to avoid conflict - Map map = new HashMap<>(); - map.put(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, "false"); - map.put(PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, "false"); - // provide initial sources as placeholders to avoid duplicate loading - return Arrays.asList( - new ApolloConfigEmptyPropertySource( - PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME), - new MapPropertySource(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME, - Collections.unmodifiableMap(map))); - } - // provide initial sources as placeholders to avoid duplicate loading - return Arrays.asList( - new ApolloConfigEmptyPropertySource(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME), - new ApolloConfigEmptyPropertySource( - PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)); - } - } - - private void initApolloClientInternal() { - new ApolloClientSystemPropertyInitializer(this.log) - .initializeSystemProperty(this.binder, this.bindHandler); - new ApolloClientExtensionInitializeFactory(this.log, - this.bootstrapContext).initializeExtension(this.binder, this.bindHandler); - DeferredLogger.enable(); - ApolloConfigDataInjectorCustomizer.register(ConfigFactory.class, - PureApolloConfigFactory::new); - } - - private boolean forceDisableApolloBootstrap() { - boolean bootstrapEnabled = this.binder - .bind(this.camelCasedToKebabCase(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED), - Bindable.of(Boolean.class), - this.bindHandler) - .orElse(false); - if (bootstrapEnabled) { - this.log.warn(Slf4jLogMessageFormatter.format( - "apollo bootstrap is force disabled. please don't configure the property [{}=true] and [spring.config.import=apollo://...] at the same time", - PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED)); - return true; - } - boolean bootstrapEagerLoadEnabled = this.binder - .bind(this.camelCasedToKebabCase( - PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED), - Bindable.of(Boolean.class), - this.bindHandler) - .orElse(false); - if (bootstrapEagerLoadEnabled) { - this.log.warn(Slf4jLogMessageFormatter.format( - "apollo bootstrap eager load is force disabled. please don't configure the property [{}=true] and [spring.config.import=apollo://...] at the same time", - PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED)); - return true; - } - return false; - } - - /** - * {@link ConfigurationPropertyName#isValid(java.lang.CharSequence)} - * - * @param source origin propertyName - * @return valid propertyName - */ - private String camelCasedToKebabCase(String source) { - if (ConfigurationPropertyName.isValid(source)) { - return source; - } - StringBuilder stringBuilder = new StringBuilder(source.length() * 2); - for (char ch : source.toCharArray()) { - if (Character.isUpperCase(ch)) { - stringBuilder.append("-").append(Character.toLowerCase(ch)); - continue; - } - stringBuilder.append(ch); - } - return stringBuilder.toString(); - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataLocationResolver.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataLocationResolver.java deleted file mode 100644 index cf1c088b5a2..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataLocationResolver.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2022 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.importer; - -import com.ctrip.framework.apollo.config.data.util.Slf4jLogMessageFormatter; -import com.ctrip.framework.apollo.core.ConfigConsts; -import java.util.Collections; -import java.util.List; -import org.apache.commons.logging.Log; -import org.springframework.boot.context.config.ConfigDataLocation; -import org.springframework.boot.context.config.ConfigDataLocationNotFoundException; -import org.springframework.boot.context.config.ConfigDataLocationResolver; -import org.springframework.boot.context.config.ConfigDataLocationResolverContext; -import org.springframework.boot.context.config.ConfigDataResourceNotFoundException; -import org.springframework.boot.context.config.Profiles; -import org.springframework.core.Ordered; -import org.springframework.util.StringUtils; - -/** - * @author vdisk - */ -public class ApolloConfigDataLocationResolver implements - ConfigDataLocationResolver, Ordered { - - private static final String PREFIX = "apollo://"; - - private final Log log; - - public ApolloConfigDataLocationResolver(Log log) { - this.log = log; - } - - @Override - public boolean isResolvable(ConfigDataLocationResolverContext context, - ConfigDataLocation location) { - return location.hasPrefix(PREFIX); - } - - @Override - public List resolve(ConfigDataLocationResolverContext context, - ConfigDataLocation location) - throws ConfigDataLocationNotFoundException, ConfigDataResourceNotFoundException { - return Collections.emptyList(); - } - - @Override - public List resolveProfileSpecific( - ConfigDataLocationResolverContext context, ConfigDataLocation location, Profiles profiles) - throws ConfigDataLocationNotFoundException { - String namespace = location.getNonPrefixedValue(PREFIX); - if (StringUtils.hasText(namespace)) { - log.debug(Slf4jLogMessageFormatter.format("apollo config namespace [{}]", namespace)); - return Collections.singletonList(new ApolloConfigDataResource(namespace)); - } - log.debug(Slf4jLogMessageFormatter.format("apollo config namespace is empty, default to [{}]", - ConfigConsts.NAMESPACE_APPLICATION)); - return Collections.singletonList(ApolloConfigDataResource.DEFAULT); - } - - @Override - public int getOrder() { - return Ordered.HIGHEST_PRECEDENCE + 100; - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataResource.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataResource.java deleted file mode 100644 index 7339b6fb35a..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigDataResource.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2022 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.importer; - -import com.ctrip.framework.apollo.core.ConfigConsts; -import java.util.Objects; -import org.springframework.boot.context.config.ConfigDataResource; - -/** - * @author vdisk - */ -public class ApolloConfigDataResource extends ConfigDataResource { - - /** - * default resource instance - */ - public static final ApolloConfigDataResource DEFAULT = new ApolloConfigDataResource( - ConfigConsts.NAMESPACE_APPLICATION); - - /** - * apollo config namespace - */ - private final String namespace; - - public ApolloConfigDataResource(String namespace) { - this.namespace = namespace; - } - - public String getNamespace() { - return namespace; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - ApolloConfigDataResource that = (ApolloConfigDataResource) o; - return Objects.equals(namespace, that.namespace); - } - - @Override - public int hashCode() { - return Objects.hash(namespace); - } - - @Override - public String toString() { - return "ApolloConfigDataResource{" + - "namespace='" + namespace + '\'' + - '}'; - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigEmptyPropertySource.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigEmptyPropertySource.java deleted file mode 100644 index 2d68d076bd9..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/importer/ApolloConfigEmptyPropertySource.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2022 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.importer; - -import java.util.Collections; -import org.springframework.core.env.MapPropertySource; - -/** - * @author vdisk - */ -public class ApolloConfigEmptyPropertySource extends MapPropertySource { - - /** - * Create a new {@code EmptyPropertySource} with the given name. - * - * @param name the associated name - */ - public ApolloConfigEmptyPropertySource(String name) { - super(name, Collections.emptyMap()); - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/injector/ApolloConfigDataInjectorCustomizer.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/injector/ApolloConfigDataInjectorCustomizer.java deleted file mode 100644 index 59e1eb4c604..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/injector/ApolloConfigDataInjectorCustomizer.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2022 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.injector; - -import com.ctrip.framework.apollo.core.spi.Ordered; -import com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Supplier; - -/** - * @author vdisk - */ -public class ApolloConfigDataInjectorCustomizer implements ApolloInjectorCustomizer { - - /** - * the order of the injector customizer - */ - public static final int ORDER = Ordered.LOWEST_PRECEDENCE - 200; - - private static final Map, Supplier> INSTANCE_SUPPLIERS = new ConcurrentHashMap<>(); - - private static final Map, Object> INSTANCES = new ConcurrentHashMap<>(); - - /** - * Register a specific type with the registry. If the specified type has already been registered, - * it will be replaced. - * - * @param the instance type - * @param type the instance type - * @param instanceSupplier the instance supplier - */ - public static void register(Class type, Supplier instanceSupplier) { - INSTANCE_SUPPLIERS.put(type, instanceSupplier); - } - - /** - * Register a specific type with the registry if one is not already present. - * - * @param the instance type - * @param type the instance type - * @param instanceSupplier the instance supplier - */ - public static void registerIfAbsent(Class type, Supplier instanceSupplier) { - INSTANCE_SUPPLIERS.putIfAbsent(type, instanceSupplier); - } - - /** - * Return if a registration exists for the given type. - * - * @param the instance type - * @param type the instance type - * @return {@code true} if the type has already been registered - */ - public static boolean isRegistered(Class type) { - return INSTANCE_SUPPLIERS.containsKey(type); - } - - @Override - public T getInstance(Class clazz) { - @SuppressWarnings("unchecked") - Supplier instanceSupplier = (Supplier) INSTANCE_SUPPLIERS.get(clazz); - if (instanceSupplier == null) { - return null; - } - return this.getInstance(clazz, instanceSupplier); - } - - @SuppressWarnings("unchecked") - private T getInstance(Class type, Supplier instanceSupplier) { - T instance = (T) INSTANCES.get(type); - if (instance != null) { - return instance; - } - // prebuild an newInstance to prevent dead lock when recursive call computeIfAbsent - // https://bugs.openjdk.java.net/browse/JDK-8062841 - T newInstance = instanceSupplier.get(); - return (T) INSTANCES.computeIfAbsent(type, key -> newInstance); - } - - @Override - public T getInstance(Class clazz, String name) { - return null; - } - - @Override - public int getOrder() { - return ORDER; - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/internals/PureApolloConfig.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/internals/PureApolloConfig.java deleted file mode 100644 index c3bece952f1..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/internals/PureApolloConfig.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2022 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.internals; - -import com.ctrip.framework.apollo.internals.ConfigRepository; -import com.ctrip.framework.apollo.internals.DefaultConfig; -import com.ctrip.framework.apollo.internals.RepositoryChangeListener; -import com.google.common.collect.Sets; -import java.util.Set; -import org.springframework.util.CollectionUtils; - -/** - * @author vdisk - */ -public class PureApolloConfig extends DefaultConfig implements RepositoryChangeListener { - - /** - * Constructor. - * - * @param namespace the namespace of this config instance - * @param configRepository the config repository for this config instance - */ - public PureApolloConfig(String namespace, - ConfigRepository configRepository) { - super(namespace, configRepository); - } - - @Override - public String getProperty(String key, String defaultValue) { - // step 1: check local cached properties file - String value = this.getPropertyFromRepository(key); - - // step 2: check properties file from classpath - if (value == null) { - value = this.getPropertyFromAdditional(key); - } - - this.tryWarnLog(value); - - return value == null ? defaultValue : value; - } - - @Override - public Set getPropertyNames() { - // pure apollo config only contains the property from repository and the property from additional - Set fromRepository = this.getPropertyNamesFromRepository(); - Set fromAdditional = this.getPropertyNamesFromAdditional(); - if (CollectionUtils.isEmpty(fromRepository)) { - return fromAdditional; - } - if (CollectionUtils.isEmpty(fromAdditional)) { - return fromRepository; - } - Set propertyNames = Sets - .newLinkedHashSetWithExpectedSize(fromRepository.size() + fromAdditional.size()); - propertyNames.addAll(fromRepository); - propertyNames.addAll(fromAdditional); - return propertyNames; - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/internals/PureApolloConfigFactory.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/internals/PureApolloConfigFactory.java deleted file mode 100644 index c731c7f79bd..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/internals/PureApolloConfigFactory.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2022 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.internals; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.internals.ConfigRepository; -import com.ctrip.framework.apollo.spi.ConfigFactory; -import com.ctrip.framework.apollo.spi.DefaultConfigFactory; - -/** - * @author vdisk - */ -public class PureApolloConfigFactory extends DefaultConfigFactory implements ConfigFactory { - - @Override - protected Config createRepositoryConfig(String namespace, ConfigRepository configRepository) { - return new PureApolloConfig(namespace, configRepository); - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/listener/ApolloDeferredLoggerApplicationListener.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/listener/ApolloDeferredLoggerApplicationListener.java deleted file mode 100644 index 4cbe2b83eba..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/listener/ApolloDeferredLoggerApplicationListener.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2022 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.listener; - -import com.ctrip.framework.apollo.core.utils.DeferredLogger; -import org.springframework.boot.context.event.ApplicationContextInitializedEvent; -import org.springframework.boot.context.event.ApplicationFailedEvent; -import org.springframework.boot.context.event.SpringApplicationEvent; -import org.springframework.context.ApplicationListener; - -/** - * @author vdisk - */ -public class ApolloDeferredLoggerApplicationListener implements - ApplicationListener { - - @Override - public void onApplicationEvent(SpringApplicationEvent event) { - if (event instanceof ApplicationContextInitializedEvent) { - DeferredLogger.replayTo(); - } - if (event instanceof ApplicationFailedEvent) { - DeferredLogger.replayTo(); - } - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/listener/ApolloSpringApplicationRegisterListener.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/listener/ApolloSpringApplicationRegisterListener.java deleted file mode 100644 index 69ec5770460..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/listener/ApolloSpringApplicationRegisterListener.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2022 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.listener; - -import org.springframework.boot.BootstrapRegistry.InstanceSupplier; -import org.springframework.boot.ConfigurableBootstrapContext; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.context.event.ApplicationStartingEvent; -import org.springframework.context.ApplicationListener; - -/** - * @author vdisk - */ -public class ApolloSpringApplicationRegisterListener implements - ApplicationListener { - - @Override - public void onApplicationEvent(ApplicationStartingEvent event) { - ConfigurableBootstrapContext bootstrapContext = event.getBootstrapContext(); - bootstrapContext.registerIfAbsent(SpringApplication.class, - InstanceSupplier.of(event.getSpringApplication())); - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/system/ApolloClientSystemPropertyInitializer.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/system/ApolloClientSystemPropertyInitializer.java deleted file mode 100644 index 86c290dbde8..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/system/ApolloClientSystemPropertyInitializer.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2022 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.system; - -import com.ctrip.framework.apollo.config.data.util.Slf4jLogMessageFormatter; -import com.ctrip.framework.apollo.spring.boot.ApolloApplicationContextInitializer; -import org.apache.commons.logging.Log; -import org.springframework.boot.context.properties.bind.BindHandler; -import org.springframework.boot.context.properties.bind.Bindable; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.util.StringUtils; - -/** - * @author vdisk - */ -public class ApolloClientSystemPropertyInitializer { - - private final Log log; - - public ApolloClientSystemPropertyInitializer(Log log) { - this.log = log; - } - - public void initializeSystemProperty(Binder binder, BindHandler bindHandler) { - for (String propertyName : ApolloApplicationContextInitializer.APOLLO_SYSTEM_PROPERTIES) { - this.fillSystemPropertyFromBinder(propertyName, propertyName, binder, bindHandler); - } - } - - private void fillSystemPropertyFromBinder(String propertyName, String bindName, Binder binder, - BindHandler bindHandler) { - if (System.getProperty(propertyName) != null) { - return; - } - String propertyValue = binder.bind(bindName, Bindable.of(String.class), bindHandler) - .orElse(null); - if (!StringUtils.hasText(propertyValue)) { - return; - } - log.debug(Slf4jLogMessageFormatter - .format("apollo client set system property key=[{}] value=[{}]", propertyName, - propertyValue)); - System.setProperty(propertyName, propertyValue); - } -} diff --git a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/util/Slf4jLogMessageFormatter.java b/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/util/Slf4jLogMessageFormatter.java deleted file mode 100644 index 80d5337e7eb..00000000000 --- a/apollo-client-config-data/src/main/java/com/ctrip/framework/apollo/config/data/util/Slf4jLogMessageFormatter.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2022 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.util; - -import org.slf4j.helpers.MessageFormatter; -import org.springframework.core.log.LogMessage; - -/** - * @author vdisk - */ -public class Slf4jLogMessageFormatter { - - /** - * format log message - * - * @param pattern slf4j log message patten - * @param args log message args - * @return string - */ - public static LogMessage format(String pattern, Object... args) { - return LogMessage.of(() -> MessageFormatter.arrayFormat(pattern, args, null).getMessage()); - } -} diff --git a/apollo-client-config-data/src/main/resources/META-INF/services/com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer b/apollo-client-config-data/src/main/resources/META-INF/services/com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer deleted file mode 100644 index 6978b155739..00000000000 --- a/apollo-client-config-data/src/main/resources/META-INF/services/com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.config.data.injector.ApolloConfigDataInjectorCustomizer \ No newline at end of file diff --git a/apollo-client-config-data/src/main/resources/META-INF/spring.factories b/apollo-client-config-data/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 54404cdd65a..00000000000 --- a/apollo-client-config-data/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,16 +0,0 @@ -# Auto Configure -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.ctrip.framework.apollo.config.data.ApolloClientConfigDataAutoConfiguration - -# ConfigData Location Resolvers -org.springframework.boot.context.config.ConfigDataLocationResolver=\ -com.ctrip.framework.apollo.config.data.importer.ApolloConfigDataLocationResolver - -# ConfigData Loaders -org.springframework.boot.context.config.ConfigDataLoader=\ -com.ctrip.framework.apollo.config.data.importer.ApolloConfigDataLoader - -# Listener -org.springframework.context.ApplicationListener=\ -com.ctrip.framework.apollo.config.data.listener.ApolloDeferredLoggerApplicationListener,\ -com.ctrip.framework.apollo.config.data.listener.ApolloSpringApplicationRegisterListener diff --git a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/extension/initialize/ApolloClientPropertiesFactoryTest.java b/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/extension/initialize/ApolloClientPropertiesFactoryTest.java deleted file mode 100644 index 61fb59d5fda..00000000000 --- a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/extension/initialize/ApolloClientPropertiesFactoryTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2022 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.initialize; - -import com.ctrip.framework.apollo.config.data.extension.enums.ApolloClientMessagingType; -import com.ctrip.framework.apollo.config.data.extension.properties.ApolloClientProperties; -import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.Map; -import org.junit.Assert; -import org.junit.Test; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.boot.context.properties.source.MapConfigurationPropertySource; - -/** - * @author vdisk - */ -public class ApolloClientPropertiesFactoryTest { - - @Test - public void testCreateApolloClientProperties() throws IOException { - Map map = new LinkedHashMap<>(); - map.put("apollo.client.extension.enabled", "true"); - map.put("apollo.client.extension.messaging-type", "long_polling"); - MapConfigurationPropertySource propertySource = new MapConfigurationPropertySource(map); - Binder binder = new Binder(propertySource); - ApolloClientPropertiesFactory factory = new ApolloClientPropertiesFactory(); - ApolloClientProperties apolloClientProperties = factory - .createApolloClientProperties(binder, null); - - Assert.assertEquals(apolloClientProperties.getExtension().getEnabled(), true); - Assert.assertEquals(apolloClientProperties.getExtension().getMessagingType(), - ApolloClientMessagingType.LONG_POLLING); - } -} diff --git a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/importer/PureApolloConfigTest.java b/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/importer/PureApolloConfigTest.java deleted file mode 100644 index a3ea4442b97..00000000000 --- a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/importer/PureApolloConfigTest.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2022 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.importer; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.config.data.injector.ApolloMockInjectorCustomizer; -import com.ctrip.framework.apollo.config.data.internals.PureApolloConfigFactory; -import com.ctrip.framework.apollo.spi.ConfigFactory; -import com.ctrip.framework.apollo.spi.DefaultConfigFactory; -import com.github.stefanbirkner.systemlambda.SystemLambda; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - -/** - * @author vdisk - */ -public class PureApolloConfigTest { - - @Before - public void before() { - System.setProperty("env", "local"); - } - - @After - public void after() { - System.clearProperty("spring.profiles.active"); - System.clearProperty("env"); - ApolloMockInjectorCustomizer.clear(); - } - - @Test - public void testDefaultConfigWithSystemProperties() { - System.setProperty("spring.profiles.active", "test"); - ApolloMockInjectorCustomizer.register(ConfigFactory.class, - DefaultConfigFactory::new); - ConfigFactory configFactory = ApolloInjector.getInstance(ConfigFactory.class); - Config config = configFactory.create("application"); - Assert.assertEquals("test", config.getProperty("spring.profiles.active", null)); - } - - @Test - public void testPureApolloConfigWithSystemProperties() { - System.setProperty("spring.profiles.active", "test"); - ApolloMockInjectorCustomizer.register(ConfigFactory.class, - PureApolloConfigFactory::new); - ConfigFactory configFactory = ApolloInjector.getInstance(ConfigFactory.class); - Config config = configFactory.create("application"); - Assert.assertNull(config.getProperty("spring.profiles.active", null)); - } - - @Test - public void testDefaultConfigWithEnvironmentVariables() throws Exception { - SystemLambda.withEnvironmentVariable( - "SPRING_PROFILES_ACTIVE", - "test-env") - .execute(() -> { - ApolloMockInjectorCustomizer.register(ConfigFactory.class, - DefaultConfigFactory::new); - ConfigFactory configFactory = ApolloInjector.getInstance(ConfigFactory.class); - Config config = configFactory.create("application"); - Assert.assertEquals("test-env", config.getProperty("SPRING_PROFILES_ACTIVE", null)); - }); - } - - @Test - public void testPureApolloConfigWithEnvironmentVariables() throws Exception { - SystemLambda.withEnvironmentVariable( - "SPRING_PROFILES_ACTIVE", - "test-env") - .execute(() -> { - ApolloMockInjectorCustomizer.register(ConfigFactory.class, - PureApolloConfigFactory::new); - ConfigFactory configFactory = ApolloInjector.getInstance(ConfigFactory.class); - Config config = configFactory.create("application"); - Assert.assertNull(config.getProperty("SPRING_PROFILES_ACTIVE", null)); - }); - } -} diff --git a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/injector/ApolloMockInjectorCustomizer.java b/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/injector/ApolloMockInjectorCustomizer.java deleted file mode 100644 index 58e18b469ac..00000000000 --- a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/injector/ApolloMockInjectorCustomizer.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2022 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.injector; - -import com.ctrip.framework.apollo.core.spi.Ordered; -import com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Supplier; - -/** - * @author vdisk - */ -public class ApolloMockInjectorCustomizer implements ApolloInjectorCustomizer { - - private static final Map, Supplier> INSTANCE_SUPPLIERS = new ConcurrentHashMap<>(); - - private static final Map, Object> INSTANCES = new ConcurrentHashMap<>(); - - /** - * Register a specific type with the registry. If the specified type has already been registered, - * it will be replaced. - * - * @param the instance type - * @param type the instance type - * @param instanceSupplier the instance supplier - */ - public static void register(Class type, Supplier instanceSupplier) { - INSTANCE_SUPPLIERS.put(type, instanceSupplier); - } - - /** - * Register a specific type with the registry if one is not already present. - * - * @param the instance type - * @param type the instance type - * @param instanceSupplier the instance supplier - */ - public static void registerIfAbsent(Class type, Supplier instanceSupplier) { - INSTANCE_SUPPLIERS.putIfAbsent(type, instanceSupplier); - } - - /** - * Return if a registration exists for the given type. - * - * @param the instance type - * @param type the instance type - * @return {@code true} if the type has already been registered - */ - public static boolean isRegistered(Class type) { - return INSTANCE_SUPPLIERS.containsKey(type); - } - - /** - * clear the instance cache and instance suppliers - */ - public static void clear() { - INSTANCE_SUPPLIERS.clear(); - INSTANCES.clear(); - } - - @Override - public T getInstance(Class clazz) { - @SuppressWarnings("unchecked") - Supplier instanceSupplier = (Supplier) INSTANCE_SUPPLIERS.get(clazz); - if (instanceSupplier == null) { - return null; - } - return this.getInstance(clazz, instanceSupplier); - } - - @SuppressWarnings("unchecked") - private T getInstance(Class type, Supplier instanceSupplier) { - T instance = (T) INSTANCES.get(type); - if (instance != null) { - return instance; - } - // prebuild an newInstance to prevent dead lock when recursive call computeIfAbsent - // https://bugs.openjdk.java.net/browse/JDK-8062841 - T newInstance = instanceSupplier.get(); - return (T) INSTANCES.computeIfAbsent(type, key -> newInstance); - } - - @Override - public T getInstance(Class clazz, String name) { - return null; - } - - @Override - public int getOrder() { - return Ordered.HIGHEST_PRECEDENCE; - } -} diff --git a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientApplicationPropertiesCompatibleTest.java b/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientApplicationPropertiesCompatibleTest.java deleted file mode 100644 index 8f27d77100d..00000000000 --- a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientApplicationPropertiesCompatibleTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2022 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.system; - -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.spring.boot.ApolloApplicationContextInitializer; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author vdisk - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = ApolloClientPropertyCompatibleTestConfiguration.class, - webEnvironment = SpringBootTest.WebEnvironment.NONE) -@ActiveProfiles("test-compatible") -public class ApolloClientApplicationPropertiesCompatibleTest { - - @Autowired - private ConfigurableEnvironment environment; - - @Test - public void testApplicationPropertiesCompatible() { - Assert.assertEquals("test-1/cacheDir", - this.environment.getProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR)); - Assert.assertEquals("test-1-secret", - this.environment.getProperty(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET)); - Assert.assertEquals("https://test-1-config-service", - this.environment.getProperty(ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE)); - } - - @After - public void clearProperty() { - for (String propertyName : ApolloApplicationContextInitializer.APOLLO_SYSTEM_PROPERTIES) { - System.clearProperty(propertyName); - } - } -} diff --git a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientEnvironmentVariablesCompatibleTest.java b/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientEnvironmentVariablesCompatibleTest.java deleted file mode 100644 index 81a4f14d4f7..00000000000 --- a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientEnvironmentVariablesCompatibleTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2022 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.system; - -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.spring.boot.ApolloApplicationContextInitializer; -import com.github.stefanbirkner.systemlambda.SystemLambda; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author vdisk - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = ApolloClientPropertyCompatibleTestConfiguration.class, - webEnvironment = SpringBootTest.WebEnvironment.NONE) -public class ApolloClientEnvironmentVariablesCompatibleTest { - - @Autowired - private ConfigurableEnvironment environment; - - @Test - public void testEnvironmentVariablesCompatible() throws Exception { - SystemLambda.withEnvironmentVariable( - ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR_ENVIRONMENT_VARIABLES, - "test-2/cacheDir") - .and(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES, - "test-2-secret") - .and(ApolloClientSystemConsts.DEPRECATED_APOLLO_CONFIG_SERVICE_ENVIRONMENT_VARIABLES, - "https://test-2-config-service") - .execute(() -> { - Assert.assertEquals("test-2/cacheDir", - this.environment.getProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR)); - Assert.assertEquals("test-2-secret", - this.environment.getProperty(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET)); - Assert.assertEquals("https://test-2-config-service", - this.environment.getProperty(ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE)); - }); - } - - @After - public void clearProperty() { - for (String propertyName : ApolloApplicationContextInitializer.APOLLO_SYSTEM_PROPERTIES) { - System.clearProperty(propertyName); - } - } -} diff --git a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientPropertyCompatibleTestConfiguration.java b/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientPropertyCompatibleTestConfiguration.java deleted file mode 100644 index e9ab5e6c8f6..00000000000 --- a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientPropertyCompatibleTestConfiguration.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2022 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.system; - -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.context.annotation.Configuration; - -/** - * @author vdisk - */ -@Configuration -@EnableAutoConfiguration -public class ApolloClientPropertyCompatibleTestConfiguration { - -} diff --git a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientSystemPropertiesCompatibleTest.java b/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientSystemPropertiesCompatibleTest.java deleted file mode 100644 index b619b7a1546..00000000000 --- a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientSystemPropertiesCompatibleTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2022 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.system; - -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.spring.boot.ApolloApplicationContextInitializer; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -/** - * @author vdisk - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = ApolloClientPropertyCompatibleTestConfiguration.class, - webEnvironment = SpringBootTest.WebEnvironment.NONE) -public class ApolloClientSystemPropertiesCompatibleTest { - - @Autowired - private ConfigurableEnvironment environment; - - @Test - public void testSystemPropertiesCompatible() { - System.setProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, "test-3/cacheDir"); - System - .setProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET, "test-3-secret"); - System.setProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CONFIG_SERVICE, - "https://test-3-config-service"); - - Assert.assertEquals("test-3/cacheDir", - this.environment.getProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR)); - Assert.assertEquals("test-3-secret", - this.environment.getProperty(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET)); - Assert.assertEquals("https://test-3-config-service", - this.environment.getProperty(ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE)); - - System.clearProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR); - System.clearProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET); - System.clearProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CONFIG_SERVICE); - } - - @After - public void clearProperty() { - for (String propertyName : ApolloApplicationContextInitializer.APOLLO_SYSTEM_PROPERTIES) { - System.clearProperty(propertyName); - } - } -} diff --git a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientSystemPropertyInitializerTest.java b/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientSystemPropertyInitializerTest.java deleted file mode 100644 index 41a39729983..00000000000 --- a/apollo-client-config-data/src/test/java/com/ctrip/framework/apollo/config/data/system/ApolloClientSystemPropertyInitializerTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2022 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.system; - -import com.ctrip.framework.apollo.spring.boot.ApolloApplicationContextInitializer; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.concurrent.ThreadLocalRandom; -import org.apache.commons.logging.LogFactory; -import org.junit.After; -import org.junit.Assert; -import org.junit.Test; -import org.springframework.boot.context.properties.bind.Binder; -import org.springframework.boot.context.properties.source.ConfigurationPropertyName; -import org.springframework.boot.context.properties.source.MapConfigurationPropertySource; - -/** - * @author vdisk - */ -public class ApolloClientSystemPropertyInitializerTest { - - @Test - public void testSystemPropertyNames() { - for (String propertyName : ApolloApplicationContextInitializer.APOLLO_SYSTEM_PROPERTIES) { - Assert.assertTrue(ConfigurationPropertyName.isValid(propertyName)); - } - } - - @Test - public void testInitializeSystemProperty() { - Map map = new LinkedHashMap<>(); - for (String propertyName : ApolloApplicationContextInitializer.APOLLO_SYSTEM_PROPERTIES) { - System.clearProperty(propertyName); - map.put(propertyName, String.valueOf(ThreadLocalRandom.current().nextLong())); - } - MapConfigurationPropertySource propertySource = new MapConfigurationPropertySource(map); - Binder binder = new Binder(propertySource); - ApolloClientSystemPropertyInitializer initializer = new ApolloClientSystemPropertyInitializer( - LogFactory.getLog(ApolloClientSystemPropertyInitializerTest.class)); - initializer.initializeSystemProperty(binder, null); - for (String propertyName : ApolloApplicationContextInitializer.APOLLO_SYSTEM_PROPERTIES) { - Assert.assertEquals(map.get(propertyName), System.getProperty(propertyName)); - } - } - - @After - public void clearProperty() { - for (String propertyName : ApolloApplicationContextInitializer.APOLLO_SYSTEM_PROPERTIES) { - System.clearProperty(propertyName); - } - } -} diff --git a/apollo-client-config-data/src/test/resources/META-INF/services/com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer b/apollo-client-config-data/src/test/resources/META-INF/services/com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer deleted file mode 100644 index 86ef1645b48..00000000000 --- a/apollo-client-config-data/src/test/resources/META-INF/services/com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.config.data.injector.ApolloMockInjectorCustomizer \ No newline at end of file diff --git a/apollo-client-config-data/src/test/resources/application-test-compatible.properties b/apollo-client-config-data/src/test/resources/application-test-compatible.properties deleted file mode 100644 index fbab7cbea63..00000000000 --- a/apollo-client-config-data/src/test/resources/application-test-compatible.properties +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright 2022 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. -# -apollo.cacheDir=test-1/cacheDir -apollo.accesskey.secret=test-1-secret -apollo.configService=https://test-1-config-service diff --git a/apollo-client-config-data/src/test/resources/log4j2.xml b/apollo-client-config-data/src/test/resources/log4j2.xml deleted file mode 100644 index eb2cbbc5fa2..00000000000 --- a/apollo-client-config-data/src/test/resources/log4j2.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/apollo-client/pom.xml b/apollo-client/pom.xml deleted file mode 100644 index 816b45b992c..00000000000 --- a/apollo-client/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - - - com.ctrip.framework.apollo - apollo - ${revision} - ../pom.xml - - 4.0.0 - apollo-client - Apollo Client - - ${project.artifactId} - - - - - com.ctrip.framework.apollo - apollo-core - - - - - com.google.inject - guice - - - - - org.slf4j - slf4j-api - - - - org.yaml - snakeyaml - - - - - org.springframework - spring-context - true - - - - org.springframework.boot - spring-boot-autoconfigure - true - - - org.springframework.boot - spring-boot-configuration-processor - true - - - - org.eclipse.jetty - jetty-server - test - - - - org.slf4j - jcl-over-slf4j - test - - - org.apache.logging.log4j - log4j-slf4j-impl - test - - - org.apache.logging.log4j - log4j-core - test - - - - diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/Config.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/Config.java deleted file mode 100644 index 26e507d6b2d..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/Config.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.google.common.base.Function; - -import java.util.Date; -import java.util.Locale; -import java.util.Set; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface Config { - /** - * Return the property value with the given key, or {@code defaultValue} if the key doesn't exist. - * - * @param key the property name - * @param defaultValue the default value when key is not found or any error occurred - * @return the property value - */ - String getProperty(String key, String defaultValue); - - /** - * Return the integer property value with the given key, or {@code defaultValue} if the key - * doesn't exist. - * - * @param key the property name - * @param defaultValue the default value when key is not found or any error occurred - * @return the property value as integer - */ - Integer getIntProperty(String key, Integer defaultValue); - - /** - * Return the long property value with the given key, or {@code defaultValue} if the key doesn't - * exist. - * - * @param key the property name - * @param defaultValue the default value when key is not found or any error occurred - * @return the property value as long - */ - Long getLongProperty(String key, Long defaultValue); - - /** - * Return the short property value with the given key, or {@code defaultValue} if the key doesn't - * exist. - * - * @param key the property name - * @param defaultValue the default value when key is not found or any error occurred - * @return the property value as short - */ - Short getShortProperty(String key, Short defaultValue); - - /** - * Return the float property value with the given key, or {@code defaultValue} if the key doesn't - * exist. - * - * @param key the property name - * @param defaultValue the default value when key is not found or any error occurred - * @return the property value as float - */ - Float getFloatProperty(String key, Float defaultValue); - - /** - * Return the double property value with the given key, or {@code defaultValue} if the key doesn't - * exist. - * - * @param key the property name - * @param defaultValue the default value when key is not found or any error occurred - * @return the property value as double - */ - Double getDoubleProperty(String key, Double defaultValue); - - /** - * Return the byte property value with the given key, or {@code defaultValue} if the key doesn't - * exist. - * - * @param key the property name - * @param defaultValue the default value when key is not found or any error occurred - * @return the property value as byte - */ - Byte getByteProperty(String key, Byte defaultValue); - - /** - * Return the boolean property value with the given key, or {@code defaultValue} if the key - * doesn't exist. - * - * @param key the property name - * @param defaultValue the default value when key is not found or any error occurred - * @return the property value as boolean - */ - Boolean getBooleanProperty(String key, Boolean defaultValue); - - /** - * Return the array property value with the given key, or {@code defaultValue} if the key doesn't exist. - * - * @param key the property name - * @param delimiter the delimiter regex - * @param defaultValue the default value when key is not found or any error occurred - */ - String[] getArrayProperty(String key, String delimiter, String[] defaultValue); - - /** - * Return the Date property value with the given name, or {@code defaultValue} if the name doesn't exist. - * Will try to parse the date with Locale.US and formats as follows: yyyy-MM-dd HH:mm:ss.SSS, - * yyyy-MM-dd HH:mm:ss and yyyy-MM-dd - * - * @param key the property name - * @param defaultValue the default value when name is not found or any error occurred - * @return the property value - */ - Date getDateProperty(String key, Date defaultValue); - - /** - * Return the Date property value with the given name, or {@code defaultValue} if the name doesn't exist. - * Will parse the date with the format specified and Locale.US - * - * @param key the property name - * @param format the date format, see {@link java.text.SimpleDateFormat} for more - * information - * @param defaultValue the default value when name is not found or any error occurred - * @return the property value - */ - Date getDateProperty(String key, String format, Date defaultValue); - - /** - * Return the Date property value with the given name, or {@code defaultValue} if the name doesn't exist. - * - * @param key the property name - * @param format the date format, see {@link java.text.SimpleDateFormat} for more - * information - * @param locale the locale to use - * @param defaultValue the default value when name is not found or any error occurred - * @return the property value - */ - Date getDateProperty(String key, String format, Locale locale, Date defaultValue); - - /** - * Return the Enum property value with the given key, or {@code defaultValue} if the key doesn't exist. - * - * @param key the property name - * @param enumType the enum class - * @param defaultValue the default value when key is not found or any error occurred - * @param the enum - * @return the property value - */ - > T getEnumProperty(String key, Class enumType, T defaultValue); - - /** - * Return the duration property value(in milliseconds) with the given name, or {@code - * defaultValue} if the name doesn't exist. Please note the format should comply with the follow - * example (case insensitive). Examples: - *
-   *    "123MS"          -- parses as "123 milliseconds"
-   *    "20S"            -- parses as "20 seconds"
-   *    "15M"            -- parses as "15 minutes" (where a minute is 60 seconds)
-   *    "10H"            -- parses as "10 hours" (where an hour is 3600 seconds)
-   *    "2D"             -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
-   *    "2D3H4M5S123MS"  -- parses as "2 days, 3 hours, 4 minutes, 5 seconds and 123 milliseconds"
-   * 
- * - * @param key the property name - * @param defaultValue the default value when name is not found or any error occurred - * @return the parsed property value(in milliseconds) - */ - long getDurationProperty(String key, long defaultValue); - - /** - * Add change listener to this config instance, will be notified when any key is changed in this namespace. - * - * @param listener the config change listener - */ - void addChangeListener(ConfigChangeListener listener); - - /** - * Add change listener to this config instance, will only be notified when any of the interested keys is changed in this namespace. - * - * @param listener the config change listener - * @param interestedKeys the keys interested by the listener - * - * @since 1.0.0 - */ - void addChangeListener(ConfigChangeListener listener, Set interestedKeys); - - /** - * Add change listener to this config instance, will only be notified when any of the interested keys is changed in this namespace. - * - * @param listener the config change listener - * @param interestedKeys the keys that the listener is interested in - * @param interestedKeyPrefixes the key prefixes that the listener is interested in, - * e.g. "spring." means that {@code listener} is interested in keys that starts with "spring.", such as "spring.banner", "spring.jpa", etc. - * and "application" means that {@code listener} is interested in keys that starts with "application", such as "applicationName", "application.port", etc. - * For more details, see {@link com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener#interestedKeyPrefixes()} - * and {@link java.lang.String#startsWith(String)} - * - * @since 1.3.0 - */ - void addChangeListener(ConfigChangeListener listener, Set interestedKeys, - Set interestedKeyPrefixes); - - /** - * Remove the change listener - * - * @param listener the specific config change listener to remove - * @return true if the specific config change listener is found and removed - * - * @since 1.1.0 - */ - boolean removeChangeListener(ConfigChangeListener listener); - - /** - * Return a set of the property names - * - * @return the property names - */ - Set getPropertyNames(); - - /** - * Return the user-defined property value with the given key, or {@code defaultValue} if the key doesn't exist. - * - * @param key the property name - * @param function the transform {@link Function}. from String to user-defined type - * @param defaultValue the default value when key is not found or any error occurred - * @param user-defined type - * @return the property value - * - * @since 1.1.0 - */ - T getProperty(String key, Function function, T defaultValue); - - /** - * Return the config's source type, i.e. where is the config loaded from - * - * @return the config's source type - * - * @since 1.1.0 - */ - ConfigSourceType getSourceType(); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigChangeListener.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigChangeListener.java deleted file mode 100644 index c303af9c712..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigChangeListener.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.model.ConfigChangeEvent; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface ConfigChangeListener { - /** - * Invoked when there is any config change for the namespace. - * @param changeEvent the event for this change - */ - void onChange(ConfigChangeEvent changeEvent); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigFile.java deleted file mode 100644 index 50b84a38d8e..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigFile.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import com.ctrip.framework.apollo.enums.ConfigSourceType; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface ConfigFile { - /** - * Get file content of the namespace - * @return file content, {@code null} if there is no content - */ - String getContent(); - - /** - * Whether the config file has any content - * @return true if it has content, false otherwise. - */ - boolean hasContent(); - - /** - * Get the namespace of this config file instance - * @return the namespace - */ - String getNamespace(); - - /** - * Get the file format of this config file instance - * @return the config file format enum - */ - ConfigFileFormat getConfigFileFormat(); - - /** - * Add change listener to this config file instance. - * - * @param listener the config file change listener - */ - void addChangeListener(ConfigFileChangeListener listener); - - /** - * Remove the change listener - * - * @param listener the specific config change listener to remove - * @return true if the specific config change listener is found and removed - */ - boolean removeChangeListener(ConfigFileChangeListener listener); - - /** - * Return the config's source type, i.e. where is the config loaded from - * - * @return the config's source type - */ - ConfigSourceType getSourceType(); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigFileChangeListener.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigFileChangeListener.java deleted file mode 100644 index 141386567e7..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigFileChangeListener.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.model.ConfigFileChangeEvent; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface ConfigFileChangeListener { - /** - * Invoked when there is any config change for the namespace. - * @param changeEvent the event for this change - */ - void onChange(ConfigFileChangeEvent changeEvent); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigService.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigService.java deleted file mode 100644 index 184c5ee356d..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/ConfigService.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import com.ctrip.framework.apollo.internals.ConfigManager; -import com.ctrip.framework.apollo.spi.ConfigFactory; -import com.ctrip.framework.apollo.spi.ConfigRegistry; - -/** - * Entry point for client config use - * - * @author Jason Song(song_s@ctrip.com) - */ -public class ConfigService { - private static final ConfigService s_instance = new ConfigService(); - - private volatile ConfigManager m_configManager; - private volatile ConfigRegistry m_configRegistry; - - private ConfigManager getManager() { - if (m_configManager == null) { - synchronized (this) { - if (m_configManager == null) { - m_configManager = ApolloInjector.getInstance(ConfigManager.class); - } - } - } - - return m_configManager; - } - - private ConfigRegistry getRegistry() { - if (m_configRegistry == null) { - synchronized (this) { - if (m_configRegistry == null) { - m_configRegistry = ApolloInjector.getInstance(ConfigRegistry.class); - } - } - } - - return m_configRegistry; - } - - /** - * Get Application's config instance. - * - * @return config instance - */ - public static Config getAppConfig() { - return getConfig(ConfigConsts.NAMESPACE_APPLICATION); - } - - /** - * Get the config instance for the namespace. - * - * @param namespace the namespace of the config - * @return config instance - */ - public static Config getConfig(String namespace) { - return s_instance.getManager().getConfig(namespace); - } - - public static ConfigFile getConfigFile(String namespace, ConfigFileFormat configFileFormat) { - return s_instance.getManager().getConfigFile(namespace, configFileFormat); - } - - static void setConfig(Config config) { - setConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - } - - /** - * Manually set the config for the namespace specified, use with caution. - * - * @param namespace the namespace - * @param config the config instance - */ - static void setConfig(String namespace, final Config config) { - s_instance.getRegistry().register(namespace, new ConfigFactory() { - @Override - public Config create(String namespace) { - return config; - } - - @Override - public ConfigFile createConfigFile(String namespace, ConfigFileFormat configFileFormat) { - return null; - } - - }); - } - - static void setConfigFactory(ConfigFactory factory) { - setConfigFactory(ConfigConsts.NAMESPACE_APPLICATION, factory); - } - - /** - * Manually set the config factory for the namespace specified, use with caution. - * - * @param namespace the namespace - * @param factory the factory instance - */ - static void setConfigFactory(String namespace, ConfigFactory factory) { - s_instance.getRegistry().register(namespace, factory); - } - - // for test only - static void reset() { - synchronized (s_instance) { - s_instance.m_configManager = null; - s_instance.m_configRegistry = null; - } - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/PropertiesCompatibleConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/PropertiesCompatibleConfigFile.java deleted file mode 100644 index 7e428ef6d4c..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/PropertiesCompatibleConfigFile.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2022 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; - -import java.util.Properties; - -/** - * Config files that are properties compatible, e.g. yaml - * - * @since 1.3.0 - */ -public interface PropertiesCompatibleConfigFile extends ConfigFile { - - /** - * @return the properties form of the config file - * - * @throws RuntimeException if the content could not be transformed to properties - */ - Properties asProperties(); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/build/ApolloInjector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/build/ApolloInjector.java deleted file mode 100644 index 2871cc96494..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/build/ApolloInjector.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2022 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.build; - -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.internals.Injector; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.foundation.internals.ServiceBootstrap; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ApolloInjector { - private static volatile Injector s_injector; - private static final Object lock = new Object(); - - private static Injector getInjector() { - if (s_injector == null) { - synchronized (lock) { - if (s_injector == null) { - try { - s_injector = ServiceBootstrap.loadFirst(Injector.class); - } catch (Throwable ex) { - ApolloConfigException exception = new ApolloConfigException("Unable to initialize Apollo Injector!", ex); - Tracer.logError(exception); - throw exception; - } - } - } - } - - return s_injector; - } - - public static T getInstance(Class clazz) { - try { - return getInjector().getInstance(clazz); - } catch (Throwable ex) { - Tracer.logError(ex); - throw new ApolloConfigException(String.format("Unable to load instance for type %s!", clazz.getName()), ex); - } - } - - public static T getInstance(Class clazz, String name) { - try { - return getInjector().getInstance(clazz, name); - } catch (Throwable ex) { - Tracer.logError(ex); - throw new ApolloConfigException( - String.format("Unable to load instance for type %s and name %s !", clazz.getName(), name), ex); - } - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/enums/ConfigSourceType.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/enums/ConfigSourceType.java deleted file mode 100644 index b8249472fb8..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/enums/ConfigSourceType.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2022 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.enums; - -/** - * To indicate the config's source type, i.e. where is the config loaded from - * - * @since 1.1.0 - */ -public enum ConfigSourceType { - REMOTE("Loaded from remote config service"), LOCAL("Loaded from local cache"), NONE("Load failed"); - - private final String description; - - ConfigSourceType(String description) { - this.description = description; - } - - public String getDescription() { - return description; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/enums/PropertyChangeType.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/enums/PropertyChangeType.java deleted file mode 100644 index ec72282e113..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/enums/PropertyChangeType.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2022 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.enums; - - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public enum PropertyChangeType { - ADDED, MODIFIED, DELETED -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/exceptions/ApolloConfigException.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/exceptions/ApolloConfigException.java deleted file mode 100644 index 3a7483cb0c9..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/exceptions/ApolloConfigException.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2022 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.exceptions; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ApolloConfigException extends RuntimeException { - public ApolloConfigException(String message) { - super(message); - } - - public ApolloConfigException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/exceptions/ApolloConfigStatusCodeException.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/exceptions/ApolloConfigStatusCodeException.java deleted file mode 100644 index ea2e0fe856e..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/exceptions/ApolloConfigStatusCodeException.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2022 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.exceptions; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ApolloConfigStatusCodeException extends RuntimeException{ - private final int m_statusCode; - - public ApolloConfigStatusCodeException(int statusCode, String message) { - super(String.format("[status code: %d] %s", statusCode, message)); - this.m_statusCode = statusCode; - } - - public ApolloConfigStatusCodeException(int statusCode, Throwable cause) { - super(cause); - this.m_statusCode = statusCode; - } - - public int getStatusCode() { - return m_statusCode; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfig.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfig.java deleted file mode 100644 index 7ce41dcaf9a..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfig.java +++ /dev/null @@ -1,611 +0,0 @@ -/* - * Copyright 2022 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.Config; -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; -import com.ctrip.framework.apollo.enums.PropertyChangeType; -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.model.ConfigChange; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.apollo.tracer.spi.Transaction; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.ctrip.framework.apollo.util.factory.PropertiesFactory; -import com.ctrip.framework.apollo.util.function.Functions; -import com.ctrip.framework.apollo.util.parser.Parsers; -import com.google.common.base.Function; -import com.google.common.base.Objects; -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; - -import java.util.*; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicLong; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public abstract class AbstractConfig implements Config { - private static final Logger logger = LoggerFactory.getLogger(AbstractConfig.class); - - private static final ExecutorService m_executorService; - - private final List m_listeners = Lists.newCopyOnWriteArrayList(); - private final Map> m_interestedKeys = Maps.newConcurrentMap(); - private final Map> m_interestedKeyPrefixes = Maps.newConcurrentMap(); - private final ConfigUtil m_configUtil; - private volatile Cache m_integerCache; - private volatile Cache m_longCache; - private volatile Cache m_shortCache; - private volatile Cache m_floatCache; - private volatile Cache m_doubleCache; - private volatile Cache m_byteCache; - private volatile Cache m_booleanCache; - private volatile Cache m_dateCache; - private volatile Cache m_durationCache; - private final Map> m_arrayCache; - private final List allCaches; - private final AtomicLong m_configVersion; //indicate config version - - protected PropertiesFactory propertiesFactory; - - static { - m_executorService = Executors.newCachedThreadPool(ApolloThreadFactory - .create("Config", true)); - } - - public AbstractConfig() { - m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); - m_configVersion = new AtomicLong(); - m_arrayCache = Maps.newConcurrentMap(); - allCaches = Lists.newArrayList(); - propertiesFactory = ApolloInjector.getInstance(PropertiesFactory.class); - } - - @Override - public void addChangeListener(ConfigChangeListener listener) { - addChangeListener(listener, null); - } - - @Override - public void addChangeListener(ConfigChangeListener listener, Set interestedKeys) { - addChangeListener(listener, interestedKeys, null); - } - - @Override - public void addChangeListener(ConfigChangeListener listener, Set interestedKeys, Set interestedKeyPrefixes) { - if (!m_listeners.contains(listener)) { - m_listeners.add(listener); - if (interestedKeys != null && !interestedKeys.isEmpty()) { - m_interestedKeys.put(listener, Sets.newHashSet(interestedKeys)); - } - if (interestedKeyPrefixes != null && !interestedKeyPrefixes.isEmpty()) { - m_interestedKeyPrefixes.put(listener, Sets.newHashSet(interestedKeyPrefixes)); - } - } - } - - @Override - public boolean removeChangeListener(ConfigChangeListener listener) { - m_interestedKeys.remove(listener); - m_interestedKeyPrefixes.remove(listener); - return m_listeners.remove(listener); - } - - @Override - public Integer getIntProperty(String key, Integer defaultValue) { - try { - if (m_integerCache == null) { - synchronized (this) { - if (m_integerCache == null) { - m_integerCache = newCache(); - } - } - } - - return getValueFromCache(key, Functions.TO_INT_FUNCTION, m_integerCache, defaultValue); - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getIntProperty for %s failed, return default value %d", key, - defaultValue), ex)); - } - return defaultValue; - } - - @Override - public Long getLongProperty(String key, Long defaultValue) { - try { - if (m_longCache == null) { - synchronized (this) { - if (m_longCache == null) { - m_longCache = newCache(); - } - } - } - - return getValueFromCache(key, Functions.TO_LONG_FUNCTION, m_longCache, defaultValue); - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getLongProperty for %s failed, return default value %d", key, - defaultValue), ex)); - } - return defaultValue; - } - - @Override - public Short getShortProperty(String key, Short defaultValue) { - try { - if (m_shortCache == null) { - synchronized (this) { - if (m_shortCache == null) { - m_shortCache = newCache(); - } - } - } - - return getValueFromCache(key, Functions.TO_SHORT_FUNCTION, m_shortCache, defaultValue); - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getShortProperty for %s failed, return default value %d", key, - defaultValue), ex)); - } - return defaultValue; - } - - @Override - public Float getFloatProperty(String key, Float defaultValue) { - try { - if (m_floatCache == null) { - synchronized (this) { - if (m_floatCache == null) { - m_floatCache = newCache(); - } - } - } - - return getValueFromCache(key, Functions.TO_FLOAT_FUNCTION, m_floatCache, defaultValue); - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getFloatProperty for %s failed, return default value %f", key, - defaultValue), ex)); - } - return defaultValue; - } - - @Override - public Double getDoubleProperty(String key, Double defaultValue) { - try { - if (m_doubleCache == null) { - synchronized (this) { - if (m_doubleCache == null) { - m_doubleCache = newCache(); - } - } - } - - return getValueFromCache(key, Functions.TO_DOUBLE_FUNCTION, m_doubleCache, defaultValue); - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getDoubleProperty for %s failed, return default value %f", key, - defaultValue), ex)); - } - return defaultValue; - } - - @Override - public Byte getByteProperty(String key, Byte defaultValue) { - try { - if (m_byteCache == null) { - synchronized (this) { - if (m_byteCache == null) { - m_byteCache = newCache(); - } - } - } - - return getValueFromCache(key, Functions.TO_BYTE_FUNCTION, m_byteCache, defaultValue); - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getByteProperty for %s failed, return default value %d", key, - defaultValue), ex)); - } - return defaultValue; - } - - @Override - public Boolean getBooleanProperty(String key, Boolean defaultValue) { - try { - if (m_booleanCache == null) { - synchronized (this) { - if (m_booleanCache == null) { - m_booleanCache = newCache(); - } - } - } - - return getValueFromCache(key, Functions.TO_BOOLEAN_FUNCTION, m_booleanCache, defaultValue); - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getBooleanProperty for %s failed, return default value %b", key, - defaultValue), ex)); - } - return defaultValue; - } - - @Override - public String[] getArrayProperty(String key, final String delimiter, String[] defaultValue) { - try { - if (!m_arrayCache.containsKey(delimiter)) { - synchronized (this) { - if (!m_arrayCache.containsKey(delimiter)) { - m_arrayCache.put(delimiter, this.newCache()); - } - } - } - - Cache cache = m_arrayCache.get(delimiter); - String[] result = cache.getIfPresent(key); - - if (result != null) { - return result; - } - - return getValueAndStoreToCache(key, new Function() { - @Override - public String[] apply(String input) { - return input.split(delimiter); - } - }, cache, defaultValue); - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getArrayProperty for %s failed, return default value", key), ex)); - } - return defaultValue; - } - - @Override - public > T getEnumProperty(String key, Class enumType, T defaultValue) { - try { - String value = getProperty(key, null); - - if (value != null) { - return Enum.valueOf(enumType, value); - } - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getEnumProperty for %s failed, return default value %s", key, - defaultValue), ex)); - } - - return defaultValue; - } - - @Override - public Date getDateProperty(String key, Date defaultValue) { - try { - if (m_dateCache == null) { - synchronized (this) { - if (m_dateCache == null) { - m_dateCache = newCache(); - } - } - } - - return getValueFromCache(key, Functions.TO_DATE_FUNCTION, m_dateCache, defaultValue); - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getDateProperty for %s failed, return default value %s", key, - defaultValue), ex)); - } - - return defaultValue; - } - - @Override - public Date getDateProperty(String key, String format, Date defaultValue) { - try { - String value = getProperty(key, null); - - if (value != null) { - return Parsers.forDate().parse(value, format); - } - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getDateProperty for %s failed, return default value %s", key, - defaultValue), ex)); - } - - return defaultValue; - } - - @Override - public Date getDateProperty(String key, String format, Locale locale, Date defaultValue) { - try { - String value = getProperty(key, null); - - if (value != null) { - return Parsers.forDate().parse(value, format, locale); - } - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getDateProperty for %s failed, return default value %s", key, - defaultValue), ex)); - } - - return defaultValue; - } - - @Override - public long getDurationProperty(String key, long defaultValue) { - try { - if (m_durationCache == null) { - synchronized (this) { - if (m_durationCache == null) { - m_durationCache = newCache(); - } - } - } - - return getValueFromCache(key, Functions.TO_DURATION_FUNCTION, m_durationCache, defaultValue); - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getDurationProperty for %s failed, return default value %d", key, - defaultValue), ex)); - } - - return defaultValue; - } - - @Override - public T getProperty(String key, Function function, T defaultValue) { - try { - String value = getProperty(key, null); - - if (value != null) { - return function.apply(value); - } - } catch (Throwable ex) { - Tracer.logError(new ApolloConfigException( - String.format("getProperty for %s failed, return default value %s", key, - defaultValue), ex)); - } - - return defaultValue; - } - - private T getValueFromCache(String key, Function parser, Cache cache, T defaultValue) { - T result = cache.getIfPresent(key); - - if (result != null) { - return result; - } - - return getValueAndStoreToCache(key, parser, cache, defaultValue); - } - - private T getValueAndStoreToCache(String key, Function parser, Cache cache, T defaultValue) { - long currentConfigVersion = m_configVersion.get(); - String value = getProperty(key, null); - - if (value != null) { - T result = parser.apply(value); - - if (result != null) { - synchronized (this) { - if (m_configVersion.get() == currentConfigVersion) { - cache.put(key, result); - } - } - return result; - } - } - - return defaultValue; - } - - private Cache newCache() { - Cache cache = CacheBuilder.newBuilder() - .maximumSize(m_configUtil.getMaxConfigCacheSize()) - .expireAfterAccess(m_configUtil.getConfigCacheExpireTime(), m_configUtil.getConfigCacheExpireTimeUnit()) - .build(); - allCaches.add(cache); - return cache; - } - - /** - * Clear config cache - */ - protected void clearConfigCache() { - synchronized (this) { - for (Cache c : allCaches) { - if (c != null) { - c.invalidateAll(); - } - } - m_configVersion.incrementAndGet(); - } - } - - /** - * @param changes map's key is config property's key - */ - protected void fireConfigChange(String namespace, Map changes) { - final Set changedKeys = changes.keySet(); - final List listeners = this.findMatchedConfigChangeListeners(changedKeys); - - // notify those listeners - for (ConfigChangeListener listener : listeners) { - Set interestedChangedKeys = resolveInterestedChangedKeys(listener, changedKeys); - InterestedConfigChangeEvent interestedConfigChangeEvent = new InterestedConfigChangeEvent( - namespace, changes, interestedChangedKeys); - this.notifyAsync(listener, interestedConfigChangeEvent); - } - } - - /** - * Fire the listeners by event. - */ - protected void fireConfigChange(final ConfigChangeEvent changeEvent) { - final List listeners = this - .findMatchedConfigChangeListeners(changeEvent.changedKeys()); - - // notify those listeners - for (ConfigChangeListener listener : listeners) { - this.notifyAsync(listener, changeEvent); - } - } - - private List findMatchedConfigChangeListeners(Set changedKeys) { - final List configChangeListeners = new ArrayList<>(); - for (ConfigChangeListener configChangeListener : this.m_listeners) { - // check whether the listener is interested in this change event - if (this.isConfigChangeListenerInterested(configChangeListener, changedKeys)) { - configChangeListeners.add(configChangeListener); - } - } - return configChangeListeners; - } - - private void notifyAsync(final ConfigChangeListener listener, final ConfigChangeEvent changeEvent) { - m_executorService.submit(new Runnable() { - @Override - public void run() { - String listenerName = listener.getClass().getName(); - Transaction transaction = Tracer.newTransaction("Apollo.ConfigChangeListener", listenerName); - try { - listener.onChange(changeEvent); - transaction.setStatus(Transaction.SUCCESS); - } catch (Throwable ex) { - transaction.setStatus(ex); - Tracer.logError(ex); - logger.error("Failed to invoke config change listener {}", listenerName, ex); - } finally { - transaction.complete(); - } - } - }); - } - - private boolean isConfigChangeListenerInterested(ConfigChangeListener configChangeListener, Set changedKeys) { - Set interestedKeys = m_interestedKeys.get(configChangeListener); - Set interestedKeyPrefixes = m_interestedKeyPrefixes.get(configChangeListener); - - if ((interestedKeys == null || interestedKeys.isEmpty()) - && (interestedKeyPrefixes == null || interestedKeyPrefixes.isEmpty())) { - return true; // no interested keys means interested in all keys - } - - if (interestedKeys != null) { - for (String interestedKey : interestedKeys) { - if (changedKeys.contains(interestedKey)) { - return true; - } - } - } - - if (interestedKeyPrefixes != null) { - for (String prefix : interestedKeyPrefixes) { - for (final String changedKey : changedKeys) { - if (changedKey.startsWith(prefix)) { - return true; - } - } - } - } - - return false; - } - - private Set resolveInterestedChangedKeys(ConfigChangeListener configChangeListener, Set changedKeys) { - Set interestedChangedKeys = new HashSet<>(); - - if (this.m_interestedKeys.containsKey(configChangeListener)) { - Set interestedKeys = this.m_interestedKeys.get(configChangeListener); - for (String interestedKey : interestedKeys) { - if (changedKeys.contains(interestedKey)) { - interestedChangedKeys.add(interestedKey); - } - } - } - - if (this.m_interestedKeyPrefixes.containsKey(configChangeListener)) { - Set interestedKeyPrefixes = this.m_interestedKeyPrefixes.get(configChangeListener); - for (String interestedKeyPrefix : interestedKeyPrefixes) { - for (String changedKey : changedKeys) { - if (changedKey.startsWith(interestedKeyPrefix)) { - interestedChangedKeys.add(changedKey); - } - } - } - } - - return Collections.unmodifiableSet(interestedChangedKeys); - } - - List calcPropertyChanges(String namespace, Properties previous, - Properties current) { - if (previous == null) { - previous = propertiesFactory.getPropertiesInstance(); - } - - if (current == null) { - current = propertiesFactory.getPropertiesInstance(); - } - - Set previousKeys = previous.stringPropertyNames(); - Set currentKeys = current.stringPropertyNames(); - - Set commonKeys = Sets.intersection(previousKeys, currentKeys); - Set newKeys = Sets.difference(currentKeys, commonKeys); - Set removedKeys = Sets.difference(previousKeys, commonKeys); - - List changes = Lists.newArrayList(); - - for (String newKey : newKeys) { - changes.add(new ConfigChange(namespace, newKey, null, current.getProperty(newKey), - PropertyChangeType.ADDED)); - } - - for (String removedKey : removedKeys) { - changes.add(new ConfigChange(namespace, removedKey, previous.getProperty(removedKey), null, - PropertyChangeType.DELETED)); - } - - for (String commonKey : commonKeys) { - String previousValue = previous.getProperty(commonKey); - String currentValue = current.getProperty(commonKey); - if (Objects.equal(previousValue, currentValue)) { - continue; - } - changes.add(new ConfigChange(namespace, commonKey, previousValue, currentValue, - PropertyChangeType.MODIFIED)); - } - - return changes; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigFile.java deleted file mode 100644 index 3a1c0df077c..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigFile.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright 2022 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.build.ApolloInjector; -import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.ctrip.framework.apollo.util.factory.PropertiesFactory; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicReference; - -import org.slf4j.Logger; - -import com.ctrip.framework.apollo.ConfigFile; -import com.ctrip.framework.apollo.ConfigFileChangeListener; -import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; -import com.ctrip.framework.apollo.enums.PropertyChangeType; -import com.ctrip.framework.apollo.model.ConfigFileChangeEvent; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.apollo.tracer.spi.Transaction; -import com.ctrip.framework.apollo.util.ExceptionUtil; -import com.google.common.collect.Lists; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public abstract class AbstractConfigFile implements ConfigFile, RepositoryChangeListener { - private static final Logger logger = DeferredLoggerFactory.getLogger(AbstractConfigFile.class); - private static ExecutorService m_executorService; - protected final ConfigRepository m_configRepository; - protected final String m_namespace; - protected final AtomicReference m_configProperties; - private final List m_listeners = Lists.newCopyOnWriteArrayList(); - protected final PropertiesFactory propertiesFactory; - - private volatile ConfigSourceType m_sourceType = ConfigSourceType.NONE; - - static { - m_executorService = Executors.newCachedThreadPool(ApolloThreadFactory - .create("ConfigFile", true)); - } - - public AbstractConfigFile(String namespace, ConfigRepository configRepository) { - m_configRepository = configRepository; - m_namespace = namespace; - m_configProperties = new AtomicReference<>(); - propertiesFactory = ApolloInjector.getInstance(PropertiesFactory.class); - initialize(); - } - - private void initialize() { - try { - m_configProperties.set(m_configRepository.getConfig()); - m_sourceType = m_configRepository.getSourceType(); - } catch (Throwable ex) { - Tracer.logError(ex); - logger.warn("Init Apollo Config File failed - namespace: {}, reason: {}.", - m_namespace, ExceptionUtil.getDetailMessage(ex)); - } finally { - //register the change listener no matter config repository is working or not - //so that whenever config repository is recovered, config could get changed - m_configRepository.addChangeListener(this); - } - } - - @Override - public String getNamespace() { - return m_namespace; - } - - protected abstract void update(Properties newProperties); - - @Override - public synchronized void onRepositoryChange(String namespace, Properties newProperties) { - if (newProperties.equals(m_configProperties.get())) { - return; - } - Properties newConfigProperties = propertiesFactory.getPropertiesInstance(); - newConfigProperties.putAll(newProperties); - - String oldValue = getContent(); - - update(newProperties); - m_sourceType = m_configRepository.getSourceType(); - - String newValue = getContent(); - - PropertyChangeType changeType = PropertyChangeType.MODIFIED; - - if (oldValue == null) { - changeType = PropertyChangeType.ADDED; - } else if (newValue == null) { - changeType = PropertyChangeType.DELETED; - } - - this.fireConfigChange(new ConfigFileChangeEvent(m_namespace, oldValue, newValue, changeType)); - - Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace); - } - - @Override - public void addChangeListener(ConfigFileChangeListener listener) { - if (!m_listeners.contains(listener)) { - m_listeners.add(listener); - } - } - - @Override - public boolean removeChangeListener(ConfigFileChangeListener listener) { - return m_listeners.remove(listener); - } - - @Override - public ConfigSourceType getSourceType() { - return m_sourceType; - } - - private void fireConfigChange(final ConfigFileChangeEvent changeEvent) { - for (final ConfigFileChangeListener listener : m_listeners) { - m_executorService.submit(new Runnable() { - @Override - public void run() { - String listenerName = listener.getClass().getName(); - Transaction transaction = Tracer.newTransaction("Apollo.ConfigFileChangeListener", listenerName); - try { - listener.onChange(changeEvent); - transaction.setStatus(Transaction.SUCCESS); - } catch (Throwable ex) { - transaction.setStatus(ex); - Tracer.logError(ex); - logger.error("Failed to invoke config file change listener {}", listenerName, ex); - } finally { - transaction.complete(); - } - } - }); - } - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java deleted file mode 100644 index 35ff55616c6..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/AbstractConfigRepository.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2022 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.build.ApolloInjector; -import com.ctrip.framework.apollo.util.factory.PropertiesFactory; -import java.util.List; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.apollo.util.ExceptionUtil; -import com.google.common.collect.Lists; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public abstract class AbstractConfigRepository implements ConfigRepository { - private static final Logger logger = LoggerFactory.getLogger(AbstractConfigRepository.class); - private List m_listeners = Lists.newCopyOnWriteArrayList(); - protected PropertiesFactory propertiesFactory = ApolloInjector.getInstance(PropertiesFactory.class); - - protected boolean trySync() { - try { - sync(); - return true; - } catch (Throwable ex) { - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex)); - logger - .warn("Sync config failed, will retry. Repository {}, reason: {}", this.getClass(), ExceptionUtil - .getDetailMessage(ex)); - } - return false; - } - - protected abstract void sync(); - - @Override - public void addChangeListener(RepositoryChangeListener listener) { - if (!m_listeners.contains(listener)) { - m_listeners.add(listener); - } - } - - @Override - public void removeChangeListener(RepositoryChangeListener listener) { - m_listeners.remove(listener); - } - - protected void fireRepositoryChange(String namespace, Properties newProperties) { - for (RepositoryChangeListener listener : m_listeners) { - try { - listener.onRepositoryChange(namespace, newProperties); - } catch (Throwable ex) { - Tracer.logError(ex); - logger.error("Failed to invoke repository change listener {}", listener.getClass(), ex); - } - } - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigManager.java deleted file mode 100644 index 0fedcbea8ce..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigManager.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2022 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.Config; -import com.ctrip.framework.apollo.ConfigFile; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface ConfigManager { - /** - * Get the config instance for the namespace specified. - * @param namespace the namespace - * @return the config instance for the namespace - */ - Config getConfig(String namespace); - - /** - * Get the config file instance for the namespace specified. - * @param namespace the namespace - * @param configFileFormat the config file format - * @return the config file instance for the namespace - */ - ConfigFile getConfigFile(String namespace, ConfigFileFormat configFileFormat); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigRepository.java deleted file mode 100644 index faf4b6103ec..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigRepository.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2022 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(song_s@ctrip.com) - */ -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(); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java deleted file mode 100644 index e7cba404beb..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/ConfigServiceLocator.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * Copyright 2022 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.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.core.ServiceNameConsts; -import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; -import com.ctrip.framework.apollo.core.utils.DeprecatedPropertyNotifyUtil; -import com.ctrip.framework.foundation.Foundation; -import java.lang.reflect.Type; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.atomic.AtomicReference; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.core.dto.ServiceDTO; -import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.apollo.tracer.spi.Transaction; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.ctrip.framework.apollo.util.ExceptionUtil; -import com.ctrip.framework.apollo.util.http.HttpRequest; -import com.ctrip.framework.apollo.util.http.HttpResponse; -import com.ctrip.framework.apollo.util.http.HttpClient; -import com.google.common.base.Joiner; -import com.google.common.base.Strings; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.escape.Escaper; -import com.google.common.net.UrlEscapers; -import com.google.gson.reflect.TypeToken; - -public class ConfigServiceLocator { - private static final Logger logger = DeferredLoggerFactory.getLogger(ConfigServiceLocator.class); - private HttpClient m_httpClient; - private ConfigUtil m_configUtil; - private AtomicReference> m_configServices; - private Type m_responseType; - private ScheduledExecutorService m_executorService; - private static final Joiner.MapJoiner MAP_JOINER = Joiner.on("&").withKeyValueSeparator("="); - private static final Escaper queryParamEscaper = UrlEscapers.urlFormParameterEscaper(); - - /** - * Create a config service locator. - */ - public ConfigServiceLocator() { - List initial = Lists.newArrayList(); - m_configServices = new AtomicReference<>(initial); - m_responseType = new TypeToken>() { - }.getType(); - m_httpClient = ApolloInjector.getInstance(HttpClient.class); - m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); - this.m_executorService = Executors.newScheduledThreadPool(1, - ApolloThreadFactory.create("ConfigServiceLocator", true)); - initConfigServices(); - } - - private void initConfigServices() { - // get from run time configurations - List customizedConfigServices = getCustomizedConfigService(); - - if (customizedConfigServices != null) { - setConfigServices(customizedConfigServices); - return; - } - - // update from meta service - this.tryUpdateConfigServices(); - this.schedulePeriodicRefresh(); - } - - private List getCustomizedConfigService() { - // 1. Get from System Property - String configServices = System.getProperty(ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE); - if (Strings.isNullOrEmpty(configServices)) { - // 2. Get from OS environment variable - configServices = System.getenv(ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE_ENVIRONMENT_VARIABLES); - } - if (Strings.isNullOrEmpty(configServices)) { - // 3. Get from server.properties - configServices = Foundation.server().getProperty(ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE, null); - } - if (Strings.isNullOrEmpty(configServices)) { - // 4. Get from deprecated config - configServices = getDeprecatedCustomizedConfigService(); - } - - if (Strings.isNullOrEmpty(configServices)) { - return null; - } - - logger.info("Located config services from apollo.config-service configuration: {}, will not refresh config services from remote meta service!", configServices); - - // mock service dto list - String[] configServiceUrls = configServices.split(","); - List serviceDTOS = Lists.newArrayList(); - - for (String configServiceUrl : configServiceUrls) { - configServiceUrl = configServiceUrl.trim(); - ServiceDTO serviceDTO = new ServiceDTO(); - serviceDTO.setHomepageUrl(configServiceUrl); - serviceDTO.setAppName(ServiceNameConsts.APOLLO_CONFIGSERVICE); - serviceDTO.setInstanceId(configServiceUrl); - serviceDTOS.add(serviceDTO); - } - - return serviceDTOS; - } - - @SuppressWarnings("deprecation") - private String getDeprecatedCustomizedConfigService() { - // 1. Get from System Property - String configServices = System.getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CONFIG_SERVICE); - if (!Strings.isNullOrEmpty(configServices)) { - DeprecatedPropertyNotifyUtil.warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_CONFIG_SERVICE, - ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE); - } - if (Strings.isNullOrEmpty(configServices)) { - // 2. Get from OS environment variable - configServices = System.getenv(ApolloClientSystemConsts.DEPRECATED_APOLLO_CONFIG_SERVICE_ENVIRONMENT_VARIABLES); - if (!Strings.isNullOrEmpty(configServices)) { - DeprecatedPropertyNotifyUtil.warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_CONFIG_SERVICE_ENVIRONMENT_VARIABLES, - ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE_ENVIRONMENT_VARIABLES); - } - } - if (Strings.isNullOrEmpty(configServices)) { - // 3. Get from server.properties - configServices = Foundation.server().getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CONFIG_SERVICE, null); - if (!Strings.isNullOrEmpty(configServices)) { - DeprecatedPropertyNotifyUtil.warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_CONFIG_SERVICE, - ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE); - } - } - return configServices; - } - - /** - * Get the config service info from remote meta server. - * - * @return the services dto - */ - public List getConfigServices() { - if (m_configServices.get().isEmpty()) { - updateConfigServices(); - } - - return m_configServices.get(); - } - - private boolean tryUpdateConfigServices() { - try { - updateConfigServices(); - return true; - } catch (Throwable ex) { - //ignore - } - return false; - } - - private void schedulePeriodicRefresh() { - this.m_executorService.scheduleAtFixedRate( - new Runnable() { - @Override - public void run() { - logger.debug("refresh config services"); - Tracer.logEvent("Apollo.MetaService", "periodicRefresh"); - tryUpdateConfigServices(); - } - }, m_configUtil.getRefreshInterval(), m_configUtil.getRefreshInterval(), - m_configUtil.getRefreshIntervalTimeUnit()); - } - - private synchronized void updateConfigServices() { - String url = assembleMetaServiceUrl(); - - HttpRequest request = new HttpRequest(url); - int maxRetries = 2; - Throwable exception = null; - - for (int i = 0; i < maxRetries; i++) { - Transaction transaction = Tracer.newTransaction("Apollo.MetaService", "getConfigService"); - transaction.addData("Url", url); - try { - HttpResponse> response = m_httpClient.doGet(request, m_responseType); - transaction.setStatus(Transaction.SUCCESS); - List services = response.getBody(); - if (services == null || services.isEmpty()) { - logConfigService("Empty response!"); - continue; - } - setConfigServices(services); - return; - } catch (Throwable ex) { - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex)); - transaction.setStatus(ex); - exception = ex; - } finally { - transaction.complete(); - } - - try { - m_configUtil.getOnErrorRetryIntervalTimeUnit().sleep(m_configUtil.getOnErrorRetryInterval()); - } catch (InterruptedException ex) { - //ignore - } - } - - throw new ApolloConfigException( - String.format("Get config services failed from %s", url), exception); - } - - private void setConfigServices(List services) { - m_configServices.set(services); - logConfigServices(services); - } - - private String assembleMetaServiceUrl() { - String domainName = m_configUtil.getMetaServerDomainName(); - String appId = m_configUtil.getAppId(); - String localIp = m_configUtil.getLocalIp(); - - Map queryParams = Maps.newHashMap(); - queryParams.put("appId", queryParamEscaper.escape(appId)); - if (!Strings.isNullOrEmpty(localIp)) { - queryParams.put("ip", queryParamEscaper.escape(localIp)); - } - - return domainName + "/services/config?" + MAP_JOINER.join(queryParams); - } - - private void logConfigServices(List serviceDtos) { - for (ServiceDTO serviceDto : serviceDtos) { - logConfigService(serviceDto.getHomepageUrl()); - } - } - - private void logConfigService(String serviceUrl) { - Tracer.logEvent("Apollo.Config.Services", serviceUrl); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfig.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfig.java deleted file mode 100644 index 7b17d75f0b2..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfig.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright 2022 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.core.utils.DeferredLoggerFactory; -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import java.io.IOException; -import java.io.InputStream; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.atomic.AtomicReference; - -import org.slf4j.Logger; - -import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil; -import com.ctrip.framework.apollo.enums.PropertyChangeType; -import com.ctrip.framework.apollo.model.ConfigChange; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.apollo.util.ExceptionUtil; -import com.google.common.collect.ImmutableMap; -import com.google.common.util.concurrent.RateLimiter; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class DefaultConfig extends AbstractConfig implements RepositoryChangeListener { - - private static final Logger logger = DeferredLoggerFactory.getLogger(DefaultConfig.class); - private final String m_namespace; - private final Properties m_resourceProperties; - private final AtomicReference m_configProperties; - private final ConfigRepository m_configRepository; - private final RateLimiter m_warnLogRateLimiter; - - private volatile ConfigSourceType m_sourceType = ConfigSourceType.NONE; - - /** - * Constructor. - * - * @param namespace the namespace of this config instance - * @param configRepository the config repository for this config instance - */ - public DefaultConfig(String namespace, ConfigRepository configRepository) { - m_namespace = namespace; - m_resourceProperties = loadFromResource(m_namespace); - m_configRepository = configRepository; - m_configProperties = new AtomicReference<>(); - m_warnLogRateLimiter = RateLimiter.create(0.017); // 1 warning log output per minute - initialize(); - } - - private void initialize() { - try { - updateConfig(m_configRepository.getConfig(), m_configRepository.getSourceType()); - } catch (Throwable ex) { - Tracer.logError(ex); - logger.warn("Init Apollo Local Config failed - namespace: {}, reason: {}.", - m_namespace, ExceptionUtil.getDetailMessage(ex)); - } finally { - //register the change listener no matter config repository is working or not - //so that whenever config repository is recovered, config could get changed - m_configRepository.addChangeListener(this); - } - } - - /** - * get property from cached repository properties file - * - * @param key property key - * @return value - */ - protected String getPropertyFromRepository(String key) { - Properties properties = m_configProperties.get(); - if (properties != null) { - return properties.getProperty(key); - } - return null; - } - - /** - * get property from additional properties file on classpath - * - * @param key property key - * @return value - */ - protected String getPropertyFromAdditional(String key) { - Properties properties = this.m_resourceProperties; - if (properties != null) { - return properties.getProperty(key); - } - return null; - } - - /** - * try to print a warn log when can not find a property - * - * @param value value - */ - protected void tryWarnLog(String value) { - if (value == null && m_configProperties.get() == null && m_warnLogRateLimiter.tryAcquire()) { - logger.warn( - "Could not load config for namespace {} from Apollo, please check whether the configs are released in Apollo! Return default value now!", - m_namespace); - } - } - - /** - * get property names from cached repository properties file - * - * @return property names - */ - protected Set getPropertyNamesFromRepository() { - Properties properties = m_configProperties.get(); - if (properties == null) { - return Collections.emptySet(); - } - return this.stringPropertyNames(properties); - } - - /** - * get property names from additional properties file on classpath - * - * @return property names - */ - protected Set getPropertyNamesFromAdditional() { - Properties properties = m_resourceProperties; - if (properties == null) { - return Collections.emptySet(); - } - return this.stringPropertyNames(properties); - } - - @Override - public String getProperty(String key, String defaultValue) { - // step 1: check system properties, i.e. -Dkey=value - String value = System.getProperty(key); - - // step 2: check local cached properties file - if (value == null) { - value = this.getPropertyFromRepository(key); - } - - /* - * step 3: check env variable, i.e. PATH=... - * normally system environment variables are in UPPERCASE, however there might be exceptions. - * so the caller should provide the key in the right case - */ - if (value == null) { - value = System.getenv(key); - } - - // step 4: check properties file from classpath - if (value == null) { - value = this.getPropertyFromAdditional(key); - } - - this.tryWarnLog(value); - - return value == null ? defaultValue : value; - } - - @Override - public Set getPropertyNames() { - // propertyNames include system property and system env might cause some compatibility issues, though that looks like the correct implementation. - Set fromRepository = this.getPropertyNamesFromRepository(); - Set fromAdditional = this.getPropertyNamesFromAdditional(); - if (fromRepository == null || fromRepository.isEmpty()) { - return fromAdditional; - } - if (fromAdditional == null || fromAdditional.isEmpty()) { - return fromRepository; - } - Set propertyNames = Sets - .newLinkedHashSetWithExpectedSize(fromRepository.size() + fromAdditional.size()); - propertyNames.addAll(fromRepository); - propertyNames.addAll(fromAdditional); - return propertyNames; - } - - @Override - public ConfigSourceType getSourceType() { - return m_sourceType; - } - - private Set stringPropertyNames(Properties properties) { - //jdk9以下版本Properties#enumerateStringProperties方法存在性能问题,keys() + get(k) 重复迭代, jdk9之后改为entrySet遍历. - Map h = Maps.newLinkedHashMapWithExpectedSize(properties.size()); - for (Map.Entry e : properties.entrySet()) { - Object k = e.getKey(); - Object v = e.getValue(); - if (k instanceof String && v instanceof String) { - h.put((String) k, (String) v); - } - } - return h.keySet(); - } - - @Override - public synchronized void onRepositoryChange(String namespace, Properties newProperties) { - if (newProperties.equals(m_configProperties.get())) { - return; - } - - ConfigSourceType sourceType = m_configRepository.getSourceType(); - Properties newConfigProperties = propertiesFactory.getPropertiesInstance(); - newConfigProperties.putAll(newProperties); - - Map actualChanges = updateAndCalcConfigChanges(newConfigProperties, - sourceType); - - //check double checked result - if (actualChanges.isEmpty()) { - return; - } - - this.fireConfigChange(m_namespace, actualChanges); - - Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace); - } - - private void updateConfig(Properties newConfigProperties, ConfigSourceType sourceType) { - m_configProperties.set(newConfigProperties); - m_sourceType = sourceType; - } - - private Map updateAndCalcConfigChanges(Properties newConfigProperties, - ConfigSourceType sourceType) { - List configChanges = - calcPropertyChanges(m_namespace, m_configProperties.get(), newConfigProperties); - - ImmutableMap.Builder actualChanges = - new ImmutableMap.Builder<>(); - - /** === Double check since DefaultConfig has multiple config sources ==== **/ - - //1. use getProperty to update configChanges's old value - for (ConfigChange change : configChanges) { - change.setOldValue(this.getProperty(change.getPropertyName(), change.getOldValue())); - } - - //2. update m_configProperties - updateConfig(newConfigProperties, sourceType); - clearConfigCache(); - - //3. use getProperty to update configChange's new value and calc the final changes - for (ConfigChange change : configChanges) { - change.setNewValue(this.getProperty(change.getPropertyName(), change.getNewValue())); - switch (change.getChangeType()) { - case ADDED: - if (Objects.equals(change.getOldValue(), change.getNewValue())) { - break; - } - if (change.getOldValue() != null) { - change.setChangeType(PropertyChangeType.MODIFIED); - } - actualChanges.put(change.getPropertyName(), change); - break; - case MODIFIED: - if (!Objects.equals(change.getOldValue(), change.getNewValue())) { - actualChanges.put(change.getPropertyName(), change); - } - break; - case DELETED: - if (Objects.equals(change.getOldValue(), change.getNewValue())) { - break; - } - if (change.getNewValue() != null) { - change.setChangeType(PropertyChangeType.MODIFIED); - } - actualChanges.put(change.getPropertyName(), change); - break; - default: - //do nothing - break; - } - } - return actualChanges.build(); - } - - private Properties loadFromResource(String namespace) { - String name = String.format("META-INF/config/%s.properties", namespace); - InputStream in = ClassLoaderUtil.getLoader().getResourceAsStream(name); - Properties properties = null; - - if (in != null) { - properties = propertiesFactory.getPropertiesInstance(); - - try { - properties.load(in); - } catch (IOException ex) { - Tracer.logError(ex); - logger.error("Load resource config for namespace {} failed", namespace, ex); - } finally { - try { - in.close(); - } catch (IOException ex) { - // ignore - } - } - } - - return properties; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java deleted file mode 100644 index f583a915ffa..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultConfigManager.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2022 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 java.util.Map; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigFile; -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import com.ctrip.framework.apollo.spi.ConfigFactory; -import com.ctrip.framework.apollo.spi.ConfigFactoryManager; -import com.google.common.collect.Maps; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class DefaultConfigManager implements ConfigManager { - private ConfigFactoryManager m_factoryManager; - - private Map m_configs = Maps.newConcurrentMap(); - private Map m_configFiles = Maps.newConcurrentMap(); - - public DefaultConfigManager() { - m_factoryManager = ApolloInjector.getInstance(ConfigFactoryManager.class); - } - - @Override - public Config getConfig(String namespace) { - Config config = m_configs.get(namespace); - - if (config == null) { - synchronized (this) { - config = m_configs.get(namespace); - - if (config == null) { - ConfigFactory factory = m_factoryManager.getFactory(namespace); - - config = factory.create(namespace); - m_configs.put(namespace, config); - } - } - } - - return config; - } - - @Override - public ConfigFile getConfigFile(String namespace, ConfigFileFormat configFileFormat) { - String namespaceFileName = String.format("%s.%s", namespace, configFileFormat.getValue()); - ConfigFile configFile = m_configFiles.get(namespaceFileName); - - if (configFile == null) { - synchronized (this) { - configFile = m_configFiles.get(namespaceFileName); - - if (configFile == null) { - ConfigFactory factory = m_factoryManager.getFactory(namespaceFileName); - - configFile = factory.createConfigFile(namespaceFileName, configFileFormat); - m_configFiles.put(namespaceFileName, configFile); - } - } - } - - return configFile; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java deleted file mode 100644 index 707ad6c519c..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultInjector.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2022 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(song_s@ctrip.com) - */ -public class DefaultInjector implements Injector { - private final com.google.inject.Injector m_injector; - private final List 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 getInstance(Class 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 getInstance(Class 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); - } - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProvider.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProvider.java deleted file mode 100644 index 1a00395976e..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProvider.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2022 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.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.core.enums.Env; -import com.ctrip.framework.apollo.core.spi.MetaServerProvider; -import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; -import com.ctrip.framework.foundation.Foundation; -import com.google.common.base.Strings; -import org.slf4j.Logger; - -public class DefaultMetaServerProvider implements MetaServerProvider { - - public static final int ORDER = 0; - private static final Logger logger = DeferredLoggerFactory - .getLogger(DefaultMetaServerProvider.class); - - private final String metaServerAddress; - - public DefaultMetaServerProvider() { - metaServerAddress = initMetaServerAddress(); - } - - private String initMetaServerAddress() { - // 1. Get from System Property - String metaAddress = System.getProperty(ConfigConsts.APOLLO_META_KEY); - if (Strings.isNullOrEmpty(metaAddress)) { - // 2. Get from OS environment variable, which could not contain dot and is normally in UPPER case - metaAddress = System.getenv(ApolloClientSystemConsts.APOLLO_META_ENVIRONMENT_VARIABLES); - } - if (Strings.isNullOrEmpty(metaAddress)) { - // 3. Get from server.properties - metaAddress = Foundation.server().getProperty(ConfigConsts.APOLLO_META_KEY, null); - } - if (Strings.isNullOrEmpty(metaAddress)) { - // 4. Get from app.properties - metaAddress = Foundation.app().getProperty(ConfigConsts.APOLLO_META_KEY, null); - } - - if (Strings.isNullOrEmpty(metaAddress)) { - logger.warn( - "Could not find meta server address, because it is not available in neither (1) JVM system property 'apollo.meta', (2) OS env variable 'APOLLO_META' (3) property 'apollo.meta' from server.properties nor (4) property 'apollo.meta' from app.properties"); - } else { - metaAddress = metaAddress.trim(); - logger.info("Located meta services from apollo.meta configuration: {}!", metaAddress); - } - - return metaAddress; - } - - @Override - public String getMetaServerAddress(Env targetEnv) { - //for default meta server provider, we don't care the actual environment - return metaServerAddress; - } - - @Override - public int getOrder() { - return ORDER; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/Injector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/Injector.java deleted file mode 100644 index fab83b5fc9d..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/Injector.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2022 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; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface Injector { - - /** - * Returns the appropriate instance for the given injection type - */ - T getInstance(Class clazz); - - /** - * Returns the appropriate instance for the given injection type and name - */ - T getInstance(Class clazz, String name); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/InterestedConfigChangeEvent.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/InterestedConfigChangeEvent.java deleted file mode 100644 index 2d3365070f7..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/InterestedConfigChangeEvent.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2022 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.Config; -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.model.ConfigChange; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -/** - * In {@link ApolloConfigChangeListener} you set some interested key's rule, you can get those keys - * by this class's instance. - * - * @author wxq - */ -class InterestedConfigChangeEvent extends ConfigChangeEvent { - - /** - * @see Config#addChangeListener(ConfigChangeListener, Set) - * @see Config#addChangeListener(ConfigChangeListener, Set, Set) - * @see ApolloConfigChangeListener#interestedKeys() - * @see ApolloConfigChangeListener#interestedKeyPrefixes() - */ - private final Set m_interestedChangedKeys; - - public InterestedConfigChangeEvent(String namespace, - Map changes, Set interestedChangedKeys) { - super(namespace, changes); - this.m_interestedChangedKeys = interestedChangedKeys; - } - - /** - * @return interested and changed keys - */ - @Override - public Set interestedChangedKeys() { - return Collections.unmodifiableSet(this.m_interestedChangedKeys); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/JsonConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/JsonConfigFile.java deleted file mode 100644 index 80befc927e8..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/JsonConfigFile.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2022 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.core.enums.ConfigFileFormat; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class JsonConfigFile extends PlainTextConfigFile { - public JsonConfigFile(String namespace, - ConfigRepository configRepository) { - super(namespace, configRepository); - } - - @Override - public ConfigFileFormat getConfigFileFormat() { - return ConfigFileFormat.JSON; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepository.java deleted file mode 100644 index f5e481161c4..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepository.java +++ /dev/null @@ -1,297 +0,0 @@ -/* - * Copyright 2022 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.core.utils.DeferredLoggerFactory; -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Properties; - -import org.slf4j.Logger; - -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil; -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.apollo.tracer.spi.Transaction; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.ctrip.framework.apollo.util.ExceptionUtil; -import com.google.common.base.Joiner; -import com.google.common.base.Preconditions; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class LocalFileConfigRepository extends AbstractConfigRepository - implements RepositoryChangeListener { - private static final Logger logger = DeferredLoggerFactory.getLogger(LocalFileConfigRepository.class); - private static final String CONFIG_DIR = "/config-cache"; - private final String m_namespace; - private File m_baseDir; - private final ConfigUtil m_configUtil; - private volatile Properties m_fileProperties; - private volatile ConfigRepository m_upstream; - - private volatile ConfigSourceType m_sourceType = ConfigSourceType.LOCAL; - - /** - * Constructor. - * - * @param namespace the namespace - */ - public LocalFileConfigRepository(String namespace) { - this(namespace, null); - } - - public LocalFileConfigRepository(String namespace, ConfigRepository upstream) { - m_namespace = namespace; - m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); - this.setLocalCacheDir(findLocalCacheDir(), false); - this.setUpstreamRepository(upstream); - this.trySync(); - } - - void setLocalCacheDir(File baseDir, boolean syncImmediately) { - m_baseDir = baseDir; - this.checkLocalConfigCacheDir(m_baseDir); - if (syncImmediately) { - this.trySync(); - } - } - - private File findLocalCacheDir() { - try { - String defaultCacheDir = m_configUtil.getDefaultLocalCacheDir(); - Path path = Paths.get(defaultCacheDir); - if (!Files.exists(path)) { - Files.createDirectories(path); - } - if (Files.exists(path) && Files.isWritable(path)) { - return new File(defaultCacheDir, CONFIG_DIR); - } - } catch (Throwable ex) { - //ignore - } - - return new File(ClassLoaderUtil.getClassPath(), CONFIG_DIR); - } - - @Override - public Properties getConfig() { - if (m_fileProperties == null) { - sync(); - } - Properties result = propertiesFactory.getPropertiesInstance(); - result.putAll(m_fileProperties); - return result; - } - - @Override - public void setUpstreamRepository(ConfigRepository upstreamConfigRepository) { - if (upstreamConfigRepository == null) { - return; - } - //clear previous listener - if (m_upstream != null) { - m_upstream.removeChangeListener(this); - } - m_upstream = upstreamConfigRepository; - upstreamConfigRepository.addChangeListener(this); - } - - @Override - public ConfigSourceType getSourceType() { - return m_sourceType; - } - - @Override - public void onRepositoryChange(String namespace, Properties newProperties) { - if (newProperties.equals(m_fileProperties)) { - return; - } - Properties newFileProperties = propertiesFactory.getPropertiesInstance(); - newFileProperties.putAll(newProperties); - updateFileProperties(newFileProperties, m_upstream.getSourceType()); - this.fireRepositoryChange(namespace, newProperties); - } - - @Override - protected void sync() { - //sync with upstream immediately - boolean syncFromUpstreamResultSuccess = trySyncFromUpstream(); - - if (syncFromUpstreamResultSuccess) { - return; - } - - Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "syncLocalConfig"); - Throwable exception = null; - try { - transaction.addData("Basedir", m_baseDir.getAbsolutePath()); - m_fileProperties = this.loadFromLocalCacheFile(m_baseDir, m_namespace); - m_sourceType = ConfigSourceType.LOCAL; - transaction.setStatus(Transaction.SUCCESS); - } catch (Throwable ex) { - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex)); - transaction.setStatus(ex); - exception = ex; - //ignore - } finally { - transaction.complete(); - } - - if (m_fileProperties == null) { - m_sourceType = ConfigSourceType.NONE; - throw new ApolloConfigException( - "Load config from local config failed!", exception); - } - } - - private boolean trySyncFromUpstream() { - if (m_upstream == null) { - return false; - } - try { - updateFileProperties(m_upstream.getConfig(), m_upstream.getSourceType()); - return true; - } catch (Throwable ex) { - Tracer.logError(ex); - logger - .warn("Sync config from upstream repository {} failed, reason: {}", m_upstream.getClass(), - ExceptionUtil.getDetailMessage(ex)); - } - return false; - } - - private synchronized void updateFileProperties(Properties newProperties, ConfigSourceType sourceType) { - this.m_sourceType = sourceType; - if (newProperties.equals(m_fileProperties)) { - return; - } - this.m_fileProperties = newProperties; - persistLocalCacheFile(m_baseDir, m_namespace); - } - - private Properties loadFromLocalCacheFile(File baseDir, String namespace) throws IOException { - Preconditions.checkNotNull(baseDir, "Basedir cannot be null"); - - File file = assembleLocalCacheFile(baseDir, namespace); - Properties properties = null; - - if (file.isFile() && file.canRead()) { - InputStream in = null; - - try { - in = new FileInputStream(file); - properties = propertiesFactory.getPropertiesInstance(); - properties.load(in); - logger.debug("Loading local config file {} successfully!", file.getAbsolutePath()); - } catch (IOException ex) { - Tracer.logError(ex); - throw new ApolloConfigException(String - .format("Loading config from local cache file %s failed", file.getAbsolutePath()), ex); - } finally { - try { - if (in != null) { - in.close(); - } - } catch (IOException ex) { - // ignore - } - } - } else { - throw new ApolloConfigException( - String.format("Cannot read from local cache file %s", file.getAbsolutePath())); - } - - return properties; - } - - void persistLocalCacheFile(File baseDir, String namespace) { - if (baseDir == null) { - return; - } - File file = assembleLocalCacheFile(baseDir, namespace); - - OutputStream out = null; - - Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "persistLocalConfigFile"); - transaction.addData("LocalConfigFile", file.getAbsolutePath()); - try { - out = new FileOutputStream(file); - m_fileProperties.store(out, "Persisted by DefaultConfig"); - transaction.setStatus(Transaction.SUCCESS); - } catch (IOException ex) { - ApolloConfigException exception = - new ApolloConfigException( - String.format("Persist local cache file %s failed", file.getAbsolutePath()), ex); - Tracer.logError(exception); - transaction.setStatus(exception); - logger.warn("Persist local cache file {} failed, reason: {}.", file.getAbsolutePath(), - ExceptionUtil.getDetailMessage(ex)); - } finally { - if (out != null) { - try { - out.close(); - } catch (IOException ex) { - //ignore - } - } - transaction.complete(); - } - } - - private void checkLocalConfigCacheDir(File baseDir) { - if (baseDir.exists()) { - return; - } - Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "createLocalConfigDir"); - transaction.addData("BaseDir", baseDir.getAbsolutePath()); - try { - Files.createDirectory(baseDir.toPath()); - transaction.setStatus(Transaction.SUCCESS); - } catch (IOException ex) { - ApolloConfigException exception = - new ApolloConfigException( - String.format("Create local config directory %s failed", baseDir.getAbsolutePath()), - ex); - Tracer.logError(exception); - transaction.setStatus(exception); - logger.warn( - "Unable to create local config cache directory {}, reason: {}. Will not able to cache config file.", - baseDir.getAbsolutePath(), ExceptionUtil.getDetailMessage(ex)); - } finally { - transaction.complete(); - } - } - - File assembleLocalCacheFile(File baseDir, String namespace) { - String fileName = - String.format("%s.properties", Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR) - .join(m_configUtil.getAppId(), m_configUtil.getCluster(), namespace)); - return new File(baseDir, fileName); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/PlainTextConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/PlainTextConfigFile.java deleted file mode 100644 index f5f05d0ee19..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/PlainTextConfigFile.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2022 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.core.ConfigConsts; -import java.util.Properties; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public abstract class PlainTextConfigFile extends AbstractConfigFile { - - public PlainTextConfigFile(String namespace, ConfigRepository configRepository) { - super(namespace, configRepository); - } - - @Override - public String getContent() { - if (!this.hasContent()) { - return null; - } - return m_configProperties.get().getProperty(ConfigConsts.CONFIG_FILE_CONTENT_KEY); - } - - @Override - public boolean hasContent() { - if (m_configProperties.get() == null) { - return false; - } - return m_configProperties.get().containsKey(ConfigConsts.CONFIG_FILE_CONTENT_KEY); - } - - @Override - protected void update(Properties newProperties) { - m_configProperties.set(newProperties); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/PropertiesCompatibleFileConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/PropertiesCompatibleFileConfigRepository.java deleted file mode 100644 index e505d18ac07..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/PropertiesCompatibleFileConfigRepository.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2022 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 java.util.Properties; - -import com.ctrip.framework.apollo.ConfigFileChangeListener; -import com.ctrip.framework.apollo.PropertiesCompatibleConfigFile; -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.ctrip.framework.apollo.model.ConfigFileChangeEvent; -import com.google.common.base.Preconditions; - -public class PropertiesCompatibleFileConfigRepository extends AbstractConfigRepository implements - ConfigFileChangeListener { - private final PropertiesCompatibleConfigFile configFile; - private volatile Properties cachedProperties; - - public PropertiesCompatibleFileConfigRepository(PropertiesCompatibleConfigFile configFile) { - this.configFile = configFile; - this.configFile.addChangeListener(this); - this.trySync(); - } - - @Override - protected synchronized void sync() { - Properties current = configFile.asProperties(); - - Preconditions.checkState(current != null, "PropertiesCompatibleConfigFile.asProperties should never return null"); - - if (cachedProperties != current) { - cachedProperties = current; - this.fireRepositoryChange(configFile.getNamespace(), cachedProperties); - } - } - - @Override - public Properties getConfig() { - if (cachedProperties == null) { - sync(); - } - return cachedProperties; - } - - @Override - public void setUpstreamRepository(ConfigRepository upstreamConfigRepository) { - //config file is the upstream, so no need to set up extra upstream - } - - @Override - public ConfigSourceType getSourceType() { - return configFile.getSourceType(); - } - - @Override - public void onChange(ConfigFileChangeEvent changeEvent) { - this.trySync(); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/PropertiesConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/PropertiesConfigFile.java deleted file mode 100644 index 205941a7e5e..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/PropertiesConfigFile.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2022 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.PropertiesCompatibleConfigFile; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import com.ctrip.framework.apollo.core.utils.PropertiesUtil; -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.apollo.util.ExceptionUtil; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicReference; - -/** - * Represents a config file that is of the file format `.properties` - * - * @author Jason Song(song_s@ctrip.com) - * @author Diego Krupitza(info@diegokrupitza.com) - */ -public class PropertiesConfigFile extends AbstractConfigFile implements - PropertiesCompatibleConfigFile { - - protected AtomicReference m_contentCache; - - public PropertiesConfigFile(String namespace, - ConfigRepository configRepository) { - super(namespace, configRepository); - m_contentCache = new AtomicReference<>(); - } - - @Override - protected void update(Properties newProperties) { - m_configProperties.set(newProperties); - m_contentCache.set(null); - } - - @Override - public String getContent() { - if (m_contentCache.get() == null) { - m_contentCache.set(doGetContent()); - } - return m_contentCache.get(); - } - - String doGetContent() { - if (!this.hasContent()) { - return null; - } - - try { - return PropertiesUtil.toString(m_configProperties.get()); - } catch (Throwable ex) { - ApolloConfigException exception = - new ApolloConfigException(String - .format("Parse properties file content failed for namespace: %s, cause: %s", - m_namespace, ExceptionUtil.getDetailMessage(ex))); - Tracer.logError(exception); - throw exception; - } - } - - @Override - public boolean hasContent() { - return m_configProperties.get() != null && !m_configProperties.get().isEmpty(); - } - - @Override - public ConfigFileFormat getConfigFileFormat() { - return ConfigFileFormat.Properties; - } - - @Override - public Properties asProperties() { - return this.hasContent() ? m_configProperties.get() : propertiesFactory.getPropertiesInstance(); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java deleted file mode 100644 index 59806b2a745..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java +++ /dev/null @@ -1,342 +0,0 @@ -/* - * Copyright 2022 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.build.ApolloInjector; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification; -import com.ctrip.framework.apollo.core.dto.ApolloNotificationMessages; -import com.ctrip.framework.apollo.core.dto.ServiceDTO; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import com.ctrip.framework.apollo.core.schedule.ExponentialSchedulePolicy; -import com.ctrip.framework.apollo.core.schedule.SchedulePolicy; -import com.ctrip.framework.apollo.core.signature.Signature; -import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; -import com.ctrip.framework.apollo.core.utils.StringUtils; -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.spi.ConfigServiceLoadBalancerClient; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.apollo.tracer.spi.Transaction; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.ctrip.framework.apollo.util.ExceptionUtil; -import com.ctrip.framework.apollo.util.http.HttpRequest; -import com.ctrip.framework.apollo.util.http.HttpResponse; -import com.ctrip.framework.apollo.util.http.HttpClient; -import com.ctrip.framework.foundation.internals.ServiceBootstrap; -import com.google.common.base.Joiner; -import com.google.common.base.Strings; -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multimaps; -import com.google.common.escape.Escaper; -import com.google.common.net.UrlEscapers; -import com.google.common.reflect.TypeToken; -import com.google.common.util.concurrent.RateLimiter; -import com.google.gson.Gson; -import java.lang.reflect.Type; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class RemoteConfigLongPollService { - private static final Logger logger = LoggerFactory.getLogger(RemoteConfigLongPollService.class); - private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR); - private static final Joiner.MapJoiner MAP_JOINER = Joiner.on("&").withKeyValueSeparator("="); - private static final Escaper queryParamEscaper = UrlEscapers.urlFormParameterEscaper(); - private static final long INIT_NOTIFICATION_ID = ConfigConsts.NOTIFICATION_ID_PLACEHOLDER; - //90 seconds, should be longer than server side's long polling timeout, which is now 60 seconds - private static final int LONG_POLLING_READ_TIMEOUT = 90 * 1000; - private final ExecutorService m_longPollingService; - private final AtomicBoolean m_longPollingStopped; - private SchedulePolicy m_longPollFailSchedulePolicyInSecond; - private RateLimiter m_longPollRateLimiter; - private final AtomicBoolean m_longPollStarted; - private final Multimap m_longPollNamespaces; - private final ConcurrentMap m_notifications; - private final Map m_remoteNotificationMessages;//namespaceName -> watchedKey -> notificationId - private Type m_responseType; - private static final Gson GSON = new Gson(); - private ConfigUtil m_configUtil; - private HttpClient m_httpClient; - private ConfigServiceLocator m_serviceLocator; - private final ConfigServiceLoadBalancerClient configServiceLoadBalancerClient = ServiceBootstrap.loadPrimary( - ConfigServiceLoadBalancerClient.class); - - /** - * Constructor. - */ - public RemoteConfigLongPollService() { - m_longPollFailSchedulePolicyInSecond = new ExponentialSchedulePolicy(1, 120); //in second - m_longPollingStopped = new AtomicBoolean(false); - m_longPollingService = Executors.newSingleThreadExecutor( - ApolloThreadFactory.create("RemoteConfigLongPollService", true)); - m_longPollStarted = new AtomicBoolean(false); - m_longPollNamespaces = - Multimaps.synchronizedSetMultimap(HashMultimap.create()); - m_notifications = Maps.newConcurrentMap(); - m_remoteNotificationMessages = Maps.newConcurrentMap(); - m_responseType = new TypeToken>() { - }.getType(); - m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); - m_httpClient = ApolloInjector.getInstance(HttpClient.class); - m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class); - m_longPollRateLimiter = RateLimiter.create(m_configUtil.getLongPollQPS()); - } - - public boolean submit(String namespace, RemoteConfigRepository remoteConfigRepository) { - boolean added = m_longPollNamespaces.put(namespace, remoteConfigRepository); - m_notifications.putIfAbsent(namespace, INIT_NOTIFICATION_ID); - if (!m_longPollStarted.get()) { - startLongPolling(); - } - return added; - } - - private void startLongPolling() { - if (!m_longPollStarted.compareAndSet(false, true)) { - //already started - return; - } - try { - final String appId = m_configUtil.getAppId(); - final String cluster = m_configUtil.getCluster(); - final String dataCenter = m_configUtil.getDataCenter(); - final String secret = m_configUtil.getAccessKeySecret(); - final long longPollingInitialDelayInMills = m_configUtil.getLongPollingInitialDelayInMills(); - m_longPollingService.submit(new Runnable() { - @Override - public void run() { - if (longPollingInitialDelayInMills > 0) { - try { - logger.debug("Long polling will start in {} ms.", longPollingInitialDelayInMills); - TimeUnit.MILLISECONDS.sleep(longPollingInitialDelayInMills); - } catch (InterruptedException e) { - //ignore - } - } - doLongPollingRefresh(appId, cluster, dataCenter, secret); - } - }); - } catch (Throwable ex) { - m_longPollStarted.set(false); - ApolloConfigException exception = - new ApolloConfigException("Schedule long polling refresh failed", ex); - Tracer.logError(exception); - logger.warn(ExceptionUtil.getDetailMessage(exception)); - } - } - - void stopLongPollingRefresh() { - this.m_longPollingStopped.compareAndSet(false, true); - } - - private void doLongPollingRefresh(String appId, String cluster, String dataCenter, String secret) { - ServiceDTO lastServiceDto = null; - while (!m_longPollingStopped.get() && !Thread.currentThread().isInterrupted()) { - if (!m_longPollRateLimiter.tryAcquire(5, TimeUnit.SECONDS)) { - //wait at most 5 seconds - try { - TimeUnit.SECONDS.sleep(5); - } catch (InterruptedException e) { - } - } - Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "pollNotification"); - String url = null; - try { - if (lastServiceDto == null) { - lastServiceDto = this.resolveConfigService(); - } - - url = - assembleLongPollRefreshUrl(lastServiceDto.getHomepageUrl(), appId, cluster, dataCenter, - m_notifications); - - logger.debug("Long polling from {}", url); - - HttpRequest request = new HttpRequest(url); - request.setReadTimeout(LONG_POLLING_READ_TIMEOUT); - if (!StringUtils.isBlank(secret)) { - Map headers = Signature.buildHttpHeaders(url, appId, secret); - request.setHeaders(headers); - } - - transaction.addData("Url", url); - - final HttpResponse> response = - m_httpClient.doGet(request, m_responseType); - - logger.debug("Long polling response: {}, url: {}", response.getStatusCode(), url); - if (response.getStatusCode() == 200 && response.getBody() != null) { - updateNotifications(response.getBody()); - updateRemoteNotifications(response.getBody()); - transaction.addData("Result", response.getBody().toString()); - notify(lastServiceDto, response.getBody()); - } - - //try to load balance - if (response.getStatusCode() == 304 && ThreadLocalRandom.current().nextBoolean()) { - lastServiceDto = null; - } - - m_longPollFailSchedulePolicyInSecond.success(); - transaction.addData("StatusCode", response.getStatusCode()); - transaction.setStatus(Transaction.SUCCESS); - } catch (Throwable ex) { - lastServiceDto = null; - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex)); - transaction.setStatus(ex); - long sleepTimeInSecond = m_longPollFailSchedulePolicyInSecond.fail(); - logger.warn( - "Long polling failed, will retry in {} seconds. appId: {}, cluster: {}, namespaces: {}, long polling url: {}, reason: {}", - sleepTimeInSecond, appId, cluster, assembleNamespaces(), url, ExceptionUtil.getDetailMessage(ex)); - try { - TimeUnit.SECONDS.sleep(sleepTimeInSecond); - } catch (InterruptedException ie) { - //ignore - } - } finally { - transaction.complete(); - } - } - } - - private void notify(ServiceDTO lastServiceDto, List notifications) { - if (notifications == null || notifications.isEmpty()) { - return; - } - for (ApolloConfigNotification notification : notifications) { - String namespaceName = notification.getNamespaceName(); - //create a new list to avoid ConcurrentModificationException - List toBeNotified = - Lists.newArrayList(m_longPollNamespaces.get(namespaceName)); - ApolloNotificationMessages originalMessages = m_remoteNotificationMessages.get(namespaceName); - ApolloNotificationMessages remoteMessages = originalMessages == null ? null : originalMessages.clone(); - //since .properties are filtered out by default, so we need to check if there is any listener for it - toBeNotified.addAll(m_longPollNamespaces - .get(String.format("%s.%s", namespaceName, ConfigFileFormat.Properties.getValue()))); - for (RemoteConfigRepository remoteConfigRepository : toBeNotified) { - try { - remoteConfigRepository.onLongPollNotified(lastServiceDto, remoteMessages); - } catch (Throwable ex) { - Tracer.logError(ex); - } - } - } - } - - private void updateNotifications(List deltaNotifications) { - for (ApolloConfigNotification notification : deltaNotifications) { - if (Strings.isNullOrEmpty(notification.getNamespaceName())) { - continue; - } - String namespaceName = notification.getNamespaceName(); - if (m_notifications.containsKey(namespaceName)) { - m_notifications.put(namespaceName, notification.getNotificationId()); - } - //since .properties are filtered out by default, so we need to check if there is notification with .properties suffix - String namespaceNameWithPropertiesSuffix = - String.format("%s.%s", namespaceName, ConfigFileFormat.Properties.getValue()); - if (m_notifications.containsKey(namespaceNameWithPropertiesSuffix)) { - m_notifications.put(namespaceNameWithPropertiesSuffix, notification.getNotificationId()); - } - } - } - - private void updateRemoteNotifications(List deltaNotifications) { - for (ApolloConfigNotification notification : deltaNotifications) { - if (Strings.isNullOrEmpty(notification.getNamespaceName())) { - continue; - } - - if (notification.getMessages() == null || notification.getMessages().isEmpty()) { - continue; - } - - ApolloNotificationMessages localRemoteMessages = - m_remoteNotificationMessages.get(notification.getNamespaceName()); - if (localRemoteMessages == null) { - localRemoteMessages = new ApolloNotificationMessages(); - m_remoteNotificationMessages.put(notification.getNamespaceName(), localRemoteMessages); - } - - localRemoteMessages.mergeFrom(notification.getMessages()); - } - } - - private String assembleNamespaces() { - return STRING_JOINER.join(m_longPollNamespaces.keySet()); - } - - String assembleLongPollRefreshUrl(String uri, String appId, String cluster, String dataCenter, - Map notificationsMap) { - Map queryParams = Maps.newHashMap(); - queryParams.put("appId", queryParamEscaper.escape(appId)); - queryParams.put("cluster", queryParamEscaper.escape(cluster)); - queryParams - .put("notifications", queryParamEscaper.escape(assembleNotifications(notificationsMap))); - - if (!Strings.isNullOrEmpty(dataCenter)) { - queryParams.put("dataCenter", queryParamEscaper.escape(dataCenter)); - } - String localIp = m_configUtil.getLocalIp(); - if (!Strings.isNullOrEmpty(localIp)) { - queryParams.put("ip", queryParamEscaper.escape(localIp)); - } - - String params = MAP_JOINER.join(queryParams); - if (!uri.endsWith("/")) { - uri += "/"; - } - - return uri + "notifications/v2?" + params; - } - - String assembleNotifications(Map notificationsMap) { - List notifications = Lists.newArrayList(); - for (Map.Entry entry : notificationsMap.entrySet()) { - ApolloConfigNotification notification = new ApolloConfigNotification(entry.getKey(), entry.getValue()); - notifications.add(notification); - } - return GSON.toJson(notifications); - } - - private ServiceDTO resolveConfigService() { - List configServices = this.getConfigServices(); - return this.configServiceLoadBalancerClient.chooseOneFrom(configServices); - } - - private List getConfigServices() { - List services = m_serviceLocator.getConfigServices(); - if (services.size() == 0) { - throw new ApolloConfigException("No available config service"); - } - - return services; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java deleted file mode 100644 index 6008f63e84f..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigRepository.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - * Copyright 2022 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.Apollo; -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.ApolloNotificationMessages; -import com.ctrip.framework.apollo.core.dto.ServiceDTO; -import com.ctrip.framework.apollo.core.schedule.ExponentialSchedulePolicy; -import com.ctrip.framework.apollo.core.schedule.SchedulePolicy; -import com.ctrip.framework.apollo.core.signature.Signature; -import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; -import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; -import com.ctrip.framework.apollo.core.utils.StringUtils; -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.apollo.tracer.spi.Transaction; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.ctrip.framework.apollo.util.ExceptionUtil; -import com.ctrip.framework.apollo.util.http.HttpRequest; -import com.ctrip.framework.apollo.util.http.HttpResponse; -import com.ctrip.framework.apollo.util.http.HttpClient; -import com.google.common.base.Joiner; -import com.google.common.base.Strings; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.escape.Escaper; -import com.google.common.net.UrlEscapers; -import com.google.common.util.concurrent.RateLimiter; -import com.google.gson.Gson; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -import org.slf4j.Logger; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class RemoteConfigRepository extends AbstractConfigRepository { - private static final Logger logger = DeferredLoggerFactory.getLogger(RemoteConfigRepository.class); - private static final Joiner STRING_JOINER = Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR); - private static final Joiner.MapJoiner MAP_JOINER = Joiner.on("&").withKeyValueSeparator("="); - private static final Escaper pathEscaper = UrlEscapers.urlPathSegmentEscaper(); - private static final Escaper queryParamEscaper = UrlEscapers.urlFormParameterEscaper(); - - private final ConfigServiceLocator m_serviceLocator; - private final HttpClient m_httpClient; - private final ConfigUtil m_configUtil; - private final RemoteConfigLongPollService remoteConfigLongPollService; - private volatile AtomicReference m_configCache; - private final String m_namespace; - private final static ScheduledExecutorService m_executorService; - private final AtomicReference m_longPollServiceDto; - private final AtomicReference m_remoteMessages; - private final RateLimiter m_loadConfigRateLimiter; - private final AtomicBoolean m_configNeedForceRefresh; - private final SchedulePolicy m_loadConfigFailSchedulePolicy; - private static final Gson GSON = new Gson(); - - static { - m_executorService = Executors.newScheduledThreadPool(1, - ApolloThreadFactory.create("RemoteConfigRepository", true)); - } - - /** - * Constructor. - * - * @param namespace the namespace - */ - public RemoteConfigRepository(String namespace) { - m_namespace = namespace; - m_configCache = new AtomicReference<>(); - m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); - m_httpClient = ApolloInjector.getInstance(HttpClient.class); - m_serviceLocator = ApolloInjector.getInstance(ConfigServiceLocator.class); - remoteConfigLongPollService = ApolloInjector.getInstance(RemoteConfigLongPollService.class); - m_longPollServiceDto = new AtomicReference<>(); - m_remoteMessages = new AtomicReference<>(); - m_loadConfigRateLimiter = RateLimiter.create(m_configUtil.getLoadConfigQPS()); - m_configNeedForceRefresh = new AtomicBoolean(true); - m_loadConfigFailSchedulePolicy = new ExponentialSchedulePolicy(m_configUtil.getOnErrorRetryInterval(), - m_configUtil.getOnErrorRetryInterval() * 8); - this.trySync(); - this.schedulePeriodicRefresh(); - this.scheduleLongPollingRefresh(); - } - - @Override - public Properties getConfig() { - if (m_configCache.get() == null) { - this.sync(); - } - return transformApolloConfigToProperties(m_configCache.get()); - } - - @Override - public void setUpstreamRepository(ConfigRepository upstreamConfigRepository) { - //remote config doesn't need upstream - } - - @Override - public ConfigSourceType getSourceType() { - return ConfigSourceType.REMOTE; - } - - private void schedulePeriodicRefresh() { - logger.debug("Schedule periodic refresh with interval: {} {}", - m_configUtil.getRefreshInterval(), m_configUtil.getRefreshIntervalTimeUnit()); - m_executorService.scheduleAtFixedRate( - new Runnable() { - @Override - public void run() { - Tracer.logEvent("Apollo.ConfigService", String.format("periodicRefresh: %s", m_namespace)); - logger.debug("refresh config for namespace: {}", m_namespace); - trySync(); - Tracer.logEvent("Apollo.Client.Version", Apollo.VERSION); - } - }, m_configUtil.getRefreshInterval(), m_configUtil.getRefreshInterval(), - m_configUtil.getRefreshIntervalTimeUnit()); - } - - @Override - protected synchronized void sync() { - Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "syncRemoteConfig"); - - try { - ApolloConfig previous = m_configCache.get(); - ApolloConfig current = loadApolloConfig(); - - //reference equals means HTTP 304 - if (previous != current) { - logger.debug("Remote Config refreshed!"); - m_configCache.set(current); - this.fireRepositoryChange(m_namespace, this.getConfig()); - } - - if (current != null) { - Tracer.logEvent(String.format("Apollo.Client.Configs.%s", current.getNamespaceName()), - current.getReleaseKey()); - } - - transaction.setStatus(Transaction.SUCCESS); - } catch (Throwable ex) { - transaction.setStatus(ex); - throw ex; - } finally { - transaction.complete(); - } - } - - private Properties transformApolloConfigToProperties(ApolloConfig apolloConfig) { - Properties result = propertiesFactory.getPropertiesInstance(); - result.putAll(apolloConfig.getConfigurations()); - return result; - } - - private ApolloConfig loadApolloConfig() { - if (!m_loadConfigRateLimiter.tryAcquire(5, TimeUnit.SECONDS)) { - //wait at most 5 seconds - try { - TimeUnit.SECONDS.sleep(5); - } catch (InterruptedException e) { - } - } - String appId = m_configUtil.getAppId(); - String cluster = m_configUtil.getCluster(); - String dataCenter = m_configUtil.getDataCenter(); - String secret = m_configUtil.getAccessKeySecret(); - Tracer.logEvent("Apollo.Client.ConfigMeta", STRING_JOINER.join(appId, cluster, m_namespace)); - int maxRetries = m_configNeedForceRefresh.get() ? 2 : 1; - long onErrorSleepTime = 0; // 0 means no sleep - Throwable exception = null; - - List configServices = getConfigServices(); - String url = null; - retryLoopLabel: - for (int i = 0; i < maxRetries; i++) { - List randomConfigServices = Lists.newLinkedList(configServices); - Collections.shuffle(randomConfigServices); - //Access the server which notifies the client first - if (m_longPollServiceDto.get() != null) { - randomConfigServices.add(0, m_longPollServiceDto.getAndSet(null)); - } - - for (ServiceDTO configService : randomConfigServices) { - if (onErrorSleepTime > 0) { - logger.warn( - "Load config failed, will retry in {} {}. appId: {}, cluster: {}, namespaces: {}", - onErrorSleepTime, m_configUtil.getOnErrorRetryIntervalTimeUnit(), appId, cluster, m_namespace); - - try { - m_configUtil.getOnErrorRetryIntervalTimeUnit().sleep(onErrorSleepTime); - } catch (InterruptedException e) { - //ignore - } - } - - url = assembleQueryConfigUrl(configService.getHomepageUrl(), appId, cluster, m_namespace, - dataCenter, m_remoteMessages.get(), m_configCache.get()); - - logger.debug("Loading config from {}", url); - - HttpRequest request = new HttpRequest(url); - if (!StringUtils.isBlank(secret)) { - Map headers = Signature.buildHttpHeaders(url, appId, secret); - request.setHeaders(headers); - } - - Transaction transaction = Tracer.newTransaction("Apollo.ConfigService", "queryConfig"); - transaction.addData("Url", url); - try { - - HttpResponse response = m_httpClient.doGet(request, ApolloConfig.class); - m_configNeedForceRefresh.set(false); - m_loadConfigFailSchedulePolicy.success(); - - transaction.addData("StatusCode", response.getStatusCode()); - transaction.setStatus(Transaction.SUCCESS); - - if (response.getStatusCode() == 304) { - logger.debug("Config server responds with 304 HTTP status code."); - return m_configCache.get(); - } - - ApolloConfig result = response.getBody(); - - logger.debug("Loaded config for {}: {}", m_namespace, result); - - return result; - } catch (ApolloConfigStatusCodeException ex) { - ApolloConfigStatusCodeException statusCodeException = ex; - //config not found - if (ex.getStatusCode() == 404) { - String message = String.format( - "Could not find config for namespace - appId: %s, cluster: %s, namespace: %s, " + - "please check whether the configs are released in Apollo!", - appId, cluster, m_namespace); - statusCodeException = new ApolloConfigStatusCodeException(ex.getStatusCode(), - message); - } - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(statusCodeException)); - transaction.setStatus(statusCodeException); - exception = statusCodeException; - if(ex.getStatusCode() == 404) { - break retryLoopLabel; - } - } catch (Throwable ex) { - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex)); - transaction.setStatus(ex); - exception = ex; - } finally { - transaction.complete(); - } - - // if force refresh, do normal sleep, if normal config load, do exponential sleep - onErrorSleepTime = m_configNeedForceRefresh.get() ? m_configUtil.getOnErrorRetryInterval() : - m_loadConfigFailSchedulePolicy.fail(); - } - - } - String message = String.format( - "Load Apollo Config failed - appId: %s, cluster: %s, namespace: %s, url: %s", - appId, cluster, m_namespace, url); - throw new ApolloConfigException(message, exception); - } - - String assembleQueryConfigUrl(String uri, String appId, String cluster, String namespace, - String dataCenter, ApolloNotificationMessages remoteMessages, ApolloConfig previousConfig) { - - String path = "configs/%s/%s/%s"; - List pathParams = - Lists.newArrayList(pathEscaper.escape(appId), pathEscaper.escape(cluster), - pathEscaper.escape(namespace)); - Map queryParams = Maps.newHashMap(); - - if (previousConfig != null) { - queryParams.put("releaseKey", queryParamEscaper.escape(previousConfig.getReleaseKey())); - } - - if (!Strings.isNullOrEmpty(dataCenter)) { - queryParams.put("dataCenter", queryParamEscaper.escape(dataCenter)); - } - - String localIp = m_configUtil.getLocalIp(); - if (!Strings.isNullOrEmpty(localIp)) { - queryParams.put("ip", queryParamEscaper.escape(localIp)); - } - - String label = m_configUtil.getApolloLabel(); - if (!Strings.isNullOrEmpty(label)) { - queryParams.put("label", queryParamEscaper.escape(label)); - } - - if (remoteMessages != null) { - queryParams.put("messages", queryParamEscaper.escape(GSON.toJson(remoteMessages))); - } - - String pathExpanded = String.format(path, pathParams.toArray()); - - if (!queryParams.isEmpty()) { - pathExpanded += "?" + MAP_JOINER.join(queryParams); - } - if (!uri.endsWith("/")) { - uri += "/"; - } - return uri + pathExpanded; - } - - private void scheduleLongPollingRefresh() { - remoteConfigLongPollService.submit(m_namespace, this); - } - - public void onLongPollNotified(ServiceDTO longPollNotifiedServiceDto, ApolloNotificationMessages remoteMessages) { - m_longPollServiceDto.set(longPollNotifiedServiceDto); - m_remoteMessages.set(remoteMessages); - m_executorService.submit(new Runnable() { - @Override - public void run() { - m_configNeedForceRefresh.set(true); - trySync(); - } - }); - } - - private List getConfigServices() { - List services = m_serviceLocator.getConfigServices(); - if (services.size() == 0) { - throw new ApolloConfigException("No available config service"); - } - - return services; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RepositoryChangeListener.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RepositoryChangeListener.java deleted file mode 100644 index 77334d961cf..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RepositoryChangeListener.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2022 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 java.util.Properties; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface RepositoryChangeListener { - /** - * Invoked when config repository changes. - * @param namespace the namespace of this repository change - * @param newProperties the properties after change - */ - void onRepositoryChange(String namespace, Properties newProperties); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/SimpleConfig.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/SimpleConfig.java deleted file mode 100644 index c8897bbd918..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/SimpleConfig.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2022 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.Collections; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.ctrip.framework.apollo.model.ConfigChange; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.apollo.util.ExceptionUtil; -import com.google.common.base.Function; -import com.google.common.collect.Maps; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class SimpleConfig extends AbstractConfig implements RepositoryChangeListener { - private static final Logger logger = LoggerFactory.getLogger(SimpleConfig.class); - private final String m_namespace; - private final ConfigRepository m_configRepository; - private volatile Properties m_configProperties; - private volatile ConfigSourceType m_sourceType = ConfigSourceType.NONE; - - /** - * Constructor. - * - * @param namespace the namespace for this config instance - * @param configRepository the config repository for this config instance - */ - public SimpleConfig(String namespace, ConfigRepository configRepository) { - m_namespace = namespace; - m_configRepository = configRepository; - this.initialize(); - } - - private void initialize() { - try { - updateConfig(m_configRepository.getConfig(), m_configRepository.getSourceType()); - } catch (Throwable ex) { - Tracer.logError(ex); - logger.warn("Init Apollo Simple Config failed - namespace: {}, reason: {}", m_namespace, - ExceptionUtil.getDetailMessage(ex)); - } finally { - //register the change listener no matter config repository is working or not - //so that whenever config repository is recovered, config could get changed - m_configRepository.addChangeListener(this); - } - } - - @Override - public String getProperty(String key, String defaultValue) { - if (m_configProperties == null) { - logger.warn("Could not load config from Apollo, always return default value!"); - return defaultValue; - } - return this.m_configProperties.getProperty(key, defaultValue); - } - - @Override - public Set getPropertyNames() { - if (m_configProperties == null) { - return Collections.emptySet(); - } - - return m_configProperties.stringPropertyNames(); - } - - @Override - public ConfigSourceType getSourceType() { - return m_sourceType; - } - - @Override - public synchronized void onRepositoryChange(String namespace, Properties newProperties) { - if (newProperties.equals(m_configProperties)) { - return; - } - Properties newConfigProperties = propertiesFactory.getPropertiesInstance(); - newConfigProperties.putAll(newProperties); - - List changes = calcPropertyChanges(namespace, m_configProperties, newConfigProperties); - Map changeMap = Maps.uniqueIndex(changes, - new Function() { - @Override - public String apply(ConfigChange input) { - return input.getPropertyName(); - } - }); - - updateConfig(newConfigProperties, m_configRepository.getSourceType()); - clearConfigCache(); - - this.fireConfigChange(m_namespace, changeMap); - - Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace); - } - - private void updateConfig(Properties newConfigProperties, ConfigSourceType sourceType) { - m_configProperties = newConfigProperties; - m_sourceType = sourceType; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/TxtConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/TxtConfigFile.java deleted file mode 100644 index dcffbcd6b5c..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/TxtConfigFile.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2022 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.core.enums.ConfigFileFormat; - -public class TxtConfigFile extends PlainTextConfigFile { - - public TxtConfigFile(String namespace, ConfigRepository configRepository) { - super(namespace, configRepository); - } - - @Override - public ConfigFileFormat getConfigFileFormat() { - return ConfigFileFormat.TXT; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/XmlConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/XmlConfigFile.java deleted file mode 100644 index 8300a8360ce..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/XmlConfigFile.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2022 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.core.enums.ConfigFileFormat; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class XmlConfigFile extends PlainTextConfigFile { - public XmlConfigFile(String namespace, - ConfigRepository configRepository) { - super(namespace, configRepository); - } - - @Override - public ConfigFileFormat getConfigFileFormat() { - return ConfigFileFormat.XML; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YamlConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YamlConfigFile.java deleted file mode 100644 index 3443d582e08..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YamlConfigFile.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2022 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.util.ExceptionUtil; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.ctrip.framework.apollo.PropertiesCompatibleConfigFile; -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.apollo.util.yaml.YamlParser; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class YamlConfigFile extends PlainTextConfigFile implements PropertiesCompatibleConfigFile { - private static final Logger logger = LoggerFactory.getLogger(YamlConfigFile.class); - private volatile Properties cachedProperties; - - public YamlConfigFile(String namespace, ConfigRepository configRepository) { - super(namespace, configRepository); - tryTransformToProperties(); - } - - @Override - public ConfigFileFormat getConfigFileFormat() { - return ConfigFileFormat.YAML; - } - - @Override - protected void update(Properties newProperties) { - super.update(newProperties); - tryTransformToProperties(); - } - - @Override - public Properties asProperties() { - if (cachedProperties == null) { - transformToProperties(); - } - return cachedProperties; - } - - private boolean tryTransformToProperties() { - try { - transformToProperties(); - return true; - } catch (Throwable ex) { - Tracer.logEvent("ApolloConfigException", ExceptionUtil.getDetailMessage(ex)); - logger.warn("yaml to properties failed, reason: {}", ExceptionUtil.getDetailMessage(ex)); - } - return false; - } - - private synchronized void transformToProperties() { - cachedProperties = toProperties(); - } - - private Properties toProperties() { - if (!this.hasContent()) { - return propertiesFactory.getPropertiesInstance(); - } - - try { - return ApolloInjector.getInstance(YamlParser.class).yamlToProperties(getContent()); - } catch (Throwable ex) { - ApolloConfigException exception = new ApolloConfigException( - "Parse yaml file content failed for namespace: " + m_namespace, ex); - Tracer.logError(exception); - throw exception; - } - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YmlConfigFile.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YmlConfigFile.java deleted file mode 100644 index 5e922a53145..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/YmlConfigFile.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2022 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.core.enums.ConfigFileFormat; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class YmlConfigFile extends YamlConfigFile { - public YmlConfigFile(String namespace, ConfigRepository configRepository) { - super(namespace, configRepository); - } - - @Override - public ConfigFileFormat getConfigFileFormat() { - return ConfigFileFormat.YML; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/model/ConfigChange.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/model/ConfigChange.java deleted file mode 100644 index bcc6e4e66c5..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/model/ConfigChange.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2022 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.model; - - -import com.ctrip.framework.apollo.enums.PropertyChangeType; - -/** - * Holds the information for a config change. - * @author Jason Song(song_s@ctrip.com) - */ -public class ConfigChange { - private final String namespace; - private final String propertyName; - private String oldValue; - private String newValue; - private PropertyChangeType changeType; - - /** - * Constructor. - * @param namespace the namespace of the key - * @param propertyName the key whose value is changed - * @param oldValue the value before change - * @param newValue the value after change - * @param changeType the change type - */ - public ConfigChange(String namespace, String propertyName, String oldValue, String newValue, - PropertyChangeType changeType) { - this.namespace = namespace; - this.propertyName = propertyName; - this.oldValue = oldValue; - this.newValue = newValue; - this.changeType = changeType; - } - - public String getPropertyName() { - return propertyName; - } - - public String getOldValue() { - return oldValue; - } - - public String getNewValue() { - return newValue; - } - - public PropertyChangeType getChangeType() { - return changeType; - } - - public void setOldValue(String oldValue) { - this.oldValue = oldValue; - } - - public void setNewValue(String newValue) { - this.newValue = newValue; - } - - public void setChangeType(PropertyChangeType changeType) { - this.changeType = changeType; - } - - public String getNamespace() { - return namespace; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("ConfigChange{"); - sb.append("namespace='").append(namespace).append('\''); - sb.append(", propertyName='").append(propertyName).append('\''); - sb.append(", oldValue='").append(oldValue).append('\''); - sb.append(", newValue='").append(newValue).append('\''); - sb.append(", changeType=").append(changeType); - sb.append('}'); - return sb.toString(); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/model/ConfigChangeEvent.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/model/ConfigChangeEvent.java deleted file mode 100644 index eddf003f71c..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/model/ConfigChangeEvent.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2022 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.model; - -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -/** - * A change event when a namespace's config is changed. - * @author Jason Song(song_s@ctrip.com) - */ -public class ConfigChangeEvent { - private final String m_namespace; - private final Map m_changes; - /** - * Constructor. - * @param namespace the namespace of this change - * @param changes the actual changes - */ - public ConfigChangeEvent(String namespace, - Map changes) { - this.m_namespace = namespace; - this.m_changes = changes; - } - - /** - * Get the keys changed. - * @return the list of the keys - */ - public Set changedKeys() { - return m_changes.keySet(); - } - - /** - * Maybe subclass override this method. - * - * @return interested and changed keys - */ - public Set interestedChangedKeys() { - return Collections.emptySet(); - } - - /** - * Get a specific change instance for the key specified. - * @param key the changed key - * @return the change instance - */ - public ConfigChange getChange(String key) { - return m_changes.get(key); - } - - /** - * Check whether the specified key is changed - * @param key the key - * @return true if the key is changed, false otherwise. - */ - public boolean isChanged(String key) { - return m_changes.containsKey(key); - } - - /** - * Get the namespace of this change event. - * @return the namespace - */ - public String getNamespace() { - return m_namespace; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/model/ConfigFileChangeEvent.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/model/ConfigFileChangeEvent.java deleted file mode 100644 index 4c3569bf86d..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/model/ConfigFileChangeEvent.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2022 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.model; - -import com.ctrip.framework.apollo.enums.PropertyChangeType; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ConfigFileChangeEvent { - private final String namespace; - private final String oldValue; - private final String newValue; - private final PropertyChangeType changeType; - - /** - * Constructor. - * - * @param namespace the namespace of the config file change event - * @param oldValue the value before change - * @param newValue the value after change - * @param changeType the change type - */ - public ConfigFileChangeEvent(String namespace, String oldValue, String newValue, - PropertyChangeType changeType) { - this.namespace = namespace; - this.oldValue = oldValue; - this.newValue = newValue; - this.changeType = changeType; - } - - public String getNamespace() { - return namespace; - } - - public String getOldValue() { - return oldValue; - } - - public String getNewValue() { - return newValue; - } - - public PropertyChangeType getChangeType() { - return changeType; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("ConfigFileChangeEvent{"); - sb.append("namespace='").append(namespace).append('\''); - sb.append(", oldValue='").append(oldValue).append('\''); - sb.append(", newValue='").append(newValue).append('\''); - sb.append(", changeType=").append(changeType); - sb.append('}'); - return sb.toString(); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ApolloInjectorCustomizer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ApolloInjectorCustomizer.java deleted file mode 100644 index 632ba40f13f..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ApolloInjectorCustomizer.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import com.ctrip.framework.apollo.core.spi.Ordered; -import com.ctrip.framework.apollo.internals.DefaultInjector; -import com.ctrip.framework.apollo.internals.Injector; - -/** - * Allow users to inject customized instances, see {@link DefaultInjector#getInstance(java.lang.Class)} - */ -public interface ApolloInjectorCustomizer extends Injector, Ordered { - -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ConfigFactory.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ConfigFactory.java deleted file mode 100644 index da4223f8195..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ConfigFactory.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigFile; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface ConfigFactory { - /** - * Create the config instance for the namespace. - * - * @param namespace the namespace - * @return the newly created config instance - */ - Config create(String namespace); - - /** - * Create the config file instance for the namespace - * @param namespace the namespace - * @return the newly created config file instance - */ - ConfigFile createConfigFile(String namespace, ConfigFileFormat configFileFormat); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ConfigFactoryManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ConfigFactoryManager.java deleted file mode 100644 index 5d77a2bca9b..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ConfigFactoryManager.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright 2022 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.spi; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface ConfigFactoryManager { - /** - * Get the config factory for the namespace. - * - * @param namespace the namespace - * @return the config factory for this namespace - */ - ConfigFactory getFactory(String namespace); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ConfigRegistry.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ConfigRegistry.java deleted file mode 100644 index 8e34df6df36..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ConfigRegistry.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2022 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.spi; - -/** - * The manually config registry, use with caution! - * - * @author Jason Song(song_s@ctrip.com) - */ -public interface ConfigRegistry { - /** - * Register the config factory for the namespace specified. - * - * @param namespace the namespace - * @param factory the factory for this namespace - */ - void register(String namespace, ConfigFactory factory); - - /** - * Get the registered config factory for the namespace. - * - * @param namespace the namespace - * @return the factory registered for this namespace - */ - ConfigFactory getFactory(String namespace); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ConfigServiceLoadBalancerClient.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ConfigServiceLoadBalancerClient.java deleted file mode 100644 index 29d6530af88..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/ConfigServiceLoadBalancerClient.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import com.ctrip.framework.apollo.core.dto.ServiceDTO; -import com.ctrip.framework.apollo.core.spi.Ordered; -import com.ctrip.framework.apollo.internals.ConfigServiceLocator; -import java.util.List; - -public interface ConfigServiceLoadBalancerClient extends Ordered { - - /** - * choose 1 config service from multiple service instances - * - * @param configServices the return of {@link ConfigServiceLocator#getConfigServices()} - * @return return 1 config service chosen, null if there is no unavailable config service - * @throws IllegalArgumentException if arg is null of empty - */ - ServiceDTO chooseOneFrom(List configServices); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/DefaultConfigFactory.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/DefaultConfigFactory.java deleted file mode 100644 index 36c300f47b6..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/DefaultConfigFactory.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigFile; -import com.ctrip.framework.apollo.ConfigService; -import com.ctrip.framework.apollo.PropertiesCompatibleConfigFile; -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import com.ctrip.framework.apollo.internals.ConfigRepository; -import com.ctrip.framework.apollo.internals.DefaultConfig; -import com.ctrip.framework.apollo.internals.JsonConfigFile; -import com.ctrip.framework.apollo.internals.LocalFileConfigRepository; -import com.ctrip.framework.apollo.internals.PropertiesCompatibleFileConfigRepository; -import com.ctrip.framework.apollo.internals.PropertiesConfigFile; -import com.ctrip.framework.apollo.internals.RemoteConfigRepository; -import com.ctrip.framework.apollo.internals.TxtConfigFile; -import com.ctrip.framework.apollo.internals.XmlConfigFile; -import com.ctrip.framework.apollo.internals.YamlConfigFile; -import com.ctrip.framework.apollo.internals.YmlConfigFile; -import com.ctrip.framework.apollo.util.ConfigUtil; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * The default implementation of {@link ConfigFactory}. - *

- * Supports namespaces of format: - *

    - *
  • {@link ConfigFileFormat#Properties}
  • - *
  • {@link ConfigFileFormat#XML}
  • - *
  • {@link ConfigFileFormat#JSON}
  • - *
  • {@link ConfigFileFormat#YML}
  • - *
  • {@link ConfigFileFormat#YAML}
  • - *
  • {@link ConfigFileFormat#TXT}
  • - *
- * - * @author Jason Song(song_s@ctrip.com) - * @author Diego Krupitza(info@diegokrupitza.com) - */ -public class DefaultConfigFactory implements ConfigFactory { - - private static final Logger logger = LoggerFactory.getLogger(DefaultConfigFactory.class); - private final ConfigUtil m_configUtil; - - public DefaultConfigFactory() { - m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); - } - - @Override - public Config create(String namespace) { - ConfigFileFormat format = determineFileFormat(namespace); - - ConfigRepository configRepository = null; - - // although ConfigFileFormat.Properties are compatible with themselves we - // should not create a PropertiesCompatibleFileConfigRepository for them - // calling the method `createLocalConfigRepository(...)` is more suitable - // for ConfigFileFormat.Properties - if (ConfigFileFormat.isPropertiesCompatible(format) && - format != ConfigFileFormat.Properties) { - configRepository = createPropertiesCompatibleFileConfigRepository(namespace, format); - } else { - configRepository = createConfigRepository(namespace); - } - - logger.debug("Created a configuration repository of type [{}] for namespace [{}]", - configRepository.getClass().getName(), namespace); - - return this.createRepositoryConfig(namespace, configRepository); - } - - protected Config createRepositoryConfig(String namespace, ConfigRepository configRepository) { - return new DefaultConfig(namespace, configRepository); - } - - @Override - public ConfigFile createConfigFile(String namespace, ConfigFileFormat configFileFormat) { - ConfigRepository configRepository = createConfigRepository(namespace); - switch (configFileFormat) { - case Properties: - return new PropertiesConfigFile(namespace, configRepository); - case XML: - return new XmlConfigFile(namespace, configRepository); - case JSON: - return new JsonConfigFile(namespace, configRepository); - case YAML: - return new YamlConfigFile(namespace, configRepository); - case YML: - return new YmlConfigFile(namespace, configRepository); - case TXT: - return new TxtConfigFile(namespace, configRepository); - } - - return null; - } - - ConfigRepository createConfigRepository(String namespace) { - if (m_configUtil.isPropertyFileCacheEnabled()) { - return createLocalConfigRepository(namespace); - } - return createRemoteConfigRepository(namespace); - } - - /** - * Creates a local repository for a given namespace - * - * @param namespace the namespace of the repository - * @return the newly created repository for the given namespace - */ - LocalFileConfigRepository createLocalConfigRepository(String namespace) { - if (m_configUtil.isInLocalMode()) { - logger.warn( - "==== Apollo is in local mode! Won't pull configs from remote server for namespace {} ! ====", - namespace); - return new LocalFileConfigRepository(namespace); - } - return new LocalFileConfigRepository(namespace, createRemoteConfigRepository(namespace)); - } - - RemoteConfigRepository createRemoteConfigRepository(String namespace) { - return new RemoteConfigRepository(namespace); - } - - PropertiesCompatibleFileConfigRepository createPropertiesCompatibleFileConfigRepository( - String namespace, ConfigFileFormat format) { - String actualNamespaceName = trimNamespaceFormat(namespace, format); - PropertiesCompatibleConfigFile configFile = (PropertiesCompatibleConfigFile) ConfigService - .getConfigFile(actualNamespaceName, format); - - return new PropertiesCompatibleFileConfigRepository(configFile); - } - - // for namespaces whose format are not properties, the file extension must be present, e.g. application.yaml - ConfigFileFormat determineFileFormat(String namespaceName) { - String lowerCase = namespaceName.toLowerCase(); - for (ConfigFileFormat format : ConfigFileFormat.values()) { - if (lowerCase.endsWith("." + format.getValue())) { - return format; - } - } - - return ConfigFileFormat.Properties; - } - - String trimNamespaceFormat(String namespaceName, ConfigFileFormat format) { - String extension = "." + format.getValue(); - if (!namespaceName.toLowerCase().endsWith(extension)) { - return namespaceName; - } - - return namespaceName.substring(0, namespaceName.length() - extension.length()); - } - -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/DefaultConfigFactoryManager.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/DefaultConfigFactoryManager.java deleted file mode 100644 index b57a89b5dea..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/DefaultConfigFactoryManager.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import java.util.Map; - -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.google.common.collect.Maps; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class DefaultConfigFactoryManager implements ConfigFactoryManager { - private ConfigRegistry m_registry; - - private Map m_factories = Maps.newConcurrentMap(); - - public DefaultConfigFactoryManager() { - m_registry = ApolloInjector.getInstance(ConfigRegistry.class); - } - - @Override - public ConfigFactory getFactory(String namespace) { - // step 1: check hacked factory - ConfigFactory factory = m_registry.getFactory(namespace); - - if (factory != null) { - return factory; - } - - // step 2: check cache - factory = m_factories.get(namespace); - - if (factory != null) { - return factory; - } - - // step 3: check declared config factory - factory = ApolloInjector.getInstance(ConfigFactory.class, namespace); - - if (factory != null) { - return factory; - } - - // step 4: check default config factory - factory = ApolloInjector.getInstance(ConfigFactory.class); - - m_factories.put(namespace, factory); - - // factory should not be null - return factory; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/DefaultConfigRegistry.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/DefaultConfigRegistry.java deleted file mode 100644 index 02acc24cc51..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/DefaultConfigRegistry.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.Maps; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class DefaultConfigRegistry implements ConfigRegistry { - private static final Logger s_logger = LoggerFactory.getLogger(DefaultConfigRegistry.class); - private Map m_instances = Maps.newConcurrentMap(); - - @Override - public void register(String namespace, ConfigFactory factory) { - if (m_instances.containsKey(namespace)) { - s_logger.warn("ConfigFactory({}) is overridden by {}!", namespace, factory.getClass()); - } - - m_instances.put(namespace, factory); - } - - @Override - public ConfigFactory getFactory(String namespace) { - ConfigFactory config = m_instances.get(namespace); - - return config; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/RandomConfigServiceLoadBalancerClient.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/RandomConfigServiceLoadBalancerClient.java deleted file mode 100644 index 4c437061023..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spi/RandomConfigServiceLoadBalancerClient.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import com.ctrip.framework.apollo.core.dto.ServiceDTO; -import java.util.List; -import java.util.concurrent.ThreadLocalRandom; - -/** - * default service provider of {@link ConfigServiceLoadBalancerClient} - */ -public class RandomConfigServiceLoadBalancerClient implements ConfigServiceLoadBalancerClient { - - private static final int ORDER = 0; - - @Override - public ServiceDTO chooseOneFrom(List configServices) { - if (null == configServices) { - throw new IllegalArgumentException("arg is null"); - } - if (configServices.isEmpty()) { - throw new IllegalArgumentException("arg is empty"); - } - int index = ThreadLocalRandom.current().nextInt(configServices.size()); - return configServices.get(index); - } - - @Override - public int getOrder() { - return ORDER; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloAnnotationProcessor.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloAnnotationProcessor.java deleted file mode 100644 index 45cae764781..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloAnnotationProcessor.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright 2022 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 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.model.ConfigChangeEvent; -import com.ctrip.framework.apollo.spring.property.PlaceholderHelper; -import com.ctrip.framework.apollo.spring.property.SpringValue; -import com.ctrip.framework.apollo.spring.property.SpringValueRegistry; -import com.ctrip.framework.apollo.spring.util.SpringInjector; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.base.Preconditions; -import com.google.common.collect.Sets; -import com.google.gson.Gson; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.util.Set; -import javax.annotation.Nullable; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.core.env.Environment; -import org.springframework.util.ReflectionUtils; - -/** - * Apollo Annotation Processor for Spring Application - * - * @author Jason Song(song_s@ctrip.com) - */ -public class ApolloAnnotationProcessor extends ApolloProcessor implements BeanFactoryAware, - EnvironmentAware { - - private static final Logger logger = LoggerFactory.getLogger(ApolloAnnotationProcessor.class); - private static final Gson GSON = new Gson(); - - private final ConfigUtil configUtil; - private final PlaceholderHelper placeholderHelper; - private final SpringValueRegistry springValueRegistry; - - /** - * resolve the expression. - */ - private ConfigurableBeanFactory configurableBeanFactory; - - private Environment environment; - - public ApolloAnnotationProcessor() { - configUtil = ApolloInjector.getInstance(ConfigUtil.class); - placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class); - springValueRegistry = SpringInjector.getInstance(SpringValueRegistry.class); - } - - @Override - protected void processField(Object bean, String beanName, Field field) { - this.processApolloConfig(bean, field); - this.processApolloJsonValue(bean, beanName, field); - } - - @Override - protected void processMethod(final Object bean, String beanName, final Method method) { - this.processApolloConfigChangeListener(bean, method); - this.processApolloJsonValue(bean, beanName, method); - } - - private void processApolloConfig(Object bean, Field field) { - ApolloConfig annotation = AnnotationUtils.getAnnotation(field, ApolloConfig.class); - if (annotation == null) { - return; - } - - Preconditions.checkArgument(Config.class.isAssignableFrom(field.getType()), - "Invalid type: %s for field: %s, should be Config", field.getType(), field); - - final String namespace = annotation.value(); - final String resolvedNamespace = this.environment.resolveRequiredPlaceholders(namespace); - Config config = ConfigService.getConfig(resolvedNamespace); - - ReflectionUtils.makeAccessible(field); - ReflectionUtils.setField(field, bean, config); - } - - private void processApolloConfigChangeListener(final Object bean, final Method method) { - ApolloConfigChangeListener annotation = AnnotationUtils - .findAnnotation(method, ApolloConfigChangeListener.class); - if (annotation == null) { - return; - } - Class[] parameterTypes = method.getParameterTypes(); - Preconditions.checkArgument(parameterTypes.length == 1, - "Invalid number of parameters: %s for method: %s, should be 1", parameterTypes.length, - method); - Preconditions.checkArgument(ConfigChangeEvent.class.isAssignableFrom(parameterTypes[0]), - "Invalid parameter type: %s for method: %s, should be ConfigChangeEvent", parameterTypes[0], - method); - - ReflectionUtils.makeAccessible(method); - String[] namespaces = annotation.value(); - String[] annotatedInterestedKeys = annotation.interestedKeys(); - String[] annotatedInterestedKeyPrefixes = annotation.interestedKeyPrefixes(); - ConfigChangeListener configChangeListener = changeEvent -> ReflectionUtils.invokeMethod(method, bean, changeEvent); - - Set interestedKeys = - annotatedInterestedKeys.length > 0 ? Sets.newHashSet(annotatedInterestedKeys) : null; - Set interestedKeyPrefixes = - annotatedInterestedKeyPrefixes.length > 0 ? Sets.newHashSet(annotatedInterestedKeyPrefixes) - : null; - - for (String namespace : namespaces) { - final String resolvedNamespace = this.environment.resolveRequiredPlaceholders(namespace); - Config config = ConfigService.getConfig(resolvedNamespace); - - if (interestedKeys == null && interestedKeyPrefixes == null) { - config.addChangeListener(configChangeListener); - } else { - config.addChangeListener(configChangeListener, interestedKeys, interestedKeyPrefixes); - } - } - } - - private void processApolloJsonValue(Object bean, String beanName, Field field) { - ApolloJsonValue apolloJsonValue = AnnotationUtils.getAnnotation(field, ApolloJsonValue.class); - if (apolloJsonValue == null) { - return; - } - - String placeholder = apolloJsonValue.value(); - Object propertyValue = this.resolvePropertyValue(beanName, placeholder); - if (propertyValue == null) { - return; - } - - boolean accessible = field.isAccessible(); - field.setAccessible(true); - ReflectionUtils - .setField(field, bean, parseJsonValue((String) propertyValue, field.getGenericType())); - field.setAccessible(accessible); - - if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) { - Set keys = placeholderHelper.extractPlaceholderKeys(placeholder); - for (String key : keys) { - SpringValue springValue = new SpringValue(key, placeholder, bean, beanName, field, true); - springValueRegistry.register(this.configurableBeanFactory, key, springValue); - logger.debug("Monitoring {}", springValue); - } - } - } - - private void processApolloJsonValue(Object bean, String beanName, Method method) { - ApolloJsonValue apolloJsonValue = AnnotationUtils.getAnnotation(method, ApolloJsonValue.class); - if (apolloJsonValue == null) { - return; - } - - String placeHolder = apolloJsonValue.value(); - Object propertyValue = this.resolvePropertyValue(beanName, placeHolder); - if (propertyValue == null) { - return; - } - - Type[] types = method.getGenericParameterTypes(); - Preconditions.checkArgument(types.length == 1, - "Ignore @ApolloJsonValue setter {}.{}, expecting 1 parameter, actual {} parameters", - bean.getClass().getName(), method.getName(), method.getParameterTypes().length); - - boolean accessible = method.isAccessible(); - method.setAccessible(true); - ReflectionUtils.invokeMethod(method, bean, parseJsonValue((String) propertyValue, types[0])); - method.setAccessible(accessible); - - if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) { - Set keys = placeholderHelper.extractPlaceholderKeys(placeHolder); - for (String key : keys) { - SpringValue springValue = new SpringValue(key, placeHolder, bean, beanName, method, true); - springValueRegistry.register(this.configurableBeanFactory, key, springValue); - logger.debug("Monitoring {}", springValue); - } - } - } - - @Nullable - private Object resolvePropertyValue(String beanName, String placeHolder) { - Object propertyValue = placeholderHelper - .resolvePropertyValue(this.configurableBeanFactory, beanName, placeHolder); - - // propertyValue will never be null, as @ApolloJsonValue will not allow that - if (!(propertyValue instanceof String)) { - return null; - } - - return propertyValue; - } - - private Object parseJsonValue(String json, Type targetType) { - try { - return GSON.fromJson(json, targetType); - } catch (Throwable ex) { - logger.error("Parsing json '{}' to type {} failed!", json, targetType, ex); - throw ex; - } - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.configurableBeanFactory = (ConfigurableBeanFactory) beanFactory; - } - - @Override - public void setEnvironment(Environment environment) { - this.environment = environment; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloConfig.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloConfig.java deleted file mode 100644 index 5b465ad1318..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloConfig.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2022 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. - * - *

Usage example:

- *
- * //Inject the config for "someNamespace"
- * @ApolloConfig("someNamespace")
- * private Config config;
- * 
- * - *

Usage example with placeholder:

- *
- * // 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;
- * 
- * - * - * @author Jason Song(song_s@ctrip.com) - */ -@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; -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloConfigChangeListener.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloConfigChangeListener.java deleted file mode 100644 index 85a2c4da800..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloConfigChangeListener.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2022 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 com.ctrip.framework.apollo.core.ConfigConsts; -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; - -/** - * Use this annotation to register Apollo ConfigChangeListener. - * - *

Usage example:

- *
- * //Listener on namespaces of "someNamespace" and "anotherNamespace", will be notified when any key is changed
- * @ApolloConfigChangeListener({"someNamespace","anotherNamespace"})
- * private void onChange(ConfigChangeEvent changeEvent) {
- *     //handle change event
- * }
- * 
- * //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. - * @ApolloConfigChangeListener({"${redis.namespace:xxx}"}) - * private void onChange(ConfigChangeEvent changeEvent) { - * //handle change event - * } - *
- * //Listener on namespaces of "someNamespace" and "anotherNamespace", will only be notified when "someKey" or "anotherKey" is changed - * @ApolloConfigChangeListener(value = {"someNamespace","anotherNamespace"}, interestedKeys = {"someKey", "anotherKey"}) - * private void onChange(ConfigChangeEvent changeEvent) { - * //handle change event - * } - *
- * - * @author Jason Song(song_s@ctrip.com) - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.METHOD) -@Documented -public @interface ApolloConfigChangeListener { - /** - * Apollo namespace for the config, if not specified then default to application - */ - String[] value() default {ConfigConsts.NAMESPACE_APPLICATION}; - - /** - * The keys interested by the listener, will only be notified if any of the interested keys is changed. - *
- * If neither of {@code interestedKeys} and {@code interestedKeyPrefixes} is specified then the {@code listener} will be notified when any key is changed. - */ - String[] interestedKeys() default {}; - - /** - * The key prefixes that the listener is interested in, will be notified if and only if the changed keys start with anyone of the prefixes. - * The prefixes will simply be used to determine whether the {@code listener} should be notified or not using {@code changedKey.startsWith(prefix)}. - * e.g. "spring." means that {@code listener} is interested in keys that starts with "spring.", such as "spring.banner", "spring.jpa", etc. - * and "application" means that {@code listener} is interested in keys that starts with "application", such as "applicationName", "application.port", etc. - *
- * If neither of {@code interestedKeys} and {@code interestedKeyPrefixes} is specified then the {@code listener} will be notified when whatever key is changed. - */ - String[] interestedKeyPrefixes() default {}; -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloConfigRegistrar.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloConfigRegistrar.java deleted file mode 100644 index 3576026b17d..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloConfigRegistrar.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2022 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 com.ctrip.framework.apollo.spring.spi.ApolloConfigRegistrarHelper; -import com.ctrip.framework.foundation.internals.ServiceBootstrap; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.EnvironmentAware; -import org.springframework.context.annotation.ImportBeanDefinitionRegistrar; -import org.springframework.core.env.Environment; -import org.springframework.core.type.AnnotationMetadata; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ApolloConfigRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware { - - private final ApolloConfigRegistrarHelper helper = ServiceBootstrap.loadPrimary(ApolloConfigRegistrarHelper.class); - - @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { - helper.registerBeanDefinitions(importingClassMetadata, registry); - } - - @Override - public void setEnvironment(Environment environment) { - this.helper.setEnvironment(environment); - } - -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloJsonValue.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloJsonValue.java deleted file mode 100644 index 3e057f760ef..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloJsonValue.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2022 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; - -/** - * Use this annotation to inject json property from Apollo, support the same format as Spring @Value. - * - *

Usage example:

- *
- * // Inject the json property value for type SomeObject.
- * // Suppose SomeObject has 2 properties, someString and someInt, then the possible config
- * // in Apollo is someJsonPropertyKey={"someString":"someValue", "someInt":10}.
- * @ApolloJsonValue("${someJsonPropertyKey:someDefaultValue}")
- * private SomeObject someObject;
- * 
- * - * Create by zhangzheng on 2018/3/6 - * - * @see org.springframework.beans.factory.annotation.Value - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD, ElementType.METHOD}) -@Documented -public @interface ApolloJsonValue { - - /** - * The actual value expression: e.g. "${someJsonPropertyKey:someDefaultValue}". - */ - String value(); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloProcessor.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloProcessor.java deleted file mode 100644 index ce5bbf9d8f7..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/ApolloProcessor.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2022 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 findAllField(Class clazz) { - final List res = new LinkedList<>(); - ReflectionUtils.doWithFields(clazz, res::add); - return res; - } - - private List findAllMethod(Class clazz) { - final List res = new LinkedList<>(); - ReflectionUtils.doWithMethods(clazz, res::add); - return res; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/EnableApolloConfig.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/EnableApolloConfig.java deleted file mode 100644 index 6b670945a5c..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/EnableApolloConfig.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2022 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 org.springframework.context.annotation.Import; -import org.springframework.core.Ordered; - -import com.ctrip.framework.apollo.core.ConfigConsts; - -/** - * Use this annotation to register Apollo property sources when using Java Config. - * - *

Configuration example with multiple namespaces:

- *
- * @Configuration
- * @EnableApolloConfig({"someNamespace","anotherNamespace"})
- * public class AppConfig {
- *
- * }
- * 
- * - *

Configuration example with placeholder:

- *
- * // 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.
- * // Please note that this placeholder could not be configured in Apollo as Apollo is not activated during this phase.
- * @Configuration
- * @EnableApolloConfig({"${redis.namespace:xxx}"})
- * public class AppConfig {
- *
- * }
- * 
- * - * @author Jason Song(song_s@ctrip.com) - */ -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -@Documented -@Import(ApolloConfigRegistrar.class) -public @interface EnableApolloConfig { - /** - * Apollo namespaces to inject configuration into Spring Property Sources. - */ - String[] value() default {ConfigConsts.NAMESPACE_APPLICATION}; - - /** - * The order of the apollo config, default is {@link Ordered#LOWEST_PRECEDENCE}, which is Integer.MAX_VALUE. - * If there are properties with the same name in different apollo configs, the apollo config with smaller order wins. - * @return - */ - int order() default Ordered.LOWEST_PRECEDENCE; -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/SpringValueProcessor.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/SpringValueProcessor.java deleted file mode 100644 index 3265f55568a..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/annotation/SpringValueProcessor.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright 2022 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 com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.spring.property.PlaceholderHelper; -import com.ctrip.framework.apollo.spring.property.SpringValue; -import com.ctrip.framework.apollo.spring.property.SpringValueDefinition; -import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor; -import com.ctrip.framework.apollo.spring.property.SpringValueRegistry; -import com.ctrip.framework.apollo.spring.util.SpringInjector; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.collect.LinkedListMultimap; -import com.google.common.collect.Multimap; -import java.beans.PropertyDescriptor; -import java.lang.reflect.Field; -import java.lang.reflect.Member; -import java.lang.reflect.Method; -import java.util.Collection; -import java.util.Set; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.BeanFactoryAware; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.annotation.Bean; - -/** - * Spring value processor of field or method which has @Value and xml config placeholders. - * - * @author github.com/zhegexiaohuozi seimimaster@gmail.com mghio.dev@gmail.com - * @since 2017/12/20. - */ -public class SpringValueProcessor extends ApolloProcessor implements BeanFactoryPostProcessor, BeanFactoryAware { - - private static final Logger logger = LoggerFactory.getLogger(SpringValueProcessor.class); - - private final ConfigUtil configUtil; - private final PlaceholderHelper placeholderHelper; - private final SpringValueRegistry springValueRegistry; - - private BeanFactory beanFactory; - private Multimap beanName2SpringValueDefinitions; - - public SpringValueProcessor() { - configUtil = ApolloInjector.getInstance(ConfigUtil.class); - placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class); - springValueRegistry = SpringInjector.getInstance(SpringValueRegistry.class); - beanName2SpringValueDefinitions = LinkedListMultimap.create(); - } - - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { - if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled() && beanFactory instanceof BeanDefinitionRegistry) { - beanName2SpringValueDefinitions = SpringValueDefinitionProcessor - .getBeanName2SpringValueDefinitions((BeanDefinitionRegistry) beanFactory); - } - } - - @Override - public Object postProcessBeforeInitialization(Object bean, String beanName) - throws BeansException { - if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) { - super.postProcessBeforeInitialization(bean, beanName); - processBeanPropertyValues(bean, beanName); - } - return bean; - } - - @Override - protected void processField(Object bean, String beanName, Field field) { - // register @Value on field - Value value = field.getAnnotation(Value.class); - if (value == null) { - return; - } - - doRegister(bean, beanName, field, value); - } - - @Override - protected void processMethod(Object bean, String beanName, Method method) { - //register @Value on method - Value value = method.getAnnotation(Value.class); - if (value == null) { - return; - } - //skip Configuration bean methods - if (method.getAnnotation(Bean.class) != null) { - return; - } - if (method.getParameterTypes().length != 1) { - logger.error("Ignore @Value setter {}.{}, expecting 1 parameter, actual {} parameters", - bean.getClass().getName(), method.getName(), method.getParameterTypes().length); - return; - } - - doRegister(bean, beanName, method, value); - } - - private void doRegister(Object bean, String beanName, Member member, Value value) { - Set keys = placeholderHelper.extractPlaceholderKeys(value.value()); - if (keys.isEmpty()) { - return; - } - - for (String key : keys) { - SpringValue springValue; - if (member instanceof Field) { - Field field = (Field) member; - springValue = new SpringValue(key, value.value(), bean, beanName, field, false); - } else if (member instanceof Method) { - Method method = (Method) member; - springValue = new SpringValue(key, value.value(), bean, beanName, method, false); - } else { - logger.error("Apollo @Value annotation currently only support to be used on methods and fields, " - + "but is used on {}", member.getClass()); - return; - } - springValueRegistry.register(beanFactory, key, springValue); - logger.info("Monitoring {}", springValue); - } - } - - private void processBeanPropertyValues(Object bean, String beanName) { - Collection propertySpringValues = beanName2SpringValueDefinitions - .get(beanName); - if (propertySpringValues == null || propertySpringValues.isEmpty()) { - return; - } - - for (SpringValueDefinition definition : propertySpringValues) { - try { - PropertyDescriptor pd = BeanUtils - .getPropertyDescriptor(bean.getClass(), definition.getPropertyName()); - Method method = pd.getWriteMethod(); - if (method == null) { - continue; - } - SpringValue springValue = new SpringValue(definition.getKey(), definition.getPlaceholder(), - bean, beanName, method, false); - springValueRegistry.register(beanFactory, definition.getKey(), springValue); - logger.debug("Monitoring {}", springValue); - } catch (Throwable ex) { - logger.error("Failed to enable auto update feature for {}.{}", bean.getClass(), - definition.getPropertyName()); - } - } - - // clear - beanName2SpringValueDefinitions.removeAll(beanName); - } - - @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { - this.beanFactory = beanFactory; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializer.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializer.java deleted file mode 100644 index fa37484fc64..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializer.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Copyright 2022 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.boot; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigService; -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.core.utils.DeferredLogger; -import com.ctrip.framework.apollo.spring.config.CachedCompositePropertySource; -import com.ctrip.framework.apollo.spring.config.ConfigPropertySourceFactory; -import com.ctrip.framework.apollo.spring.config.PropertySourcesConstants; -import com.ctrip.framework.apollo.spring.util.SpringInjector; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.base.Splitter; -import com.google.common.base.Strings; -import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.env.EnvironmentPostProcessor; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.Ordered; -import org.springframework.core.env.CompositePropertySource; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.StandardEnvironment; - -/** - * Initialize apollo system properties and inject the Apollo config in Spring Boot bootstrap phase - * - *

Configuration example:

- *
- *   # set app.id
- *   app.id = 100004458
- *   # enable apollo bootstrap config and inject 'application' namespace in bootstrap phase
- *   apollo.bootstrap.enabled = true
- * 
- * - * or - * - *
- *   # set app.id
- *   app.id = 100004458
- *   # enable apollo bootstrap config
- *   apollo.bootstrap.enabled = true
- *   # will inject 'application' and 'FX.apollo' namespaces in bootstrap phase
- *   apollo.bootstrap.namespaces = application,FX.apollo
- * 
- * - * - * If you want to load Apollo configurations even before Logging System Initialization Phase, - * add - *
- *   # set apollo.bootstrap.eagerLoad.enabled
- *   apollo.bootstrap.eagerLoad.enabled = true
- * 
- * - * This would be very helpful when your logging configurations is set by Apollo. - * - * for example, you have defined logback-spring.xml in your project, and you want to inject some attributes into logback-spring.xml. - * - */ -public class ApolloApplicationContextInitializer implements - ApplicationContextInitializer , EnvironmentPostProcessor, Ordered { - public static final int DEFAULT_ORDER = 0; - - private static final Logger logger = LoggerFactory.getLogger(ApolloApplicationContextInitializer.class); - private static final Splitter NAMESPACE_SPLITTER = Splitter.on(",").omitEmptyStrings() - .trimResults(); - public static final String[] APOLLO_SYSTEM_PROPERTIES = {ApolloClientSystemConsts.APP_ID, - ApolloClientSystemConsts.APOLLO_LABEL, - ApolloClientSystemConsts.APOLLO_CLUSTER, - ApolloClientSystemConsts.APOLLO_CACHE_DIR, - ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET, - ApolloClientSystemConsts.APOLLO_META, - ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE, - ApolloClientSystemConsts.APOLLO_PROPERTY_ORDER_ENABLE, - ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE, - ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES}; - - private final ConfigPropertySourceFactory configPropertySourceFactory = SpringInjector - .getInstance(ConfigPropertySourceFactory.class); - - private int order = DEFAULT_ORDER; - - @Override - public void initialize(ConfigurableApplicationContext context) { - ConfigurableEnvironment environment = context.getEnvironment(); - - if (!environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, Boolean.class, false)) { - logger.debug("Apollo bootstrap config is not enabled for context {}, see property: ${{}}", context, PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED); - return; - } - logger.debug("Apollo bootstrap config is enabled for context {}", context); - - initialize(environment); - } - - - /** - * Initialize Apollo Configurations Just after environment is ready. - * - * @param environment - */ - protected void initialize(ConfigurableEnvironment environment) { - - if (environment.getPropertySources().contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)) { - //already initialized, replay the logs that were printed before the logging system was initialized - DeferredLogger.replayTo(); - return; - } - - String namespaces = environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, ConfigConsts.NAMESPACE_APPLICATION); - logger.debug("Apollo bootstrap namespaces: {}", namespaces); - List namespaceList = NAMESPACE_SPLITTER.splitToList(namespaces); - - CompositePropertySource composite; - final ConfigUtil configUtil = ApolloInjector.getInstance(ConfigUtil.class); - if (configUtil.isPropertyNamesCacheEnabled()) { - composite = new CachedCompositePropertySource(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME); - } else { - composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME); - } - for (String namespace : namespaceList) { - Config config = ConfigService.getConfig(namespace); - - composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config)); - } - if (!configUtil.isOverrideSystemProperties()) { - if (environment.getPropertySources().contains(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { - environment.getPropertySources().addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, composite); - return; - } - } - environment.getPropertySources().addFirst(composite); - } - - /** - * To fill system properties from environment config - */ - void initializeSystemProperty(ConfigurableEnvironment environment) { - for (String propertyName : APOLLO_SYSTEM_PROPERTIES) { - fillSystemPropertyFromEnvironment(environment, propertyName); - } - } - - private void fillSystemPropertyFromEnvironment(ConfigurableEnvironment environment, String propertyName) { - if (System.getProperty(propertyName) != null) { - return; - } - - String propertyValue = environment.getProperty(propertyName); - - if (Strings.isNullOrEmpty(propertyValue)) { - return; - } - - System.setProperty(propertyName, propertyValue); - } - - /** - * - * In order to load Apollo configurations as early as even before Spring loading logging system phase, - * this EnvironmentPostProcessor can be called Just After ConfigFileApplicationListener has succeeded. - * - *
- * The processing sequence would be like this:
- * Load Bootstrap properties and application properties -----> load Apollo configuration properties ----> Initialize Logging systems - * - * @param configurableEnvironment - * @param springApplication - */ - @Override - public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) { - - // should always initialize system properties like app.id in the first place - initializeSystemProperty(configurableEnvironment); - - Boolean eagerLoadEnabled = configurableEnvironment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, Boolean.class, false); - - //EnvironmentPostProcessor should not be triggered if you don't want Apollo Loading before Logging System Initialization - if (!eagerLoadEnabled) { - return; - } - - Boolean bootstrapEnabled = configurableEnvironment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, Boolean.class, false); - - if (bootstrapEnabled) { - DeferredLogger.enable(); - initialize(configurableEnvironment); - } - - } - - /** - * @since 1.3.0 - */ - @Override - public int getOrder() { - return order; - } - - /** - * @since 1.3.0 - */ - public void setOrder(int order) { - this.order = order; - } - -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloAutoConfiguration.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloAutoConfiguration.java deleted file mode 100644 index f0f5a0202a7..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/boot/ApolloAutoConfiguration.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2022 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.boot; - -import com.ctrip.framework.apollo.spring.config.ConfigPropertySourcesProcessor; -import com.ctrip.framework.apollo.spring.config.PropertySourcesConstants; -import com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -@Configuration -@ConditionalOnProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED) -@ConditionalOnMissingBean(PropertySourcesProcessor.class) -public class ApolloAutoConfiguration { - - @Bean - public ConfigPropertySourcesProcessor configPropertySourcesProcessor() { - return new ConfigPropertySourcesProcessor(); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/CachedCompositePropertySource.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/CachedCompositePropertySource.java deleted file mode 100644 index fc44459cb6b..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/CachedCompositePropertySource.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2022 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.config; - -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import org.springframework.core.env.CompositePropertySource; -import org.springframework.core.env.PropertySource; - -/** - * @author Shawyeok (shawyeok@outlook.com) - */ -public class CachedCompositePropertySource extends CompositePropertySource implements - ConfigChangeListener { - - private volatile String[] names; - - public CachedCompositePropertySource(String name) { - super(name); - } - - @Override - public String[] getPropertyNames() { - String[] propertyNames = this.names; - if (propertyNames == null) { - this.names = propertyNames = super.getPropertyNames(); - } - return propertyNames; - } - - @Override - public void addPropertySource(PropertySource propertySource) { - super.addPropertySource(propertySource); - if (propertySource instanceof ConfigPropertySource) { - ((ConfigPropertySource) propertySource).addChangeListener(this); - } - } - - @Override - public void addFirstPropertySource(PropertySource propertySource) { - super.addFirstPropertySource(propertySource); - if (propertySource instanceof ConfigPropertySource) { - ((ConfigPropertySource) propertySource).addChangeListener(this); - } - } - - @Override - public void onChange(ConfigChangeEvent changeEvent) { - // clear property names cache if any sources has changed - this.names = null; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/ConfigPropertySource.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/ConfigPropertySource.java deleted file mode 100644 index f2e913ae9d9..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/ConfigPropertySource.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2022 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.config; - -import com.ctrip.framework.apollo.ConfigChangeListener; -import java.util.Set; - -import org.springframework.core.env.EnumerablePropertySource; - -import com.ctrip.framework.apollo.Config; - -/** - * Property source wrapper for Config - * - * @author Jason Song(song_s@ctrip.com) - */ -public class ConfigPropertySource extends EnumerablePropertySource { - private static final String[] EMPTY_ARRAY = new String[0]; - - ConfigPropertySource(String name, Config source) { - super(name, source); - } - - @Override - public boolean containsProperty(String name) { - return this.source.getProperty(name, null) != null; - } - - @Override - public String[] getPropertyNames() { - Set propertyNames = this.source.getPropertyNames(); - if (propertyNames.isEmpty()) { - return EMPTY_ARRAY; - } - return propertyNames.toArray(new String[propertyNames.size()]); - } - - @Override - public Object getProperty(String name) { - return this.source.getProperty(name, null); - } - - public void addChangeListener(ConfigChangeListener listener) { - this.source.addChangeListener(listener); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/ConfigPropertySourceFactory.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/ConfigPropertySourceFactory.java deleted file mode 100644 index 2e13152f52f..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/ConfigPropertySourceFactory.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2022 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.config; - -import java.util.List; - -import com.ctrip.framework.apollo.Config; -import com.google.common.collect.Lists; - -public class ConfigPropertySourceFactory { - - private final List configPropertySources = Lists.newLinkedList(); - - public ConfigPropertySource getConfigPropertySource(String name, Config source) { - ConfigPropertySource configPropertySource = new ConfigPropertySource(name, source); - - configPropertySources.add(configPropertySource); - - return configPropertySource; - } - - public List getAllConfigPropertySources() { - return Lists.newLinkedList(configPropertySources); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/ConfigPropertySourcesProcessor.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/ConfigPropertySourcesProcessor.java deleted file mode 100644 index 0ffce29b5c9..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/ConfigPropertySourcesProcessor.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2022 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.config; - -import com.ctrip.framework.apollo.spring.spi.ConfigPropertySourcesProcessorHelper; -import com.ctrip.framework.foundation.internals.ServiceBootstrap; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; - -/** - * Apollo Property Sources processor for Spring XML Based Application - * - * @author Jason Song(song_s@ctrip.com) - */ -public class ConfigPropertySourcesProcessor extends PropertySourcesProcessor - implements BeanDefinitionRegistryPostProcessor { - - private ConfigPropertySourcesProcessorHelper helper = ServiceBootstrap.loadPrimary(ConfigPropertySourcesProcessorHelper.class); - - @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { - helper.postProcessBeanDefinitionRegistry(registry); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/NamespaceHandler.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/NamespaceHandler.java deleted file mode 100644 index d82db9d913b..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/NamespaceHandler.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2022 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.config; - -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; -import org.springframework.beans.factory.xml.NamespaceHandlerSupport; -import org.springframework.core.Ordered; -import org.springframework.util.SystemPropertyUtils; -import org.w3c.dom.Element; - -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.google.common.base.Splitter; -import com.google.common.base.Strings; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class NamespaceHandler extends NamespaceHandlerSupport { - - private static final Splitter NAMESPACE_SPLITTER = Splitter.on(",").omitEmptyStrings() - .trimResults(); - - @Override - public void init() { - registerBeanDefinitionParser("config", new BeanParser()); - } - - static class BeanParser extends AbstractSingleBeanDefinitionParser { - - @Override - protected Class getBeanClass(Element element) { - return ConfigPropertySourcesProcessor.class; - } - - @Override - protected boolean shouldGenerateId() { - return true; - } - - private String resolveNamespaces(Element element) { - String namespaces = element.getAttribute("namespaces"); - if (Strings.isNullOrEmpty(namespaces)) { - //default to application - return ConfigConsts.NAMESPACE_APPLICATION; - } - return SystemPropertyUtils.resolvePlaceholders(namespaces); - } - - @Override - protected void doParse(Element element, BeanDefinitionBuilder builder) { - String namespaces = this.resolveNamespaces(element); - - int order = Ordered.LOWEST_PRECEDENCE; - String orderAttribute = element.getAttribute("order"); - - if (!Strings.isNullOrEmpty(orderAttribute)) { - try { - order = Integer.parseInt(orderAttribute); - } catch (Throwable ex) { - throw new IllegalArgumentException( - String.format("Invalid order: %s for namespaces: %s", orderAttribute, namespaces)); - } - } - PropertySourcesProcessor.addNamespaces(NAMESPACE_SPLITTER.splitToList(namespaces), order); - } - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/PropertySourcesConstants.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/PropertySourcesConstants.java deleted file mode 100644 index 05e0a11040b..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/PropertySourcesConstants.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2022 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.config; - -public interface PropertySourcesConstants { - String APOLLO_PROPERTY_SOURCE_NAME = "ApolloPropertySources"; - String APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME = "ApolloBootstrapPropertySources"; - String APOLLO_BOOTSTRAP_ENABLED = "apollo.bootstrap.enabled"; - String APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED = "apollo.bootstrap.eagerLoad.enabled"; - String APOLLO_BOOTSTRAP_NAMESPACES = "apollo.bootstrap.namespaces"; -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/PropertySourcesProcessor.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/PropertySourcesProcessor.java deleted file mode 100644 index 2e26a153c1c..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/PropertySourcesProcessor.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright 2022 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.config; - -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.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.spring.events.ApolloConfigChangeEvent; -import com.ctrip.framework.apollo.spring.util.SpringInjector; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.collect.ImmutableSortedSet; -import com.google.common.collect.LinkedHashMultimap; -import com.google.common.collect.Multimap; -import com.google.common.collect.Sets; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.context.ApplicationEventPublisherAware; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.Ordered; -import org.springframework.core.PriorityOrdered; -import org.springframework.core.env.*; - -/** - * Apollo Property Sources processor for Spring Annotation Based Application.

- * - * The reason why PropertySourcesProcessor implements {@link BeanFactoryPostProcessor} instead of - * {@link org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor} is that lower versions of - * Spring (e.g. 3.1.1) doesn't support registering BeanDefinitionRegistryPostProcessor in ImportBeanDefinitionRegistrar - * - {@link com.ctrip.framework.apollo.spring.annotation.ApolloConfigRegistrar} - * - * @author Jason Song(song_s@ctrip.com) - */ -public class PropertySourcesProcessor implements BeanFactoryPostProcessor, EnvironmentAware, - ApplicationEventPublisherAware, PriorityOrdered { - private static final Multimap NAMESPACE_NAMES = LinkedHashMultimap.create(); - private static final Set AUTO_UPDATE_INITIALIZED_BEAN_FACTORIES = Sets.newConcurrentHashSet(); - - private final ConfigPropertySourceFactory configPropertySourceFactory = SpringInjector - .getInstance(ConfigPropertySourceFactory.class); - private ConfigUtil configUtil; - private ConfigurableEnvironment environment; - private ApplicationEventPublisher applicationEventPublisher; - - public static boolean addNamespaces(Collection namespaces, int order) { - return NAMESPACE_NAMES.putAll(order, namespaces); - } - - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - this.configUtil = ApolloInjector.getInstance(ConfigUtil.class); - initializePropertySources(); - initializeAutoUpdatePropertiesFeature(beanFactory); - } - - private void initializePropertySources() { - if (environment.getPropertySources().contains(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME)) { - //already initialized - return; - } - CompositePropertySource composite; - if (configUtil.isPropertyNamesCacheEnabled()) { - composite = new CachedCompositePropertySource(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME); - } else { - composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME); - } - - //sort by order asc - ImmutableSortedSet orders = ImmutableSortedSet.copyOf(NAMESPACE_NAMES.keySet()); - Iterator iterator = orders.iterator(); - - while (iterator.hasNext()) { - int order = iterator.next(); - for (String namespace : NAMESPACE_NAMES.get(order)) { - Config config = ConfigService.getConfig(namespace); - - composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config)); - } - } - - // clean up - NAMESPACE_NAMES.clear(); - - // add after the bootstrap property source or to the first - if (environment.getPropertySources() - .contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)) { - - if (configUtil.isOverrideSystemProperties()) { - // ensure ApolloBootstrapPropertySources is still the first - ensureBootstrapPropertyPrecedence(environment); - } - - environment.getPropertySources() - .addAfter(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME, composite); - } else { - if (!configUtil.isOverrideSystemProperties()) { - if (environment.getPropertySources().contains(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)) { - environment.getPropertySources().addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, composite); - return; - } - } - environment.getPropertySources().addFirst(composite); - } - } - - private void ensureBootstrapPropertyPrecedence(ConfigurableEnvironment environment) { - MutablePropertySources propertySources = environment.getPropertySources(); - - PropertySource bootstrapPropertySource = propertySources - .get(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME); - - // not exists or already in the first place - if (bootstrapPropertySource == null || propertySources.precedenceOf(bootstrapPropertySource) == 0) { - return; - } - - propertySources.remove(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME); - propertySources.addFirst(bootstrapPropertySource); - } - - private void initializeAutoUpdatePropertiesFeature(ConfigurableListableBeanFactory beanFactory) { - if (!AUTO_UPDATE_INITIALIZED_BEAN_FACTORIES.add(beanFactory)) { - return; - } - - ConfigChangeListener configChangeEventPublisher = changeEvent -> - applicationEventPublisher.publishEvent(new ApolloConfigChangeEvent(changeEvent)); - - List configPropertySources = configPropertySourceFactory.getAllConfigPropertySources(); - for (ConfigPropertySource configPropertySource : configPropertySources) { - configPropertySource.addChangeListener(configChangeEventPublisher); - } - } - - @Override - public void setEnvironment(Environment environment) { - //it is safe enough to cast as all known environment is derived from ConfigurableEnvironment - this.environment = (ConfigurableEnvironment) environment; - } - - @Override - public int getOrder() { - //make it as early as possible - return Ordered.HIGHEST_PRECEDENCE; - } - - // for test only - static void reset() { - NAMESPACE_NAMES.clear(); - AUTO_UPDATE_INITIALIZED_BEAN_FACTORIES.clear(); - } - - @Override - public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { - this.applicationEventPublisher = applicationEventPublisher; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/events/ApolloConfigChangeEvent.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/events/ApolloConfigChangeEvent.java deleted file mode 100644 index fe465d486e2..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/events/ApolloConfigChangeEvent.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2022 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.events; - -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import org.springframework.context.ApplicationEvent; - -/** - * A Spring Application Event that is fired when Apollo config changes. - */ -public class ApolloConfigChangeEvent extends ApplicationEvent { - - public ApolloConfigChangeEvent(ConfigChangeEvent source) { - super(source); - } - - public ConfigChangeEvent getConfigChangeEvent() { - return (ConfigChangeEvent) getSource(); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/package-info.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/package-info.java deleted file mode 100644 index 7eb42bb996c..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/package-info.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2022 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. - * - */ -/** - * This package contains Apollo Spring integration codes and enables the following features:
- *

1. Support Spring XML based configuration

- *
    - *
  • <apollo:config namespaces="someNamespace"/> to inject configurations from Apollo into Spring Property - * Sources so that placeholders like ${someProperty} and @Value("someProperty") are supported.
  • - *
- *

2. Support Spring Java based configuration

- *
    - *
  • @EnableApolloConfig(namespaces={"someNamespace"}) to inject configurations from Apollo into Spring Property - * Sources so that placeholders like ${someProperty} and @Value("someProperty") are supported.
  • - *
- * - * With the above configuration, annotations like @ApolloConfig("someNamespace") - * and @ApolloConfigChangeListener("someNamespace) are also supported.
- *
- * Requires Spring 3.1.1+ - */ -package com.ctrip.framework.apollo.spring; \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/AutoUpdateConfigChangeListener.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/AutoUpdateConfigChangeListener.java deleted file mode 100644 index 05b5e98986a..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/AutoUpdateConfigChangeListener.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright 2022 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.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import com.ctrip.framework.apollo.spring.events.ApolloConfigChangeEvent; -import com.ctrip.framework.apollo.spring.util.SpringInjector; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.gson.Gson; -import java.lang.reflect.Field; -import java.lang.reflect.Type; -import java.util.Collection; -import java.util.Set; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeansException; -import org.springframework.beans.TypeConverter; -import org.springframework.beans.factory.config.ConfigurableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.ApplicationListener; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.util.CollectionUtils; - -/** - * Create by zhangzheng on 2018/3/6 - */ -public class AutoUpdateConfigChangeListener implements ConfigChangeListener, - ApplicationListener, ApplicationContextAware { - - private static final Logger logger = LoggerFactory.getLogger( - AutoUpdateConfigChangeListener.class); - - private final boolean typeConverterHasConvertIfNecessaryWithFieldParameter; - private ConfigurableBeanFactory beanFactory; - private TypeConverter typeConverter; - private final PlaceholderHelper placeholderHelper; - private final SpringValueRegistry springValueRegistry; - private final Gson gson; - private final ConfigUtil configUtil; - - public AutoUpdateConfigChangeListener() { - this.typeConverterHasConvertIfNecessaryWithFieldParameter = testTypeConverterHasConvertIfNecessaryWithFieldParameter(); - this.placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class); - this.springValueRegistry = SpringInjector.getInstance(SpringValueRegistry.class); - this.gson = new Gson(); - this.configUtil = ApolloInjector.getInstance(ConfigUtil.class); - } - - @Override - public void onChange(ConfigChangeEvent changeEvent) { - Set keys = changeEvent.changedKeys(); - if (CollectionUtils.isEmpty(keys)) { - return; - } - for (String key : keys) { - // 1. check whether the changed key is relevant - Collection targetValues = springValueRegistry.get(beanFactory, key); - if (targetValues == null || targetValues.isEmpty()) { - continue; - } - - // 2. update the value - for (SpringValue val : targetValues) { - updateSpringValue(val); - } - } - } - - private void updateSpringValue(SpringValue springValue) { - try { - Object value = resolvePropertyValue(springValue); - springValue.update(value); - - logger.info("Auto update apollo changed value successfully, new value: {}, {}", value, - springValue); - } catch (Throwable ex) { - logger.error("Auto update apollo changed value failed, {}", springValue.toString(), ex); - } - } - - /** - * Logic transplanted from DefaultListableBeanFactory - * - * @see org.springframework.beans.factory.support.DefaultListableBeanFactory#doResolveDependency(org.springframework.beans.factory.config.DependencyDescriptor, - * java.lang.String, java.util.Set, org.springframework.beans.TypeConverter) - */ - private Object resolvePropertyValue(SpringValue springValue) { - // value will never be null, as @Value and @ApolloJsonValue will not allow that - Object value = placeholderHelper - .resolvePropertyValue(beanFactory, springValue.getBeanName(), springValue.getPlaceholder()); - - if (springValue.isJson()) { - value = parseJsonValue((String) value, springValue.getGenericType()); - } else { - if (springValue.isField()) { - // org.springframework.beans.TypeConverter#convertIfNecessary(java.lang.Object, java.lang.Class, java.lang.reflect.Field) is available from Spring 3.2.0+ - if (typeConverterHasConvertIfNecessaryWithFieldParameter) { - value = this.typeConverter - .convertIfNecessary(value, springValue.getTargetType(), springValue.getField()); - } else { - value = this.typeConverter.convertIfNecessary(value, springValue.getTargetType()); - } - } else { - value = this.typeConverter.convertIfNecessary(value, springValue.getTargetType(), - springValue.getMethodParameter()); - } - } - - return value; - } - - private Object parseJsonValue(String json, Type targetType) { - try { - return gson.fromJson(json, targetType); - } catch (Throwable ex) { - logger.error("Parsing json '{}' to type {} failed!", json, targetType, ex); - throw ex; - } - } - - private boolean testTypeConverterHasConvertIfNecessaryWithFieldParameter() { - try { - TypeConverter.class.getMethod("convertIfNecessary", Object.class, Class.class, Field.class); - } catch (Throwable ex) { - return false; - } - - return true; - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - //it is safe enough to cast as all known application context is derived from ConfigurableApplicationContext - this.beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory(); - this.typeConverter = this.beanFactory.getTypeConverter(); - } - - @Override - public void onApplicationEvent(ApolloConfigChangeEvent event) { - if (!configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) { - return; - } - this.onChange(event.getConfigChangeEvent()); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/PlaceholderHelper.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/PlaceholderHelper.java deleted file mode 100644 index 761e08a0030..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/PlaceholderHelper.java +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright 2022 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. - *
- *
- * "${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. - *
    - *
  • ${some.key} => "some.key"
  • - *
  • ${some.key:${some.other.key:100}} => "some.key", "some.other.key"
  • - *
  • ${${some.key}} => "some.key"
  • - *
  • ${${some.key:other.key}} => "some.key"
  • - *
  • ${${some.key}:${another.key}} => "some.key", "another.key"
  • - *
  • #{new java.text.SimpleDateFormat('${some.key}').parse('${another.key}')} => "some.key", "another.key"
  • - *
- */ - public Set extractPlaceholderKeys(String propertyString) { - Set placeholderKeys = Sets.newHashSet(); - - if (Strings.isNullOrEmpty(propertyString) || (!isNormalizedPlaceholder(propertyString) && !isExpressionWithPlaceholder(propertyString))) { - return placeholderKeys; - } - - Stack 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; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/SpringValue.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/SpringValue.java deleted file mode 100644 index 159d3b554b1..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/SpringValue.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright 2022 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 java.lang.ref.WeakReference; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import org.springframework.core.MethodParameter; - -/** - * Spring @Value method info - * - * @author github.com/zhegexiaohuozi seimimaster@gmail.com - * @since 2018/2/6. - */ -public class SpringValue { - - private MethodParameter methodParameter; - private Field field; - private WeakReference beanRef; - private String beanName; - private String key; - private String placeholder; - private Class targetType; - private Type genericType; - private boolean isJson; - - public SpringValue(String key, String placeholder, Object bean, String beanName, Field field, boolean isJson) { - this.beanRef = new WeakReference<>(bean); - this.beanName = beanName; - this.field = field; - this.key = key; - this.placeholder = placeholder; - this.targetType = field.getType(); - this.isJson = isJson; - if(isJson){ - this.genericType = field.getGenericType(); - } - } - - public SpringValue(String key, String placeholder, Object bean, String beanName, Method method, boolean isJson) { - this.beanRef = new WeakReference<>(bean); - this.beanName = beanName; - this.methodParameter = new MethodParameter(method, 0); - this.key = key; - this.placeholder = placeholder; - Class[] paramTps = method.getParameterTypes(); - this.targetType = paramTps[0]; - this.isJson = isJson; - if(isJson){ - this.genericType = method.getGenericParameterTypes()[0]; - } - } - - public void update(Object newVal) throws IllegalAccessException, InvocationTargetException { - if (isField()) { - injectField(newVal); - } else { - injectMethod(newVal); - } - } - - private void injectField(Object newVal) throws IllegalAccessException { - Object bean = beanRef.get(); - if (bean == null) { - return; - } - boolean accessible = field.isAccessible(); - field.setAccessible(true); - field.set(bean, newVal); - field.setAccessible(accessible); - } - - private void injectMethod(Object newVal) - throws InvocationTargetException, IllegalAccessException { - Object bean = beanRef.get(); - if (bean == null) { - return; - } - methodParameter.getMethod().invoke(bean, newVal); - } - - public String getBeanName() { - return beanName; - } - - public Class getTargetType() { - return targetType; - } - - public String getPlaceholder() { - return this.placeholder; - } - - public MethodParameter getMethodParameter() { - return methodParameter; - } - - public boolean isField() { - return this.field != null; - } - - public Field getField() { - return field; - } - - public Type getGenericType() { - return genericType; - } - - public boolean isJson() { - return isJson; - } - - boolean isTargetBeanValid() { - return beanRef.get() != null; - } - - @Override - public String toString() { - Object bean = beanRef.get(); - if (bean == null) { - return ""; - } - if (isField()) { - return String - .format("key: %s, beanName: %s, field: %s.%s", key, beanName, bean.getClass().getName(), field.getName()); - } - return String.format("key: %s, beanName: %s, method: %s.%s", key, beanName, bean.getClass().getName(), - methodParameter.getMethod().getName()); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/SpringValueDefinition.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/SpringValueDefinition.java deleted file mode 100644 index 59a089b6a8b..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/SpringValueDefinition.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2022 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; - -public class SpringValueDefinition { - - private final String key; - private final String placeholder; - private final String propertyName; - - public SpringValueDefinition(String key, String placeholder, String propertyName) { - this.key = key; - this.placeholder = placeholder; - this.propertyName = propertyName; - } - - public String getKey() { - return key; - } - - public String getPlaceholder() { - return placeholder; - } - - public String getPropertyName() { - return propertyName; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/SpringValueDefinitionProcessor.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/SpringValueDefinitionProcessor.java deleted file mode 100644 index 92701e2981b..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/SpringValueDefinitionProcessor.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright 2022 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.ctrip.framework.apollo.spring.util.SpringInjector; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.springframework.beans.BeansException; -import org.springframework.beans.MutablePropertyValues; -import org.springframework.beans.PropertyValue; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.beans.factory.config.TypedStringValue; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor; - -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.collect.LinkedListMultimap; -import com.google.common.collect.Multimap; - -/** - * To process xml config placeholders, e.g. - * - *
- *  <bean class="com.ctrip.framework.apollo.demo.spring.xmlConfigDemo.bean.XmlBean">
- *    <property name="timeout" value="${timeout:200}"/>
- *    <property name="batch" value="${batch:100}"/>
- *  </bean>
- * 
- */ -public class SpringValueDefinitionProcessor implements BeanDefinitionRegistryPostProcessor { - private static final Map> beanName2SpringValueDefinitions = - Maps.newConcurrentMap(); - private static final Set PROPERTY_VALUES_PROCESSED_BEAN_FACTORIES = Sets.newConcurrentHashSet(); - - private final ConfigUtil configUtil; - private final PlaceholderHelper placeholderHelper; - - public SpringValueDefinitionProcessor() { - configUtil = ApolloInjector.getInstance(ConfigUtil.class); - placeholderHelper = SpringInjector.getInstance(PlaceholderHelper.class); - } - - @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { - if (configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()) { - processPropertyValues(registry); - } - } - - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { - - } - - public static Multimap getBeanName2SpringValueDefinitions(BeanDefinitionRegistry registry) { - Multimap springValueDefinitions = beanName2SpringValueDefinitions.get(registry); - if (springValueDefinitions == null) { - springValueDefinitions = LinkedListMultimap.create(); - } - - return springValueDefinitions; - } - - private void processPropertyValues(BeanDefinitionRegistry beanRegistry) { - if (!PROPERTY_VALUES_PROCESSED_BEAN_FACTORIES.add(beanRegistry)) { - // already initialized - return; - } - - if (!beanName2SpringValueDefinitions.containsKey(beanRegistry)) { - beanName2SpringValueDefinitions.put(beanRegistry, LinkedListMultimap.create()); - } - - Multimap springValueDefinitions = beanName2SpringValueDefinitions.get(beanRegistry); - - String[] beanNames = beanRegistry.getBeanDefinitionNames(); - for (String beanName : beanNames) { - BeanDefinition beanDefinition = beanRegistry.getBeanDefinition(beanName); - MutablePropertyValues mutablePropertyValues = beanDefinition.getPropertyValues(); - List propertyValues = mutablePropertyValues.getPropertyValueList(); - for (PropertyValue propertyValue : propertyValues) { - Object value = propertyValue.getValue(); - if (!(value instanceof TypedStringValue)) { - continue; - } - String placeholder = ((TypedStringValue) value).getValue(); - Set keys = placeholderHelper.extractPlaceholderKeys(placeholder); - - if (keys.isEmpty()) { - continue; - } - - for (String key : keys) { - springValueDefinitions.put(beanName, new SpringValueDefinition(key, placeholder, propertyValue.getName())); - } - } - } - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/SpringValueRegistry.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/SpringValueRegistry.java deleted file mode 100644 index 2600960ece1..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/property/SpringValueRegistry.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2022 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.ctrip.framework.apollo.core.utils.ApolloThreadFactory; -import com.google.common.collect.LinkedListMultimap; -import com.google.common.collect.Maps; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multimaps; -import java.util.Collection; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.BeanFactory; - -public class SpringValueRegistry { - private static final Logger logger = LoggerFactory.getLogger(SpringValueRegistry.class); - - private static final long CLEAN_INTERVAL_IN_SECONDS = 5; - private final Map> registry = Maps.newConcurrentMap(); - private final AtomicBoolean initialized = new AtomicBoolean(false); - private final Object LOCK = new Object(); - - public void register(BeanFactory beanFactory, String key, SpringValue springValue) { - if (!registry.containsKey(beanFactory)) { - synchronized (LOCK) { - if (!registry.containsKey(beanFactory)) { - registry.put(beanFactory, Multimaps.synchronizedListMultimap(LinkedListMultimap.create())); - } - } - } - - registry.get(beanFactory).put(key, springValue); - - // lazy initialize - if (initialized.compareAndSet(false, true)) { - initialize(); - } - } - - public Collection get(BeanFactory beanFactory, String key) { - Multimap beanFactorySpringValues = registry.get(beanFactory); - if (beanFactorySpringValues == null) { - return null; - } - return beanFactorySpringValues.get(key); - } - - private void initialize() { - Executors.newSingleThreadScheduledExecutor(ApolloThreadFactory.create("SpringValueRegistry", true)).scheduleAtFixedRate( - new Runnable() { - @Override - public void run() { - try { - scanAndClean(); - } catch (Throwable ex) { - logger.error(ex.getMessage(), ex); - } - } - }, CLEAN_INTERVAL_IN_SECONDS, CLEAN_INTERVAL_IN_SECONDS, TimeUnit.SECONDS); - } - - private void scanAndClean() { - Iterator> iterator = registry.values().iterator(); - while (!Thread.currentThread().isInterrupted() && iterator.hasNext()) { - Multimap springValues = iterator.next(); - Iterator> springValueIterator = springValues.entries().iterator(); - while (springValueIterator.hasNext()) { - Entry springValue = springValueIterator.next(); - if (!springValue.getValue().isTargetBeanValid()) { - // clear unused spring values - springValueIterator.remove(); - } - } - } - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/ApolloConfigRegistrarHelper.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/ApolloConfigRegistrarHelper.java deleted file mode 100644 index 826e73bcdab..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/ApolloConfigRegistrarHelper.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import com.ctrip.framework.apollo.core.spi.Ordered; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.EnvironmentAware; -import org.springframework.core.type.AnnotationMetadata; - -public interface ApolloConfigRegistrarHelper extends Ordered, EnvironmentAware { - - void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/ConfigPropertySourcesProcessorHelper.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/ConfigPropertySourcesProcessorHelper.java deleted file mode 100644 index 90d7075fb3a..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/ConfigPropertySourcesProcessorHelper.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import com.ctrip.framework.apollo.core.spi.Ordered; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; - -public interface ConfigPropertySourcesProcessorHelper extends Ordered { - - void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException; -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/DefaultApolloConfigRegistrarHelper.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/DefaultApolloConfigRegistrarHelper.java deleted file mode 100644 index 8bd2b7610ef..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/DefaultApolloConfigRegistrarHelper.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import com.ctrip.framework.apollo.core.spi.Ordered; -import com.ctrip.framework.apollo.spring.annotation.ApolloAnnotationProcessor; -import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; -import com.ctrip.framework.apollo.spring.annotation.SpringValueProcessor; -import com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor; -import com.ctrip.framework.apollo.spring.property.AutoUpdateConfigChangeListener; -import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor; -import com.ctrip.framework.apollo.spring.util.BeanRegistrationUtil; -import com.google.common.collect.Lists; -import java.util.HashMap; -import java.util.Map; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; -import org.springframework.core.annotation.AnnotationAttributes; -import org.springframework.core.env.Environment; -import org.springframework.core.type.AnnotationMetadata; - -public class DefaultApolloConfigRegistrarHelper implements ApolloConfigRegistrarHelper { - private static final Logger logger = LoggerFactory.getLogger( - DefaultApolloConfigRegistrarHelper.class); - - private Environment environment; - - @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { - AnnotationAttributes attributes = AnnotationAttributes - .fromMap(importingClassMetadata.getAnnotationAttributes(EnableApolloConfig.class.getName())); - final String[] namespaces = attributes.getStringArray("value"); - final int order = attributes.getNumber("order"); - final String[] resolvedNamespaces = this.resolveNamespaces(namespaces); - PropertySourcesProcessor.addNamespaces(Lists.newArrayList(resolvedNamespaces), order); - - Map propertySourcesPlaceholderPropertyValues = new HashMap<>(); - // to make sure the default PropertySourcesPlaceholderConfigurer's priority is higher than PropertyPlaceholderConfigurer - propertySourcesPlaceholderPropertyValues.put("order", 0); - - BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class, - propertySourcesPlaceholderPropertyValues); - BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, AutoUpdateConfigChangeListener.class); - BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesProcessor.class); - BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloAnnotationProcessor.class); - BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueProcessor.class); - BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueDefinitionProcessor.class); - } - - private String[] resolveNamespaces(String[] namespaces) { - // no support for Spring version prior to 3.2.x, see https://github.com/apolloconfig/apollo/issues/4178 - if (this.environment == null) { - logNamespacePlaceholderNotSupportedMessage(namespaces); - return namespaces; - } - String[] resolvedNamespaces = new String[namespaces.length]; - for (int i = 0; i < namespaces.length; i++) { - // throw IllegalArgumentException if given text is null or if any placeholders are unresolvable - resolvedNamespaces[i] = this.environment.resolveRequiredPlaceholders(namespaces[i]); - } - return resolvedNamespaces; - } - - private void logNamespacePlaceholderNotSupportedMessage(String[] namespaces) { - for (String namespace : namespaces) { - if (namespace.contains("${")) { - logger.warn("Namespace placeholder {} is not supported for Spring version prior to 3.2.x," - + " see https://github.com/apolloconfig/apollo/issues/4178 for more details.", - namespace); - break; - } - } - } - - @Override - public int getOrder() { - return Ordered.LOWEST_PRECEDENCE; - } - - @Override - public void setEnvironment(Environment environment) { - this.environment = environment; - } -} \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/DefaultConfigPropertySourcesProcessorHelper.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/DefaultConfigPropertySourcesProcessorHelper.java deleted file mode 100644 index 51dc7697cf9..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/spi/DefaultConfigPropertySourcesProcessorHelper.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import com.ctrip.framework.apollo.core.spi.Ordered; -import com.ctrip.framework.apollo.spring.annotation.ApolloAnnotationProcessor; -import com.ctrip.framework.apollo.spring.annotation.SpringValueProcessor; -import com.ctrip.framework.apollo.spring.property.AutoUpdateConfigChangeListener; -import com.ctrip.framework.apollo.spring.property.SpringValueDefinitionProcessor; -import com.ctrip.framework.apollo.spring.util.BeanRegistrationUtil; -import java.util.HashMap; -import java.util.Map; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; - -public class DefaultConfigPropertySourcesProcessorHelper implements ConfigPropertySourcesProcessorHelper { - - @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { - Map propertySourcesPlaceholderPropertyValues = new HashMap<>(); - // to make sure the default PropertySourcesPlaceholderConfigurer's priority is higher than PropertyPlaceholderConfigurer - propertySourcesPlaceholderPropertyValues.put("order", 0); - - BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, PropertySourcesPlaceholderConfigurer.class, - propertySourcesPlaceholderPropertyValues); - BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, AutoUpdateConfigChangeListener.class); - BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, ApolloAnnotationProcessor.class); - BeanRegistrationUtil.registerBeanDefinitionIfNotExists(registry, SpringValueProcessor.class); - - processSpringValueDefinition(registry); - } - - /** - * For Spring 3.x versions, the BeanDefinitionRegistryPostProcessor would not be instantiated if - * it is added in postProcessBeanDefinitionRegistry phase, so we have to manually call the - * postProcessBeanDefinitionRegistry method of SpringValueDefinitionProcessor here... - */ - private void processSpringValueDefinition(BeanDefinitionRegistry registry) { - SpringValueDefinitionProcessor springValueDefinitionProcessor = new SpringValueDefinitionProcessor(); - - springValueDefinitionProcessor.postProcessBeanDefinitionRegistry(registry); - } - - @Override - public int getOrder() { - return Ordered.LOWEST_PRECEDENCE; - } -} \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/util/BeanRegistrationUtil.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/util/BeanRegistrationUtil.java deleted file mode 100644 index 46044957def..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/util/BeanRegistrationUtil.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2022 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.util; - -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; - -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.core.type.MethodMetadata; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class BeanRegistrationUtil { - // reserved bean definitions, we should consider drop this if we will upgrade Spring version - private static final Map RESERVED_BEAN_DEFINITIONS = new ConcurrentHashMap<>(); - - static { - RESERVED_BEAN_DEFINITIONS.put( - "org.springframework.context.support.PropertySourcesPlaceholderConfigurer", - "org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration#propertySourcesPlaceholderConfigurer" - ); - } - - public static boolean registerBeanDefinitionIfNotExists(BeanDefinitionRegistry registry, Class beanClass) { - return registerBeanDefinitionIfNotExists(registry, beanClass, null); - } - - public static boolean registerBeanDefinitionIfNotExists(BeanDefinitionRegistry registry, Class beanClass, - Map extraPropertyValues) { - return registerBeanDefinitionIfNotExists(registry, beanClass.getName(), beanClass, extraPropertyValues); - } - - public static boolean registerBeanDefinitionIfNotExists(BeanDefinitionRegistry registry, String beanName, - Class beanClass) { - return registerBeanDefinitionIfNotExists(registry, beanName, beanClass, null); - } - - public static boolean registerBeanDefinitionIfNotExists(BeanDefinitionRegistry registry, String beanName, - Class beanClass, Map extraPropertyValues) { - if (registry.containsBeanDefinition(beanName)) { - return false; - } - - String[] candidates = registry.getBeanDefinitionNames(); - - String reservedBeanDefinition = RESERVED_BEAN_DEFINITIONS.get(beanClass.getName()); - for (String candidate : candidates) { - BeanDefinition beanDefinition = registry.getBeanDefinition(candidate); - if (Objects.equals(beanDefinition.getBeanClassName(), beanClass.getName())) { - return false; - } - - if (reservedBeanDefinition != null && beanDefinition.getSource() != null && beanDefinition.getSource() instanceof MethodMetadata) { - MethodMetadata metadata = (MethodMetadata) beanDefinition.getSource(); - if (Objects.equals(reservedBeanDefinition, String.format("%s#%s", metadata.getDeclaringClassName(), metadata.getMethodName()))) { - return false; - } - } - } - - BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(beanClass).getBeanDefinition(); - - if (extraPropertyValues != null) { - for (Map.Entry entry : extraPropertyValues.entrySet()) { - beanDefinition.getPropertyValues().add(entry.getKey(), entry.getValue()); - } - } - - registry.registerBeanDefinition(beanName, beanDefinition); - - return true; - } - -} \ No newline at end of file diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/util/SpringInjector.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/util/SpringInjector.java deleted file mode 100644 index 098a01bd676..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/util/SpringInjector.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2022 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.util; - -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.spring.config.ConfigPropertySourceFactory; -import com.ctrip.framework.apollo.spring.property.PlaceholderHelper; -import com.ctrip.framework.apollo.spring.property.SpringValueRegistry; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.google.inject.AbstractModule; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Singleton; - -public class SpringInjector { - private static volatile Injector s_injector; - private static final Object lock = new Object(); - - private static Injector getInjector() { - if (s_injector == null) { - synchronized (lock) { - if (s_injector == null) { - try { - s_injector = Guice.createInjector(new SpringModule()); - } catch (Throwable ex) { - ApolloConfigException exception = new ApolloConfigException("Unable to initialize Apollo Spring Injector!", ex); - Tracer.logError(exception); - throw exception; - } - } - } - } - - return s_injector; - } - - public static T getInstance(Class clazz) { - try { - return getInjector().getInstance(clazz); - } catch (Throwable ex) { - Tracer.logError(ex); - throw new ApolloConfigException( - String.format("Unable to load instance for %s!", clazz.getName()), ex); - } - } - - private static class SpringModule extends AbstractModule { - @Override - protected void configure() { - bind(PlaceholderHelper.class).in(Singleton.class); - bind(ConfigPropertySourceFactory.class).in(Singleton.class); - bind(SpringValueRegistry.class).in(Singleton.class); - } - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java deleted file mode 100644 index 8f9407d94e2..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ConfigUtil.java +++ /dev/null @@ -1,461 +0,0 @@ -/* - * Copyright 2022 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.util; - -import static com.ctrip.framework.apollo.util.factory.PropertiesFactory.APOLLO_PROPERTY_ORDER_ENABLE; - -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.core.MetaDomainConsts; -import com.ctrip.framework.apollo.core.enums.Env; -import com.ctrip.framework.apollo.core.enums.EnvUtils; -import com.ctrip.framework.apollo.core.utils.DeprecatedPropertyNotifyUtil; -import com.ctrip.framework.foundation.Foundation; -import com.google.common.base.Strings; -import com.google.common.util.concurrent.RateLimiter; -import java.io.File; -import java.util.concurrent.TimeUnit; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ConfigUtil { - - private static final Logger logger = LoggerFactory.getLogger(ConfigUtil.class); - private int refreshInterval = 5; - private TimeUnit refreshIntervalTimeUnit = TimeUnit.MINUTES; - private int connectTimeout = 1000; //1 second - private int readTimeout = 5000; //5 seconds - private String cluster; - private int loadConfigQPS = 2; //2 times per second - private int longPollQPS = 2; //2 times per second - //for on error retry - private long onErrorRetryInterval = 1;//1 second - private TimeUnit onErrorRetryIntervalTimeUnit = TimeUnit.SECONDS;//1 second - //for typed config cache of parser result, e.g. integer, double, long, etc. - private long maxConfigCacheSize = 500;//500 cache key - private long configCacheExpireTime = 1;//1 minute - private TimeUnit configCacheExpireTimeUnit = TimeUnit.MINUTES;//1 minute - private long longPollingInitialDelayInMills = 2000;//2 seconds - private boolean autoUpdateInjectedSpringProperties = true; - private final RateLimiter warnLogRateLimiter; - private boolean propertiesOrdered = false; - private boolean propertyNamesCacheEnabled = false; - private boolean propertyFileCacheEnabled = true; - private boolean overrideSystemProperties = true; - - public ConfigUtil() { - warnLogRateLimiter = RateLimiter.create(0.017); // 1 warning log output per minute - initRefreshInterval(); - initConnectTimeout(); - initReadTimeout(); - initCluster(); - initQPS(); - initMaxConfigCacheSize(); - initLongPollingInitialDelayInMills(); - initAutoUpdateInjectedSpringProperties(); - initPropertiesOrdered(); - initPropertyNamesCacheEnabled(); - initPropertyFileCacheEnabled(); - initOverrideSystemProperties(); - } - - /** - * Get the app id for the current application. - * - * @return the app id or ConfigConsts.NO_APPID_PLACEHOLDER if app id is not available - */ - public String getAppId() { - String appId = Foundation.app().getAppId(); - if (Strings.isNullOrEmpty(appId)) { - appId = ConfigConsts.NO_APPID_PLACEHOLDER; - if (warnLogRateLimiter.tryAcquire()) { - logger.warn( - "app.id is not set, please make sure it is set in classpath:/META-INF/app.properties, now apollo will only load public namespace configurations!"); - } - } - return appId; - } - - /** - * Get the apollo label for the current application. - * - * @return apollo Label - */ - public String getApolloLabel() { - return Foundation.app().getApolloLabel(); - } - - /** - * Get the access key secret for the current application. - * - * @return the current access key secret, null if there is no such secret. - */ - public String getAccessKeySecret() { - return Foundation.app().getAccessKeySecret(); - } - - /** - * Get the data center info for the current application. - * - * @return the current data center, null if there is no such info. - */ - public String getDataCenter() { - return Foundation.server().getDataCenter(); - } - - private void initCluster() { - //Load data center from system property - cluster = System.getProperty(ConfigConsts.APOLLO_CLUSTER_KEY); - - //Use data center as cluster - if (Strings.isNullOrEmpty(cluster)) { - cluster = getDataCenter(); - } - - //Use default cluster - if (Strings.isNullOrEmpty(cluster)) { - cluster = ConfigConsts.CLUSTER_NAME_DEFAULT; - } - } - - /** - * Get the cluster name for the current application. - * - * @return the cluster name, or "default" if not specified - */ - public String getCluster() { - return cluster; - } - - /** - * Get the current environment. - * - * @return the env, UNKNOWN if env is not set or invalid - */ - public Env getApolloEnv() { - return EnvUtils.transformEnv(Foundation.server().getEnvType()); - } - - public String getLocalIp() { - return Foundation.net().getHostAddress(); - } - - public String getMetaServerDomainName() { - return MetaDomainConsts.getDomain(getApolloEnv()); - } - - private void initConnectTimeout() { - String customizedConnectTimeout = System.getProperty("apollo.connectTimeout"); - if (!Strings.isNullOrEmpty(customizedConnectTimeout)) { - try { - connectTimeout = Integer.parseInt(customizedConnectTimeout); - } catch (Throwable ex) { - logger.error("Config for apollo.connectTimeout is invalid: {}", customizedConnectTimeout); - } - } - } - - public int getConnectTimeout() { - return connectTimeout; - } - - private void initReadTimeout() { - String customizedReadTimeout = System.getProperty("apollo.readTimeout"); - if (!Strings.isNullOrEmpty(customizedReadTimeout)) { - try { - readTimeout = Integer.parseInt(customizedReadTimeout); - } catch (Throwable ex) { - logger.error("Config for apollo.readTimeout is invalid: {}", customizedReadTimeout); - } - } - } - - public int getReadTimeout() { - return readTimeout; - } - - private void initRefreshInterval() { - String customizedRefreshInterval = System.getProperty("apollo.refreshInterval"); - if (!Strings.isNullOrEmpty(customizedRefreshInterval)) { - try { - refreshInterval = Integer.parseInt(customizedRefreshInterval); - } catch (Throwable ex) { - logger.error("Config for apollo.refreshInterval is invalid: {}", customizedRefreshInterval); - } - } - } - - public int getRefreshInterval() { - return refreshInterval; - } - - public TimeUnit getRefreshIntervalTimeUnit() { - return refreshIntervalTimeUnit; - } - - private void initQPS() { - String customizedLoadConfigQPS = System.getProperty("apollo.loadConfigQPS"); - if (!Strings.isNullOrEmpty(customizedLoadConfigQPS)) { - try { - loadConfigQPS = Integer.parseInt(customizedLoadConfigQPS); - } catch (Throwable ex) { - logger.error("Config for apollo.loadConfigQPS is invalid: {}", customizedLoadConfigQPS); - } - } - - String customizedLongPollQPS = System.getProperty("apollo.longPollQPS"); - if (!Strings.isNullOrEmpty(customizedLongPollQPS)) { - try { - longPollQPS = Integer.parseInt(customizedLongPollQPS); - } catch (Throwable ex) { - logger.error("Config for apollo.longPollQPS is invalid: {}", customizedLongPollQPS); - } - } - } - - public int getLoadConfigQPS() { - return loadConfigQPS; - } - - public int getLongPollQPS() { - return longPollQPS; - } - - public long getOnErrorRetryInterval() { - return onErrorRetryInterval; - } - - public TimeUnit getOnErrorRetryIntervalTimeUnit() { - return onErrorRetryIntervalTimeUnit; - } - - public String getDefaultLocalCacheDir() { - String cacheRoot = getCustomizedCacheRoot(); - - if (!Strings.isNullOrEmpty(cacheRoot)) { - return cacheRoot + File.separator + getAppId(); - } - - cacheRoot = isOSWindows() ? "C:\\opt\\data\\%s" : "/opt/data/%s"; - return String.format(cacheRoot, getAppId()); - } - - private String getCustomizedCacheRoot() { - // 1. Get from System Property - String cacheRoot = System.getProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR); - if (Strings.isNullOrEmpty(cacheRoot)) { - // 2. Get from OS environment variable - cacheRoot = System.getenv(ApolloClientSystemConsts.APOLLO_CACHE_DIR_ENVIRONMENT_VARIABLES); - } - if (Strings.isNullOrEmpty(cacheRoot)) { - // 3. Get from server.properties - cacheRoot = Foundation.server().getProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR, null); - } - if (Strings.isNullOrEmpty(cacheRoot)) { - // 4. Get from app.properties - cacheRoot = Foundation.app().getProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR, null); - } - if (Strings.isNullOrEmpty(cacheRoot)) { - // 5. Get from deprecated config - cacheRoot = getDeprecatedCustomizedCacheRoot(); - } - return cacheRoot; - } - - @SuppressWarnings("deprecation") - private String getDeprecatedCustomizedCacheRoot() { - // 1. Get from System Property - String cacheRoot = System.getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR); - if (!Strings.isNullOrEmpty(cacheRoot)) { - DeprecatedPropertyNotifyUtil.warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, - ApolloClientSystemConsts.APOLLO_CACHE_DIR); - } - if (Strings.isNullOrEmpty(cacheRoot)) { - // 2. Get from OS environment variable - cacheRoot = System.getenv(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR_ENVIRONMENT_VARIABLES); - if (!Strings.isNullOrEmpty(cacheRoot)) { - DeprecatedPropertyNotifyUtil - .warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR_ENVIRONMENT_VARIABLES, - ApolloClientSystemConsts.APOLLO_CACHE_DIR_ENVIRONMENT_VARIABLES); - } - } - if (Strings.isNullOrEmpty(cacheRoot)) { - // 3. Get from server.properties - cacheRoot = Foundation.server().getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, null); - if (!Strings.isNullOrEmpty(cacheRoot)) { - DeprecatedPropertyNotifyUtil.warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, - ApolloClientSystemConsts.APOLLO_CACHE_DIR); - } - } - if (Strings.isNullOrEmpty(cacheRoot)) { - // 4. Get from app.properties - cacheRoot = Foundation.app().getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, null); - if (!Strings.isNullOrEmpty(cacheRoot)) { - DeprecatedPropertyNotifyUtil.warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_CACHE_DIR, - ApolloClientSystemConsts.APOLLO_CACHE_DIR); - } - } - return cacheRoot; - } - - public boolean isInLocalMode() { - try { - return Env.LOCAL == getApolloEnv(); - } catch (Throwable ex) { - //ignore - } - return false; - } - - public boolean isOSWindows() { - String osName = System.getProperty("os.name"); - if (Strings.isNullOrEmpty(osName)) { - return false; - } - return osName.startsWith("Windows"); - } - - private void initMaxConfigCacheSize() { - String customizedConfigCacheSize = System.getProperty("apollo.configCacheSize"); - if (!Strings.isNullOrEmpty(customizedConfigCacheSize)) { - try { - maxConfigCacheSize = Long.parseLong(customizedConfigCacheSize); - } catch (Throwable ex) { - logger.error("Config for apollo.configCacheSize is invalid: {}", customizedConfigCacheSize); - } - } - } - - public long getMaxConfigCacheSize() { - return maxConfigCacheSize; - } - - public long getConfigCacheExpireTime() { - return configCacheExpireTime; - } - - public TimeUnit getConfigCacheExpireTimeUnit() { - return configCacheExpireTimeUnit; - } - - private void initLongPollingInitialDelayInMills() { - String customizedLongPollingInitialDelay = System - .getProperty("apollo.longPollingInitialDelayInMills"); - if (!Strings.isNullOrEmpty(customizedLongPollingInitialDelay)) { - try { - longPollingInitialDelayInMills = Long.parseLong(customizedLongPollingInitialDelay); - } catch (Throwable ex) { - logger.error("Config for apollo.longPollingInitialDelayInMills is invalid: {}", - customizedLongPollingInitialDelay); - } - } - } - - public long getLongPollingInitialDelayInMills() { - return longPollingInitialDelayInMills; - } - - private void initAutoUpdateInjectedSpringProperties() { - // 1. Get from System Property - String enableAutoUpdate = System.getProperty("apollo.autoUpdateInjectedSpringProperties"); - if (Strings.isNullOrEmpty(enableAutoUpdate)) { - // 2. Get from app.properties - enableAutoUpdate = Foundation.app() - .getProperty("apollo.autoUpdateInjectedSpringProperties", null); - } - if (!Strings.isNullOrEmpty(enableAutoUpdate)) { - autoUpdateInjectedSpringProperties = Boolean.parseBoolean(enableAutoUpdate.trim()); - } - } - - public boolean isAutoUpdateInjectedSpringPropertiesEnabled() { - return autoUpdateInjectedSpringProperties; - } - - private void initPropertiesOrdered() { - String enablePropertiesOrdered = System.getProperty(APOLLO_PROPERTY_ORDER_ENABLE); - - if (Strings.isNullOrEmpty(enablePropertiesOrdered)) { - enablePropertiesOrdered = Foundation.app().getProperty(APOLLO_PROPERTY_ORDER_ENABLE, "false"); - } - - if (!Strings.isNullOrEmpty(enablePropertiesOrdered)) { - try { - propertiesOrdered = Boolean.parseBoolean(enablePropertiesOrdered); - } catch (Throwable ex) { - logger.warn("Config for {} is invalid: {}, set default value: false", - APOLLO_PROPERTY_ORDER_ENABLE, enablePropertiesOrdered); - } - } - } - - public boolean isPropertiesOrderEnabled() { - return propertiesOrdered; - } - - public boolean isPropertyNamesCacheEnabled() { - return propertyNamesCacheEnabled; - } - - public boolean isPropertyFileCacheEnabled() { - return propertyFileCacheEnabled; - } - - public boolean isOverrideSystemProperties() { - return overrideSystemProperties; - } - - private void initPropertyNamesCacheEnabled() { - propertyNamesCacheEnabled = getPropertyBoolean(ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE, - ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE_ENVIRONMENT_VARIABLES, - propertyNamesCacheEnabled); - } - - private void initPropertyFileCacheEnabled() { - propertyFileCacheEnabled = getPropertyBoolean(ApolloClientSystemConsts.APOLLO_CACHE_FILE_ENABLE, - ApolloClientSystemConsts.APOLLO_CACHE_FILE_ENABLE_ENVIRONMENT_VARIABLES, - propertyFileCacheEnabled); - } - - private void initOverrideSystemProperties() { - overrideSystemProperties = getPropertyBoolean(ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES, - ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES, - overrideSystemProperties); - } - - private boolean getPropertyBoolean(String propertyName, String envName, boolean defaultVal) { - String enablePropertyNamesCache = System.getProperty(propertyName); - if (Strings.isNullOrEmpty(enablePropertyNamesCache)) { - enablePropertyNamesCache = System.getenv(envName); - } - if (Strings.isNullOrEmpty(enablePropertyNamesCache)) { - enablePropertyNamesCache = Foundation.app().getProperty(propertyName, null); - } - if (!Strings.isNullOrEmpty(enablePropertyNamesCache)) { - try { - return Boolean.parseBoolean(enablePropertyNamesCache); - } catch (Throwable ex) { - logger.warn("Config for {} is invalid: {}, set default value: {}", - propertyName, enablePropertyNamesCache, defaultVal); - } - } - return defaultVal; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ExceptionUtil.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ExceptionUtil.java deleted file mode 100644 index 0a179d977ec..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/ExceptionUtil.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2022 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.util; - -import java.util.List; - -import com.google.common.base.Strings; -import com.google.common.collect.Lists; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ExceptionUtil { - /** - * Assemble the detail message for the throwable with all of its cause included (at most 10 causes). - * @param ex the exception - * @return the message along with its causes - */ - public static String getDetailMessage(Throwable ex) { - if (ex == null || Strings.isNullOrEmpty(ex.getMessage())) { - return ""; - } - StringBuilder builder = new StringBuilder(ex.getMessage()); - List causes = Lists.newLinkedList(); - - int counter = 0; - Throwable current = ex; - //retrieve up to 10 causes - while (current.getCause() != null && counter < 10) { - Throwable next = current.getCause(); - causes.add(next); - current = next; - counter++; - } - - for (Throwable cause : causes) { - if (Strings.isNullOrEmpty(cause.getMessage())) { - counter--; - continue; - } - builder.append(" [Cause: ").append(cause.getMessage()); - } - - builder.append(Strings.repeat("]", counter)); - - return builder.toString(); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/OrderedProperties.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/OrderedProperties.java deleted file mode 100755 index 4fc0e0da4d7..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/OrderedProperties.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2022 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.util; - -import java.util.Collections; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Properties; -import java.util.Set; - -/** - * An OrderedProperties instance will keep appearance order in config file. - * - * - * Warnings: 1. It should be noticed that stream APIs or JDk1.8 APIs( listed in - * https://github.com/ctripcorp/apollo/pull/2861) are not implemented here. 2. {@link Properties} - * implementation are different between JDK1.8 and later JDKs. At least, {@link Properties} have an - * individual implementation in JDK10. Hence, there should be an individual putAll method here. - * - * - * @author songdragon@zts.io - */ -public class OrderedProperties extends Properties { - - private static final long serialVersionUID = -1741073539526213291L; - private final Set propertyNames; - - public OrderedProperties() { - propertyNames = Collections.synchronizedSet(new LinkedHashSet()); - } - - @Override - public synchronized Object put(Object key, Object value) { - addPropertyName(key); - return super.put(key, value); - } - - private void addPropertyName(Object key) { - if (key instanceof String) { - propertyNames.add((String) key); - } - } - - @Override - public Set stringPropertyNames() { - return propertyNames; - } - - @Override - public Enumeration propertyNames() { - return Collections.enumeration(propertyNames); - } - - @Override - public synchronized Enumeration keys() { - return new Enumeration() { - private final Iterator i = propertyNames.iterator(); - - @Override - public boolean hasMoreElements() { - return i.hasNext(); - } - - @Override - public Object nextElement() { - return i.next(); - } - }; - } - - @Override - public Set keySet() { - return new LinkedHashSet(propertyNames); - } - - - @Override - public Set> entrySet() { - Set> original = super.entrySet(); - LinkedHashMap> entryMap = new LinkedHashMap<>(); - for (String propertyName : propertyNames) { - entryMap.put(propertyName, null); - } - - for (Entry entry : original) { - entryMap.put(entry.getKey(), entry); - } - - return new LinkedHashSet<>(entryMap.values()); - } - - @Override - public synchronized void putAll(Map t) { - super.putAll(t); - for (Object name : t.keySet()) { - addPropertyName(name); - } - } - - @Override - public synchronized void clear() { - super.clear(); - this.propertyNames.clear(); - } - - @Override - public synchronized Object remove(Object key) { - if (key instanceof String) { - this.propertyNames.remove(key); - } - return super.remove(key); - } - -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/factory/DefaultPropertiesFactory.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/factory/DefaultPropertiesFactory.java deleted file mode 100644 index a2c2e2b37da..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/factory/DefaultPropertiesFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2022 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.util.factory; - -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.ctrip.framework.apollo.util.OrderedProperties; -import java.util.Properties; - -/** - * Default PropertiesFactory implementation. - * - * @author songdragon@zts.io - */ -public class DefaultPropertiesFactory implements PropertiesFactory { - - private ConfigUtil m_configUtil; - - public DefaultPropertiesFactory() { - m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); - } - - @Override - public Properties getPropertiesInstance() { - if (m_configUtil.isPropertiesOrderEnabled()) { - return new OrderedProperties(); - } else { - return new Properties(); - } - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/factory/PropertiesFactory.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/factory/PropertiesFactory.java deleted file mode 100644 index 316b902c73f..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/factory/PropertiesFactory.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2022 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.util.factory; - -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import java.util.Properties; - -/** - * Factory interface to construct Properties instances. - * - * @author songdragon@zts.io - */ -public interface PropertiesFactory { - - /** - * Configuration to keep properties order as same as line order in .yml/.yaml/.properties file. - */ - String APOLLO_PROPERTY_ORDER_ENABLE = ApolloClientSystemConsts.APOLLO_PROPERTY_ORDER_ENABLE; - - /** - *
-   * Default implementation:
-   * 1. if {@link APOLLO_PROPERTY_ORDER_ENABLE} is true return a new
-   * instance of {@link com.ctrip.framework.apollo.util.OrderedProperties}.
-   * 2. else return a new instance of {@link Properties}
-   * 
- * - * @return - */ - Properties getPropertiesInstance(); -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/function/Functions.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/function/Functions.java deleted file mode 100644 index 3d9dff754c2..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/function/Functions.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2022 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.util.function; - -import java.util.Date; - -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.util.parser.ParserException; -import com.ctrip.framework.apollo.util.parser.Parsers; -import com.google.common.base.Function; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface Functions { - Function TO_INT_FUNCTION = Integer::parseInt; - Function TO_LONG_FUNCTION = Long::parseLong; - Function TO_SHORT_FUNCTION = Short::parseShort; - Function TO_FLOAT_FUNCTION = Float::parseFloat; - Function TO_DOUBLE_FUNCTION = Double::parseDouble; - Function TO_BYTE_FUNCTION = Byte::parseByte; - Function TO_BOOLEAN_FUNCTION = Boolean::parseBoolean; - Function TO_DATE_FUNCTION = input -> { - try { - return Parsers.forDate().parse(input); - } catch (ParserException ex) { - throw new ApolloConfigException("Parse date failed", ex); - } - }; - Function TO_DURATION_FUNCTION = input -> { - try { - return Parsers.forDuration().parseToMillis(input); - } catch (ParserException ex) { - throw new ApolloConfigException("Parse duration failed", ex); - } - }; -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/DefaultHttpClient.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/DefaultHttpClient.java deleted file mode 100644 index 5d5fb40ed0f..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/DefaultHttpClient.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright 2022 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.util.http; - -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.base.Function; -import com.google.common.io.CharStreams; -import com.google.gson.Gson; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Type; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Map; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class DefaultHttpClient implements HttpClient { - private ConfigUtil m_configUtil; - private static final Gson GSON = new Gson(); - - /** - * Constructor. - */ - public DefaultHttpClient() { - m_configUtil = ApolloInjector.getInstance(ConfigUtil.class); - } - - /** - * Do get operation for the http request. - * - * @param httpRequest the request - * @param responseType the response type - * @return the response - * @throws ApolloConfigException if any error happened or response code is neither 200 nor 304 - */ - @Override - public HttpResponse doGet(HttpRequest httpRequest, final Class responseType) { - Function convertResponse = new Function() { - @Override - public T apply(String input) { - return GSON.fromJson(input, responseType); - } - }; - - return doGetWithSerializeFunction(httpRequest, convertResponse); - } - - /** - * Do get operation for the http request. - * - * @param httpRequest the request - * @param responseType the response type - * @return the response - * @throws ApolloConfigException if any error happened or response code is neither 200 nor 304 - */ - @Override - public HttpResponse doGet(HttpRequest httpRequest, final Type responseType) { - Function convertResponse = new Function() { - @Override - public T apply(String input) { - return GSON.fromJson(input, responseType); - } - }; - - return doGetWithSerializeFunction(httpRequest, convertResponse); - } - - private HttpResponse doGetWithSerializeFunction(HttpRequest httpRequest, - Function serializeFunction) { - InputStreamReader isr = null; - InputStreamReader esr = null; - int statusCode; - try { - HttpURLConnection conn = (HttpURLConnection) new URL(httpRequest.getUrl()).openConnection(); - - conn.setRequestMethod("GET"); - - Map headers = httpRequest.getHeaders(); - if (headers != null && headers.size() > 0) { - for (Map.Entry entry : headers.entrySet()) { - conn.setRequestProperty(entry.getKey(), entry.getValue()); - } - } - - int connectTimeout = httpRequest.getConnectTimeout(); - if (connectTimeout < 0) { - connectTimeout = m_configUtil.getConnectTimeout(); - } - - int readTimeout = httpRequest.getReadTimeout(); - if (readTimeout < 0) { - readTimeout = m_configUtil.getReadTimeout(); - } - - conn.setConnectTimeout(connectTimeout); - conn.setReadTimeout(readTimeout); - - conn.connect(); - - statusCode = conn.getResponseCode(); - String response; - - try { - isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); - response = CharStreams.toString(isr); - } catch (IOException ex) { - /** - * according to https://docs.oracle.com/javase/7/docs/technotes/guides/net/http-keepalive.html, - * we should clean up the connection by reading the response body so that the connection - * could be reused. - */ - InputStream errorStream = conn.getErrorStream(); - - if (errorStream != null) { - esr = new InputStreamReader(errorStream, StandardCharsets.UTF_8); - try { - CharStreams.toString(esr); - } catch (IOException ioe) { - //ignore - } - } - - // 200 and 304 should not trigger IOException, thus we must throw the original exception out - if (statusCode == 200 || statusCode == 304) { - throw ex; - } - // for status codes like 404, IOException is expected when calling conn.getInputStream() - throw new ApolloConfigStatusCodeException(statusCode, ex); - } - - if (statusCode == 200) { - return new HttpResponse<>(statusCode, serializeFunction.apply(response)); - } - - if (statusCode == 304) { - return new HttpResponse<>(statusCode, null); - } - } catch (ApolloConfigStatusCodeException ex) { - throw ex; - } catch (Throwable ex) { - throw new ApolloConfigException("Could not complete get operation", ex); - } finally { - if (isr != null) { - try { - isr.close(); - } catch (IOException ex) { - // ignore - } - } - - if (esr != null) { - try { - esr.close(); - } catch (IOException ex) { - // ignore - } - } - } - - throw new ApolloConfigStatusCodeException(statusCode, - String.format("Get operation failed for %s", httpRequest.getUrl())); - } - -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpClient.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpClient.java deleted file mode 100644 index 852fcda489e..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpClient.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2022 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.util.http; - -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import java.lang.reflect.Type; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface HttpClient { - - /** - * Do get operation for the http request. - * - * @param httpRequest the request - * @param responseType the response type - * @return the response - * @throws ApolloConfigException if any error happened or response code is neither 200 nor 304 - */ - HttpResponse doGet(HttpRequest httpRequest, final Class responseType) - throws ApolloConfigException; - - /** - * Do get operation for the http request. - * - * @param httpRequest the request - * @param responseType the response type - * @return the response - * @throws ApolloConfigException if any error happened or response code is neither 200 nor 304 - */ - HttpResponse doGet(HttpRequest httpRequest, final Type responseType) - throws ApolloConfigException; -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpRequest.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpRequest.java deleted file mode 100644 index 39e666a2424..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpRequest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2022 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.util.http; - -import java.util.Map; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class HttpRequest { - private final String m_url; - private Map headers; - private int m_connectTimeout; - private int m_readTimeout; - - /** - * Create the request for the url. - * @param url the url - */ - public HttpRequest(String url) { - this.m_url = url; - m_connectTimeout = -1; - m_readTimeout = -1; - } - - public String getUrl() { - return m_url; - } - - public Map getHeaders() { - return headers; - } - - public void setHeaders(Map headers) { - this.headers = headers; - } - - public int getConnectTimeout() { - return m_connectTimeout; - } - - public void setConnectTimeout(int connectTimeout) { - this.m_connectTimeout = connectTimeout; - } - - public int getReadTimeout() { - return m_readTimeout; - } - - public void setReadTimeout(int readTimeout) { - this.m_readTimeout = readTimeout; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpResponse.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpResponse.java deleted file mode 100644 index 85374c4cfdc..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpResponse.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2022 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.util.http; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class HttpResponse { - private final int m_statusCode; - private final T m_body; - - public HttpResponse(int statusCode, T body) { - this.m_statusCode = statusCode; - this.m_body = body; - } - - public int getStatusCode() { - return m_statusCode; - } - - public T getBody() { - return m_body; - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpUtil.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpUtil.java deleted file mode 100644 index 60ef11e3c59..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/http/HttpUtil.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2022 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.util.http; - -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import java.lang.reflect.Type; - -/** - * @author Jason Song(song_s@ctrip.com) - * @deprecated in favor of the interface {@link HttpClient} and it's default implementation {@link - * DefaultHttpClient} - */ -@Deprecated -public class HttpUtil implements HttpClient { - - private HttpClient m_httpClient; - - /** - * Constructor. - */ - public HttpUtil() { - m_httpClient = new DefaultHttpClient(); - } - - /** - * Do get operation for the http request. - * - * @param httpRequest the request - * @param responseType the response type - * @return the response - * @throws ApolloConfigException if any error happened or response code is neither 200 nor 304 - */ - @Override - public HttpResponse doGet(HttpRequest httpRequest, final Class responseType) { - return m_httpClient.doGet(httpRequest, responseType); - } - - /** - * Do get operation for the http request. - * - * @param httpRequest the request - * @param responseType the response type - * @return the response - * @throws ApolloConfigException if any error happened or response code is neither 200 nor 304 - */ - @Override - public HttpResponse doGet(HttpRequest httpRequest, final Type responseType) { - return m_httpClient.doGet(httpRequest, responseType); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/parser/ParserException.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/parser/ParserException.java deleted file mode 100644 index cb49f73f911..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/parser/ParserException.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2022 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.util.parser; - -public class ParserException extends Exception { - public ParserException(String message) { - super(message); - } - - public ParserException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/parser/Parsers.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/parser/Parsers.java deleted file mode 100644 index b6c1dae1184..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/parser/Parsers.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright 2022 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.util.parser; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class Parsers { - public static DateParser forDate() { - return DateParser.INSTANCE; - } - - public static DurationParser forDuration() { - return DurationParser.INSTANCE; - } - - public enum DateParser { - INSTANCE; - - private static final String LONG_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS"; - private static final String MEDIUM_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; - private static final String SHORT_DATE_FORMAT = "yyyy-MM-dd"; - - /** - * Will try to parse the date with Locale.US and formats as follows: - * yyyy-MM-dd HH:mm:ss.SSS, yyyy-MM-dd HH:mm:ss and yyyy-MM-dd - * - * @param text the text to parse - * @return the parsed date - * @throws ParserException if the text cannot be parsed - */ - public Date parse(String text) throws ParserException { - text = text.trim(); - int length = text.length(); - - if (length == LONG_DATE_FORMAT.length()) { - return parse(text, LONG_DATE_FORMAT); - } - - if (length == MEDIUM_DATE_FORMAT.length()) { - return parse(text, MEDIUM_DATE_FORMAT); - } - - return parse(text, SHORT_DATE_FORMAT); - } - - /** - * Parse the text with the format specified and Locale.US - * - * @param text the text to parse - * @param format the date format, see {@link java.text.SimpleDateFormat} for more information - * @return the parsed date - * @throws ParserException if the text cannot be parsed - */ - public Date parse(String text, String format) throws ParserException { - return parse(text, format, Locale.US); - } - - /** - * Parse the text with the format and locale specified - * - * @param text the text to parse - * @param format the date format, see {@link java.text.SimpleDateFormat} for more information - * @param locale the locale - * @return the parsed date - * @throws ParserException if the text cannot be parsed - */ - public Date parse(String text, String format, Locale locale) throws ParserException { - SimpleDateFormat dateFormat = getDateFormat(format, locale); - - try { - return dateFormat.parse(text.trim()); - } catch (ParseException e) { - throw new ParserException("Error when parsing date(" + dateFormat.toPattern() + ") from " + text, e); - } - } - - private SimpleDateFormat getDateFormat(String format, Locale locale) { - return new SimpleDateFormat(format, locale); - } - } - - public enum DurationParser { - INSTANCE; - - private static final Pattern PATTERN = - Pattern.compile("(?:([0-9]+)D)?(?:([0-9]+)H)?(?:([0-9]+)M)?(?:([0-9]+)S)?(?:([0-9]+)(?:MS)?)?", - Pattern.CASE_INSENSITIVE); - - private static final int HOURS_PER_DAY = 24; - private static final int MINUTES_PER_HOUR = 60; - private static final int SECONDS_PER_MINUTE = 60; - private static final int MILLIS_PER_SECOND = 1000; - private static final int MILLIS_PER_MINUTE = MILLIS_PER_SECOND * SECONDS_PER_MINUTE; - private static final int MILLIS_PER_HOUR = MILLIS_PER_MINUTE * MINUTES_PER_HOUR; - private static final int MILLIS_PER_DAY = MILLIS_PER_HOUR * HOURS_PER_DAY; - - public long parseToMillis(String text) throws ParserException { - Matcher matcher = PATTERN.matcher(text); - if (matcher.matches()) { - String dayMatch = matcher.group(1); - String hourMatch = matcher.group(2); - String minuteMatch = matcher.group(3); - String secondMatch = matcher.group(4); - String fractionMatch = matcher.group(5); - if (dayMatch != null || hourMatch != null || minuteMatch != null || secondMatch != null || fractionMatch != null) { - int daysAsMilliSecs = parseNumber(dayMatch, MILLIS_PER_DAY); - int hoursAsMilliSecs = parseNumber(hourMatch, MILLIS_PER_HOUR); - int minutesAsMilliSecs = parseNumber(minuteMatch, MILLIS_PER_MINUTE); - int secondsAsMilliSecs = parseNumber(secondMatch, MILLIS_PER_SECOND); - int milliseconds = parseNumber(fractionMatch, 1); - - return daysAsMilliSecs + hoursAsMilliSecs + minutesAsMilliSecs + secondsAsMilliSecs + milliseconds; - } - } - throw new ParserException(String.format("Text %s cannot be parsed to duration)", text)); - } - - - private static int parseNumber(String parsed, int multiplier) { - // regex limits to [0-9]+ - if (parsed == null || parsed.trim().isEmpty()) { - return 0; - } - return Integer.parseInt(parsed) * multiplier; - } - } -} diff --git a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/yaml/YamlParser.java b/apollo-client/src/main/java/com/ctrip/framework/apollo/util/yaml/YamlParser.java deleted file mode 100644 index 5b98233ff7b..00000000000 --- a/apollo-client/src/main/java/com/ctrip/framework/apollo/util/yaml/YamlParser.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright 2022 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.util.yaml; - -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.util.factory.PropertiesFactory; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Properties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.yaml.snakeyaml.DumperOptions; -import org.yaml.snakeyaml.LoaderOptions; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.SafeConstructor; -import org.yaml.snakeyaml.nodes.MappingNode; -import org.yaml.snakeyaml.parser.ParserException; - -import com.ctrip.framework.apollo.core.utils.StringUtils; -import org.yaml.snakeyaml.representer.Representer; - -/** - * Transplanted from org.springframework.beans.factory.config.YamlProcessor since apollo can't depend on Spring directly - * - * @since 1.3.0 - */ -public class YamlParser { - private static final Logger logger = LoggerFactory.getLogger(YamlParser.class); - - private PropertiesFactory propertiesFactory = ApolloInjector.getInstance(PropertiesFactory.class); - - /** - * Transform yaml content to properties - */ - public Properties yamlToProperties(String yamlContent) { - Yaml yaml = createYaml(); - final Properties result = propertiesFactory.getPropertiesInstance(); - process(new MatchCallback() { - @Override - public void process(Properties properties, Map map) { - result.putAll(properties); - } - }, yaml, yamlContent); - return result; - } - - /** - * Create the {@link Yaml} instance to use. - */ - private Yaml createYaml() { - LoaderOptions loadingConfig = new LoaderOptions(); - loadingConfig.setAllowDuplicateKeys(false); - return new Yaml(new SafeConstructor(), new Representer(), new DumperOptions(), loadingConfig); - } - - private boolean process(MatchCallback callback, Yaml yaml, String content) { - int count = 0; - if (logger.isDebugEnabled()) { - logger.debug("Loading from YAML: " + content); - } - for (Object object : yaml.loadAll(content)) { - if (object != null && process(asMap(object), callback)) { - count++; - } - } - if (logger.isDebugEnabled()) { - logger.debug("Loaded " + count + " document" + (count > 1 ? "s" : "") + " from YAML resource: " + content); - } - return (count > 0); - } - - @SuppressWarnings("unchecked") - private Map asMap(Object object) { - // YAML can have numbers as keys - Map result = new LinkedHashMap<>(); - if (!(object instanceof Map)) { - // A document can be a text literal - result.put("document", object); - return result; - } - - Map map = (Map) object; - for (Map.Entry entry : map.entrySet()) { - Object value = entry.getValue(); - if (value instanceof Map) { - value = asMap(value); - } - Object key = entry.getKey(); - if (key instanceof CharSequence) { - result.put(key.toString(), value); - } else { - // It has to be a map key in this case - result.put("[" + key.toString() + "]", value); - } - } - return result; - } - - private boolean process(Map map, MatchCallback callback) { - Properties properties = propertiesFactory.getPropertiesInstance(); - properties.putAll(getFlattenedMap(map)); - - if (logger.isDebugEnabled()) { - logger.debug("Merging document (no matchers set): " + map); - } - callback.process(properties, map); - return true; - } - - private Map getFlattenedMap(Map source) { - Map result = new LinkedHashMap<>(); - buildFlattenedMap(result, source, null); - return result; - } - - private void buildFlattenedMap(Map result, Map source, String path) { - for (Map.Entry entry : source.entrySet()) { - String key = entry.getKey(); - if (!StringUtils.isBlank(path)) { - if (key.startsWith("[")) { - key = path + key; - } else { - key = path + '.' + key; - } - } - Object value = entry.getValue(); - if (value instanceof String) { - result.put(key, value); - } else if (value instanceof Map) { - // Need a compound key - @SuppressWarnings("unchecked") - Map map = (Map) value; - buildFlattenedMap(result, map, key); - } else if (value instanceof Collection) { - // Need a compound key - @SuppressWarnings("unchecked") - Collection collection = (Collection) value; - int count = 0; - for (Object object : collection) { - buildFlattenedMap(result, Collections.singletonMap("[" + (count++) + "]", object), key); - } - } else { - result.put(key, (value != null ? value.toString() : "")); - } - } - } - - private interface MatchCallback { - void process(Properties properties, Map map); - } - -} diff --git a/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json deleted file mode 100644 index a14b1d03b89..00000000000 --- a/apollo-client/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "properties": [ - { - "name": "apollo.access-key.secret", - "type": "java.lang.String", - "sourceType": "com.ctrip.framework.foundation.internals.provider.DefaultApplicationProvider", - "description": "apollo client access key.", - "defaultValue": "" - }, - { - "name": "apollo.autoUpdateInjectedSpringProperties", - "type": "java.lang.Boolean", - "sourceType": "com.ctrip.framework.apollo.util.ConfigUtil", - "description": "whether to auto update spring placeholder or not.", - "defaultValue": true - }, - { - "name": "apollo.bootstrap.enabled", - "type": "java.lang.Boolean", - "sourceType": "com.ctrip.framework.apollo.spring.config.PropertySourcesConstants", - "description": "enable injecting namespaces in bootstrap phase.", - "defaultValue": false - }, - { - "name": "apollo.bootstrap.namespaces", - "type": "java.lang.String", - "sourceType": "com.ctrip.framework.apollo.spring.config.PropertySourcesConstants", - "description": "namespaces to be injected during bootstrap phase, multiple namespaces should be comma-separated.", - "defaultValue": "application" - }, - { - "name": "apollo.bootstrap.eagerLoad.enabled", - "type": "java.lang.Boolean", - "sourceType": "com.ctrip.framework.apollo.spring.config.PropertySourcesConstants", - "description": "enable apollo initialization before logging system initialization.", - "defaultValue": false - }, - { - "name": "apollo.override-system-properties", - "type": "java.lang.Boolean", - "sourceType": "com.ctrip.framework.apollo.util.ConfigUtil", - "description": "enable apollo server config override system properties.", - "defaultValue": true - }, - { - "name": "apollo.cache-dir", - "type": "java.lang.String", - "sourceType": "com.ctrip.framework.apollo.util.ConfigUtil", - "description": "local cache directory. the default value on windows is 'c:\\opt\\data', while on mac/linux is '/opt/data'.", - "defaultValue": "/opt/data" - }, - { - "name": "apollo.cluster", - "type": "java.lang.String", - "sourceType": "com.ctrip.framework.apollo.core.ConfigConsts", - "description": "cluster name.", - "defaultValue": "default" - }, - { - "name": "apollo.config-service", - "type": "java.lang.String", - "sourceType": "com.ctrip.framework.apollo.core.ApolloClientSystemConsts", - "description": "apollo config service address. if it's configured apollo client will not refresh config services from remote meta service.", - "defaultValue": "" - }, - { - "name": "apollo.meta", - "type": "java.net.URI", - "sourceType": "com.ctrip.framework.apollo.core.ConfigConsts", - "description": "apollo meta server address." - }, - { - "name": "apollo.property.names.cache.enable", - "type": "java.lang.Boolean", - "sourceType": "com.ctrip.framework.apollo.util.ConfigUtil", - "description": "enable property names cache.", - "defaultValue": false - }, - { - "name": "apollo.property.order.enable", - "type": "java.lang.Boolean", - "sourceType": "com.ctrip.framework.apollo.util.factory.PropertiesFactory", - "description": "enable property order.", - "defaultValue": false - }, - { - "name": "app.id", - "type": "java.lang.String", - "sourceType": "com.ctrip.framework.foundation.spi.provider.ApplicationProvider", - "description": "apollo client app id. if it's empty apollo will only load public namespace configurations!." - } - ] -} diff --git a/apollo-client/src/main/resources/META-INF/apollo-1.0.0.xsd b/apollo-client/src/main/resources/META-INF/apollo-1.0.0.xsd deleted file mode 100644 index f9fc6a1126e..00000000000 --- a/apollo-client/src/main/resources/META-INF/apollo-1.0.0.xsd +++ /dev/null @@ -1,57 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.core.spi.MetaServerProvider b/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.core.spi.MetaServerProvider deleted file mode 100644 index 35db9bfc4b5..00000000000 --- a/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.core.spi.MetaServerProvider +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.internals.DefaultMetaServerProvider diff --git a/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.internals.Injector b/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.internals.Injector deleted file mode 100644 index 5ed606a64e0..00000000000 --- a/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.internals.Injector +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.internals.DefaultInjector \ No newline at end of file diff --git a/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.spi.ConfigServiceLoadBalancerClient b/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.spi.ConfigServiceLoadBalancerClient deleted file mode 100644 index de02f87b38f..00000000000 --- a/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.spi.ConfigServiceLoadBalancerClient +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.spi.RandomConfigServiceLoadBalancerClient \ No newline at end of file diff --git a/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.spring.spi.ApolloConfigRegistrarHelper b/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.spring.spi.ApolloConfigRegistrarHelper deleted file mode 100644 index cb6e900846e..00000000000 --- a/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.spring.spi.ApolloConfigRegistrarHelper +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.spring.spi.DefaultApolloConfigRegistrarHelper diff --git a/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.spring.spi.ConfigPropertySourcesProcessorHelper b/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.spring.spi.ConfigPropertySourcesProcessorHelper deleted file mode 100644 index 07fd0df3c96..00000000000 --- a/apollo-client/src/main/resources/META-INF/services/com.ctrip.framework.apollo.spring.spi.ConfigPropertySourcesProcessorHelper +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.spring.spi.DefaultConfigPropertySourcesProcessorHelper diff --git a/apollo-client/src/main/resources/META-INF/spring.factories b/apollo-client/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 80c3b509bd3..00000000000 --- a/apollo-client/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,6 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.ctrip.framework.apollo.spring.boot.ApolloAutoConfiguration -org.springframework.context.ApplicationContextInitializer=\ -com.ctrip.framework.apollo.spring.boot.ApolloApplicationContextInitializer -org.springframework.boot.env.EnvironmentPostProcessor=\ -com.ctrip.framework.apollo.spring.boot.ApolloApplicationContextInitializer diff --git a/apollo-client/src/main/resources/META-INF/spring.handlers b/apollo-client/src/main/resources/META-INF/spring.handlers deleted file mode 100644 index d17e58518e2..00000000000 --- a/apollo-client/src/main/resources/META-INF/spring.handlers +++ /dev/null @@ -1 +0,0 @@ -http\://www.ctrip.com/schema/apollo=com.ctrip.framework.apollo.spring.config.NamespaceHandler \ No newline at end of file diff --git a/apollo-client/src/main/resources/META-INF/spring.schemas b/apollo-client/src/main/resources/META-INF/spring.schemas deleted file mode 100644 index 50fbe550c34..00000000000 --- a/apollo-client/src/main/resources/META-INF/spring.schemas +++ /dev/null @@ -1,2 +0,0 @@ -http\://www.ctrip.com/schema/apollo-1.0.0.xsd=/META-INF/apollo-1.0.0.xsd -http\://www.ctrip.com/schema/apollo.xsd=/META-INF/apollo-1.0.0.xsd diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/BaseIntegrationTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/BaseIntegrationTest.java deleted file mode 100644 index aa1154cfd61..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/BaseIntegrationTest.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.core.ConfigConsts; -import java.io.IOException; -import java.net.ServerSocket; -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.Server; -import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.server.handler.ContextHandler; -import org.eclipse.jetty.server.handler.ContextHandlerCollection; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.core.dto.ServiceDTO; -import com.ctrip.framework.apollo.core.enums.Env; -import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.collect.Lists; -import com.google.gson.Gson; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public abstract class BaseIntegrationTest { - - private static final int PORT = findFreePort(); - private static final String metaServiceUrl = "http://localhost:" + PORT; - private static final String someAppName = "someAppName"; - private static final String someInstanceId = "someInstanceId"; - private static final String configServiceURL = "http://localhost:" + PORT; - protected static String someAppId; - protected static String someClusterName; - protected static String someDataCenter; - protected static int refreshInterval; - protected static TimeUnit refreshTimeUnit; - protected static boolean propertiesOrderEnabled; - private Server server; - protected Gson gson = new Gson(); - - @BeforeClass - public static void beforeClass() throws Exception { - System.setProperty(ConfigConsts.APOLLO_META_KEY, metaServiceUrl); - } - - @AfterClass - public static void afterClass() throws Exception { - System.clearProperty(ConfigConsts.APOLLO_META_KEY); - } - - @Before - public void setUp() throws Exception { - someAppId = "1003171"; - someClusterName = "someClusterName"; - someDataCenter = "someDC"; - refreshInterval = 5; - refreshTimeUnit = TimeUnit.MINUTES; - propertiesOrderEnabled = false; - - MockInjector.setInstance(ConfigUtil.class, new MockConfigUtil()); - } - - @After - public void tearDown() throws Exception { - //as ConfigService is singleton, so we must manually clear its container - ConfigService.reset(); - MockInjector.reset(); - - if (server != null && server.isStarted()) { - server.stop(); - } - } - - /** - * init and start a jetty server, remember to call server.stop when the task is finished - * - * @param handlers - * @throws Exception - */ - protected Server startServerWithHandlers(ContextHandler... handlers) throws Exception { - server = new Server(PORT); - - ContextHandlerCollection contexts = new ContextHandlerCollection(); - contexts.setHandlers(handlers); - contexts.addHandler(mockMetaServerHandler()); - - server.setHandler(contexts); - server.start(); - - return server; - } - - protected ContextHandler mockMetaServerHandler() { - return mockMetaServerHandler(false); - } - - protected ContextHandler mockMetaServerHandler(final boolean failedAtFirstTime) { - final ServiceDTO someServiceDTO = new ServiceDTO(); - someServiceDTO.setAppName(someAppName); - someServiceDTO.setInstanceId(someInstanceId); - someServiceDTO.setHomepageUrl(configServiceURL); - final AtomicInteger counter = new AtomicInteger(0); - - ContextHandler context = new ContextHandler("/services/config"); - context.setHandler(new AbstractHandler() { - @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(HttpServletResponse.SC_OK); - - response.getWriter().println(gson.toJson(Lists.newArrayList(someServiceDTO))); - - baseRequest.setHandled(true); - } - }); - - return context; - } - - protected void setRefreshInterval(int refreshInterval) { - BaseIntegrationTest.refreshInterval = refreshInterval; - } - - protected void setRefreshTimeUnit(TimeUnit refreshTimeUnit) { - BaseIntegrationTest.refreshTimeUnit = refreshTimeUnit; - } - - protected void setPropertiesOrderEnabled(boolean propertiesOrderEnabled) { - BaseIntegrationTest.propertiesOrderEnabled = propertiesOrderEnabled; - } - - public static class MockConfigUtil extends ConfigUtil { - - @Override - public String getAppId() { - return someAppId; - } - - @Override - public String getCluster() { - return someClusterName; - } - - @Override - public int getRefreshInterval() { - return refreshInterval; - } - - @Override - public TimeUnit getRefreshIntervalTimeUnit() { - return refreshTimeUnit; - } - - @Override - public Env getApolloEnv() { - return Env.DEV; - } - - @Override - public String getDataCenter() { - return someDataCenter; - } - - @Override - public int getLoadConfigQPS() { - return 200; - } - - @Override - public int getLongPollQPS() { - return 200; - } - - @Override - public String getDefaultLocalCacheDir() { - return ClassLoaderUtil.getClassPath(); - } - - @Override - public long getOnErrorRetryInterval() { - return 10; - } - - @Override - public TimeUnit getOnErrorRetryIntervalTimeUnit() { - return TimeUnit.MILLISECONDS; - } - - @Override - public long getLongPollingInitialDelayInMills() { - return 0; - } - - @Override - public boolean isPropertiesOrderEnabled() { - return propertiesOrderEnabled; - } - } - - /** - * Returns a free port number on localhost. - *

- * Heavily inspired from org.eclipse.jdt.launching.SocketUtil (to avoid a dependency to JDT just - * because of this). Slightly improved with close() missing in JDT. And throws exception instead - * of returning -1. - * - * @return a free port number on localhost - * @throws IllegalStateException if unable to find a free port - */ - private static int findFreePort() { - ServerSocket socket = null; - try { - socket = new ServerSocket(0); - socket.setReuseAddress(true); - int port = socket.getLocalPort(); - try { - socket.close(); - } catch (IOException e) { - // Ignore IOException on close() - } - return port; - } catch (IOException e) { - } finally { - if (socket != null) { - try { - socket.close(); - } catch (IOException e) { - } - } - } - throw new IllegalStateException( - "Could not find a free TCP/IP port to start embedded Jetty HTTP Server on"); - } - -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/ConfigServiceTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/ConfigServiceTest.java deleted file mode 100644 index bc77259f37b..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/ConfigServiceTest.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright 2022 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; - -import static org.junit.Assert.assertEquals; - -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import java.util.Set; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import com.ctrip.framework.apollo.internals.AbstractConfig; -import com.ctrip.framework.apollo.spi.ConfigFactory; -import com.ctrip.framework.apollo.util.ConfigUtil; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ConfigServiceTest { - private static String someAppId; - - @Before - public void setUp() throws Exception { - someAppId = "someAppId"; - - MockInjector.setInstance(ConfigUtil.class, new MockConfigUtil()); - } - - @After - public void tearDown() throws Exception { - //as ConfigService is singleton, so we must manually clear its container - ConfigService.reset(); - MockInjector.reset(); - } - - @Test - public void testHackConfig() { - String someNamespace = "hack"; - String someKey = "first"; - ConfigService.setConfig(new MockConfig(someNamespace)); - - Config config = ConfigService.getAppConfig(); - - assertEquals(someNamespace + ":" + someKey, config.getProperty(someKey, null)); - assertEquals(null, config.getProperty("unknown", null)); - } - - @Test - public void testHackConfigFactory() throws Exception { - String someKey = "someKey"; - ConfigService.setConfigFactory(new MockConfigFactory()); - - Config config = ConfigService.getAppConfig(); - - assertEquals(ConfigConsts.NAMESPACE_APPLICATION + ":" + someKey, - config.getProperty(someKey, null)); - } - - @Test - public void testMockConfigFactory() throws Exception { - String someNamespace = "mock"; - String someKey = "someKey"; - MockInjector.setInstance(ConfigFactory.class, someNamespace, new MockConfigFactory()); - - Config config = ConfigService.getConfig(someNamespace); - - assertEquals(someNamespace + ":" + someKey, config.getProperty(someKey, null)); - assertEquals(null, config.getProperty("unknown", null)); - } - - @Test - public void testMockConfigFactoryForConfigFile() throws Exception { - String someNamespace = "mock"; - ConfigFileFormat someConfigFileFormat = ConfigFileFormat.Properties; - String someNamespaceFileName = - String.format("%s.%s", someNamespace, someConfigFileFormat.getValue()); - MockInjector.setInstance(ConfigFactory.class, someNamespaceFileName, new MockConfigFactory()); - - ConfigFile configFile = ConfigService.getConfigFile(someNamespace, someConfigFileFormat); - - assertEquals(someNamespaceFileName, configFile.getNamespace()); - assertEquals(someNamespaceFileName + ":" + someConfigFileFormat.getValue(), configFile.getContent()); - } - - private static class MockConfig extends AbstractConfig { - private final String m_namespace; - - public MockConfig(String namespace) { - m_namespace = namespace; - } - - @Override - public String getProperty(String key, String defaultValue) { - if (key.equals("unknown")) { - return null; - } - - return m_namespace + ":" + key; - } - - @Override - public Set getPropertyNames() { - return null; - } - - @Override - public ConfigSourceType getSourceType() { - return null; - } - } - - private static class MockConfigFile implements ConfigFile { - private ConfigFileFormat m_configFileFormat; - private String m_namespace; - - public MockConfigFile(String namespace, - ConfigFileFormat configFileFormat) { - m_namespace = namespace; - m_configFileFormat = configFileFormat; - } - - @Override - public String getContent() { - return m_namespace + ":" + m_configFileFormat.getValue(); - } - - @Override - public boolean hasContent() { - return true; - } - - @Override - public String getNamespace() { - return m_namespace; - } - - @Override - public ConfigFileFormat getConfigFileFormat() { - return m_configFileFormat; - } - - @Override - public void addChangeListener(ConfigFileChangeListener listener) { - - } - - @Override - public boolean removeChangeListener(ConfigFileChangeListener listener) { - return false; - } - - @Override - public ConfigSourceType getSourceType() { - return null; - } - } - - public static class MockConfigFactory implements ConfigFactory { - @Override - public Config create(String namespace) { - return new MockConfig(namespace); - } - - @Override - public ConfigFile createConfigFile(String namespace, ConfigFileFormat configFileFormat) { - return new MockConfigFile(namespace, configFileFormat); - } - } - - public static class MockConfigUtil extends ConfigUtil { - @Override - public String getAppId() { - return someAppId; - } - } - -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/build/MockInjector.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/build/MockInjector.java deleted file mode 100644 index 896f02f55b0..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/build/MockInjector.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2022 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.build; - -import com.ctrip.framework.apollo.internals.DefaultInjector; -import com.ctrip.framework.apollo.internals.Injector; -import com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer; -import com.google.common.collect.HashBasedTable; -import com.google.common.collect.Maps; -import com.google.common.collect.Table; -import java.util.Map; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class MockInjector implements Injector { - - private static Map classMap = Maps.newHashMap(); - private static Table classTable = HashBasedTable.create(); - private static Injector delegate = new DefaultInjector(); - - @Override - public T getInstance(Class clazz) { - if (delegate != null) { - return delegate.getInstance(clazz); - } - - return null; - } - - @Override - public T getInstance(Class clazz, String name) { - if (delegate != null) { - return delegate.getInstance(clazz, name); - } - - return null; - } - - public static void setInstance(Class clazz, Object o) { - classMap.put(clazz, o); - } - - public static void setInstance(Class clazz, String name, Object o) { - classTable.put(clazz, name, o); - } - - public static void setDelegate(Injector delegateInjector) { - delegate = delegateInjector; - } - - public static void reset() { - classMap.clear(); - classTable.clear(); - delegate = new DefaultInjector(); - } - - public static class InjectCustomizer implements ApolloInjectorCustomizer { - - @Override - public T getInstance(Class clazz) { - return (T) classMap.get(clazz); - } - - @Override - public T getInstance(Class clazz, String name) { - return (T) classTable.get(clazz, name); - } - - @Override - public int getOrder() { - return 0; - } - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/integration/ConfigIntegrationTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/integration/ConfigIntegrationTest.java deleted file mode 100644 index 1f1d74b6259..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/integration/ConfigIntegrationTest.java +++ /dev/null @@ -1,570 +0,0 @@ -/* - * Copyright 2022 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.hamcrest.MatcherAssert.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(song_s@ctrip.com) - */ -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 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 propertyNames = config.getPropertyNames(); - Iterator 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 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 propertyNames = config.getPropertyNames(); - Iterator 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 propertyNames = config.getPropertyNames(); - Iterator 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 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 changeEvents = Lists.newArrayList(); - - final SettableFuture 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 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 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 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 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 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 longPollFinished = SettableFuture.create(); - final SettableFuture 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 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 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)); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/AbstractConfigTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/AbstractConfigTest.java deleted file mode 100644 index 55d3e317297..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/AbstractConfigTest.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.ctrip.framework.apollo.enums.PropertyChangeType; -import com.ctrip.framework.apollo.model.ConfigChange; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import com.google.common.util.concurrent.SettableFuture; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Test; - -/** - * @author wxq - */ -public class AbstractConfigTest { - - /** - * @see AbstractConfig#fireConfigChange(ConfigChangeEvent) - */ - @Test - public void testFireConfigChange_cannot_notify() throws InterruptedException { - AbstractConfig abstractConfig = spy(new ErrorConfig()); - final String namespace = "app-namespace-0"; - - ConfigChangeListener configChangeListener = spy(new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - - } - }); - abstractConfig - .addChangeListener(configChangeListener, Collections.singleton("cannot-be-match-key")); - - Map changes = new HashMap<>(); - changes.put("key1", - new ConfigChange(namespace, "key1", null, "new-value", PropertyChangeType.ADDED)); - ConfigChangeEvent configChangeEvent = new ConfigChangeEvent(namespace, changes); - - abstractConfig.fireConfigChange(configChangeEvent); - abstractConfig.fireConfigChange(namespace, changes); - - // wait a minute for invoking - Thread.sleep(100); - - verify(configChangeListener, times(0)).onChange(any()); - } - - @Test - public void testFireConfigChange_event_notify_once() - throws ExecutionException, InterruptedException, TimeoutException { - AbstractConfig abstractConfig = new ErrorConfig(); - final String namespace = "app-namespace-1"; - final String key = "great-key"; - - final SettableFuture future1 = SettableFuture.create(); - final SettableFuture future2 = SettableFuture.create(); - - final AtomicInteger invokeCount = new AtomicInteger(); - - final ConfigChangeListener configChangeListener1 = spy(new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - invokeCount.incrementAndGet(); - future1.set(changeEvent); - } - }); - final ConfigChangeListener configChangeListener2 = spy(new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - invokeCount.incrementAndGet(); - future2.set(changeEvent); - } - }); - abstractConfig.addChangeListener(configChangeListener1, Collections.singleton(key)); - abstractConfig.addChangeListener(configChangeListener2, Collections.singleton(key)); - - Map changes = new HashMap<>(); - changes.put(key, - new ConfigChange(namespace, key, "old-value", "new-value", PropertyChangeType.MODIFIED)); - ConfigChangeEvent configChangeEvent = new ConfigChangeEvent(namespace, changes); - - abstractConfig.fireConfigChange(configChangeEvent); - - assertEquals(configChangeEvent, future1.get(500, TimeUnit.MILLISECONDS)); - assertEquals(configChangeEvent, future2.get(500, TimeUnit.MILLISECONDS)); - - assertEquals(2, invokeCount.get()); - - verify(configChangeListener1, times(1)).onChange(eq(configChangeEvent)); - verify(configChangeListener2, times(1)).onChange(eq(configChangeEvent)); - } - - @Test - public void testFireConfigChange_changes_notify_once() - throws ExecutionException, InterruptedException, TimeoutException { - AbstractConfig abstractConfig = new ErrorConfig(); - final String namespace = "app-namespace-1"; - final String key = "great-key"; - - final SettableFuture future1 = SettableFuture.create(); - final SettableFuture future2 = SettableFuture.create(); - - final AtomicInteger invokeCount = new AtomicInteger(); - - final ConfigChangeListener configChangeListener1 = spy(new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - invokeCount.incrementAndGet(); - future1.set(changeEvent); - } - }); - final ConfigChangeListener configChangeListener2 = spy(new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - invokeCount.incrementAndGet(); - future2.set(changeEvent); - } - }); - abstractConfig.addChangeListener(configChangeListener1, Collections.singleton(key)); - abstractConfig.addChangeListener(configChangeListener2, Collections.singleton(key)); - - Map changes = new HashMap<>(); - changes.put(key, - new ConfigChange(namespace, key, "old-value", "new-value", PropertyChangeType.MODIFIED)); - - abstractConfig.fireConfigChange(namespace, changes); - - assertEquals(Collections.singleton(key), future1.get(500, TimeUnit.MILLISECONDS).changedKeys()); - assertEquals(Collections.singleton(key), future2.get(500, TimeUnit.MILLISECONDS).changedKeys()); - - assertEquals(2, invokeCount.get()); - - verify(configChangeListener1, times(1)).onChange(any()); - verify(configChangeListener2, times(1)).onChange(any()); - } - - /** - * Only for current test usage. - * - * @author wxq - */ - private static class ErrorConfig extends AbstractConfig { - - @Override - public String getProperty(String key, String defaultValue) { - throw new UnsupportedOperationException(); - } - - @Override - public Set getPropertyNames() { - throw new UnsupportedOperationException(); - } - - @Override - public ConfigSourceType getSourceType() { - throw new UnsupportedOperationException(); - } - } -} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigServiceLocatorTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigServiceLocatorTest.java deleted file mode 100644 index 4ce4a855624..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/ConfigServiceLocatorTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.assertEquals; - -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.core.dto.ServiceDTO; -import java.util.List; -import org.junit.After; -import org.junit.Test; - -public class ConfigServiceLocatorTest { - - @After - public void tearDown() throws Exception { - System.clearProperty(ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE); - System.clearProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CONFIG_SERVICE); - } - - @Test - public void testGetConfigServicesWithSystemProperty() throws Exception { - String someConfigServiceUrl = " someConfigServiceUrl "; - String anotherConfigServiceUrl = " anotherConfigServiceUrl "; - - System.setProperty(ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE, someConfigServiceUrl + "," + anotherConfigServiceUrl); - - ConfigServiceLocator configServiceLocator = new ConfigServiceLocator(); - - List result = configServiceLocator.getConfigServices(); - - assertEquals(2, result.size()); - - assertEquals(someConfigServiceUrl.trim(), result.get(0).getHomepageUrl()); - assertEquals(anotherConfigServiceUrl.trim(), result.get(1).getHomepageUrl()); - } - - @Test - public void testGetConfigServicesWithSystemPropertyCompatible() throws Exception { - String someConfigServiceUrl = " someConfigServiceUrl "; - String anotherConfigServiceUrl = " anotherConfigServiceUrl "; - - System.setProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_CONFIG_SERVICE, - someConfigServiceUrl + "," + anotherConfigServiceUrl); - - ConfigServiceLocator configServiceLocator = new ConfigServiceLocator(); - - List result = configServiceLocator.getConfigServices(); - - assertEquals(2, result.size()); - - assertEquals(someConfigServiceUrl.trim(), result.get(0).getHomepageUrl()); - assertEquals(anotherConfigServiceUrl.trim(), result.get(1).getHomepageUrl()); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/DefaultConfigManagerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/DefaultConfigManagerTest.java deleted file mode 100644 index fdc9bb41976..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/DefaultConfigManagerTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright 2022 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.hamcrest.MatcherAssert.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(song_s@ctrip.com) - */ -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 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; - } - }; - } - }; - } - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/DefaultConfigTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/DefaultConfigTest.java deleted file mode 100644 index 93792b41cb1..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/DefaultConfigTest.java +++ /dev/null @@ -1,998 +0,0 @@ -/* - * Copyright 2022 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.awaitility.Awaitility.await; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.ctrip.framework.apollo.util.OrderedProperties; -import com.ctrip.framework.apollo.util.factory.PropertiesFactory; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import java.io.File; -import java.util.Calendar; -import java.util.Date; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import com.google.common.base.Function; -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; -import org.awaitility.core.ThrowingRunnable; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil; -import com.ctrip.framework.apollo.enums.PropertyChangeType; -import com.ctrip.framework.apollo.model.ConfigChange; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.base.Charsets; -import com.google.common.base.Joiner; -import com.google.common.collect.ImmutableMap; -import com.google.common.io.Files; -import com.google.common.util.concurrent.SettableFuture; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class DefaultConfigTest { - private File someResourceDir; - private String someNamespace; - private ConfigRepository configRepository; - private Properties someProperties; - private ConfigSourceType someSourceType; - private PropertiesFactory propertiesFactory; - - @Before - public void setUp() throws Exception { - MockInjector.setInstance(ConfigUtil.class, new MockConfigUtil()); - - propertiesFactory = mock(PropertiesFactory.class); - when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer() { - @Override - public Properties answer(InvocationOnMock invocation) { - return new Properties(); - } - }); - MockInjector.setInstance(PropertiesFactory.class, propertiesFactory); - - someResourceDir = new File(ClassLoaderUtil.getClassPath() + "/META-INF/config"); - someResourceDir.mkdirs(); - someNamespace = "someName"; - configRepository = mock(ConfigRepository.class); - } - - @After - public void tearDown() throws Exception { - MockInjector.reset(); - recursiveDelete(someResourceDir); - } - - //helper method to clean created files - private void recursiveDelete(File file) { - if (!file.exists()) { - return; - } - if (file.isDirectory()) { - for (File f : file.listFiles()) { - recursiveDelete(f); - } - } - file.delete(); - } - - @Test - public void testGetPropertyWithAllPropertyHierarchy() throws Exception { - String someKey = "someKey"; - String someSystemPropertyValue = "system-property-value"; - - String anotherKey = "anotherKey"; - String someLocalFileValue = "local-file-value"; - - String lastKey = "lastKey"; - String someResourceValue = "resource-value"; - - //set up system property - System.setProperty(someKey, someSystemPropertyValue); - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty(someKey, someLocalFileValue); - someProperties.setProperty(anotherKey, someLocalFileValue); - when(configRepository.getConfig()).thenReturn(someProperties); - someSourceType = ConfigSourceType.LOCAL; - when(configRepository.getSourceType()).thenReturn(someSourceType); - - //set up resource file - File resourceFile = new File(someResourceDir, someNamespace + ".properties"); - Files.write(someKey + "=" + someResourceValue, resourceFile, Charsets.UTF_8); - Files.append(System.getProperty("line.separator"), resourceFile, Charsets.UTF_8); - Files.append(anotherKey + "=" + someResourceValue, resourceFile, Charsets.UTF_8); - Files.append(System.getProperty("line.separator"), resourceFile, Charsets.UTF_8); - Files.append(lastKey + "=" + someResourceValue, resourceFile, Charsets.UTF_8); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - String someKeyValue = defaultConfig.getProperty(someKey, null); - String anotherKeyValue = defaultConfig.getProperty(anotherKey, null); - String lastKeyValue = defaultConfig.getProperty(lastKey, null); - - //clean up - System.clearProperty(someKey); - - assertEquals(someSystemPropertyValue, someKeyValue); - assertEquals(someLocalFileValue, anotherKeyValue); - assertEquals(someResourceValue, lastKeyValue); - - assertEquals(someSourceType, defaultConfig.getSourceType()); - } - - @Test - public void testGetIntProperty() throws Exception { - String someStringKey = "someStringKey"; - String someStringValue = "someStringValue"; - - String someKey = "someKey"; - Integer someValue = 2; - - Integer someDefaultValue = -1; - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty(someStringKey, someStringValue); - someProperties.setProperty(someKey, String.valueOf(someValue)); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(someValue, defaultConfig.getIntProperty(someKey, someDefaultValue)); - assertEquals(someDefaultValue, defaultConfig.getIntProperty(someStringKey, someDefaultValue)); - } - - @Test - public void testGetIntPropertyMultipleTimesWithCache() throws Exception { - String someKey = "someKey"; - Integer someValue = 2; - - Integer someDefaultValue = -1; - - //set up config repo - someProperties = mock(Properties.class); - when(someProperties.getProperty(someKey)).thenReturn(String.valueOf(someValue)); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(someValue, defaultConfig.getIntProperty(someKey, someDefaultValue)); - assertEquals(someValue, defaultConfig.getIntProperty(someKey, someDefaultValue)); - assertEquals(someValue, defaultConfig.getIntProperty(someKey, someDefaultValue)); - - verify(someProperties, times(1)).getProperty(someKey); - } - - @Test - public void testGetIntPropertyMultipleTimesWithPropertyChanges() throws Exception { - String someKey = "someKey"; - Integer someValue = 2; - Integer anotherValue = 3; - - Integer someDefaultValue = -1; - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty(someKey, String.valueOf(someValue)); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(someValue, defaultConfig.getIntProperty(someKey, someDefaultValue)); - - Properties anotherProperties = new Properties(); - anotherProperties.setProperty(someKey, String.valueOf(anotherValue)); - - defaultConfig.onRepositoryChange(someNamespace, anotherProperties); - - assertEquals(anotherValue, defaultConfig.getIntProperty(someKey, someDefaultValue)); - } - - @Test - public void testGetIntPropertyMultipleTimesWithSmallCache() throws Exception { - String someKey = "someKey"; - Integer someValue = 2; - - String anotherKey = "anotherKey"; - Integer anotherValue = 3; - - Integer someDefaultValue = -1; - - MockInjector.setInstance(ConfigUtil.class, new MockConfigUtilWithSmallCache()); - - //set up config repo - someProperties = mock(Properties.class); - when(someProperties.getProperty(someKey)).thenReturn(String.valueOf(someValue)); - when(someProperties.getProperty(anotherKey)).thenReturn(String.valueOf(anotherValue)); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(someValue, defaultConfig.getIntProperty(someKey, someDefaultValue)); - assertEquals(someValue, defaultConfig.getIntProperty(someKey, someDefaultValue)); - - verify(someProperties, times(1)).getProperty(someKey); - - assertEquals(anotherValue, defaultConfig.getIntProperty(anotherKey, someDefaultValue)); - assertEquals(anotherValue, defaultConfig.getIntProperty(anotherKey, someDefaultValue)); - - verify(someProperties, times(1)).getProperty(anotherKey); - - assertEquals(someValue, defaultConfig.getIntProperty(someKey, someDefaultValue)); - - verify(someProperties, times(2)).getProperty(someKey); - } - - @Test - public void testGetIntPropertyMultipleTimesWithShortExpireTime() throws Exception { - final String someKey = "someKey"; - final Integer someValue = 2; - - final Integer someDefaultValue = -1; - - MockInjector.setInstance(ConfigUtil.class, new MockConfigUtilWithShortExpireTime()); - - //set up config repo - someProperties = mock(Properties.class); - when(someProperties.getProperty(someKey)).thenReturn(String.valueOf(someValue)); - when(configRepository.getConfig()).thenReturn(someProperties); - - final DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(someValue, defaultConfig.getIntProperty(someKey, someDefaultValue)); - assertEquals(someValue, defaultConfig.getIntProperty(someKey, someDefaultValue)); - - verify(someProperties, times(1)).getProperty(someKey); - - await().atMost(500, TimeUnit.MILLISECONDS).untilAsserted(new ThrowingRunnable() { - @Override - public void run() throws Throwable { - assertEquals(someValue, defaultConfig.getIntProperty(someKey, someDefaultValue)); - assertEquals(someValue, defaultConfig.getIntProperty(someKey, someDefaultValue)); - - verify(someProperties, times(2)).getProperty(someKey); - } - }); - } - - @Test - public void testGetLongProperty() throws Exception { - String someStringKey = "someStringKey"; - String someStringValue = "someStringValue"; - - String someKey = "someKey"; - Long someValue = 2L; - - Long someDefaultValue = -1L; - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty(someStringKey, someStringValue); - someProperties.setProperty(someKey, String.valueOf(someValue)); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(someValue, defaultConfig.getLongProperty(someKey, someDefaultValue)); - assertEquals(someDefaultValue, defaultConfig.getLongProperty(someStringKey, someDefaultValue)); - } - - @Test - public void testGetShortProperty() throws Exception { - String someStringKey = "someStringKey"; - String someStringValue = "someStringValue"; - - String someKey = "someKey"; - Short someValue = 2; - - Short someDefaultValue = -1; - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty(someStringKey, someStringValue); - someProperties.setProperty(someKey, String.valueOf(someValue)); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(someValue, defaultConfig.getShortProperty(someKey, someDefaultValue)); - assertEquals(someDefaultValue, defaultConfig.getShortProperty(someStringKey, someDefaultValue)); - } - - @Test - public void testGetFloatProperty() throws Exception { - String someStringKey = "someStringKey"; - String someStringValue = "someStringValue"; - - String someKey = "someKey"; - Float someValue = 2.20f; - - Float someDefaultValue = -1f; - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty(someStringKey, someStringValue); - someProperties.setProperty(someKey, String.valueOf(someValue)); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(someValue, defaultConfig.getFloatProperty(someKey, someDefaultValue), 0.001); - assertEquals(someDefaultValue, defaultConfig.getFloatProperty(someStringKey, someDefaultValue), 0.001); - } - - @Test - public void testGetDoubleProperty() throws Exception { - String someStringKey = "someStringKey"; - String someStringValue = "someStringValue"; - - String someKey = "someKey"; - Double someValue = 2.20d; - - Double someDefaultValue = -1d; - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty(someStringKey, someStringValue); - someProperties.setProperty(someKey, String.valueOf(someValue)); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(someValue, defaultConfig.getDoubleProperty(someKey, someDefaultValue), 0.001); - assertEquals(someDefaultValue, defaultConfig.getDoubleProperty(someStringKey, someDefaultValue), 0.001); - } - - @Test - public void testGetByteProperty() throws Exception { - String someStringKey = "someStringKey"; - String someStringValue = "someStringValue"; - - String someKey = "someKey"; - Byte someValue = 10; - - Byte someDefaultValue = -1; - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty(someStringKey, someStringValue); - someProperties.setProperty(someKey, String.valueOf(someValue)); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(someValue, defaultConfig.getByteProperty(someKey, someDefaultValue)); - assertEquals(someDefaultValue, defaultConfig.getByteProperty(someStringKey, someDefaultValue)); - } - - @Test - public void testGetBooleanProperty() throws Exception { - String someStringKey = "someStringKey"; - String someStringValue = "someStringValue"; - - String someKey = "someKey"; - Boolean someValue = true; - - Boolean someDefaultValue = false; - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty(someStringKey, someStringValue); - someProperties.setProperty(someKey, String.valueOf(someValue)); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(someValue, defaultConfig.getBooleanProperty(someKey, someDefaultValue)); - assertEquals(someDefaultValue, defaultConfig.getBooleanProperty(someStringKey, someDefaultValue)); - } - - @Test - public void testGetArrayProperty() throws Exception { - String someKey = "someKey"; - String someDelimiter = ","; - String someInvalidDelimiter = "{"; - - String[] values = new String[]{"a", "b", "c"}; - String someValue = Joiner.on(someDelimiter).join(values); - - String[] someDefaultValue = new String[]{"1", "2"}; - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty(someKey, someValue); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertArrayEquals(values, defaultConfig.getArrayProperty(someKey, someDelimiter, someDefaultValue)); - assertArrayEquals(someDefaultValue, defaultConfig.getArrayProperty(someKey, someInvalidDelimiter, - someDefaultValue)); - } - - @Test - public void testGetArrayPropertyMultipleTimesWithCache() throws Exception { - String someKey = "someKey"; - String someDelimiter = ","; - String someInvalidDelimiter = "{"; - - String[] values = new String[]{"a", "b", "c"}; - String someValue = Joiner.on(someDelimiter).join(values); - - String[] someDefaultValue = new String[]{"1", "2"}; - - //set up config repo - someProperties = mock(Properties.class); - when(someProperties.getProperty(someKey)).thenReturn(someValue); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertArrayEquals(values, defaultConfig.getArrayProperty(someKey, someDelimiter, someDefaultValue)); - assertArrayEquals(values, defaultConfig.getArrayProperty(someKey, someDelimiter, someDefaultValue)); - - verify(someProperties, times(1)).getProperty(someKey); - - assertArrayEquals(someDefaultValue, defaultConfig.getArrayProperty(someKey, someInvalidDelimiter, - someDefaultValue)); - assertArrayEquals(someDefaultValue, defaultConfig.getArrayProperty(someKey, someInvalidDelimiter, - someDefaultValue)); - - verify(someProperties, times(3)).getProperty(someKey); - } - - @Test - public void testGetArrayPropertyMultipleTimesWithCacheAndValueChanges() throws Exception { - String someKey = "someKey"; - String someDelimiter = ","; - - String[] values = new String[]{"a", "b", "c"}; - String[] anotherValues = new String[]{"b", "c", "d"}; - String someValue = Joiner.on(someDelimiter).join(values); - String anotherValue = Joiner.on(someDelimiter).join(anotherValues); - - String[] someDefaultValue = new String[]{"1", "2"}; - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty(someKey, someValue); - when(configRepository.getConfig()).thenReturn(someProperties); - - Properties anotherProperties = new Properties(); - anotherProperties.setProperty(someKey, anotherValue); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertArrayEquals(values, defaultConfig.getArrayProperty(someKey, someDelimiter, someDefaultValue)); - - defaultConfig.onRepositoryChange(someNamespace, anotherProperties); - - assertArrayEquals(anotherValues, defaultConfig.getArrayProperty(someKey, someDelimiter, someDefaultValue)); - } - - @Test - public void testGetDatePropertyWithFormat() throws Exception { - Date someDefaultValue = new Date(); - - Date shortDate = assembleDate(2016, 9, 28, 0, 0, 0, 0); - Date mediumDate = assembleDate(2016, 9, 28, 15, 10, 10, 0); - Date longDate = assembleDate(2016, 9, 28, 15, 10, 10, 123); - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty("shortDateProperty", "2016-09-28"); - someProperties.setProperty("mediumDateProperty", "2016-09-28 15:10:10"); - someProperties.setProperty("longDateProperty", "2016-09-28 15:10:10.123"); - someProperties.setProperty("stringProperty", "someString"); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - checkDatePropertyWithFormat(defaultConfig, shortDate, "shortDateProperty", "yyyy-MM-dd", someDefaultValue); - checkDatePropertyWithFormat(defaultConfig, mediumDate, "mediumDateProperty", "yyyy-MM-dd HH:mm:ss", - someDefaultValue); - checkDatePropertyWithFormat(defaultConfig, shortDate, "mediumDateProperty", "yyyy-MM-dd", someDefaultValue); - checkDatePropertyWithFormat(defaultConfig, longDate, "longDateProperty", "yyyy-MM-dd HH:mm:ss.SSS", - someDefaultValue); - checkDatePropertyWithFormat(defaultConfig, mediumDate, "longDateProperty", "yyyy-MM-dd HH:mm:ss", someDefaultValue); - checkDatePropertyWithFormat(defaultConfig, shortDate, "longDateProperty", "yyyy-MM-dd", someDefaultValue); - checkDatePropertyWithFormat(defaultConfig, someDefaultValue, "stringProperty", "yyyy-MM-dd", someDefaultValue); - } - - @Test - public void testGetDatePropertyWithNoFormat() throws Exception { - Date someDefaultValue = new Date(); - - Date shortDate = assembleDate(2016, 9, 28, 0, 0, 0, 0); - Date mediumDate = assembleDate(2016, 9, 28, 15, 10, 10, 0); - Date longDate = assembleDate(2016, 9, 28, 15, 10, 10, 123); - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty("shortDateProperty", "2016-09-28"); - someProperties.setProperty("mediumDateProperty", "2016-09-28 15:10:10"); - someProperties.setProperty("longDateProperty", "2016-09-28 15:10:10.123"); - someProperties.setProperty("stringProperty", "someString"); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - checkDatePropertyWithoutFormat(defaultConfig, shortDate, "shortDateProperty", someDefaultValue); - checkDatePropertyWithoutFormat(defaultConfig, mediumDate, "mediumDateProperty", someDefaultValue); - checkDatePropertyWithoutFormat(defaultConfig, longDate, "longDateProperty", someDefaultValue); - checkDatePropertyWithoutFormat(defaultConfig, someDefaultValue, "stringProperty", someDefaultValue); - } - - @Test - public void testGetEnumProperty() throws Exception { - SomeEnum someDefaultValue = SomeEnum.defaultValue; - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty("enumProperty", "someValue"); - someProperties.setProperty("stringProperty", "someString"); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(SomeEnum.someValue, defaultConfig.getEnumProperty("enumProperty", SomeEnum.class, someDefaultValue)); - assertEquals(someDefaultValue, defaultConfig.getEnumProperty("stringProperty", SomeEnum.class, someDefaultValue)); - } - - @Test - public void testGetDurationProperty() throws Exception { - long someDefaultValue = 1000; - long result = 2 * 24 * 3600 * 1000 + 3 * 3600 * 1000 + 4 * 60 * 1000 + 5 * 1000 + 123; - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty("durationProperty", "2D3H4m5S123ms"); - someProperties.setProperty("stringProperty", "someString"); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(result, defaultConfig.getDurationProperty("durationProperty", someDefaultValue)); - assertEquals(someDefaultValue, defaultConfig.getDurationProperty("stringProperty", someDefaultValue)); - } - - @Test - public void testOnRepositoryChange() throws Exception { - String someKey = "someKey"; - String someSystemPropertyValue = "system-property-value"; - - String anotherKey = "anotherKey"; - String someLocalFileValue = "local-file-value"; - - String keyToBeDeleted = "keyToBeDeleted"; - String keyToBeDeletedValue = "keyToBeDeletedValue"; - - String yetAnotherKey = "yetAnotherKey"; - String yetAnotherValue = "yetAnotherValue"; - - String yetAnotherResourceValue = "yetAnotherResourceValue"; - //set up system property - System.setProperty(someKey, someSystemPropertyValue); - - //set up config repo - someProperties = new Properties(); - someProperties.putAll(ImmutableMap - .of(someKey, someLocalFileValue, anotherKey, someLocalFileValue, keyToBeDeleted, - keyToBeDeletedValue, yetAnotherKey, yetAnotherValue)); - when(configRepository.getConfig()).thenReturn(someProperties); - someSourceType = ConfigSourceType.LOCAL; - when(configRepository.getSourceType()).thenReturn(someSourceType); - - //set up resource file - File resourceFile = new File(someResourceDir, someNamespace + ".properties"); - Files.append(yetAnotherKey + "=" + yetAnotherResourceValue, resourceFile, Charsets.UTF_8); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(someSourceType, defaultConfig.getSourceType()); - - final SettableFuture configChangeFuture = SettableFuture.create(); - ConfigChangeListener someListener = new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - configChangeFuture.set(changeEvent); - } - }; - - defaultConfig.addChangeListener(someListener); - - Properties newProperties = new Properties(); - String someKeyNewValue = "new-some-value"; - String anotherKeyNewValue = "another-new-value"; - String newKey = "newKey"; - String newValue = "newValue"; - newProperties.putAll(ImmutableMap - .of(someKey, someKeyNewValue, anotherKey, anotherKeyNewValue, newKey, newValue)); - - ConfigSourceType anotherSourceType = ConfigSourceType.REMOTE; - when(configRepository.getSourceType()).thenReturn(anotherSourceType); - - defaultConfig.onRepositoryChange(someNamespace, newProperties); - - ConfigChangeEvent changeEvent = configChangeFuture.get(500, TimeUnit.MILLISECONDS); - - //clean up - System.clearProperty(someKey); - - assertEquals(someNamespace, changeEvent.getNamespace()); - assertEquals(4, changeEvent.changedKeys().size()); - - ConfigChange anotherKeyChange = changeEvent.getChange(anotherKey); - assertEquals(someLocalFileValue, anotherKeyChange.getOldValue()); - assertEquals(anotherKeyNewValue, anotherKeyChange.getNewValue()); - assertEquals(PropertyChangeType.MODIFIED, anotherKeyChange.getChangeType()); - - ConfigChange yetAnotherKeyChange = changeEvent.getChange(yetAnotherKey); - assertEquals(yetAnotherValue, yetAnotherKeyChange.getOldValue()); - assertEquals(yetAnotherResourceValue, yetAnotherKeyChange.getNewValue()); - assertEquals(PropertyChangeType.MODIFIED, yetAnotherKeyChange.getChangeType()); - - ConfigChange keyToBeDeletedChange = changeEvent.getChange(keyToBeDeleted); - assertEquals(keyToBeDeletedValue, keyToBeDeletedChange.getOldValue()); - assertEquals(null, keyToBeDeletedChange.getNewValue()); - assertEquals(PropertyChangeType.DELETED, keyToBeDeletedChange.getChangeType()); - - ConfigChange newKeyChange = changeEvent.getChange(newKey); - assertEquals(null, newKeyChange.getOldValue()); - assertEquals(newValue, newKeyChange.getNewValue()); - assertEquals(PropertyChangeType.ADDED, newKeyChange.getChangeType()); - - assertEquals(anotherSourceType, defaultConfig.getSourceType()); - } - - @Test - public void testFireConfigChangeWithInterestedKeys() throws Exception { - String someKeyChanged = "someKeyChanged"; - String anotherKeyChanged = "anotherKeyChanged"; - String someKeyNotChanged = "someKeyNotChanged"; - String someNamespace = "someNamespace"; - Map changes = Maps.newHashMap(); - changes.put(someKeyChanged, mock(ConfigChange.class)); - changes.put(anotherKeyChanged, mock(ConfigChange.class)); - ConfigChangeEvent someChangeEvent = new ConfigChangeEvent(someNamespace, changes); - - final SettableFuture interestedInAllKeysFuture = SettableFuture.create(); - ConfigChangeListener interestedInAllKeys = new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - interestedInAllKeysFuture.set(changeEvent); - } - }; - - final SettableFuture interestedInSomeKeyFuture = SettableFuture.create(); - ConfigChangeListener interestedInSomeKey = new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - interestedInSomeKeyFuture.set(changeEvent); - } - }; - - final SettableFuture interestedInSomeKeyNotChangedFuture = SettableFuture.create(); - ConfigChangeListener interestedInSomeKeyNotChanged = new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - interestedInSomeKeyNotChangedFuture.set(changeEvent); - } - }; - - DefaultConfig config = new DefaultConfig(someNamespace, mock(ConfigRepository.class)); - - config.addChangeListener(interestedInAllKeys); - config.addChangeListener(interestedInSomeKey, Sets.newHashSet(someKeyChanged)); - config.addChangeListener(interestedInSomeKeyNotChanged, Sets.newHashSet(someKeyNotChanged)); - - config.fireConfigChange(someChangeEvent); - - ConfigChangeEvent changeEvent = interestedInAllKeysFuture.get(500, TimeUnit.MILLISECONDS); - - assertEquals(someChangeEvent, changeEvent); - - { - // hidden variables in scope - ConfigChangeEvent actualConfigChangeEvent = interestedInSomeKeyFuture.get(500, TimeUnit.MILLISECONDS); - assertEquals(someChangeEvent.changedKeys(), actualConfigChangeEvent.changedKeys()); - for (String changedKey : someChangeEvent.changedKeys()) { - ConfigChange expectConfigChange = someChangeEvent.getChange(changedKey); - ConfigChange actualConfigChange = actualConfigChangeEvent.getChange(changedKey); - assertEquals(expectConfigChange, actualConfigChange); - } - } - - assertFalse(interestedInSomeKeyNotChangedFuture.isDone()); - } - - @Test - public void testRemoveChangeListener() throws Exception { - String someNamespace = "someNamespace"; - final ConfigChangeEvent someConfigChangeEvent = mock(ConfigChangeEvent.class); - ConfigChangeEvent anotherConfigChangeEvent = mock(ConfigChangeEvent.class); - - final SettableFuture someListenerFuture1 = SettableFuture.create(); - final SettableFuture someListenerFuture2 = SettableFuture.create(); - ConfigChangeListener someListener = new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - if (someConfigChangeEvent == changeEvent) { - someListenerFuture1.set(changeEvent); - } else { - someListenerFuture2.set(changeEvent); - } - } - }; - - final SettableFuture anotherListenerFuture1 = SettableFuture.create(); - final SettableFuture anotherListenerFuture2 = SettableFuture.create(); - ConfigChangeListener anotherListener = new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - if (someConfigChangeEvent == changeEvent) { - anotherListenerFuture1.set(changeEvent); - } else { - anotherListenerFuture2.set(changeEvent); - } - } - }; - - ConfigChangeListener yetAnotherListener = mock(ConfigChangeListener.class); - - DefaultConfig config = new DefaultConfig(someNamespace, mock(ConfigRepository.class)); - - config.addChangeListener(someListener); - config.addChangeListener(anotherListener); - - config.fireConfigChange(someConfigChangeEvent); - - assertEquals(someConfigChangeEvent, someListenerFuture1.get(500, TimeUnit.MILLISECONDS)); - assertEquals(someConfigChangeEvent, anotherListenerFuture1.get(500, TimeUnit.MILLISECONDS)); - - assertFalse(config.removeChangeListener(yetAnotherListener)); - assertTrue(config.removeChangeListener(someListener)); - - config.fireConfigChange(anotherConfigChangeEvent); - - assertEquals(anotherConfigChangeEvent, anotherListenerFuture2.get(500, TimeUnit.MILLISECONDS)); - - TimeUnit.MILLISECONDS.sleep(100); - - assertFalse(someListenerFuture2.isDone()); - } - - @Test - public void testGetPropertyNames() { - String someKeyPrefix = "someKey"; - String someValuePrefix = "someValue"; - - //set up config repo - someProperties = new Properties(); - for (int i = 0; i < 10; i++) { - someProperties.setProperty(someKeyPrefix + i, someValuePrefix + i); - } - - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = new DefaultConfig(someNamespace, configRepository); - - Set propertyNames = defaultConfig.getPropertyNames(); - - assertEquals(10, propertyNames.size()); - assertEquals(someProperties.stringPropertyNames(), propertyNames); - } - - @Test - public void testGetPropertyNamesWithOrderedProperties() { - String someKeyPrefix = "someKey"; - String someValuePrefix = "someValue"; - - when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer() { - @Override - public Properties answer(InvocationOnMock invocation) { - return new OrderedProperties(); - } - }); - //set up config repo - someProperties = new OrderedProperties(); - for (int i = 0; i < 10; i++) { - someProperties.setProperty(someKeyPrefix + i, someValuePrefix + i); - } - - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = new DefaultConfig(someNamespace, configRepository); - - Set propertyNames = defaultConfig.getPropertyNames(); - - assertEquals(10, propertyNames.size()); - assertEquals(someProperties.stringPropertyNames(), propertyNames); - } - - @Test - public void testGetPropertyNamesWithNullProp() { - when(configRepository.getConfig()).thenReturn(null); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - Set propertyNames = defaultConfig.getPropertyNames(); - assertEquals(Collections.emptySet(), propertyNames); - } - - @Test - public void testGetPropertyWithFunction() throws Exception { - - String someKey = "someKey"; - String someValue = "a,b,c"; - - String someNullKey = "someNullKey"; - - //set up config repo - someProperties = new Properties(); - someProperties.setProperty(someKey, someValue); - when(configRepository.getConfig()).thenReturn(someProperties); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - assertEquals(defaultConfig.getProperty(someKey, new Function>() { - @Override - public List apply(String s) { - return Splitter.on(",").trimResults().omitEmptyStrings().splitToList(s); - } - }, Lists.newArrayList()), Lists.newArrayList("a", "b", "c")); - assertEquals(defaultConfig.getProperty(someNullKey, new Function>() { - @Override - public List apply(String s) { - return Splitter.on(",").trimResults().omitEmptyStrings().splitToList(s); - } - }, Lists.newArrayList()), Lists.newArrayList()); - } - - @Test - public void testLoadFromRepositoryFailedAndThenRecovered() { - String someKey = "someKey"; - String someValue = "someValue"; - String someDefaultValue = "someDefaultValue"; - ConfigSourceType someSourceType = ConfigSourceType.REMOTE; - - when(configRepository.getConfig()).thenThrow(mock(RuntimeException.class)); - - DefaultConfig defaultConfig = - new DefaultConfig(someNamespace, configRepository); - - verify(configRepository, times(1)).addChangeListener(defaultConfig); - - assertEquals(ConfigSourceType.NONE, defaultConfig.getSourceType()); - assertEquals(someDefaultValue, defaultConfig.getProperty(someKey, someDefaultValue)); - - someProperties = new Properties(); - someProperties.setProperty(someKey, someValue); - - when(configRepository.getSourceType()).thenReturn(someSourceType); - - defaultConfig.onRepositoryChange(someNamespace, someProperties); - - assertEquals(someSourceType, defaultConfig.getSourceType()); - assertEquals(someValue, defaultConfig.getProperty(someKey, someDefaultValue)); - } - - private void checkDatePropertyWithFormat(Config config, Date expected, String propertyName, String format, Date - defaultValue) { - assertEquals(expected, config.getDateProperty(propertyName, format, defaultValue)); - } - - private void checkDatePropertyWithoutFormat(Config config, Date expected, String propertyName, Date defaultValue) { - assertEquals(expected, config.getDateProperty(propertyName, defaultValue)); - } - - private Date assembleDate(int year, int month, int day, int hour, int minute, int second, int millisecond) { - Calendar date = Calendar.getInstance(); - date.set(year, month - 1, day, hour, minute, second); //Month in Calendar is 0 based - date.set(Calendar.MILLISECOND, millisecond); - - return date.getTime(); - } - - private enum SomeEnum { - someValue, defaultValue - } - - public static class MockConfigUtil extends ConfigUtil { - @Override - public long getMaxConfigCacheSize() { - return 10; - } - - @Override - public long getConfigCacheExpireTime() { - return 1; - } - - @Override - public TimeUnit getConfigCacheExpireTimeUnit() { - return TimeUnit.MINUTES; - } - } - - public static class MockConfigUtilWithSmallCache extends MockConfigUtil { - @Override - public long getMaxConfigCacheSize() { - return 1; - } - } - - public static class MockConfigUtilWithShortExpireTime extends MockConfigUtil { - @Override - public long getConfigCacheExpireTime() { - return 50; - } - - @Override - public TimeUnit getConfigCacheExpireTimeUnit() { - return TimeUnit.MILLISECONDS; - } - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProviderTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProviderTest.java deleted file mode 100644 index 603a4f8e369..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProviderTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.assertEquals; - -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.core.enums.Env; -import org.junit.After; -import org.junit.Test; - -public class DefaultMetaServerProviderTest { - - @After - public void tearDown() throws Exception { - System.clearProperty(ConfigConsts.APOLLO_META_KEY); - } - - @Test - public void testWithSystemProperty() throws Exception { - String someMetaAddress = "someMetaAddress"; - Env someEnv = Env.DEV; - - System.setProperty(ConfigConsts.APOLLO_META_KEY, " " + someMetaAddress + " "); - - DefaultMetaServerProvider defaultMetaServerProvider = new DefaultMetaServerProvider(); - - assertEquals(someMetaAddress, defaultMetaServerProvider.getMetaServerAddress(someEnv)); - } - -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/InterestedConfigChangeEventTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/InterestedConfigChangeEventTest.java deleted file mode 100644 index 9ffdfcb8d03..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/InterestedConfigChangeEventTest.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.*; - -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.ctrip.framework.apollo.enums.PropertyChangeType; -import com.ctrip.framework.apollo.model.ConfigChange; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import com.google.common.collect.Sets; -import com.google.common.util.concurrent.SettableFuture; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import org.junit.Test; - -import static org.mockito.Mockito.*; - -/** - * @author wxq - */ -public class InterestedConfigChangeEventTest { - - @Test - public void TestInterestedChangedKeys() - throws ExecutionException, InterruptedException, TimeoutException { - - final String namespace = "app"; - final String keyPrefix = "key-abc."; - final String key = keyPrefix + UUID.randomUUID(); - final String anotherKey = UUID.randomUUID().toString(); - - final SettableFuture onChangeFuture = SettableFuture.create(); - ConfigChangeListener configChangeListener = spy(new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - assertEquals(namespace, changeEvent.getNamespace()); - assertEquals(2, changeEvent.changedKeys().size()); - assertTrue(changeEvent.changedKeys().containsAll(Sets.newHashSet(key, anotherKey))); - assertEquals(1, changeEvent.interestedChangedKeys().size()); - assertTrue(changeEvent.interestedChangedKeys().contains(key)); - onChangeFuture.set(changeEvent); - } - }); - - UnsupportedOperationConfig config = new UnsupportedOperationConfig(); - config.addChangeListener(configChangeListener, Collections.singleton("key-nothing"), Collections.singleton(keyPrefix)); - - - Map changes = new HashMap<>(); - changes.put(key, new ConfigChange(namespace, key, "123", "456", PropertyChangeType.MODIFIED)); - changes.put(anotherKey, - new ConfigChange(namespace, anotherKey, null, "someValue", PropertyChangeType.ADDED)); - config.fireConfigChange(namespace, changes); - - onChangeFuture.get(500, TimeUnit.MILLISECONDS); - - verify(configChangeListener, atLeastOnce()).onChange(any()); - } - - /** - * @author wxq - */ - private static class UnsupportedOperationConfig extends AbstractConfig { - - @Override - public String getProperty(String key, String defaultValue) { - throw new UnsupportedOperationException(); - } - - @Override - public Set getPropertyNames() { - throw new UnsupportedOperationException(); - } - - @Override - public ConfigSourceType getSourceType() { - throw new UnsupportedOperationException(); - } - } -} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/JsonConfigFileTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/JsonConfigFileTest.java deleted file mode 100644 index cf93cd417d0..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/JsonConfigFileTest.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import java.util.Properties; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -@RunWith(MockitoJUnitRunner.class) -public class JsonConfigFileTest { - private String someNamespace; - @Mock - private ConfigRepository configRepository; - - private ConfigSourceType someSourceType; - - @Before - public void setUp() throws Exception { - someNamespace = "someName"; - } - - @Test - public void testWhenHasContent() throws Exception { - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someValue = "someValue"; - someProperties.setProperty(key, someValue); - - someSourceType = ConfigSourceType.LOCAL; - - when(configRepository.getConfig()).thenReturn(someProperties); - when(configRepository.getSourceType()).thenReturn(someSourceType); - - JsonConfigFile configFile = new JsonConfigFile(someNamespace, configRepository); - - assertEquals(ConfigFileFormat.JSON, configFile.getConfigFileFormat()); - assertEquals(someNamespace, configFile.getNamespace()); - assertTrue(configFile.hasContent()); - assertEquals(someValue, configFile.getContent()); - assertEquals(someSourceType, configFile.getSourceType()); - } - - @Test - public void testWhenHasNoContent() throws Exception { - when(configRepository.getConfig()).thenReturn(null); - - JsonConfigFile configFile = new JsonConfigFile(someNamespace, configRepository); - - assertFalse(configFile.hasContent()); - assertNull(configFile.getContent()); - } - - @Test - public void testWhenConfigRepositoryHasError() throws Exception { - when(configRepository.getConfig()).thenThrow(new RuntimeException("someError")); - - JsonConfigFile configFile = new JsonConfigFile(someNamespace, configRepository); - - assertFalse(configFile.hasContent()); - assertNull(configFile.getContent()); - assertEquals(ConfigSourceType.NONE, configFile.getSourceType()); - } - - @Test - public void testOnRepositoryChange() throws Exception { - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someValue = "someValue"; - String anotherValue = "anotherValue"; - someProperties.setProperty(key, someValue); - - someSourceType = ConfigSourceType.LOCAL; - - when(configRepository.getConfig()).thenReturn(someProperties); - when(configRepository.getSourceType()).thenReturn(someSourceType); - - JsonConfigFile configFile = new JsonConfigFile(someNamespace, configRepository); - - assertEquals(someValue, configFile.getContent()); - assertEquals(someSourceType, configFile.getSourceType()); - - Properties anotherProperties = new Properties(); - anotherProperties.setProperty(key, anotherValue); - - ConfigSourceType anotherSourceType = ConfigSourceType.REMOTE; - when(configRepository.getSourceType()).thenReturn(anotherSourceType); - - configFile.onRepositoryChange(someNamespace, anotherProperties); - - assertEquals(anotherValue, configFile.getContent()); - assertEquals(anotherSourceType, configFile.getSourceType()); - } - - @Test - public void testWhenConfigRepositoryHasErrorAndThenRecovered() throws Exception { - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someValue = "someValue"; - someProperties.setProperty(key, someValue); - - someSourceType = ConfigSourceType.LOCAL; - - when(configRepository.getConfig()).thenThrow(new RuntimeException("someError")); - when(configRepository.getSourceType()).thenReturn(someSourceType); - - JsonConfigFile configFile = new JsonConfigFile(someNamespace, configRepository); - - assertFalse(configFile.hasContent()); - assertNull(configFile.getContent()); - assertEquals(ConfigSourceType.NONE, configFile.getSourceType()); - - configFile.onRepositoryChange(someNamespace, someProperties); - - assertTrue(configFile.hasContent()); - assertEquals(someValue, configFile.getContent()); - assertEquals(someSourceType, configFile.getSourceType()); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepositoryTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepositoryTest.java deleted file mode 100644 index 9636e312772..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/LocalFileConfigRepositoryTest.java +++ /dev/null @@ -1,237 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.ctrip.framework.apollo.util.factory.PropertiesFactory; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Properties; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.base.Charsets; -import com.google.common.base.Joiner; -import com.google.common.io.Files; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; - -/** - * Created by Jason on 4/9/16. - */ -public class LocalFileConfigRepositoryTest { - private File someBaseDir; - private String someNamespace; - private ConfigRepository upstreamRepo; - private Properties someProperties; - private static String someAppId = "someApp"; - private static String someCluster = "someCluster"; - private String defaultKey; - private String defaultValue; - private ConfigSourceType someSourceType; - - @Before - public void setUp() throws Exception { - someBaseDir = new File("src/test/resources/config-cache"); - someBaseDir.mkdir(); - - someNamespace = "someName"; - someProperties = new Properties(); - defaultKey = "defaultKey"; - defaultValue = "defaultValue"; - someProperties.setProperty(defaultKey, defaultValue); - someSourceType = ConfigSourceType.REMOTE; - upstreamRepo = mock(ConfigRepository.class); - when(upstreamRepo.getConfig()).thenReturn(someProperties); - when(upstreamRepo.getSourceType()).thenReturn(someSourceType); - - MockInjector.setInstance(ConfigUtil.class, new MockConfigUtil()); - PropertiesFactory propertiesFactory = mock(PropertiesFactory.class); - when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer() { - @Override - public Properties answer(InvocationOnMock invocation) { - return new Properties(); - } - }); - MockInjector.setInstance(PropertiesFactory.class, propertiesFactory); - } - - @After - public void tearDown() throws Exception { - MockInjector.reset(); - recursiveDelete(someBaseDir); - } - - //helper method to clean created files - private void recursiveDelete(File file) { - if (!file.exists()) { - return; - } - if (file.isDirectory()) { - for (File f : file.listFiles()) { - recursiveDelete(f); - } - } - file.delete(); - } - - private String assembleLocalCacheFileName() { - return String.format("%s.properties", Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR) - .join(someAppId, someCluster, someNamespace)); - } - - - @Test - public void testLoadConfigWithLocalFile() throws Exception { - - String someKey = "someKey"; - String someValue = "someValue\nxxx\nyyy"; - - Properties someProperties = new Properties(); - someProperties.setProperty(someKey, someValue); - createLocalCachePropertyFile(someProperties); - - LocalFileConfigRepository localRepo = new LocalFileConfigRepository(someNamespace); - localRepo.setLocalCacheDir(someBaseDir, true); - Properties properties = localRepo.getConfig(); - - assertEquals(someValue, properties.getProperty(someKey)); - assertEquals(ConfigSourceType.LOCAL, localRepo.getSourceType()); - } - - @Test - public void testLoadConfigWithLocalFileAndFallbackRepo() throws Exception { - File file = new File(someBaseDir, assembleLocalCacheFileName()); - - String someValue = "someValue"; - - Files.write(defaultKey + "=" + someValue, file, Charsets.UTF_8); - - LocalFileConfigRepository localRepo = new LocalFileConfigRepository(someNamespace, upstreamRepo); - localRepo.setLocalCacheDir(someBaseDir, true); - - Properties properties = localRepo.getConfig(); - - assertEquals(defaultValue, properties.getProperty(defaultKey)); - assertEquals(someSourceType, localRepo.getSourceType()); - } - - @Test - public void testLoadConfigWithNoLocalFile() throws Exception { - LocalFileConfigRepository localFileConfigRepository = - new LocalFileConfigRepository(someNamespace, upstreamRepo); - localFileConfigRepository.setLocalCacheDir(someBaseDir, true); - - Properties result = localFileConfigRepository.getConfig(); - - assertEquals( - "LocalFileConfigRepository's properties should be the same as fallback repo's when there is no local cache", - result, someProperties); - assertEquals(someSourceType, localFileConfigRepository.getSourceType()); - } - - @Test - public void testLoadConfigWithNoLocalFileMultipleTimes() throws Exception { - LocalFileConfigRepository localRepo = - new LocalFileConfigRepository(someNamespace, upstreamRepo); - localRepo.setLocalCacheDir(someBaseDir, true); - - Properties someProperties = localRepo.getConfig(); - - LocalFileConfigRepository - anotherLocalRepoWithNoFallback = - new LocalFileConfigRepository(someNamespace); - anotherLocalRepoWithNoFallback.setLocalCacheDir(someBaseDir, true); - - Properties anotherProperties = anotherLocalRepoWithNoFallback.getConfig(); - - assertEquals( - "LocalFileConfigRepository should persist local cache files and return that afterwards", - someProperties, anotherProperties); - assertEquals(someSourceType, localRepo.getSourceType()); - } - - @Test - public void testOnRepositoryChange() throws Exception { - RepositoryChangeListener someListener = mock(RepositoryChangeListener.class); - - LocalFileConfigRepository localFileConfigRepository = - new LocalFileConfigRepository(someNamespace, upstreamRepo); - - assertEquals(someSourceType, localFileConfigRepository.getSourceType()); - - localFileConfigRepository.setLocalCacheDir(someBaseDir, true); - localFileConfigRepository.addChangeListener(someListener); - - localFileConfigRepository.getConfig(); - - Properties anotherProperties = new Properties(); - anotherProperties.put("anotherKey", "anotherValue"); - - ConfigSourceType anotherSourceType = ConfigSourceType.NONE; - when(upstreamRepo.getSourceType()).thenReturn(anotherSourceType); - - localFileConfigRepository.onRepositoryChange(someNamespace, anotherProperties); - - final ArgumentCaptor captor = ArgumentCaptor.forClass(Properties.class); - - verify(someListener, times(1)).onRepositoryChange(eq(someNamespace), captor.capture()); - - assertEquals(anotherProperties, captor.getValue()); - assertEquals(anotherSourceType, localFileConfigRepository.getSourceType()); - } - - public static class MockConfigUtil extends ConfigUtil { - @Override - public String getAppId() { - return someAppId; - } - - @Override - public String getCluster() { - return someCluster; - } - } - - private File createLocalCachePropertyFile(Properties properties) throws IOException { - File file = new File(someBaseDir, assembleLocalCacheFileName()); - FileOutputStream in = null; - try { - in = new FileOutputStream(file); - properties.store(in, "Persisted by LocalFileConfigRepositoryTest"); - } finally { - if (in != null) { - in.close(); - } - } - return file; - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/PropertiesCompatibleFileConfigRepositoryTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/PropertiesCompatibleFileConfigRepositoryTest.java deleted file mode 100644 index 1b90a355853..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/PropertiesCompatibleFileConfigRepositoryTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.PropertiesCompatibleConfigFile; -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.ctrip.framework.apollo.model.ConfigFileChangeEvent; -import java.util.Properties; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class PropertiesCompatibleFileConfigRepositoryTest { - - @Mock - private PropertiesCompatibleConfigFile configFile; - - private String someNamespaceName; - - @Mock - private Properties someProperties; - - @Before - public void setUp() throws Exception { - someNamespaceName = "someNamespaceName"; - when(configFile.getNamespace()).thenReturn(someNamespaceName); - when(configFile.asProperties()).thenReturn(someProperties); - } - - @Test - public void testGetConfig() throws Exception { - PropertiesCompatibleFileConfigRepository configFileRepository = new PropertiesCompatibleFileConfigRepository( - configFile); - - assertSame(someProperties, configFileRepository.getConfig()); - verify(configFile, times(1)).addChangeListener(configFileRepository); - } - - @Test - public void testGetConfigFailedAndThenRecovered() throws Exception { - RuntimeException someException = new RuntimeException("some exception"); - - when(configFile.asProperties()).thenThrow(someException); - - PropertiesCompatibleFileConfigRepository configFileRepository = new PropertiesCompatibleFileConfigRepository( - configFile); - - Throwable exceptionThrown = null; - try { - configFileRepository.getConfig(); - } catch (Throwable ex) { - exceptionThrown = ex; - } - - assertSame(someException, exceptionThrown); - - // recovered - reset(configFile); - - Properties someProperties = mock(Properties.class); - - when(configFile.asProperties()).thenReturn(someProperties); - - assertSame(someProperties, configFileRepository.getConfig()); - } - - @Test(expected = IllegalStateException.class) - public void testGetConfigWithConfigFileReturnNullProperties() throws Exception { - when(configFile.asProperties()).thenReturn(null); - - PropertiesCompatibleFileConfigRepository configFileRepository = new PropertiesCompatibleFileConfigRepository( - configFile); - - configFileRepository.getConfig(); - } - - @Test - public void testGetSourceType() throws Exception { - ConfigSourceType someType = ConfigSourceType.REMOTE; - - when(configFile.getSourceType()).thenReturn(someType); - - PropertiesCompatibleFileConfigRepository configFileRepository = new PropertiesCompatibleFileConfigRepository( - configFile); - - assertSame(someType, configFileRepository.getSourceType()); - } - - @Test - public void testOnChange() throws Exception { - Properties anotherProperties = mock(Properties.class); - ConfigFileChangeEvent someChangeEvent = mock(ConfigFileChangeEvent.class); - - RepositoryChangeListener someListener = mock(RepositoryChangeListener.class); - - PropertiesCompatibleFileConfigRepository configFileRepository = new PropertiesCompatibleFileConfigRepository( - configFile); - - configFileRepository.addChangeListener(someListener); - - assertSame(someProperties, configFileRepository.getConfig()); - - when(configFile.asProperties()).thenReturn(anotherProperties); - - configFileRepository.onChange(someChangeEvent); - - assertSame(anotherProperties, configFileRepository.getConfig()); - verify(someListener, times(1)).onRepositoryChange(someNamespaceName, anotherProperties); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/PropertiesConfigFileTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/PropertiesConfigFileTest.java deleted file mode 100644 index 41add46b1d6..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/PropertiesConfigFileTest.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.ConfigFileChangeListener; -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.enums.PropertyChangeType; -import com.ctrip.framework.apollo.model.ConfigFileChangeEvent; -import com.ctrip.framework.apollo.util.factory.PropertiesFactory; -import com.google.common.util.concurrent.SettableFuture; -import java.util.Properties; - -import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; - -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import org.mockito.stubbing.Answer; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -@RunWith(MockitoJUnitRunner.class) -public class PropertiesConfigFileTest { - - private String someNamespace; - @Mock - private ConfigRepository configRepository; - @Mock - private PropertiesFactory propertiesFactory; - - @Before - public void setUp() throws Exception { - someNamespace = "someName"; - when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer() { - @Override - public Properties answer(InvocationOnMock invocation) { - return new Properties(); - } - }); - MockInjector.setInstance(PropertiesFactory.class, propertiesFactory); - } - - @After - public void tearDown() throws Exception { - MockInjector.reset(); - } - - @Test - public void testWhenHasContent() throws Exception { - Properties someProperties = new Properties(); - String someKey = "someKey"; - String someValue = "someValue"; - someProperties.setProperty(someKey, someValue); - - when(configRepository.getConfig()).thenReturn(someProperties); - - PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); - - assertEquals(ConfigFileFormat.Properties, configFile.getConfigFileFormat()); - assertEquals(someNamespace, configFile.getNamespace()); - assertTrue(configFile.hasContent()); - assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue))); - } - - @Test - public void testWhenHasNoContent() throws Exception { - when(configRepository.getConfig()).thenReturn(null); - - PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); - - assertFalse(configFile.hasContent()); - assertNull(configFile.getContent()); - } - - @Test - public void testWhenConfigRepositoryHasError() throws Exception { - when(configRepository.getConfig()).thenThrow(new RuntimeException("someError")); - - PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); - - assertFalse(configFile.hasContent()); - assertNull(configFile.getContent()); - } - - @Test - public void testOnRepositoryChange() throws Exception { - Properties someProperties = new Properties(); - String someKey = "someKey"; - String someValue = "someValue"; - String anotherValue = "anotherValue"; - someProperties.setProperty(someKey, someValue); - - when(configRepository.getConfig()).thenReturn(someProperties); - - PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); - - assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue))); - - Properties anotherProperties = new Properties(); - anotherProperties.setProperty(someKey, anotherValue); - - final SettableFuture configFileChangeFuture = SettableFuture.create(); - ConfigFileChangeListener someListener = new ConfigFileChangeListener() { - @Override - public void onChange(ConfigFileChangeEvent changeEvent) { - configFileChangeFuture.set(changeEvent); - } - }; - - configFile.addChangeListener(someListener); - - configFile.onRepositoryChange(someNamespace, anotherProperties); - - ConfigFileChangeEvent changeEvent = configFileChangeFuture.get(500, TimeUnit.MILLISECONDS); - - assertFalse(configFile.getContent().contains(String.format("%s=%s", someKey, someValue))); - assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, anotherValue))); - - assertEquals(someNamespace, changeEvent.getNamespace()); - assertTrue(changeEvent.getOldValue().contains(String.format("%s=%s", someKey, someValue))); - assertTrue(changeEvent.getNewValue().contains(String.format("%s=%s", someKey, anotherValue))); - assertEquals(PropertyChangeType.MODIFIED, changeEvent.getChangeType()); - } - - @Test - public void testWhenConfigRepositoryHasErrorAndThenRecovered() throws Exception { - Properties someProperties = new Properties(); - String someKey = "someKey"; - String someValue = "someValue"; - someProperties.setProperty(someKey, someValue); - - when(configRepository.getConfig()).thenThrow(new RuntimeException("someError")); - - PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); - - assertFalse(configFile.hasContent()); - assertNull(configFile.getContent()); - - configFile.onRepositoryChange(someNamespace, someProperties); - - assertTrue(configFile.hasContent()); - assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue))); - } - - @Test - public void testIfCompatibleWithProperties() { - Properties someProperties = new Properties(); - String someKey = "someKey"; - String someValue = "someValue"; - someProperties.setProperty(someKey, someValue); - - when(configRepository.getConfig()).thenReturn(someProperties); - - PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); - - assertEquals(configFile.asProperties(),someProperties); - assertEquals(ConfigFileFormat.Properties, configFile.getConfigFileFormat()); - assertEquals(someNamespace, configFile.getNamespace()); - assertTrue(configFile.hasContent()); - assertTrue(configFile.getContent().contains(String.format("%s=%s", someKey, someValue))); - } - - @Test - public void testIfCompatibleWithEmptyProperties() { - Properties someProperties = new Properties(); - - when(configRepository.getConfig()).thenReturn(someProperties); - - PropertiesConfigFile configFile = new PropertiesConfigFile(someNamespace, configRepository); - - assertEquals(configFile.asProperties(),someProperties); - assertEquals(ConfigFileFormat.Properties, configFile.getConfigFileFormat()); - assertEquals(someNamespace, configFile.getNamespace()); - assertFalse(configFile.hasContent()); - - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollServiceTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollServiceTest.java deleted file mode 100644 index 37fd27c08f5..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollServiceTest.java +++ /dev/null @@ -1,582 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification; -import com.ctrip.framework.apollo.core.dto.ApolloNotificationMessages; -import com.ctrip.framework.apollo.core.dto.ServiceDTO; -import com.ctrip.framework.apollo.core.signature.Signature; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.ctrip.framework.apollo.util.http.HttpRequest; -import com.ctrip.framework.apollo.util.http.HttpResponse; -import com.ctrip.framework.apollo.util.http.HttpClient; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.net.HttpHeaders; -import com.google.common.util.concurrent.SettableFuture; -import java.lang.reflect.Type; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import javax.servlet.http.HttpServletResponse; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; -import org.springframework.test.util.ReflectionTestUtils; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -@RunWith(MockitoJUnitRunner.class) -public class RemoteConfigLongPollServiceTest { - private RemoteConfigLongPollService remoteConfigLongPollService; - @Mock - private HttpResponse> pollResponse; - @Mock - private HttpClient httpClient; - @Mock - private ConfigServiceLocator configServiceLocator; - private Type responseType; - - private static String someServerUrl; - private static String someAppId; - private static String someCluster; - private static String someSecret; - - @Before - public void setUp() throws Exception { - MockInjector.setInstance(HttpClient.class, httpClient); - - someServerUrl = "http://someServer"; - ServiceDTO serviceDTO = mock(ServiceDTO.class); - when(serviceDTO.getHomepageUrl()).thenReturn(someServerUrl); - when(configServiceLocator.getConfigServices()).thenReturn(Lists.newArrayList(serviceDTO)); - MockInjector.setInstance(ConfigServiceLocator.class, configServiceLocator); - - MockInjector.setInstance(ConfigUtil.class, new MockConfigUtil()); - - remoteConfigLongPollService = new RemoteConfigLongPollService(); - - responseType = - (Type) ReflectionTestUtils.getField(remoteConfigLongPollService, "m_responseType"); - - someAppId = "someAppId"; - someCluster = "someCluster"; - } - - @After - public void tearDown() throws Exception { - MockInjector.reset(); - } - - @Test - public void testSubmitLongPollNamespaceWith304Response() throws Exception { - RemoteConfigRepository someRepository = mock(RemoteConfigRepository.class); - final String someNamespace = "someNamespace"; - - when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_NOT_MODIFIED); - final SettableFuture longPollFinished = SettableFuture.create(); - - doAnswer(new Answer>>() { - @Override - public HttpResponse> answer(InvocationOnMock invocation) - throws Throwable { - try { - TimeUnit.MILLISECONDS.sleep(50); - } catch (InterruptedException e) { - } - HttpRequest request = invocation.getArgument(0, HttpRequest.class); - - assertTrue(request.getUrl().contains(someServerUrl + "/notifications/v2?")); - assertTrue(request.getUrl().contains("appId=" + someAppId)); - assertTrue(request.getUrl().contains("cluster=" + someCluster)); - assertTrue(request.getUrl().contains("notifications=")); - assertTrue(request.getUrl().contains(someNamespace)); - - longPollFinished.set(true); - return pollResponse; - } - }).when(httpClient).doGet(any(HttpRequest.class), eq(responseType)); - - remoteConfigLongPollService.submit(someNamespace, someRepository); - - longPollFinished.get(5000, TimeUnit.MILLISECONDS); - - remoteConfigLongPollService.stopLongPollingRefresh(); - - verify(someRepository, never()).onLongPollNotified(any(ServiceDTO.class), any(ApolloNotificationMessages.class)); - } - - @Test - public void testSubmitLongPollNamespaceWith200Response() throws Exception { - RemoteConfigRepository someRepository = mock(RemoteConfigRepository.class); - final String someNamespace = "someNamespace"; - - ApolloNotificationMessages notificationMessages = new ApolloNotificationMessages(); - String someKey = "someKey"; - long someNotificationId = 1; - String anotherKey = "anotherKey"; - long anotherNotificationId = 2; - notificationMessages.put(someKey, someNotificationId); - notificationMessages.put(anotherKey, anotherNotificationId); - - ApolloConfigNotification someNotification = mock(ApolloConfigNotification.class); - when(someNotification.getNamespaceName()).thenReturn(someNamespace); - when(someNotification.getMessages()).thenReturn(notificationMessages); - - when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_OK); - when(pollResponse.getBody()).thenReturn(Lists.newArrayList(someNotification)); - - doAnswer(new Answer>>() { - @Override - public HttpResponse> answer(InvocationOnMock invocation) - throws Throwable { - try { - TimeUnit.MILLISECONDS.sleep(50); - } catch (InterruptedException e) { - } - - return pollResponse; - } - }).when(httpClient).doGet(any(HttpRequest.class), eq(responseType)); - - final SettableFuture onNotified = SettableFuture.create(); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - onNotified.set(true); - return null; - } - }).when(someRepository).onLongPollNotified(any(ServiceDTO.class), any(ApolloNotificationMessages.class)); - - remoteConfigLongPollService.submit(someNamespace, someRepository); - - onNotified.get(5000, TimeUnit.MILLISECONDS); - - remoteConfigLongPollService.stopLongPollingRefresh(); - - final ArgumentCaptor captor = ArgumentCaptor.forClass(ApolloNotificationMessages.class); - verify(someRepository, times(1)).onLongPollNotified(any(ServiceDTO.class), captor.capture()); - - ApolloNotificationMessages captured = captor.getValue(); - - assertEquals(2, captured.getDetails().size()); - assertEquals(someNotificationId, captured.get(someKey).longValue()); - assertEquals(anotherNotificationId, captured.get(anotherKey).longValue()); - } - - @Test - public void testSubmitLongPollNamespaceWithAccessKeySecret() throws Exception { - someSecret = "someSecret"; - RemoteConfigRepository someRepository = mock(RemoteConfigRepository.class); - final String someNamespace = "someNamespace"; - ApolloNotificationMessages notificationMessages = new ApolloNotificationMessages(); - String someKey = "someKey"; - long someNotificationId = 1; - notificationMessages.put(someKey, someNotificationId); - - ApolloConfigNotification someNotification = mock(ApolloConfigNotification.class); - when(someNotification.getNamespaceName()).thenReturn(someNamespace); - when(someNotification.getMessages()).thenReturn(notificationMessages); - - when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_OK); - when(pollResponse.getBody()).thenReturn(Lists.newArrayList(someNotification)); - - doAnswer(new Answer>>() { - @Override - public HttpResponse> answer(InvocationOnMock invocation) - throws Throwable { - try { - TimeUnit.MILLISECONDS.sleep(50); - } catch (InterruptedException e) { - } - - HttpRequest request = invocation.getArgument(0, HttpRequest.class); - - Map headers = request.getHeaders(); - assertNotNull(headers); - assertTrue(headers.containsKey(Signature.HTTP_HEADER_TIMESTAMP)); - assertTrue(headers.containsKey(HttpHeaders.AUTHORIZATION)); - - return pollResponse; - } - }).when(httpClient).doGet(any(HttpRequest.class), eq(responseType)); - - final SettableFuture onNotified = SettableFuture.create(); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - onNotified.set(true); - return null; - } - }).when(someRepository).onLongPollNotified(any(ServiceDTO.class), any(ApolloNotificationMessages.class)); - - remoteConfigLongPollService.submit(someNamespace, someRepository); - onNotified.get(5000, TimeUnit.MILLISECONDS); - remoteConfigLongPollService.stopLongPollingRefresh(); - - verify(someRepository, times(1)).onLongPollNotified(any(ServiceDTO.class), any(ApolloNotificationMessages.class)); - } - - @Test - public void testSubmitLongPollMultipleNamespaces() throws Exception { - RemoteConfigRepository someRepository = mock(RemoteConfigRepository.class); - RemoteConfigRepository anotherRepository = mock(RemoteConfigRepository.class); - final String someNamespace = "someNamespace"; - final String anotherNamespace = "anotherNamespace"; - - final ApolloConfigNotification someNotification = mock(ApolloConfigNotification.class); - when(someNotification.getNamespaceName()).thenReturn(someNamespace); - - final ApolloConfigNotification anotherNotification = mock(ApolloConfigNotification.class); - when(anotherNotification.getNamespaceName()).thenReturn(anotherNamespace); - - final SettableFuture submitAnotherNamespaceStart = SettableFuture.create(); - final SettableFuture submitAnotherNamespaceFinish = SettableFuture.create(); - - doAnswer(new Answer>>() { - final AtomicInteger counter = new AtomicInteger(); - - @Override - public HttpResponse> answer(InvocationOnMock invocation) - throws Throwable { - try { - TimeUnit.MILLISECONDS.sleep(50); - } catch (InterruptedException e) { - } - - //the first time - if (counter.incrementAndGet() == 1) { - HttpRequest request = invocation.getArgument(0, HttpRequest.class); - - assertTrue(request.getUrl().contains("notifications=")); - assertTrue(request.getUrl().contains(someNamespace)); - - submitAnotherNamespaceStart.set(true); - - when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_OK); - when(pollResponse.getBody()).thenReturn(Lists.newArrayList(someNotification)); - } else if (submitAnotherNamespaceFinish.get()) { - HttpRequest request = invocation.getArgument(0, HttpRequest.class); - assertTrue(request.getUrl().contains("notifications=")); - assertTrue(request.getUrl().contains(someNamespace)); - assertTrue(request.getUrl().contains(anotherNamespace)); - - when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_OK); - when(pollResponse.getBody()).thenReturn(Lists.newArrayList(anotherNotification)); - } else { - when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_NOT_MODIFIED); - when(pollResponse.getBody()).thenReturn(null); - } - - return pollResponse; - } - }).when(httpClient).doGet(any(HttpRequest.class), eq(responseType)); - - final SettableFuture onAnotherRepositoryNotified = SettableFuture.create(); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - onAnotherRepositoryNotified.set(true); - return null; - } - }).when(anotherRepository).onLongPollNotified(Mockito.any(ServiceDTO.class), Mockito.nullable(ApolloNotificationMessages.class)); - - remoteConfigLongPollService.submit(someNamespace, someRepository); - - submitAnotherNamespaceStart.get(5000, TimeUnit.MILLISECONDS); - remoteConfigLongPollService.submit(anotherNamespace, anotherRepository); - submitAnotherNamespaceFinish.set(true); - - onAnotherRepositoryNotified.get(5000, TimeUnit.MILLISECONDS); - - remoteConfigLongPollService.stopLongPollingRefresh(); - - verify(someRepository, times(1)).onLongPollNotified(Mockito.any(ServiceDTO.class), Mockito.nullable(ApolloNotificationMessages.class)); - verify(anotherRepository, times(1)).onLongPollNotified(Mockito.any(ServiceDTO.class), Mockito.nullable(ApolloNotificationMessages.class)); - } - - @Test - public void testSubmitLongPollMultipleNamespacesWithMultipleNotificationsReturned() throws Exception { - RemoteConfigRepository someRepository = mock(RemoteConfigRepository.class); - RemoteConfigRepository anotherRepository = mock(RemoteConfigRepository.class); - final String someNamespace = "someNamespace"; - final String anotherNamespace = "anotherNamespace"; - - ApolloNotificationMessages notificationMessages = new ApolloNotificationMessages(); - String someKey = "someKey"; - long someNotificationId = 1; - notificationMessages.put(someKey, someNotificationId); - ApolloNotificationMessages anotherNotificationMessages = new ApolloNotificationMessages(); - String anotherKey = "anotherKey"; - long anotherNotificationId = 2; - anotherNotificationMessages.put(anotherKey, anotherNotificationId); - - final ApolloConfigNotification someNotification = mock(ApolloConfigNotification.class); - when(someNotification.getNamespaceName()).thenReturn(someNamespace); - when(someNotification.getMessages()).thenReturn(notificationMessages); - - final ApolloConfigNotification anotherNotification = mock(ApolloConfigNotification.class); - when(anotherNotification.getNamespaceName()).thenReturn(anotherNamespace); - when(anotherNotification.getMessages()).thenReturn(anotherNotificationMessages); - - when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_OK); - when(pollResponse.getBody()).thenReturn(Lists.newArrayList(someNotification, anotherNotification)); - - doAnswer(new Answer>>() { - @Override - public HttpResponse> answer(InvocationOnMock invocation) - throws Throwable { - try { - TimeUnit.MILLISECONDS.sleep(50); - } catch (InterruptedException e) { - } - - return pollResponse; - } - }).when(httpClient).doGet(any(HttpRequest.class), eq(responseType)); - - final SettableFuture someRepositoryNotified = SettableFuture.create(); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - someRepositoryNotified.set(true); - return null; - } - }).when(someRepository).onLongPollNotified(any(ServiceDTO.class), any(ApolloNotificationMessages.class)); - final SettableFuture anotherRepositoryNotified = SettableFuture.create(); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - anotherRepositoryNotified.set(true); - return null; - } - }).when(anotherRepository).onLongPollNotified(any(ServiceDTO.class), any(ApolloNotificationMessages.class)); - - remoteConfigLongPollService.submit(someNamespace, someRepository); - remoteConfigLongPollService.submit(anotherNamespace, anotherRepository); - - someRepositoryNotified.get(5000, TimeUnit.MILLISECONDS); - anotherRepositoryNotified.get(5000, TimeUnit.MILLISECONDS); - - remoteConfigLongPollService.stopLongPollingRefresh(); - - final ArgumentCaptor captor = ArgumentCaptor.forClass(ApolloNotificationMessages.class); - final ArgumentCaptor anotherCaptor = ArgumentCaptor.forClass(ApolloNotificationMessages.class); - verify(someRepository, times(1)).onLongPollNotified(any(ServiceDTO.class), captor.capture()); - verify(anotherRepository, times(1)).onLongPollNotified(any(ServiceDTO.class), anotherCaptor.capture()); - - ApolloNotificationMessages result = captor.getValue(); - assertEquals(1, result.getDetails().size()); - assertEquals(someNotificationId, result.get(someKey).longValue()); - - ApolloNotificationMessages anotherResult = anotherCaptor.getValue(); - assertEquals(1, anotherResult.getDetails().size()); - assertEquals(anotherNotificationId, anotherResult.get(anotherKey).longValue()); - } - - @Test - public void testSubmitLongPollNamespaceWithMessagesUpdated() throws Exception { - RemoteConfigRepository someRepository = mock(RemoteConfigRepository.class); - final String someNamespace = "someNamespace"; - - ApolloNotificationMessages notificationMessages = new ApolloNotificationMessages(); - String someKey = "someKey"; - long someNotificationId = 1; - notificationMessages.put(someKey, someNotificationId); - - ApolloConfigNotification someNotification = mock(ApolloConfigNotification.class); - when(someNotification.getNamespaceName()).thenReturn(someNamespace); - when(someNotification.getMessages()).thenReturn(notificationMessages); - - when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_OK); - when(pollResponse.getBody()).thenReturn(Lists.newArrayList(someNotification)); - - doAnswer(new Answer>>() { - @Override - public HttpResponse> answer(InvocationOnMock invocation) - throws Throwable { - try { - TimeUnit.MILLISECONDS.sleep(50); - } catch (InterruptedException e) { - } - - return pollResponse; - } - }).when(httpClient).doGet(any(HttpRequest.class), eq(responseType)); - - final SettableFuture onNotified = SettableFuture.create(); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - onNotified.set(true); - return null; - } - }).when(someRepository).onLongPollNotified(any(ServiceDTO.class), any(ApolloNotificationMessages.class)); - - remoteConfigLongPollService.submit(someNamespace, someRepository); - - onNotified.get(5000, TimeUnit.MILLISECONDS); - - //reset to 304 - when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_NOT_MODIFIED); - - final ArgumentCaptor captor = ArgumentCaptor.forClass(ApolloNotificationMessages.class); - verify(someRepository, times(1)).onLongPollNotified(any(ServiceDTO.class), captor.capture()); - - ApolloNotificationMessages captured = captor.getValue(); - - assertEquals(1, captured.getDetails().size()); - assertEquals(someNotificationId, captured.get(someKey).longValue()); - - final SettableFuture anotherOnNotified = SettableFuture.create(); - doAnswer(new Answer() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - anotherOnNotified.set(true); - return null; - } - }).when(someRepository).onLongPollNotified(any(ServiceDTO.class), any(ApolloNotificationMessages.class)); - - String anotherKey = "anotherKey"; - long anotherNotificationId = 2; - notificationMessages.put(anotherKey, anotherNotificationId); - - //send notifications - when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_OK); - - anotherOnNotified.get(5000, TimeUnit.MILLISECONDS); - - remoteConfigLongPollService.stopLongPollingRefresh(); - - verify(someRepository, times(2)).onLongPollNotified(any(ServiceDTO.class), captor.capture()); - - captured = captor.getValue(); - - assertEquals(2, captured.getDetails().size()); - assertEquals(someNotificationId, captured.get(someKey).longValue()); - assertEquals(anotherNotificationId, captured.get(anotherKey).longValue()); - } - - @Test - public void testAssembleLongPollRefreshUrl() throws Exception { - String someUri = someServerUrl; - String someAppId = "someAppId"; - String someCluster = "someCluster+ &.-_someSign"; - String someNamespace = "someName"; - long someNotificationId = 1; - Map notificationsMap = ImmutableMap.of(someNamespace, someNotificationId); - - String longPollRefreshUrl = - remoteConfigLongPollService - .assembleLongPollRefreshUrl(someUri, someAppId, someCluster, null, notificationsMap); - - assertTrue(longPollRefreshUrl.contains(someServerUrl + "/notifications/v2?")); - assertTrue(longPollRefreshUrl.contains("appId=" + someAppId)); - assertTrue(longPollRefreshUrl.contains("cluster=someCluster%2B+%26.-_someSign")); - assertTrue(longPollRefreshUrl.contains("notifications=%5B%7B") - && longPollRefreshUrl.contains("%22namespaceName%22%3A%22" + someNamespace + "%22") - && longPollRefreshUrl.contains("%22notificationId%22%3A" + someNotificationId) - && longPollRefreshUrl.contains("%7D%5D")); - } - - @Test - public void testAssembleLongPollRefreshUrlWithMultipleNamespaces() throws Exception { - String someUri = someServerUrl; - String someAppId = "someAppId"; - String someCluster = "someCluster+ &.-_someSign"; - String someNamespace = "someName"; - String anotherNamespace = "anotherName"; - long someNotificationId = 1; - long anotherNotificationId = 2; - Map notificationsMap = - ImmutableMap.of(someNamespace, someNotificationId, anotherNamespace, anotherNotificationId); - - String longPollRefreshUrl = - remoteConfigLongPollService - .assembleLongPollRefreshUrl(someUri, someAppId, someCluster, null, notificationsMap); - - assertTrue(longPollRefreshUrl.contains(someServerUrl + "/notifications/v2?")); - assertTrue(longPollRefreshUrl.contains("appId=" + someAppId)); - assertTrue(longPollRefreshUrl.contains("cluster=someCluster%2B+%26.-_someSign")); - assertTrue(longPollRefreshUrl.contains("notifications=%5B%7B") - && longPollRefreshUrl.contains("%22namespaceName%22%3A%22" + someNamespace + "%22") - && longPollRefreshUrl.contains("%22notificationId%22%3A" + someNotificationId) - && longPollRefreshUrl.contains("%22namespaceName%22%3A%22" + anotherNamespace + "%22") - && longPollRefreshUrl.contains("%22notificationId%22%3A" + anotherNotificationId) - && longPollRefreshUrl.contains("%7D%5D")); - } - - public static class MockConfigUtil extends ConfigUtil { - @Override - public String getAppId() { - return someAppId; - } - - @Override - public String getCluster() { - return someCluster; - } - - @Override - public String getAccessKeySecret() { - return someSecret; - } - - @Override - public String getDataCenter() { - return null; - } - - @Override - public int getLoadConfigQPS() { - return 200; - } - - @Override - public int getLongPollQPS() { - return 200; - } - - @Override - public long getLongPollingInitialDelayInMills() { - return 0; - } - } - -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/RemoteConfigRepositoryTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/RemoteConfigRepositoryTest.java deleted file mode 100644 index 812ec9624bd..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/RemoteConfigRepositoryTest.java +++ /dev/null @@ -1,448 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.any; -import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.core.dto.ApolloConfig; -import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification; -import com.ctrip.framework.apollo.core.dto.ApolloNotificationMessages; -import com.ctrip.framework.apollo.core.dto.ServiceDTO; -import com.ctrip.framework.apollo.core.signature.Signature; -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.exceptions.ApolloConfigStatusCodeException; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.ctrip.framework.apollo.util.OrderedProperties; -import com.ctrip.framework.apollo.util.factory.PropertiesFactory; -import com.ctrip.framework.apollo.util.http.HttpRequest; -import com.ctrip.framework.apollo.util.http.HttpResponse; -import com.ctrip.framework.apollo.util.http.HttpClient; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.net.HttpHeaders; -import com.google.common.net.UrlEscapers; -import com.google.common.util.concurrent.SettableFuture; -import com.google.gson.Gson; -import java.lang.reflect.Type; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.concurrent.TimeUnit; -import javax.servlet.http.HttpServletResponse; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; - -/** - * Created by Jason on 4/9/16. - */ -@RunWith(MockitoJUnitRunner.class) -public class RemoteConfigRepositoryTest { - - @Mock - private ConfigServiceLocator configServiceLocator; - private String someNamespace; - private String someServerUrl; - private ConfigUtil configUtil; - private HttpClient httpClient; - @Mock - private static HttpResponse someResponse; - @Mock - private static HttpResponse> pollResponse; - private RemoteConfigLongPollService remoteConfigLongPollService; - @Mock - private PropertiesFactory propertiesFactory; - - private static String someAppId; - private static String someCluster; - private static String someSecret; - - @Before - public void setUp() throws Exception { - someNamespace = "someName"; - - when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_NOT_MODIFIED); - - configUtil = new MockConfigUtil(); - MockInjector.setInstance(ConfigUtil.class, configUtil); - - someServerUrl = "http://someServer"; - - ServiceDTO serviceDTO = mock(ServiceDTO.class); - - when(serviceDTO.getHomepageUrl()).thenReturn(someServerUrl); - when(configServiceLocator.getConfigServices()).thenReturn(Lists.newArrayList(serviceDTO)); - MockInjector.setInstance(ConfigServiceLocator.class, configServiceLocator); - - httpClient = spy(new MockHttpClient()); - MockInjector.setInstance(HttpClient.class, httpClient); - - remoteConfigLongPollService = new RemoteConfigLongPollService(); - - MockInjector.setInstance(RemoteConfigLongPollService.class, remoteConfigLongPollService); - - when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer() { - @Override - public Properties answer(InvocationOnMock invocation) { - return new Properties(); - } - }); - MockInjector.setInstance(PropertiesFactory.class, propertiesFactory); - - someAppId = "someAppId"; - someCluster = "someCluster"; - } - - @After - public void tearDown() throws Exception { - MockInjector.reset(); - } - - @Test - public void testLoadConfig() throws Exception { - String someKey = "someKey"; - String someValue = "someValue"; - Map configurations = Maps.newHashMap(); - configurations.put(someKey, someValue); - ApolloConfig someApolloConfig = assembleApolloConfig(configurations); - - when(someResponse.getStatusCode()).thenReturn(200); - when(someResponse.getBody()).thenReturn(someApolloConfig); - - RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace); - - Properties config = remoteConfigRepository.getConfig(); - - assertEquals(configurations, config); - assertEquals(ConfigSourceType.REMOTE, remoteConfigRepository.getSourceType()); - remoteConfigLongPollService.stopLongPollingRefresh(); - } - - @Test - public void testLoadConfigWithOrderedProperties() throws Exception { - String someKey = "someKey"; - String someValue = "someValue"; - Map configurations = Maps.newLinkedHashMap(); - configurations.put(someKey, someValue); - configurations.put("someKey2", "someValue2"); - ApolloConfig someApolloConfig = assembleApolloConfig(configurations); - - when(someResponse.getStatusCode()).thenReturn(200); - when(someResponse.getBody()).thenReturn(someApolloConfig); - when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer() { - @Override - public Properties answer(InvocationOnMock invocation) { - return new OrderedProperties(); - } - }); - - RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace); - - Properties config = remoteConfigRepository.getConfig(); - - assertTrue(config instanceof OrderedProperties); - assertEquals(configurations, config); - assertEquals(ConfigSourceType.REMOTE, remoteConfigRepository.getSourceType()); - remoteConfigLongPollService.stopLongPollingRefresh(); - - String[] actualArrays = config.keySet().toArray(new String[]{}); - String[] expectedArrays = {"someKey", "someKey2"}; - assertArrayEquals(expectedArrays, actualArrays); - } - - @Test - public void testLoadConfigWithAccessKeySecret() throws Exception { - someSecret = "someSecret"; - String someKey = "someKey"; - String someValue = "someValue"; - Map configurations = Maps.newHashMap(); - configurations.put(someKey, someValue); - ApolloConfig someApolloConfig = assembleApolloConfig(configurations); - - when(someResponse.getStatusCode()).thenReturn(200); - when(someResponse.getBody()).thenReturn(someApolloConfig); - doAnswer(new Answer>() { - @Override - public HttpResponse answer(InvocationOnMock invocation) throws Throwable { - HttpRequest request = invocation.getArgument(0, HttpRequest.class); - Map headers = request.getHeaders(); - assertNotNull(headers); - assertTrue(headers.containsKey(Signature.HTTP_HEADER_TIMESTAMP)); - assertTrue(headers.containsKey(HttpHeaders.AUTHORIZATION)); - - return someResponse; - } - }).when(httpClient).doGet(any(HttpRequest.class), any(Class.class)); - - RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace); - - Properties config = remoteConfigRepository.getConfig(); - - assertEquals(configurations, config); - assertEquals(ConfigSourceType.REMOTE, remoteConfigRepository.getSourceType()); - remoteConfigLongPollService.stopLongPollingRefresh(); - } - - @Test(expected = ApolloConfigException.class) - public void testGetRemoteConfigWithServerError() throws Exception { - - when(someResponse.getStatusCode()).thenReturn(500); - - RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace); - - //must stop the long polling before exception occurred - remoteConfigLongPollService.stopLongPollingRefresh(); - - remoteConfigRepository.getConfig(); - } - - @Test(expected = ApolloConfigException.class) - public void testGetRemoteConfigWithNotFount() throws Exception { - - when(someResponse.getStatusCode()).thenReturn(404); - - RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace); - - //must stop the long polling before exception occurred - remoteConfigLongPollService.stopLongPollingRefresh(); - - remoteConfigRepository.getConfig(); - } - - @Test - public void testRepositoryChangeListener() throws Exception { - Map configurations = ImmutableMap.of("someKey", "someValue"); - ApolloConfig someApolloConfig = assembleApolloConfig(configurations); - - when(someResponse.getStatusCode()).thenReturn(200); - when(someResponse.getBody()).thenReturn(someApolloConfig); - - RepositoryChangeListener someListener = mock(RepositoryChangeListener.class); - RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace); - remoteConfigRepository.addChangeListener(someListener); - final ArgumentCaptor captor = ArgumentCaptor.forClass(Properties.class); - - Map newConfigurations = ImmutableMap.of("someKey", "anotherValue"); - ApolloConfig newApolloConfig = assembleApolloConfig(newConfigurations); - - when(someResponse.getBody()).thenReturn(newApolloConfig); - - remoteConfigRepository.sync(); - - verify(someListener, times(1)).onRepositoryChange(eq(someNamespace), captor.capture()); - - assertEquals(newConfigurations, captor.getValue()); - - remoteConfigLongPollService.stopLongPollingRefresh(); - } - - @Test - public void testLongPollingRefresh() throws Exception { - Map configurations = ImmutableMap.of("someKey", "someValue"); - ApolloConfig someApolloConfig = assembleApolloConfig(configurations); - - when(someResponse.getStatusCode()).thenReturn(200); - when(someResponse.getBody()).thenReturn(someApolloConfig); - - final SettableFuture longPollFinished = SettableFuture.create(); - RepositoryChangeListener someListener = mock(RepositoryChangeListener.class); - doAnswer(new Answer() { - - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - longPollFinished.set(true); - return null; - } - - }).when(someListener).onRepositoryChange(any(String.class), any(Properties.class)); - - RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace); - remoteConfigRepository.addChangeListener(someListener); - final ArgumentCaptor captor = ArgumentCaptor.forClass(Properties.class); - - Map newConfigurations = ImmutableMap.of("someKey", "anotherValue"); - ApolloConfig newApolloConfig = assembleApolloConfig(newConfigurations); - - ApolloNotificationMessages notificationMessages = new ApolloNotificationMessages(); - String someKey = "someKey"; - long someNotificationId = 1; - notificationMessages.put(someKey, someNotificationId); - - ApolloConfigNotification someNotification = mock(ApolloConfigNotification.class); - when(someNotification.getNamespaceName()).thenReturn(someNamespace); - when(someNotification.getMessages()).thenReturn(notificationMessages); - - when(pollResponse.getStatusCode()).thenReturn(HttpServletResponse.SC_OK); - when(pollResponse.getBody()).thenReturn(Lists.newArrayList(someNotification)); - when(someResponse.getBody()).thenReturn(newApolloConfig); - - longPollFinished.get(30_000, TimeUnit.MILLISECONDS); - - remoteConfigLongPollService.stopLongPollingRefresh(); - - verify(someListener, times(1)).onRepositoryChange(eq(someNamespace), captor.capture()); - assertEquals(newConfigurations, captor.getValue()); - - final ArgumentCaptor httpRequestArgumentCaptor = ArgumentCaptor - .forClass(HttpRequest.class); - verify(httpClient, atLeast(2)).doGet(httpRequestArgumentCaptor.capture(), eq(ApolloConfig.class)); - - HttpRequest request = httpRequestArgumentCaptor.getValue(); - - assertTrue(request.getUrl().contains("messages=%7B%22details%22%3A%7B%22someKey%22%3A1%7D%7D")); - } - - @Test - public void testAssembleQueryConfigUrl() throws Exception { - Gson gson = new Gson(); - String someUri = "http://someServer"; - String someAppId = "someAppId"; - String someCluster = "someCluster+ &.-_someSign"; - String someReleaseKey = "20160705193346-583078ef5716c055+20160705193308-31c471ddf9087c3f"; - - ApolloNotificationMessages notificationMessages = new ApolloNotificationMessages(); - String someKey = "someKey"; - long someNotificationId = 1; - String anotherKey = "anotherKey"; - long anotherNotificationId = 2; - notificationMessages.put(someKey, someNotificationId); - notificationMessages.put(anotherKey, anotherNotificationId); - - RemoteConfigRepository remoteConfigRepository = new RemoteConfigRepository(someNamespace); - ApolloConfig someApolloConfig = mock(ApolloConfig.class); - when(someApolloConfig.getReleaseKey()).thenReturn(someReleaseKey); - - String queryConfigUrl = remoteConfigRepository - .assembleQueryConfigUrl(someUri, someAppId, someCluster, someNamespace, null, - notificationMessages, - someApolloConfig); - - remoteConfigLongPollService.stopLongPollingRefresh(); - assertTrue(queryConfigUrl - .contains( - "http://someServer/configs/someAppId/someCluster+%20&.-_someSign/" + someNamespace)); - assertTrue(queryConfigUrl - .contains("releaseKey=20160705193346-583078ef5716c055%2B20160705193308-31c471ddf9087c3f")); - assertTrue(queryConfigUrl - .contains("messages=" + UrlEscapers.urlFormParameterEscaper() - .escape(gson.toJson(notificationMessages)))); - } - - private ApolloConfig assembleApolloConfig(Map configurations) { - String someAppId = "appId"; - String someClusterName = "cluster"; - String someReleaseKey = "1"; - ApolloConfig apolloConfig = - new ApolloConfig(someAppId, someClusterName, someNamespace, someReleaseKey); - - apolloConfig.setConfigurations(configurations); - - return apolloConfig; - } - - public static class MockConfigUtil extends ConfigUtil { - - @Override - public String getAppId() { - return someAppId; - } - - @Override - public String getCluster() { - return someCluster; - } - - @Override - public String getAccessKeySecret() { - return someSecret; - } - - @Override - public String getDataCenter() { - return null; - } - - @Override - public int getLoadConfigQPS() { - return 200; - } - - @Override - public int getLongPollQPS() { - return 200; - } - - @Override - public long getOnErrorRetryInterval() { - return 10; - } - - @Override - public TimeUnit getOnErrorRetryIntervalTimeUnit() { - return TimeUnit.MILLISECONDS; - } - - @Override - public long getLongPollingInitialDelayInMills() { - return 0; - } - } - - public static class MockHttpClient implements HttpClient { - - @Override - public HttpResponse doGet(HttpRequest httpRequest, Class responseType) { - if (someResponse.getStatusCode() == 200 || someResponse.getStatusCode() == 304) { - return (HttpResponse) someResponse; - } - throw new ApolloConfigStatusCodeException(someResponse.getStatusCode(), - String.format("Http request failed due to status code: %d", - someResponse.getStatusCode())); - } - - @Override - public HttpResponse doGet(HttpRequest httpRequest, Type responseType) { - try { - TimeUnit.MILLISECONDS.sleep(50); - } catch (InterruptedException e) { - } - return (HttpResponse) pollResponse; - } - } - -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/SimpleConfigTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/SimpleConfigTest.java deleted file mode 100644 index ee3fd753eac..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/SimpleConfigTest.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.ctrip.framework.apollo.util.factory.PropertiesFactory; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.enums.PropertyChangeType; -import com.ctrip.framework.apollo.model.ConfigChange; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import com.google.common.collect.ImmutableMap; -import com.google.common.util.concurrent.SettableFuture; -import org.mockito.stubbing.Answer; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -@RunWith(MockitoJUnitRunner.class) -public class SimpleConfigTest { - - private String someNamespace; - @Mock - private ConfigRepository configRepository; - @Mock - private PropertiesFactory propertiesFactory; - private ConfigSourceType someSourceType; - - @Before - public void setUp() throws Exception { - someNamespace = "someName"; - - when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer() { - @Override - public Properties answer(InvocationOnMock invocation) { - return new Properties(); - } - }); - MockInjector.setInstance(PropertiesFactory.class, propertiesFactory); - } - - @After - public void tearDown() throws Exception { - MockInjector.reset(); - } - - @Test - public void testGetProperty() throws Exception { - Properties someProperties = new Properties(); - String someKey = "someKey"; - String someValue = "someValue"; - someProperties.setProperty(someKey, someValue); - - someSourceType = ConfigSourceType.LOCAL; - - when(configRepository.getConfig()).thenReturn(someProperties); - when(configRepository.getSourceType()).thenReturn(someSourceType); - - SimpleConfig config = new SimpleConfig(someNamespace, configRepository); - - assertEquals(someValue, config.getProperty(someKey, null)); - assertEquals(someSourceType, config.getSourceType()); - } - - @Test - public void testLoadConfigFromConfigRepositoryError() throws Exception { - String someKey = "someKey"; - String anyValue = "anyValue" + Math.random(); - - when(configRepository.getConfig()).thenThrow(mock(RuntimeException.class)); - - Config config = new SimpleConfig(someNamespace, configRepository); - - assertEquals(anyValue, config.getProperty(someKey, anyValue)); - assertEquals(ConfigSourceType.NONE, config.getSourceType()); - } - - @Test - public void testOnRepositoryChange() throws Exception { - Properties someProperties = new Properties(); - String someKey = "someKey"; - String someValue = "someValue"; - String anotherKey = "anotherKey"; - String anotherValue = "anotherValue"; - someProperties.putAll(ImmutableMap.of(someKey, someValue, anotherKey, anotherValue)); - - Properties anotherProperties = new Properties(); - String newKey = "newKey"; - String newValue = "newValue"; - String someValueNew = "someValueNew"; - anotherProperties.putAll(ImmutableMap.of(someKey, someValueNew, newKey, newValue)); - - someSourceType = ConfigSourceType.LOCAL; - - when(configRepository.getConfig()).thenReturn(someProperties); - when(configRepository.getSourceType()).thenReturn(someSourceType); - - final SettableFuture configChangeFuture = SettableFuture.create(); - ConfigChangeListener someListener = new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - configChangeFuture.set(changeEvent); - } - }; - - SimpleConfig config = new SimpleConfig(someNamespace, configRepository); - - assertEquals(someSourceType, config.getSourceType()); - - config.addChangeListener(someListener); - - ConfigSourceType anotherSourceType = ConfigSourceType.REMOTE; - when(configRepository.getSourceType()).thenReturn(anotherSourceType); - - config.onRepositoryChange(someNamespace, anotherProperties); - - ConfigChangeEvent changeEvent = configChangeFuture.get(500, TimeUnit.MILLISECONDS); - - assertEquals(someNamespace, changeEvent.getNamespace()); - assertEquals(3, changeEvent.changedKeys().size()); - - ConfigChange someKeyChange = changeEvent.getChange(someKey); - assertEquals(someValue, someKeyChange.getOldValue()); - assertEquals(someValueNew, someKeyChange.getNewValue()); - assertEquals(PropertyChangeType.MODIFIED, someKeyChange.getChangeType()); - - ConfigChange anotherKeyChange = changeEvent.getChange(anotherKey); - assertEquals(anotherValue, anotherKeyChange.getOldValue()); - assertEquals(null, anotherKeyChange.getNewValue()); - assertEquals(PropertyChangeType.DELETED, anotherKeyChange.getChangeType()); - - ConfigChange newKeyChange = changeEvent.getChange(newKey); - assertEquals(null, newKeyChange.getOldValue()); - assertEquals(newValue, newKeyChange.getNewValue()); - assertEquals(PropertyChangeType.ADDED, newKeyChange.getChangeType()); - - assertEquals(anotherSourceType, config.getSourceType()); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/TxtConfigFileTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/TxtConfigFileTest.java deleted file mode 100644 index ee712e089c0..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/TxtConfigFileTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.*; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import java.util.Properties; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -public class TxtConfigFileTest { - - private String someNamespace; - @Mock - private ConfigRepository configRepository; - - @Before - public void setUp() throws Exception { - someNamespace = "someName"; - } - - @Test - public void testWhenHasContent() throws Exception { - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someValue = "someValue"; - someProperties.setProperty(key, someValue); - - when(configRepository.getConfig()).thenReturn(someProperties); - - TxtConfigFile configFile = new TxtConfigFile(someNamespace, configRepository); - - assertEquals(ConfigFileFormat.TXT, configFile.getConfigFileFormat()); - assertEquals(someNamespace, configFile.getNamespace()); - assertTrue(configFile.hasContent()); - assertEquals(someValue, configFile.getContent()); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/XmlConfigFileTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/XmlConfigFileTest.java deleted file mode 100644 index a875cab6140..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/XmlConfigFileTest.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.ConfigFileChangeListener; -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.enums.PropertyChangeType; -import com.ctrip.framework.apollo.model.ConfigFileChangeEvent; -import com.ctrip.framework.apollo.util.factory.PropertiesFactory; -import com.google.common.util.concurrent.SettableFuture; -import java.util.Properties; - -import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; - -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import org.mockito.stubbing.Answer; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -@RunWith(MockitoJUnitRunner.class) -public class XmlConfigFileTest { - - private String someNamespace; - @Mock - private ConfigRepository configRepository; - @Mock - private PropertiesFactory propertiesFactory; - - @Before - public void setUp() throws Exception { - someNamespace = "someName"; - - when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer() { - @Override - public Properties answer(InvocationOnMock invocation) { - return new Properties(); - } - }); - MockInjector.setInstance(PropertiesFactory.class, propertiesFactory); - } - - @After - public void tearDown() throws Exception { - MockInjector.reset(); - System.clearProperty(PropertiesFactory.APOLLO_PROPERTY_ORDER_ENABLE); - } - - @Test - public void testWhenHasContent() throws Exception { - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someValue = "someValue"; - someProperties.setProperty(key, someValue); - - when(configRepository.getConfig()).thenReturn(someProperties); - - XmlConfigFile configFile = new XmlConfigFile(someNamespace, configRepository); - - assertEquals(ConfigFileFormat.XML, configFile.getConfigFileFormat()); - assertEquals(someNamespace, configFile.getNamespace()); - assertTrue(configFile.hasContent()); - assertEquals(someValue, configFile.getContent()); - } - - @Test - public void testWhenHasNoContent() throws Exception { - when(configRepository.getConfig()).thenReturn(null); - - XmlConfigFile configFile = new XmlConfigFile(someNamespace, configRepository); - - assertFalse(configFile.hasContent()); - assertNull(configFile.getContent()); - } - - @Test - public void testWhenConfigRepositoryHasError() throws Exception { - when(configRepository.getConfig()).thenThrow(new RuntimeException("someError")); - - XmlConfigFile configFile = new XmlConfigFile(someNamespace, configRepository); - - assertFalse(configFile.hasContent()); - assertNull(configFile.getContent()); - } - - @Test - public void testOnRepositoryChange() throws Exception { - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someValue = "someValue"; - String anotherValue = "anotherValue"; - someProperties.setProperty(key, someValue); - - when(configRepository.getConfig()).thenReturn(someProperties); - - XmlConfigFile configFile = new XmlConfigFile(someNamespace, configRepository); - - assertEquals(someValue, configFile.getContent()); - - Properties anotherProperties = new Properties(); - anotherProperties.setProperty(key, anotherValue); - - final SettableFuture configFileChangeFuture = SettableFuture.create(); - ConfigFileChangeListener someListener = new ConfigFileChangeListener() { - @Override - public void onChange(ConfigFileChangeEvent changeEvent) { - configFileChangeFuture.set(changeEvent); - } - }; - - configFile.addChangeListener(someListener); - - configFile.onRepositoryChange(someNamespace, anotherProperties); - - ConfigFileChangeEvent changeEvent = configFileChangeFuture.get(500, TimeUnit.MILLISECONDS); - - assertEquals(anotherValue, configFile.getContent()); - assertEquals(someNamespace, changeEvent.getNamespace()); - assertEquals(someValue, changeEvent.getOldValue()); - assertEquals(anotherValue, changeEvent.getNewValue()); - assertEquals(PropertyChangeType.MODIFIED, changeEvent.getChangeType()); - } - - @Test - public void testOnRepositoryChangeWithContentAdded() throws Exception { - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someValue = "someValue"; - - when(configRepository.getConfig()).thenReturn(someProperties); - - XmlConfigFile configFile = new XmlConfigFile(someNamespace, configRepository); - - assertEquals(null, configFile.getContent()); - - Properties anotherProperties = new Properties(); - anotherProperties.setProperty(key, someValue); - - final SettableFuture configFileChangeFuture = SettableFuture.create(); - ConfigFileChangeListener someListener = new ConfigFileChangeListener() { - @Override - public void onChange(ConfigFileChangeEvent changeEvent) { - configFileChangeFuture.set(changeEvent); - } - }; - - configFile.addChangeListener(someListener); - - configFile.onRepositoryChange(someNamespace, anotherProperties); - - ConfigFileChangeEvent changeEvent = configFileChangeFuture.get(500, TimeUnit.MILLISECONDS); - - assertEquals(someValue, configFile.getContent()); - assertEquals(someNamespace, changeEvent.getNamespace()); - assertEquals(null, changeEvent.getOldValue()); - assertEquals(someValue, changeEvent.getNewValue()); - assertEquals(PropertyChangeType.ADDED, changeEvent.getChangeType()); - } - - @Test - public void testOnRepositoryChangeWithContentDeleted() throws Exception { - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someValue = "someValue"; - someProperties.setProperty(key, someValue); - - when(configRepository.getConfig()).thenReturn(someProperties); - - XmlConfigFile configFile = new XmlConfigFile(someNamespace, configRepository); - - assertEquals(someValue, configFile.getContent()); - - Properties anotherProperties = new Properties(); - - final SettableFuture configFileChangeFuture = SettableFuture.create(); - ConfigFileChangeListener someListener = new ConfigFileChangeListener() { - @Override - public void onChange(ConfigFileChangeEvent changeEvent) { - configFileChangeFuture.set(changeEvent); - } - }; - - configFile.addChangeListener(someListener); - - configFile.onRepositoryChange(someNamespace, anotherProperties); - - ConfigFileChangeEvent changeEvent = configFileChangeFuture.get(500, TimeUnit.MILLISECONDS); - - assertEquals(null, configFile.getContent()); - assertEquals(someNamespace, changeEvent.getNamespace()); - assertEquals(someValue, changeEvent.getOldValue()); - assertEquals(null, changeEvent.getNewValue()); - assertEquals(PropertyChangeType.DELETED, changeEvent.getChangeType()); - } - - @Test - public void testWhenConfigRepositoryHasErrorAndThenRecovered() throws Exception { - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someValue = "someValue"; - someProperties.setProperty(key, someValue); - - when(configRepository.getConfig()).thenThrow(new RuntimeException("someError")); - - XmlConfigFile configFile = new XmlConfigFile(someNamespace, configRepository); - - assertFalse(configFile.hasContent()); - assertNull(configFile.getContent()); - - configFile.onRepositoryChange(someNamespace, someProperties); - - assertTrue(configFile.hasContent()); - assertEquals(someValue, configFile.getContent()); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/YamlConfigFileTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/YamlConfigFileTest.java deleted file mode 100644 index b856d3ecffc..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/internals/YamlConfigFileTest.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright 2022 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.junit.Assert.*; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.enums.ConfigSourceType; -import com.ctrip.framework.apollo.exceptions.ApolloConfigException; -import com.ctrip.framework.apollo.util.OrderedProperties; -import com.ctrip.framework.apollo.util.factory.PropertiesFactory; -import com.ctrip.framework.apollo.util.yaml.YamlParser; -import java.util.Properties; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; - -@RunWith(MockitoJUnitRunner.class) -public class YamlConfigFileTest { - - private String someNamespace; - @Mock - private ConfigRepository configRepository; - @Mock - private YamlParser yamlParser; - @Mock - private PropertiesFactory propertiesFactory; - - private ConfigSourceType someSourceType; - - @Before - public void setUp() throws Exception { - someNamespace = "someName"; - - MockInjector.setInstance(YamlParser.class, yamlParser); - - when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer() { - @Override - public Properties answer(InvocationOnMock invocation) { - return new Properties(); - } - }); - MockInjector.setInstance(PropertiesFactory.class, propertiesFactory); - } - - @After - public void tearDown() throws Exception { - MockInjector.reset(); - } - - @Test - public void testWhenHasContent() throws Exception { - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someContent = "someKey: 'someValue'"; - someProperties.setProperty(key, someContent); - someSourceType = ConfigSourceType.LOCAL; - - Properties yamlProperties = new Properties(); - yamlProperties.setProperty("someKey", "someValue"); - - when(configRepository.getConfig()).thenReturn(someProperties); - when(configRepository.getSourceType()).thenReturn(someSourceType); - when(yamlParser.yamlToProperties(someContent)).thenReturn(yamlProperties); - - YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository); - - assertSame(someContent, configFile.getContent()); - assertSame(yamlProperties, configFile.asProperties()); - } - - @Test - public void testWhenHasContentWithOrder() throws Exception { - when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer() { - @Override - public Properties answer(InvocationOnMock invocation) { - return new OrderedProperties(); - } - }); - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someContent = "someKey: 'someValue'\nsomeKey2: 'someValue2'"; - someProperties.setProperty(key, someContent); - someSourceType = ConfigSourceType.LOCAL; - - Properties yamlProperties = new YamlParser().yamlToProperties(someContent); - - when(configRepository.getConfig()).thenReturn(someProperties); - when(configRepository.getSourceType()).thenReturn(someSourceType); - when(yamlParser.yamlToProperties(someContent)).thenReturn(yamlProperties); - - YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository); - - assertSame(someContent, configFile.getContent()); - assertSame(yamlProperties, configFile.asProperties()); - - String[] actualArrays = configFile.asProperties().keySet().toArray(new String[]{}); - String[] expectedArrays = {"someKey", "someKey2"}; - assertArrayEquals(expectedArrays, actualArrays); - } - - @Test - public void testWhenHasNoContent() throws Exception { - when(configRepository.getConfig()).thenReturn(null); - - YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository); - - assertFalse(configFile.hasContent()); - assertNull(configFile.getContent()); - - Properties properties = configFile.asProperties(); - - assertTrue(properties.isEmpty()); - } - - @Test - public void testWhenInvalidYamlContent() throws Exception { - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someInvalidContent = ","; - someProperties.setProperty(key, someInvalidContent); - someSourceType = ConfigSourceType.LOCAL; - - when(configRepository.getConfig()).thenReturn(someProperties); - when(configRepository.getSourceType()).thenReturn(someSourceType); - when(yamlParser.yamlToProperties(someInvalidContent)) - .thenThrow(new RuntimeException("some exception")); - - YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository); - - assertSame(someInvalidContent, configFile.getContent()); - - Throwable exceptionThrown = null; - try { - configFile.asProperties(); - } catch (Throwable ex) { - exceptionThrown = ex; - } - - assertTrue(exceptionThrown instanceof ApolloConfigException); - assertNotNull(exceptionThrown.getCause()); - } - - @Test - public void testWhenConfigRepositoryHasError() throws Exception { - when(configRepository.getConfig()).thenThrow(new RuntimeException("someError")); - - YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository); - - assertFalse(configFile.hasContent()); - assertNull(configFile.getContent()); - assertEquals(ConfigSourceType.NONE, configFile.getSourceType()); - - Properties properties = configFile.asProperties(); - - assertTrue(properties.isEmpty()); - } - - @Test - public void testOnRepositoryChange() throws Exception { - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someValue = "someKey: 'someValue'"; - String anotherValue = "anotherKey: 'anotherValue'"; - someProperties.setProperty(key, someValue); - - someSourceType = ConfigSourceType.LOCAL; - - Properties someYamlProperties = new Properties(); - someYamlProperties.setProperty("someKey", "someValue"); - - Properties anotherYamlProperties = new Properties(); - anotherYamlProperties.setProperty("anotherKey", "anotherValue"); - - when(configRepository.getConfig()).thenReturn(someProperties); - when(configRepository.getSourceType()).thenReturn(someSourceType); - when(yamlParser.yamlToProperties(someValue)).thenReturn(someYamlProperties); - when(yamlParser.yamlToProperties(anotherValue)).thenReturn(anotherYamlProperties); - - YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository); - - assertEquals(someValue, configFile.getContent()); - assertEquals(someSourceType, configFile.getSourceType()); - assertSame(someYamlProperties, configFile.asProperties()); - - Properties anotherProperties = new Properties(); - anotherProperties.setProperty(key, anotherValue); - - ConfigSourceType anotherSourceType = ConfigSourceType.REMOTE; - when(configRepository.getSourceType()).thenReturn(anotherSourceType); - - configFile.onRepositoryChange(someNamespace, anotherProperties); - - assertEquals(anotherValue, configFile.getContent()); - assertEquals(anotherSourceType, configFile.getSourceType()); - assertSame(anotherYamlProperties, configFile.asProperties()); - } - - @Test - public void testWhenConfigRepositoryHasErrorAndThenRecovered() throws Exception { - Properties someProperties = new Properties(); - String key = ConfigConsts.CONFIG_FILE_CONTENT_KEY; - String someValue = "someKey: 'someValue'"; - someProperties.setProperty(key, someValue); - - someSourceType = ConfigSourceType.LOCAL; - - Properties someYamlProperties = new Properties(); - someYamlProperties.setProperty("someKey", "someValue"); - - when(configRepository.getConfig()).thenThrow(new RuntimeException("someError")); - when(configRepository.getSourceType()).thenReturn(someSourceType); - when(yamlParser.yamlToProperties(someValue)).thenReturn(someYamlProperties); - - YamlConfigFile configFile = new YamlConfigFile(someNamespace, configRepository); - - assertFalse(configFile.hasContent()); - assertNull(configFile.getContent()); - assertEquals(ConfigSourceType.NONE, configFile.getSourceType()); - assertTrue(configFile.asProperties().isEmpty()); - - configFile.onRepositoryChange(someNamespace, someProperties); - - assertTrue(configFile.hasContent()); - assertEquals(someValue, configFile.getContent()); - assertEquals(someSourceType, configFile.getSourceType()); - assertSame(someYamlProperties, configFile.asProperties()); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/ConfigServiceLoadBalancerClientTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/ConfigServiceLoadBalancerClientTest.java deleted file mode 100644 index e1f0854ef6f..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/ConfigServiceLoadBalancerClientTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.junit.jupiter.api.Assertions.assertTrue; - -import com.ctrip.framework.foundation.internals.ServiceBootstrap; -import java.util.ArrayList; -import java.util.Iterator; -import org.junit.jupiter.api.Test; - -class ConfigServiceLoadBalancerClientTest { - - /** - * all {@link ConfigServiceLoadBalancerClient}'s implementations need to conform it. - */ - @Test - void chooseOneFrom() { - Iterator loadBalancerClientIterator = - ServiceBootstrap.loadAll(ConfigServiceLoadBalancerClient.class); - while (loadBalancerClientIterator.hasNext()) { - ConfigServiceLoadBalancerClient configServiceLoadBalancerClient = loadBalancerClientIterator.next(); - expectException(configServiceLoadBalancerClient); - } - } - - private static void expectException(ConfigServiceLoadBalancerClient loadBalancerClient) { - // arg is null - assertThrows(IllegalArgumentException.class, () -> loadBalancerClient.chooseOneFrom(null)); - // arg is empty - assertThrows(IllegalArgumentException.class, - () -> loadBalancerClient.chooseOneFrom(new ArrayList<>())); - } - - @Test - void classTypeMatch() { - ConfigServiceLoadBalancerClient loadBalancerClient = - ServiceBootstrap.loadPrimary(ConfigServiceLoadBalancerClient.class); - assertTrue(loadBalancerClient instanceof RandomConfigServiceLoadBalancerClient); - } -} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/DefaultConfigFactoryFileCachePropertyTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/DefaultConfigFactoryFileCachePropertyTest.java deleted file mode 100644 index 69771900e77..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/DefaultConfigFactoryFileCachePropertyTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import static org.junit.Assert.assertSame; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.internals.ConfigRepository; -import com.ctrip.framework.apollo.internals.LocalFileConfigRepository; -import com.ctrip.framework.apollo.internals.RemoteConfigRepository; -import com.ctrip.framework.apollo.util.ConfigUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -public class DefaultConfigFactoryFileCachePropertyTest { - - private DefaultConfigFactory configFactory; - private ConfigUtil someConfigUtil; - private String someNamespace; - - @Before - public void setUp() throws Exception { - someNamespace = "someNamespace"; - someConfigUtil = mock(ConfigUtil.class); - MockInjector.setInstance(ConfigUtil.class, someConfigUtil); - configFactory = spy(new DefaultConfigFactory()); - } - - @Test - public void testCreateFileEnableConfigRepository() throws Exception { - LocalFileConfigRepository someLocalConfigRepository = mock(LocalFileConfigRepository.class); - when(someConfigUtil.isPropertyFileCacheEnabled()).thenReturn(true); - doReturn(someLocalConfigRepository).when(configFactory) - .createLocalConfigRepository(someNamespace); - ConfigRepository configRepository = configFactory.createConfigRepository(someNamespace); - assertSame(someLocalConfigRepository, configRepository); - verify(configFactory, times(1)).createLocalConfigRepository(someNamespace); - verify(configFactory, never()).createRemoteConfigRepository(someNamespace); - } - - @Test - public void testCreateFileDisableConfigRepository() throws Exception { - RemoteConfigRepository someRemoteConfigRepository = mock(RemoteConfigRepository.class); - when(someConfigUtil.isPropertyFileCacheEnabled()).thenReturn(false); - doReturn(someRemoteConfigRepository).when(configFactory) - .createRemoteConfigRepository(someNamespace); - ConfigRepository configRepository = configFactory.createConfigRepository(someNamespace); - assertSame(someRemoteConfigRepository, configRepository); - verify(configFactory, never()).createLocalConfigRepository(someNamespace); - verify(configFactory, times(1)).createRemoteConfigRepository(someNamespace); - } - - @After - public void tearDown() throws Exception { - MockInjector.reset(); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/DefaultConfigFactoryManagerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/DefaultConfigFactoryManagerTest.java deleted file mode 100644 index e72fcc6d41e..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/DefaultConfigFactoryManagerTest.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import static org.hamcrest.core.IsEqual.equalTo; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.hamcrest.MatcherAssert.assertThat; - -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; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class DefaultConfigFactoryManagerTest { - private DefaultConfigFactoryManager defaultConfigFactoryManager; - - @Before - public void setUp() throws Exception { - MockInjector.setInstance(ConfigRegistry.class, new MockConfigRegistry()); - defaultConfigFactoryManager = new DefaultConfigFactoryManager(); - } - - @After - public void tearDown() throws Exception { - MockInjector.reset(); - } - - @Test - public void testGetFactoryFromRegistry() throws Exception { - ConfigFactory result = - defaultConfigFactoryManager.getFactory(MockConfigRegistry.NAMESPACE_REGISTERED); - - assertEquals(MockConfigRegistry.REGISTERED_CONFIGFACTORY, result); - } - - @Test - public void testGetFactoryFromNamespace() throws Exception { - String someNamespace = "someName"; - MockInjector.setInstance(ConfigFactory.class, someNamespace, new SomeConfigFactory()); - - ConfigFactory result = defaultConfigFactoryManager.getFactory(someNamespace); - - assertThat("When namespace is registered, should return the registerd config factory", result, - instanceOf(SomeConfigFactory.class)); - } - - @Test - public void testGetFactoryFromNamespaceMultipleTimes() throws Exception { - String someNamespace = "someName"; - MockInjector.setInstance(ConfigFactory.class, someNamespace, new SomeConfigFactory()); - - ConfigFactory result = defaultConfigFactoryManager.getFactory(someNamespace); - ConfigFactory anotherResult = defaultConfigFactoryManager.getFactory(someNamespace); - - assertThat( - "Get config factory with the same namespace multiple times should returnt the same instance", - anotherResult, equalTo(result)); - } - - @Test - public void testGetFactoryFromDefault() throws Exception { - String someNamespace = "someName"; - MockInjector.setInstance(ConfigFactory.class, new AnotherConfigFactory()); - - ConfigFactory result = defaultConfigFactoryManager.getFactory(someNamespace); - - assertThat("When namespace is not registered, should return the default config factory", result, - instanceOf(AnotherConfigFactory.class)); - } - - public static class MockConfigRegistry implements ConfigRegistry { - public static String NAMESPACE_REGISTERED = "some-namespace-registered"; - public static ConfigFactory REGISTERED_CONFIGFACTORY = new ConfigFactory() { - @Override - public Config create(String namespace) { - return null; - } - - @Override - public ConfigFile createConfigFile(String namespace, ConfigFileFormat configFileFormat) { - return null; - } - - }; - - @Override - public void register(String namespace, ConfigFactory factory) { - //do nothing - } - - @Override - public ConfigFactory getFactory(String namespace) { - if (namespace.equals(NAMESPACE_REGISTERED)) { - return REGISTERED_CONFIGFACTORY; - } - return null; - } - } - - public static class SomeConfigFactory implements ConfigFactory { - @Override - public Config create(String namespace) { - return null; - } - - @Override - public ConfigFile createConfigFile(String namespace, ConfigFileFormat configFileFormat) { - return null; - } - } - - public static class AnotherConfigFactory implements ConfigFactory { - @Override - public Config create(String namespace) { - return null; - } - - @Override - public ConfigFile createConfigFile(String namespace, ConfigFileFormat configFileFormat) { - return null; - } - } - -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/DefaultConfigFactoryTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/DefaultConfigFactoryTest.java deleted file mode 100644 index fb670fe5b7b..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/DefaultConfigFactoryTest.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.internals.PropertiesCompatibleFileConfigRepository; -import java.util.Properties; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.test.util.ReflectionTestUtils; - -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.core.enums.Env; -import com.ctrip.framework.apollo.internals.DefaultConfig; -import com.ctrip.framework.apollo.internals.JsonConfigFile; -import com.ctrip.framework.apollo.internals.LocalFileConfigRepository; -import com.ctrip.framework.apollo.internals.PropertiesConfigFile; -import com.ctrip.framework.apollo.internals.XmlConfigFile; -import com.ctrip.framework.apollo.internals.YamlConfigFile; -import com.ctrip.framework.apollo.internals.YmlConfigFile; -import com.ctrip.framework.apollo.util.ConfigUtil; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class DefaultConfigFactoryTest { - private DefaultConfigFactory defaultConfigFactory; - private static String someAppId; - private static Env someEnv; - - @Before - public void setUp() throws Exception { - someAppId = "someId"; - someEnv = Env.DEV; - MockInjector.setInstance(ConfigUtil.class, new MockConfigUtil()); - defaultConfigFactory = spy(new DefaultConfigFactory()); - } - - @After - public void tearDown() throws Exception { - MockInjector.reset(); - } - - @Test - public void testCreate() throws Exception { - String someNamespace = "someName"; - Properties someProperties = new Properties(); - String someKey = "someKey"; - String someValue = "someValue"; - someProperties.setProperty(someKey, someValue); - - LocalFileConfigRepository someLocalConfigRepo = mock(LocalFileConfigRepository.class); - when(someLocalConfigRepo.getConfig()).thenReturn(someProperties); - - doReturn(someLocalConfigRepo).when(defaultConfigFactory).createConfigRepository(someNamespace); - - Config result = defaultConfigFactory.create(someNamespace); - - assertThat("DefaultConfigFactory should create DefaultConfig", result, - is(instanceOf(DefaultConfig.class))); - assertEquals(someValue, result.getProperty(someKey, null)); - } - - @Test - public void testCreateLocalConfigRepositoryInLocalDev() throws Exception { - String someNamespace = "someName"; - someEnv = Env.LOCAL; - - LocalFileConfigRepository localFileConfigRepository = - defaultConfigFactory.createLocalConfigRepository(someNamespace); - - assertNull(ReflectionTestUtils.getField(localFileConfigRepository, "m_upstream")); - } - - @Test - public void testCreatePropertiesCompatibleFileConfigRepository() throws Exception { - ConfigFileFormat somePropertiesCompatibleFormat = ConfigFileFormat.YML; - String someNamespace = "someName" + "." + somePropertiesCompatibleFormat; - Properties someProperties = new Properties(); - String someKey = "someKey"; - String someValue = "someValue"; - someProperties.setProperty(someKey, someValue); - - PropertiesCompatibleFileConfigRepository someRepository = mock(PropertiesCompatibleFileConfigRepository.class); - when(someRepository.getConfig()).thenReturn(someProperties); - - doReturn(someRepository).when(defaultConfigFactory) - .createPropertiesCompatibleFileConfigRepository(someNamespace, somePropertiesCompatibleFormat); - - Config result = defaultConfigFactory.create(someNamespace); - - assertThat("DefaultConfigFactory should create DefaultConfig", result, - is(instanceOf(DefaultConfig.class))); - assertEquals(someValue, result.getProperty(someKey, null)); - } - - @Test - public void testCreateConfigFile() throws Exception { - String someNamespace = "someName"; - String anotherNamespace = "anotherName"; - String yetAnotherNamespace = "yetAnotherNamespace"; - Properties someProperties = new Properties(); - - LocalFileConfigRepository someLocalConfigRepo = mock(LocalFileConfigRepository.class); - when(someLocalConfigRepo.getConfig()).thenReturn(someProperties); - - doReturn(someLocalConfigRepo).when(defaultConfigFactory).createLocalConfigRepository(someNamespace); - doReturn(someLocalConfigRepo).when(defaultConfigFactory).createLocalConfigRepository(anotherNamespace); - doReturn(someLocalConfigRepo).when(defaultConfigFactory).createLocalConfigRepository(yetAnotherNamespace); - - ConfigFile propertyConfigFile = - defaultConfigFactory.createConfigFile(someNamespace, ConfigFileFormat.Properties); - ConfigFile xmlConfigFile = - defaultConfigFactory.createConfigFile(anotherNamespace, ConfigFileFormat.XML); - ConfigFile jsonConfigFile = - defaultConfigFactory.createConfigFile(yetAnotherNamespace, ConfigFileFormat.JSON); - ConfigFile ymlConfigFile = defaultConfigFactory.createConfigFile(someNamespace, - ConfigFileFormat.YML); - ConfigFile yamlConfigFile = defaultConfigFactory.createConfigFile(someNamespace, - ConfigFileFormat.YAML); - - assertThat("Should create PropertiesConfigFile for properties format", propertyConfigFile, is(instanceOf( - PropertiesConfigFile.class))); - assertEquals(someNamespace, propertyConfigFile.getNamespace()); - - assertThat("Should create XmlConfigFile for xml format", xmlConfigFile, is(instanceOf( - XmlConfigFile.class))); - assertEquals(anotherNamespace, xmlConfigFile.getNamespace()); - - assertThat("Should create JsonConfigFile for json format", jsonConfigFile, is(instanceOf( - JsonConfigFile.class))); - assertEquals(yetAnotherNamespace, jsonConfigFile.getNamespace()); - - assertThat("Should create YmlConfigFile for yml format", ymlConfigFile, is(instanceOf( - YmlConfigFile.class))); - assertEquals(someNamespace, ymlConfigFile.getNamespace()); - - assertThat("Should create YamlConfigFile for yaml format", yamlConfigFile, is(instanceOf( - YamlConfigFile.class))); - assertEquals(someNamespace, yamlConfigFile.getNamespace()); - - } - - @Test - public void testDetermineFileFormat() throws Exception { - checkFileFormat("abc", ConfigFileFormat.Properties); - checkFileFormat("abc.properties", ConfigFileFormat.Properties); - checkFileFormat("abc.pRopErties", ConfigFileFormat.Properties); - checkFileFormat("abc.xml", ConfigFileFormat.XML); - checkFileFormat("abc.xmL", ConfigFileFormat.XML); - checkFileFormat("abc.json", ConfigFileFormat.JSON); - checkFileFormat("abc.jsOn", ConfigFileFormat.JSON); - checkFileFormat("abc.yaml", ConfigFileFormat.YAML); - checkFileFormat("abc.yAml", ConfigFileFormat.YAML); - checkFileFormat("abc.yml", ConfigFileFormat.YML); - checkFileFormat("abc.yMl", ConfigFileFormat.YML); - checkFileFormat("abc.properties.yml", ConfigFileFormat.YML); - } - - @Test - public void testTrimNamespaceFormat() throws Exception { - checkNamespaceName("abc", ConfigFileFormat.Properties, "abc"); - checkNamespaceName("abc.properties", ConfigFileFormat.Properties, "abc"); - checkNamespaceName("abcproperties", ConfigFileFormat.Properties, "abcproperties"); - checkNamespaceName("abc.pRopErties", ConfigFileFormat.Properties, "abc"); - checkNamespaceName("abc.xml", ConfigFileFormat.XML, "abc"); - checkNamespaceName("abc.xmL", ConfigFileFormat.XML, "abc"); - checkNamespaceName("abc.json", ConfigFileFormat.JSON, "abc"); - checkNamespaceName("abc.jsOn", ConfigFileFormat.JSON, "abc"); - checkNamespaceName("abc.yaml", ConfigFileFormat.YAML, "abc"); - checkNamespaceName("abc.yAml", ConfigFileFormat.YAML, "abc"); - checkNamespaceName("abc.yml", ConfigFileFormat.YML, "abc"); - checkNamespaceName("abc.yMl", ConfigFileFormat.YML, "abc"); - checkNamespaceName("abc.proPerties.yml", ConfigFileFormat.YML, "abc.proPerties"); - } - - private void checkFileFormat(String namespaceName, ConfigFileFormat expectedFormat) { - assertEquals(expectedFormat, defaultConfigFactory.determineFileFormat(namespaceName)); - } - - private void checkNamespaceName(String namespaceName, ConfigFileFormat format, String expectedNamespaceName) { - assertEquals(expectedNamespaceName, defaultConfigFactory.trimNamespaceFormat(namespaceName, format)); - } - - public static class MockConfigUtil extends ConfigUtil { - @Override - public String getAppId() { - return someAppId; - } - - @Override - public Env getApolloEnv() { - return someEnv; - } - } - -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/DefaultConfigRegistryTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/DefaultConfigRegistryTest.java deleted file mode 100644 index 27d3ce62681..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/DefaultConfigRegistryTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import static org.hamcrest.core.IsEqual.equalTo; -import static org.junit.Assert.assertNull; -import static org.hamcrest.MatcherAssert.assertThat; - -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.core.enums.ConfigFileFormat; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class DefaultConfigRegistryTest { - private DefaultConfigRegistry defaultConfigRegistry; - - @Before - public void setUp() throws Exception { - defaultConfigRegistry = new DefaultConfigRegistry(); - } - - @Test - public void testGetFactory() throws Exception { - String someNamespace = "someName"; - ConfigFactory someConfigFactory = new MockConfigFactory(); - - defaultConfigRegistry.register(someNamespace, someConfigFactory); - - assertThat("Should return the registered config factory", - defaultConfigRegistry.getFactory(someNamespace), equalTo(someConfigFactory)); - } - - @Test - public void testGetFactoryWithNamespaceUnregistered() throws Exception { - String someUnregisteredNamespace = "someName"; - - assertNull(defaultConfigRegistry.getFactory(someUnregisteredNamespace)); - } - - public static class MockConfigFactory implements ConfigFactory { - - @Override - public Config create(String namespace) { - return null; - } - - @Override - public ConfigFile createConfigFile(String namespace, ConfigFileFormat configFileFormat) { - return null; - } - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/RandomConfigServiceLoadBalancerClientTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/RandomConfigServiceLoadBalancerClientTest.java deleted file mode 100644 index 3ab20af63d5..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spi/RandomConfigServiceLoadBalancerClientTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import static org.junit.jupiter.api.Assertions.assertTrue; - -import com.ctrip.framework.apollo.core.dto.ServiceDTO; -import java.util.ArrayList; -import java.util.List; -import org.junit.jupiter.api.Test; - -public class RandomConfigServiceLoadBalancerClientTest { - - @Test - public void chooseOneFrom() { - ConfigServiceLoadBalancerClient loadBalancerClient = new RandomConfigServiceLoadBalancerClient(); - List configServices = generateConfigServices(); - for (int i = 0; i < 100; i++) { - ServiceDTO serviceDTO = loadBalancerClient.chooseOneFrom(configServices); - // always contains it - assertTrue(configServices.contains(serviceDTO)); - } - } - - private static List generateConfigServices() { - List configServices = new ArrayList<>(); - { - ServiceDTO serviceDTO = new ServiceDTO(); - serviceDTO.setAppName("appName1"); - configServices.add(serviceDTO); - } - { - ServiceDTO serviceDTO = new ServiceDTO(); - serviceDTO.setAppName("appName2"); - configServices.add(serviceDTO); - } - { - ServiceDTO serviceDTO = new ServiceDTO(); - serviceDTO.setAppName("appName3"); - configServices.add(serviceDTO); - } - return configServices; - } -} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/AbstractSpringIntegrationTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/AbstractSpringIntegrationTest.java deleted file mode 100644 index c8b22d30ba3..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/AbstractSpringIntegrationTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright 2022 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; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.internals.ConfigRepository; -import com.ctrip.framework.apollo.internals.DefaultInjector; -import com.ctrip.framework.apollo.internals.SimpleConfig; -import com.ctrip.framework.apollo.internals.YamlConfigFile; -import com.ctrip.framework.apollo.spring.config.PropertySourcesProcessor; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.io.CharStreams; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.nio.charset.StandardCharsets; -import java.util.Calendar; -import java.util.Date; -import java.util.Map; - -import java.util.Objects; -import java.util.Properties; -import org.junit.After; -import org.junit.Before; -import org.springframework.util.ReflectionUtils; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigFile; -import com.ctrip.framework.apollo.ConfigService; -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import com.ctrip.framework.apollo.internals.ConfigManager; -import com.google.common.collect.Maps; -import org.springframework.util.ReflectionUtils.FieldCallback; -import org.springframework.util.ReflectionUtils.FieldFilter; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public abstract class AbstractSpringIntegrationTest { - private static final Map CONFIG_REGISTRY = Maps.newHashMap(); - private static final Map CONFIG_FILE_REGISTRY = Maps.newHashMap(); - private static Method CONFIG_SERVICE_RESET; - private static Method PROPERTY_SOURCES_PROCESSOR_RESET; - - static { - try { - CONFIG_SERVICE_RESET = ConfigService.class.getDeclaredMethod("reset"); - ReflectionUtils.makeAccessible(CONFIG_SERVICE_RESET); - PROPERTY_SOURCES_PROCESSOR_RESET = PropertySourcesProcessor.class.getDeclaredMethod("reset"); - ReflectionUtils.makeAccessible(PROPERTY_SOURCES_PROCESSOR_RESET); - } catch (NoSuchMethodException e) { - e.printStackTrace(); - } - } - - @Before - public void setUp() throws Exception { - doSetUp(); - } - - @After - public void tearDown() throws Exception { - doTearDown(); - } - - protected SimpleConfig prepareConfig(String namespaceName, Properties properties) { - ConfigRepository configRepository = mock(ConfigRepository.class); - - when(configRepository.getConfig()).thenReturn(properties); - - SimpleConfig config = new SimpleConfig(ConfigConsts.NAMESPACE_APPLICATION, configRepository); - - mockConfig(namespaceName, config); - - return config; - } - - protected static Properties readYamlContentAsConfigFileProperties(String caseName) - throws IOException { - final String filePath = "spring/yaml/" + caseName; - ClassLoader classLoader = AbstractSpringIntegrationTest.class.getClassLoader(); - - InputStream inputStream = classLoader.getResourceAsStream(filePath); - Objects.requireNonNull(inputStream, filePath + " may be not exist under src/test/resources/"); - String yamlContent = CharStreams - .toString(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); - - Properties properties = new Properties(); - properties.setProperty(ConfigConsts.CONFIG_FILE_CONTENT_KEY, yamlContent); - - return properties; - } - - protected static YamlConfigFile prepareYamlConfigFile(String namespaceNameWithFormat, Properties properties) { - ConfigRepository configRepository = mock(ConfigRepository.class); - - when(configRepository.getConfig()).thenReturn(properties); - - // spy it for testing after - YamlConfigFile configFile = spy(new YamlConfigFile(namespaceNameWithFormat, configRepository)); - - mockConfigFile(namespaceNameWithFormat, configFile); - - return configFile; - } - - protected Properties assembleProperties(String key, String value) { - Properties properties = new Properties(); - properties.setProperty(key, value); - - return properties; - } - - protected Properties assembleProperties(String key, String value, String key2, String value2) { - Properties properties = new Properties(); - properties.setProperty(key, value); - properties.setProperty(key2, value2); - - return properties; - } - - protected Properties assembleProperties(String key, String value, String key2, String value2, - String key3, String value3) { - - Properties properties = new Properties(); - properties.setProperty(key, value); - properties.setProperty(key2, value2); - properties.setProperty(key3, value3); - - return properties; - } - - protected Date assembleDate(int year, int month, int day, int hour, int minute, int second, int millisecond) { - Calendar date = Calendar.getInstance(); - date.set(year, month - 1, day, hour, minute, second); //Month in Calendar is 0 based - date.set(Calendar.MILLISECOND, millisecond); - - return date.getTime(); - } - - - protected static void mockConfig(String namespace, Config config) { - CONFIG_REGISTRY.put(namespace, config); - } - - protected static void mockConfigFile(String namespaceNameWithFormat, ConfigFile configFile) { - CONFIG_FILE_REGISTRY.put(namespaceNameWithFormat, configFile); - } - - protected static void doSetUp() { - //as ConfigService is singleton, so we must manually clear its container - ReflectionUtils.invokeMethod(CONFIG_SERVICE_RESET, null); - //as PropertySourcesProcessor has some static variables, so we must manually clear them - ReflectionUtils.invokeMethod(PROPERTY_SOURCES_PROCESSOR_RESET, null); - DefaultInjector defaultInjector = new DefaultInjector(); - ConfigManager defaultConfigManager = defaultInjector.getInstance(ConfigManager.class); - MockInjector.setInstance(ConfigManager.class, new MockConfigManager(defaultConfigManager)); - MockInjector.setDelegate(defaultInjector); - } - - protected static void doTearDown() { - MockInjector.reset(); - CONFIG_REGISTRY.clear(); - } - - private static class MockConfigManager implements ConfigManager { - - private final ConfigManager delegate; - - public MockConfigManager(ConfigManager delegate) { - this.delegate = delegate; - } - - @Override - public Config getConfig(String namespace) { - Config config = CONFIG_REGISTRY.get(namespace); - if (config != null) { - return config; - } - return delegate.getConfig(namespace); - } - - @Override - public ConfigFile getConfigFile(String namespace, ConfigFileFormat configFileFormat) { - ConfigFile configFile = CONFIG_FILE_REGISTRY.get(String.format("%s.%s", namespace, configFileFormat.getValue())); - if (configFile != null) { - return configFile; - } - return delegate.getConfigFile(namespace, configFileFormat); - } - } - - protected static class MockConfigUtil extends ConfigUtil { - - private boolean isAutoUpdateInjectedSpringProperties; - - public void setAutoUpdateInjectedSpringProperties(boolean autoUpdateInjectedSpringProperties) { - isAutoUpdateInjectedSpringProperties = autoUpdateInjectedSpringProperties; - } - - @Override - public boolean isAutoUpdateInjectedSpringPropertiesEnabled() { - return isAutoUpdateInjectedSpringProperties; - } - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/BootstrapConfigTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/BootstrapConfigTest.java deleted file mode 100644 index 1e0cd75033d..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/BootstrapConfigTest.java +++ /dev/null @@ -1,463 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.spring.annotation.ApolloConfig; -import com.ctrip.framework.apollo.spring.boot.ApolloApplicationContextInitializer; -import com.ctrip.framework.apollo.spring.config.PropertySourcesConstants; -import com.google.common.collect.Sets; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.runners.Enclosed; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.env.EnvironmentPostProcessor; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.io.support.SpringFactoriesLoader; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.util.List; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -@RunWith(Enclosed.class) -public class BootstrapConfigTest { - - private static final String TEST_BEAN_CONDITIONAL_ON_KEY = "apollo.test.testBean"; - private static final String FX_APOLLO_NAMESPACE = "FX.apollo"; - - @RunWith(SpringJUnit4ClassRunner.class) - @SpringBootTest(classes = ConfigurationWithConditionalOnProperty.class) - @DirtiesContext - public static class TestWithBootstrapEnabledAndDefaultNamespacesAndConditionalOn extends - AbstractSpringIntegrationTest { - private static final String someProperty = "someProperty"; - private static final String someValue = "someValue"; - - @Autowired(required = false) - private TestBean testBean; - - @ApolloConfig - private Config config; - - @Value("${" + someProperty + "}") - private String someInjectedValue; - - private static Config mockedConfig; - - - @BeforeClass - public static void beforeClass() throws Exception { - doSetUp(); - - System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, "true"); - - mockedConfig = mock(Config.class); - - when(mockedConfig.getPropertyNames()).thenReturn(Sets.newHashSet(TEST_BEAN_CONDITIONAL_ON_KEY, someProperty)); - - when(mockedConfig.getProperty(eq(TEST_BEAN_CONDITIONAL_ON_KEY), Mockito.nullable(String.class))).thenReturn(Boolean.TRUE.toString()); - when(mockedConfig.getProperty(eq(someProperty), Mockito.nullable(String.class))).thenReturn(someValue); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mockedConfig); - } - - @AfterClass - public static void afterClass() throws Exception { - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED); - - doTearDown(); - } - - @Test - public void test() throws Exception { - Assert.assertNotNull(testBean); - Assert.assertTrue(testBean.execute()); - - Assert.assertEquals(mockedConfig, config); - - Assert.assertEquals(someValue, someInjectedValue); - } - } - - @RunWith(SpringJUnit4ClassRunner.class) - @SpringBootTest(classes = ConfigurationWithConditionalOnProperty.class) - @DirtiesContext - public static class TestWithBootstrapEnabledAndNamespacesAndConditionalOn extends - AbstractSpringIntegrationTest { - - @Autowired(required = false) - private TestBean testBean; - - @BeforeClass - public static void beforeClass() throws Exception { - doSetUp(); - - System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, "true"); - System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, - String.format("%s, %s", ConfigConsts.NAMESPACE_APPLICATION, FX_APOLLO_NAMESPACE)); - - Config config = mock(Config.class); - Config anotherConfig = mock(Config.class); - - when(config.getPropertyNames()).thenReturn(Sets.newHashSet(TEST_BEAN_CONDITIONAL_ON_KEY)); - when(config.getProperty(eq(TEST_BEAN_CONDITIONAL_ON_KEY), Mockito.nullable(String.class))).thenReturn(Boolean.TRUE.toString()); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, anotherConfig); - mockConfig(FX_APOLLO_NAMESPACE, config); - } - - @AfterClass - public static void afterClass() throws Exception { - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED); - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES); - - doTearDown(); - } - - @Test - public void test() throws Exception { - Assert.assertNotNull(testBean); - Assert.assertTrue(testBean.execute()); - } - } - - @RunWith(SpringJUnit4ClassRunner.class) - @SpringBootTest(classes = ConfigurationWithConditionalOnProperty.class) - @DirtiesContext - public static class TestWithBootstrapEnabledAndNamespacesAndConditionalOnWithYamlFile extends - AbstractSpringIntegrationTest { - - @Autowired(required = false) - private TestBean testBean; - - @BeforeClass - public static void beforeClass() throws Exception { - doSetUp(); - - System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, "true"); - System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, - String.format("%s, %s", "application.yml", FX_APOLLO_NAMESPACE)); - - prepareYamlConfigFile("application.yml", readYamlContentAsConfigFileProperties("case6.yml")); - Config anotherConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, anotherConfig); - mockConfig(FX_APOLLO_NAMESPACE, anotherConfig); - } - - @AfterClass - public static void afterClass() throws Exception { - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED); - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES); - - doTearDown(); - } - - @Test - public void test() throws Exception { - Assert.assertNotNull(testBean); - Assert.assertTrue(testBean.execute()); - } - } - - @RunWith(SpringJUnit4ClassRunner.class) - @SpringBootTest(classes = ConfigurationWithConditionalOnProperty.class) - @DirtiesContext - public static class TestWithBootstrapEnabledAndDefaultNamespacesAndConditionalOnFailed extends - AbstractSpringIntegrationTest { - - @Autowired(required = false) - private TestBean testBean; - - @BeforeClass - public static void beforeClass() throws Exception { - doSetUp(); - - System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, "true"); - - Config config = mock(Config.class); - - when(config.getPropertyNames()).thenReturn(Sets.newHashSet(TEST_BEAN_CONDITIONAL_ON_KEY)); - when(config.getProperty(eq(TEST_BEAN_CONDITIONAL_ON_KEY), Mockito.nullable(String.class))).thenReturn(Boolean.FALSE.toString()); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - } - - @AfterClass - public static void afterClass() throws Exception { - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED); - - doTearDown(); - } - - @Test - public void test() throws Exception { - Assert.assertNull(testBean); - } - } - - @RunWith(SpringJUnit4ClassRunner.class) - @SpringBootTest(classes = ConfigurationWithConditionalOnProperty.class) - @DirtiesContext - public static class TestWithBootstrapEnabledAndDefaultNamespacesAndConditionalOnFailedWithYamlFile extends - AbstractSpringIntegrationTest { - - @Autowired(required = false) - private TestBean testBean; - - @BeforeClass - public static void beforeClass() throws Exception { - doSetUp(); - - System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, "true"); - System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, "application.yml"); - - prepareYamlConfigFile("application.yml", readYamlContentAsConfigFileProperties("case7.yml")); - } - - @AfterClass - public static void afterClass() throws Exception { - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED); - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES); - - doTearDown(); - } - - @Test - public void test() throws Exception { - Assert.assertNull(testBean); - } - } - - @RunWith(SpringJUnit4ClassRunner.class) - @SpringBootTest(classes = ConfigurationWithoutConditionalOnProperty.class) - @DirtiesContext - public static class TestWithBootstrapEnabledAndDefaultNamespacesAndConditionalOff extends - AbstractSpringIntegrationTest { - - @Autowired(required = false) - private TestBean testBean; - - @BeforeClass - public static void beforeClass() throws Exception { - doSetUp(); - - System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, "true"); - - Config config = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - } - - @AfterClass - public static void afterClass() throws Exception { - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED); - - doTearDown(); - } - - @Test - public void test() throws Exception { - Assert.assertNotNull(testBean); - Assert.assertTrue(testBean.execute()); - } - } - - @RunWith(SpringJUnit4ClassRunner.class) - @SpringBootTest(classes = ConfigurationWithoutConditionalOnProperty.class) - @DirtiesContext - public static class TestWithBootstrapEnabledAndDefaultNamespacesAndConditionalOffWithYamlFile extends - AbstractSpringIntegrationTest { - - @Autowired(required = false) - private TestBean testBean; - - @BeforeClass - public static void beforeClass() throws Exception { - doSetUp(); - - System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, "true"); - System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, "application.yml"); - - prepareYamlConfigFile("application.yml", readYamlContentAsConfigFileProperties("case8.yml")); - } - - @AfterClass - public static void afterClass() throws Exception { - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED); - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES); - - doTearDown(); - } - - @Test - public void test() throws Exception { - Assert.assertNotNull(testBean); - Assert.assertTrue(testBean.execute()); - } - } - - @RunWith(SpringJUnit4ClassRunner.class) - @SpringBootTest(classes = ConfigurationWithConditionalOnProperty.class) - @DirtiesContext - public static class TestWithBootstrapDisabledAndDefaultNamespacesAndConditionalOn extends - AbstractSpringIntegrationTest { - - @Autowired(required = false) - private TestBean testBean; - - @BeforeClass - public static void beforeClass() throws Exception { - doSetUp(); - - Config config = mock(Config.class); - - when(config.getPropertyNames()).thenReturn(Sets.newHashSet(TEST_BEAN_CONDITIONAL_ON_KEY)); - when(config.getProperty(eq(TEST_BEAN_CONDITIONAL_ON_KEY), Mockito.nullable(String.class))).thenReturn(Boolean.FALSE.toString()); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - } - - @AfterClass - public static void afterClass() throws Exception { - doTearDown(); - } - - @Test - public void test() throws Exception { - Assert.assertNull(testBean); - } - } - - @RunWith(SpringJUnit4ClassRunner.class) - @SpringBootTest(classes = ConfigurationWithoutConditionalOnProperty.class) - @DirtiesContext - public static class TestWithBootstrapDisabledAndDefaultNamespacesAndConditionalOff extends - AbstractSpringIntegrationTest { - - @Autowired(required = false) - private TestBean testBean; - - @BeforeClass - public static void beforeClass() throws Exception { - doSetUp(); - - Config config = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - } - - @AfterClass - public static void afterClass() throws Exception { - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED); - - doTearDown(); - } - - @Test - public void test() throws Exception { - Assert.assertNotNull(testBean); - Assert.assertTrue(testBean.execute()); - } - } - - @RunWith(SpringJUnit4ClassRunner.class) - @SpringBootTest(classes = ConfigurationWithoutConditionalOnProperty.class) - @DirtiesContext - public static class TestWithBootstrapEnabledAndEagerLoadEnabled extends - AbstractSpringIntegrationTest { - - @BeforeClass - public static void beforeClass() { - doSetUp(); - - System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED, "true"); - System.setProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED, "true"); - - Config config = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - } - - @AfterClass - public static void afterClass() { - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_ENABLED); - System.clearProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_EAGER_LOAD_ENABLED); - - doTearDown(); - } - - @Test - public void test() { - List names = SpringFactoriesLoader.loadFactoryNames(EnvironmentPostProcessor.class, getClass().getClassLoader()); - boolean containsApollo = false; - for (String name : names) { - if (name.equals("com.ctrip.framework.apollo.spring.boot.ApolloApplicationContextInitializer")) { - containsApollo = true; - break; - } - } - Assert.assertTrue(containsApollo); - } - } - - @EnableAutoConfiguration - @Configuration - static class ConfigurationWithoutConditionalOnProperty { - - @Bean - public TestBean testBean() { - return new TestBean(); - } - } - - @ConditionalOnProperty(TEST_BEAN_CONDITIONAL_ON_KEY) - @EnableAutoConfiguration - @Configuration - static class ConfigurationWithConditionalOnProperty { - - @Bean - public TestBean testBean() { - return new TestBean(); - } - } - - static class TestBean { - - public boolean execute() { - return true; - } - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/JavaConfigAnnotationTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/JavaConfigAnnotationTest.java deleted file mode 100644 index 40d5a127d33..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/JavaConfigAnnotationTest.java +++ /dev/null @@ -1,989 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.ConfigFileChangeListener; -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.internals.SimpleConfig; -import com.ctrip.framework.apollo.internals.YamlConfigFile; -import com.ctrip.framework.apollo.model.ConfigChange; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import com.ctrip.framework.apollo.spring.annotation.ApolloConfig; -import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener; -import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.google.common.util.concurrent.SettableFuture; -import java.io.IOException; -import java.util.Collections; -import java.util.Properties; -import java.util.UUID; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; -import org.junit.After; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import java.util.List; -import java.util.Set; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anySet; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class JavaConfigAnnotationTest extends AbstractSpringIntegrationTest { - private static final String FX_APOLLO_NAMESPACE = "FX.apollo"; - private static final String APPLICATION_YAML_NAMESPACE = "application.yaml"; - - private static T getBean(Class beanClass, Class... annotatedClasses) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(annotatedClasses); - return context.getBean(beanClass); - } - - private static T getSimpleBean(Class clazz) { - return getBean(clazz, clazz); - } - - @Override - @After - public void tearDown() throws Exception { - // clear the system properties - System.clearProperty(SystemPropertyKeyConstants.SIMPLE_NAMESPACE); - System.clearProperty(SystemPropertyKeyConstants.REDIS_NAMESPACE); - System.clearProperty(SystemPropertyKeyConstants.FROM_SYSTEM_NAMESPACE); - System.clearProperty(SystemPropertyKeyConstants.FROM_SYSTEM_YAML_NAMESPACE); - System.clearProperty(SystemPropertyKeyConstants.FROM_NAMESPACE_APPLICATION_KEY); - System.clearProperty(SystemPropertyKeyConstants.FROM_NAMESPACE_APPLICATION_KEY_YAML); - System.clearProperty(ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE); - super.tearDown(); - } - - @Test - public void testApolloConfig() throws Exception { - Config applicationConfig = mock(Config.class); - Config fxApolloConfig = mock(Config.class); - String someKey = "someKey"; - String someValue = "someValue"; - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); - - prepareYamlConfigFile(APPLICATION_YAML_NAMESPACE, readYamlContentAsConfigFileProperties("case9.yml")); - - TestApolloConfigBean1 bean = getBean(TestApolloConfigBean1.class, AppConfig1.class); - - assertEquals(applicationConfig, bean.getConfig()); - assertEquals(applicationConfig, bean.getAnotherConfig()); - assertEquals(fxApolloConfig, bean.getYetAnotherConfig()); - - Config yamlConfig = bean.getYamlConfig(); - assertEquals(someValue, yamlConfig.getProperty(someKey, null)); - } - - @Test(expected = BeanCreationException.class) - public void testApolloConfigWithWrongFieldType() throws Exception { - Config applicationConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - - getBean(TestApolloConfigBean2.class, AppConfig2.class); - } - - @Test - public void testApolloConfigWithInheritance() throws Exception { - Config applicationConfig = mock(Config.class); - Config fxApolloConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); - prepareYamlConfigFile(APPLICATION_YAML_NAMESPACE, readYamlContentAsConfigFileProperties("case9.yml")); - - TestApolloChildConfigBean bean = getBean(TestApolloChildConfigBean.class, AppConfig6.class); - - assertEquals(applicationConfig, bean.getConfig()); - assertEquals(applicationConfig, bean.getAnotherConfig()); - assertEquals(fxApolloConfig, bean.getYetAnotherConfig()); - assertEquals(applicationConfig, bean.getSomeConfig()); - } - - @Test - public void testEnableApolloConfigResolveExpressionSimple() { - String someKey = "someKey-2020-11-14-1750"; - String someValue = UUID.randomUUID().toString(); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); - Config xxxConfig = mock(Config.class); - when(xxxConfig.getProperty(eq(someKey), Mockito.nullable(String.class))).thenReturn(someValue); - mockConfig("xxx", xxxConfig); - - TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration configuration = - getSimpleBean(TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration.class); - - // check - assertEquals(someValue, configuration.getSomeKey()); - verify(xxxConfig, times(1)).getProperty(eq(someKey), Mockito.nullable(String.class)); - } - - @Test - public void testEnableApolloConfigResolveExpressionFromSystemProperty() { - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); - final String someKey = "someKey-2020-11-14-1750"; - final String someValue = UUID.randomUUID().toString(); - - final String resolvedNamespaceName = "yyy"; - System.setProperty(SystemPropertyKeyConstants.SIMPLE_NAMESPACE, resolvedNamespaceName); - - Config yyyConfig = mock(Config.class); - when(yyyConfig.getProperty(eq(someKey), Mockito.nullable(String.class))).thenReturn(someValue); - mockConfig(resolvedNamespaceName, yyyConfig); - - TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration configuration = - getSimpleBean(TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration.class); - - // check - assertEquals(someValue, configuration.getSomeKey()); - verify(yyyConfig, times(1)).getProperty(eq(someKey), Mockito.nullable(String.class)); - } - - @Test(expected = BeanCreationException.class) - public void testEnableApolloConfigUnresolvedValueInField() { - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); - mockConfig("xxx", mock(Config.class)); - getSimpleBean(TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration.class); - } - - @Test(expected = IllegalArgumentException.class) - public void testEnableApolloConfigUnresolvable() { - getSimpleBean(TestEnableApolloConfigUnresolvableConfiguration.class); - } - - @Test - public void testApolloConfigChangeListener() throws Exception { - Config applicationConfig = mock(Config.class); - Config fxApolloConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); - - final List applicationListeners = Lists.newArrayList(); - final List fxApolloListeners = Lists.newArrayList(); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - applicationListeners.add(invocation.getArgument(0, ConfigChangeListener.class)); - - return Void.class; - } - }).when(applicationConfig).addChangeListener(any(ConfigChangeListener.class)); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - fxApolloListeners.add(invocation.getArgument(0, ConfigChangeListener.class)); - - return Void.class; - } - }).when(fxApolloConfig).addChangeListener(any(ConfigChangeListener.class)); - - ConfigChangeEvent someEvent = mock(ConfigChangeEvent.class); - ConfigChangeEvent anotherEvent = mock(ConfigChangeEvent.class); - - TestApolloConfigChangeListenerBean1 bean = getBean(TestApolloConfigChangeListenerBean1.class, AppConfig3.class); - - //PropertySourcesProcessor add listeners to listen config changed of all namespace - assertEquals(4, applicationListeners.size()); - assertEquals(1, fxApolloListeners.size()); - - for (ConfigChangeListener listener : applicationListeners) { - listener.onChange(someEvent); - } - - assertEquals(someEvent, bean.getChangeEvent1()); - assertEquals(someEvent, bean.getChangeEvent2()); - assertEquals(someEvent, bean.getChangeEvent3()); - - for (ConfigChangeListener listener : fxApolloListeners) { - listener.onChange(anotherEvent); - } - - assertEquals(someEvent, bean.getChangeEvent1()); - assertEquals(someEvent, bean.getChangeEvent2()); - assertEquals(anotherEvent, bean.getChangeEvent3()); - } - - @Test(expected = BeanCreationException.class) - public void testApolloConfigChangeListenerWithWrongParamType() throws Exception { - Config applicationConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - - getBean(TestApolloConfigChangeListenerBean2.class, AppConfig4.class); - } - - @Test(expected = BeanCreationException.class) - public void testApolloConfigChangeListenerWithWrongParamCount() throws Exception { - Config applicationConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - - getBean(TestApolloConfigChangeListenerBean3.class, AppConfig5.class); - } - - @Test - public void testApolloConfigChangeListenerWithInheritance() throws Exception { - Config applicationConfig = mock(Config.class); - Config fxApolloConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); - - final List applicationListeners = Lists.newArrayList(); - final List fxApolloListeners = Lists.newArrayList(); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - applicationListeners.add(invocation.getArgument(0, ConfigChangeListener.class)); - - return Void.class; - } - }).when(applicationConfig).addChangeListener(any(ConfigChangeListener.class)); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - fxApolloListeners.add(invocation.getArgument(0, ConfigChangeListener.class)); - - return Void.class; - } - }).when(fxApolloConfig).addChangeListener(any(ConfigChangeListener.class)); - - ConfigChangeEvent someEvent = mock(ConfigChangeEvent.class); - ConfigChangeEvent anotherEvent = mock(ConfigChangeEvent.class); - - TestApolloChildConfigChangeListener bean = getBean(TestApolloChildConfigChangeListener.class, AppConfig7.class); - - //PropertySourcesProcessor add listeners to listen config changed of all namespace - assertEquals(5, applicationListeners.size()); - assertEquals(1, fxApolloListeners.size()); - - for (ConfigChangeListener listener : applicationListeners) { - listener.onChange(someEvent); - } - - assertEquals(someEvent, bean.getChangeEvent1()); - assertEquals(someEvent, bean.getChangeEvent2()); - assertEquals(someEvent, bean.getChangeEvent3()); - assertEquals(someEvent, bean.getSomeChangeEvent()); - - for (ConfigChangeListener listener : fxApolloListeners) { - listener.onChange(anotherEvent); - } - - assertEquals(someEvent, bean.getChangeEvent1()); - assertEquals(someEvent, bean.getChangeEvent2()); - assertEquals(anotherEvent, bean.getChangeEvent3()); - assertEquals(someEvent, bean.getSomeChangeEvent()); - } - - @Test - public void testApolloConfigChangeListenerWithInterestedKeys() throws Exception { - Config applicationConfig = mock(Config.class); - Config fxApolloConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); - - TestApolloConfigChangeListenerWithInterestedKeysBean bean = getBean( - TestApolloConfigChangeListenerWithInterestedKeysBean.class, AppConfig8.class); - - final ArgumentCaptor applicationConfigInterestedKeys = ArgumentCaptor.forClass(Set.class); - final ArgumentCaptor fxApolloConfigInterestedKeys = ArgumentCaptor.forClass(Set.class); - - verify(applicationConfig, times(2)) - .addChangeListener(any(ConfigChangeListener.class), applicationConfigInterestedKeys.capture(), Mockito.nullable(Set.class)); - - verify(fxApolloConfig, times(1)) - .addChangeListener(any(ConfigChangeListener.class), fxApolloConfigInterestedKeys.capture(), Mockito.nullable(Set.class)); - - assertEquals(2, applicationConfigInterestedKeys.getAllValues().size()); - - Set result = Sets.newHashSet(); - for (Set interestedKeys : applicationConfigInterestedKeys.getAllValues()) { - result.addAll(interestedKeys); - } - assertEquals(Sets.newHashSet("someKey", "anotherKey"), result); - - assertEquals(1, fxApolloConfigInterestedKeys.getAllValues().size()); - - assertEquals(Collections.singletonList(Sets.newHashSet("anotherKey")), fxApolloConfigInterestedKeys.getAllValues()); - } - - @Test - public void testApolloConfigChangeListenerWithInterestedKeyPrefixes() { - Config applicationConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - - TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean bean = getBean( - TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean.class, AppConfig10.class); - - final ArgumentCaptor interestedKeyPrefixesArgumentCaptor = ArgumentCaptor - .forClass(Set.class); - - verify(applicationConfig, times(1)) - .addChangeListener(any(ConfigChangeListener.class), Mockito.nullable(Set.class), - interestedKeyPrefixesArgumentCaptor.capture()); - - assertEquals(1, interestedKeyPrefixesArgumentCaptor.getAllValues().size()); - - Set result = Sets.newHashSet(); - for (Set interestedKeyPrefixes : interestedKeyPrefixesArgumentCaptor.getAllValues()) { - result.addAll(interestedKeyPrefixes); - } - assertEquals(Sets.newHashSet("logging.level", "number"), result); - } - - @Test - public void testApolloConfigChangeListenerWithInterestedKeyPrefixes_fire() - throws InterruptedException { - // default mock, useless here - // just for speed up test without waiting - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); - - SimpleConfig simpleConfig = spy( - this.prepareConfig( - TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1.SPECIAL_NAMESPACE, - new Properties())); - - mockConfig(TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1.SPECIAL_NAMESPACE, - simpleConfig); - - TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1 bean = getBean( - TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1.class, AppConfig11.class); - - verify(simpleConfig, atLeastOnce()) - .addChangeListener(any(ConfigChangeListener.class), Mockito.nullable(Set.class), - anySet()); - - Properties properties = new Properties(); - properties.put("logging.level.com", "debug"); - properties.put("logging.level.root", "warn"); - properties.put("number.value", "333"); - - // publish config change - simpleConfig.onRepositoryChange( - TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1.SPECIAL_NAMESPACE, properties); - - // get event from bean - ConfigChangeEvent configChangeEvent = bean.getConfigChangeEvent(); - Set interestedChangedKeys = configChangeEvent.interestedChangedKeys(); - assertEquals(Sets.newHashSet("logging.level.com", "logging.level.root", "number.value"), - interestedChangedKeys); - } - - @Test - public void testApolloConfigChangeListenerWithYamlFile() throws Exception { - String someKey = "someKey"; - String someValue = "someValue"; - String anotherValue = "anotherValue"; - - YamlConfigFile configFile = prepareYamlConfigFile(APPLICATION_YAML_NAMESPACE, - readYamlContentAsConfigFileProperties("case9.yml")); - - TestApolloConfigChangeListenerWithYamlFile bean = getBean(TestApolloConfigChangeListenerWithYamlFile.class, AppConfig9.class); - - Config yamlConfig = bean.getYamlConfig(); - SettableFuture future = bean.getConfigChangeEventFuture(); - - assertEquals(someValue, yamlConfig.getProperty(someKey, null)); - assertFalse(future.isDone()); - - configFile.onRepositoryChange(APPLICATION_YAML_NAMESPACE, readYamlContentAsConfigFileProperties("case9-new.yml")); - - ConfigChangeEvent configChangeEvent = future.get(100, TimeUnit.MILLISECONDS); - ConfigChange change = configChangeEvent.getChange(someKey); - assertEquals(someValue, change.getOldValue()); - assertEquals(anotherValue, change.getNewValue()); - - assertEquals(anotherValue, yamlConfig.getProperty(someKey, null)); - } - - @Test - public void testApolloConfigChangeListenerResolveExpressionSimple() { - // for ignore, no listener use it - Config ignoreConfig = mock(Config.class); - mockConfig("ignore.for.listener", ignoreConfig); - - Config applicationConfig = mock(Config.class); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - - System.setProperty(ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE, "true"); - - getSimpleBean(TestApolloConfigChangeListenerResolveExpressionSimpleConfiguration.class); - - // no using - verify(ignoreConfig, never()).addChangeListener(any(ConfigChangeListener.class)); - - // one invocation for spring value auto update - // one invocation for the @ApolloConfigChangeListener annotation - // one invocation for CachedCompositePropertySource clear cache listener - verify(applicationConfig, times(3)).addChangeListener(any(ConfigChangeListener.class)); - } - - /** - * resolve namespace's name from system property. - */ - @Test - public void testApolloConfigChangeListenerResolveExpressionFromSystemProperty() { - Config applicationConfig = mock(Config.class); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - - final String namespaceName = "magicRedis"; - System.setProperty(SystemPropertyKeyConstants.REDIS_NAMESPACE, namespaceName); - Config redisConfig = mock(Config.class); - mockConfig(namespaceName, redisConfig); - getSimpleBean( - TestApolloConfigChangeListenerResolveExpressionFromSystemPropertyConfiguration.class); - - // if config was used, it must be invoked on method addChangeListener 1 time - verify(redisConfig, times(1)).addChangeListener(any(ConfigChangeListener.class)); - } - - /** - * resolve namespace from config. ${mysql.namespace} will be resolved by config from namespace - * application. - */ - @Test - public void testApolloConfigChangeListenerResolveExpressionFromApplicationNamespace() { - final String namespaceKey = "mysql.namespace"; - final String namespaceName = "magicMysqlNamespaceApplication"; - - Properties properties = new Properties(); - properties.setProperty(namespaceKey, namespaceName); - this.prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - Config mysqlConfig = mock(Config.class); - mockConfig(namespaceName, mysqlConfig); - - getSimpleBean( - TestApolloConfigChangeListenerResolveExpressionFromApplicationNamespaceConfiguration.class); - - // if config was used, it must be invoked on method addChangeListener 1 time - verify(mysqlConfig, times(1)).addChangeListener(any(ConfigChangeListener.class)); - } - - @Test(expected = BeanCreationException.class) - public void testApolloConfigChangeListenerUnresolvedPlaceholder() { - Config applicationConfig = mock(Config.class); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - getSimpleBean(TestApolloConfigChangeListenerUnresolvedPlaceholderConfiguration.class); - } - - @Test - public void testApolloConfigChangeListenerResolveExpressionFromSelfYaml() throws IOException { - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); - - final String resolvedValue = "resolve.from.self.yml"; - YamlConfigFile yamlConfigFile = prepareYamlConfigFile(resolvedValue, readYamlContentAsConfigFileProperties(resolvedValue)); - getSimpleBean(TestApolloConfigChangeListenerResolveExpressionFromSelfYamlConfiguration.class); - verify(yamlConfigFile, times(1)).addChangeListener(any(ConfigFileChangeListener.class)); - } - - @Test - public void testApolloConfigResolveExpressionDefault() { - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); - Config defaultConfig = mock(Config.class); - Config yamlConfig = mock(Config.class); - mockConfig("default-2020-11-14-1733", defaultConfig); - mockConfig(APPLICATION_YAML_NAMESPACE, yamlConfig); - TestApolloConfigResolveExpressionDefaultConfiguration configuration = getSimpleBean( - TestApolloConfigResolveExpressionDefaultConfiguration.class); - assertSame(defaultConfig, configuration.getDefaultConfig()); - assertSame(yamlConfig, configuration.getYamlConfig()); - } - - @Test - public void testApolloConfigResolveExpressionFromSystemProperty() { - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); - final String namespaceName = "xxx6"; - final String yamlNamespaceName = "yyy8.yml"; - - System.setProperty(SystemPropertyKeyConstants.FROM_SYSTEM_NAMESPACE, namespaceName); - System.setProperty(SystemPropertyKeyConstants.FROM_SYSTEM_YAML_NAMESPACE, yamlNamespaceName); - Config config = mock(Config.class); - Config yamlConfig = mock(Config.class); - mockConfig(namespaceName, config); - mockConfig(yamlNamespaceName, yamlConfig); - TestApolloConfigResolveExpressionFromSystemPropertyConfiguration configuration = getSimpleBean( - TestApolloConfigResolveExpressionFromSystemPropertyConfiguration.class); - assertSame(config, configuration.getConfig()); - assertSame(yamlConfig, configuration.getYamlConfig()); - } - - @Test(expected = BeanCreationException.class) - public void testApolloConfigUnresolvedExpression() { - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, mock(Config.class)); - getSimpleBean(TestApolloConfigUnresolvedExpressionConfiguration.class); - } - - @Test - public void testApolloConfigResolveExpressionFromApolloConfigNamespaceApplication() { - - final String namespaceName = "xxx6"; - final String yamlNamespaceName = "yyy8.yml"; - { - // hide variable scope - Properties properties = new Properties(); - properties.setProperty(SystemPropertyKeyConstants.FROM_NAMESPACE_APPLICATION_KEY, namespaceName); - properties.setProperty(SystemPropertyKeyConstants.FROM_NAMESPACE_APPLICATION_KEY_YAML, yamlNamespaceName); - this.prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - } - final Config config = mock(Config.class); - final Config yamlConfig = mock(Config.class); - mockConfig(namespaceName, config); - mockConfig(yamlNamespaceName, yamlConfig); - TestApolloConfigResolveExpressionFromApolloConfigNamespaceApplication configuration = getSimpleBean( - TestApolloConfigResolveExpressionFromApolloConfigNamespaceApplication.class); - assertSame(config, configuration.getConfig()); - assertSame(yamlConfig, configuration.getYamlConfig()); - } - - private static class SystemPropertyKeyConstants { - - static final String SIMPLE_NAMESPACE = "simple.namespace"; - static final String REDIS_NAMESPACE = "redis.namespace"; - static final String FROM_SYSTEM_NAMESPACE = "from.system.namespace"; - static final String FROM_SYSTEM_YAML_NAMESPACE = "from.system.yaml.namespace"; - static final String FROM_NAMESPACE_APPLICATION_KEY = "from.namespace.application.key"; - static final String FROM_NAMESPACE_APPLICATION_KEY_YAML = "from.namespace.application.key.yaml"; - } - - @EnableApolloConfig - protected static class TestApolloConfigResolveExpressionDefaultConfiguration { - - @ApolloConfig(value = "${simple.namespace:default-2020-11-14-1733}") - private Config defaultConfig; - - @ApolloConfig(value = "${simple.yaml.namespace:" + APPLICATION_YAML_NAMESPACE + "}") - private Config yamlConfig; - - public Config getDefaultConfig() { - return defaultConfig; - } - - public Config getYamlConfig() { - return yamlConfig; - } - } - - @EnableApolloConfig - protected static class TestApolloConfigResolveExpressionFromSystemPropertyConfiguration { - - @ApolloConfig(value = "${from.system.namespace}") - private Config config; - - @ApolloConfig(value = "${from.system.yaml.namespace}") - private Config yamlConfig; - - public Config getConfig() { - return config; - } - - public Config getYamlConfig() { - return yamlConfig; - } - } - - @EnableApolloConfig - protected static class TestApolloConfigUnresolvedExpressionConfiguration { - - @ApolloConfig(value = "${so.complex.to.resolve}") - private Config config; - } - - @EnableApolloConfig - protected static class TestApolloConfigResolveExpressionFromApolloConfigNamespaceApplication { - - @ApolloConfig(value = "${from.namespace.application.key}") - private Config config; - - @ApolloConfig(value = "${from.namespace.application.key.yaml}") - private Config yamlConfig; - - public Config getConfig() { - return config; - } - - public Config getYamlConfig() { - return yamlConfig; - } - } - - - @Configuration - @EnableApolloConfig - static class TestApolloConfigChangeListenerResolveExpressionSimpleConfiguration { - - @ApolloConfigChangeListener("${simple.application:application}") - private void onChange(ConfigChangeEvent event) { - } - } - - @Configuration - @EnableApolloConfig - static class TestApolloConfigChangeListenerResolveExpressionFromSystemPropertyConfiguration { - - @ApolloConfigChangeListener("${redis.namespace}") - private void onChange(ConfigChangeEvent event) { - } - } - - @Configuration - @EnableApolloConfig - static class TestApolloConfigChangeListenerResolveExpressionFromApplicationNamespaceConfiguration { - - @ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, - "${mysql.namespace}"}) - private void onChange(ConfigChangeEvent event) { - } - } - - @Configuration - @EnableApolloConfig - static class TestApolloConfigChangeListenerUnresolvedPlaceholderConfiguration { - @ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, - "${i.can.not.be.resolved}"}) - private void onChange(ConfigChangeEvent event) { - } - } - - @Configuration - @EnableApolloConfig("resolve.from.self.yml") - static class TestApolloConfigChangeListenerResolveExpressionFromSelfYamlConfiguration { - - /** - * value in file src/test/resources/spring/yaml/resolve.from.self.yml - */ - @ApolloConfigChangeListener("${i.can.resolve.from.self}") - private void onChange(ConfigChangeEvent event) { - } - } - - @Configuration - @EnableApolloConfig(value = {ConfigConsts.NAMESPACE_APPLICATION, "${simple.namespace:xxx}"}) - static class TestEnableApolloConfigResolveExpressionWithDefaultValueConfiguration { - - @Value("${someKey-2020-11-14-1750}") - private String someKey; - - public String getSomeKey() { - return this.someKey; - } - } - - @Configuration - @EnableApolloConfig(value = "${unresolvable.property}") - static class TestEnableApolloConfigUnresolvableConfiguration { - - } - - @Configuration - @EnableApolloConfig - static class AppConfig1 { - @Bean - public TestApolloConfigBean1 bean() { - return new TestApolloConfigBean1(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig2 { - @Bean - public TestApolloConfigBean2 bean() { - return new TestApolloConfigBean2(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig3 { - @Bean - public TestApolloConfigChangeListenerBean1 bean() { - return new TestApolloConfigChangeListenerBean1(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig4 { - @Bean - public TestApolloConfigChangeListenerBean2 bean() { - return new TestApolloConfigChangeListenerBean2(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig5 { - @Bean - public TestApolloConfigChangeListenerBean3 bean() { - return new TestApolloConfigChangeListenerBean3(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig6 { - @Bean - public TestApolloChildConfigBean bean() { - return new TestApolloChildConfigBean(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig7 { - @Bean - public TestApolloChildConfigChangeListener bean() { - return new TestApolloChildConfigChangeListener(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig8 { - @Bean - public TestApolloConfigChangeListenerWithInterestedKeysBean bean() { - return new TestApolloConfigChangeListenerWithInterestedKeysBean(); - } - } - - @Configuration - @EnableApolloConfig(APPLICATION_YAML_NAMESPACE) - static class AppConfig9 { - @Bean - public TestApolloConfigChangeListenerWithYamlFile bean() { - return new TestApolloConfigChangeListenerWithYamlFile(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig10 { - @Bean - public TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean bean() { - return new TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig11 { - @Bean - public TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1 bean() { - return spy(new TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1()); - } - } - - static class TestApolloConfigBean1 { - @ApolloConfig - private Config config; - @ApolloConfig(ConfigConsts.NAMESPACE_APPLICATION) - private Config anotherConfig; - @ApolloConfig(FX_APOLLO_NAMESPACE) - private Config yetAnotherConfig; - @ApolloConfig(APPLICATION_YAML_NAMESPACE) - private Config yamlConfig; - - public Config getConfig() { - return config; - } - - public Config getAnotherConfig() { - return anotherConfig; - } - - public Config getYetAnotherConfig() { - return yetAnotherConfig; - } - - public Config getYamlConfig() { - return yamlConfig; - } - } - - static class TestApolloConfigBean2 { - @ApolloConfig - private String config; - } - - static class TestApolloChildConfigBean extends TestApolloConfigBean1 { - - @ApolloConfig - private Config someConfig; - - public Config getSomeConfig() { - return someConfig; - } - } - - static class TestApolloConfigChangeListenerBean1 { - private ConfigChangeEvent changeEvent1; - private ConfigChangeEvent changeEvent2; - private ConfigChangeEvent changeEvent3; - - @ApolloConfigChangeListener - private void onChange1(ConfigChangeEvent changeEvent) { - this.changeEvent1 = changeEvent; - } - - @ApolloConfigChangeListener(ConfigConsts.NAMESPACE_APPLICATION) - private void onChange2(ConfigChangeEvent changeEvent) { - this.changeEvent2 = changeEvent; - } - - @ApolloConfigChangeListener({ConfigConsts.NAMESPACE_APPLICATION, FX_APOLLO_NAMESPACE}) - private void onChange3(ConfigChangeEvent changeEvent) { - this.changeEvent3 = changeEvent; - } - - public ConfigChangeEvent getChangeEvent1() { - return changeEvent1; - } - - public ConfigChangeEvent getChangeEvent2() { - return changeEvent2; - } - - public ConfigChangeEvent getChangeEvent3() { - return changeEvent3; - } - } - - static class TestApolloConfigChangeListenerBean2 { - @ApolloConfigChangeListener - private void onChange(String event) { - - } - } - - static class TestApolloConfigChangeListenerBean3 { - @ApolloConfigChangeListener - private void onChange(ConfigChangeEvent event, String someParam) { - - } - } - - static class TestApolloChildConfigChangeListener extends TestApolloConfigChangeListenerBean1 { - - private ConfigChangeEvent someChangeEvent; - - @ApolloConfigChangeListener - private void someOnChange(ConfigChangeEvent changeEvent) { - this.someChangeEvent = changeEvent; - } - - public ConfigChangeEvent getSomeChangeEvent() { - return someChangeEvent; - } - } - - static class TestApolloConfigChangeListenerWithInterestedKeysBean { - - @ApolloConfigChangeListener(interestedKeys = {"someKey"}) - private void someOnChange(ConfigChangeEvent changeEvent) {} - - @ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, FX_APOLLO_NAMESPACE}, - interestedKeys = {"anotherKey"}) - private void anotherOnChange(ConfigChangeEvent changeEvent) { - - } - } - - private static class TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean { - - @ApolloConfigChangeListener(interestedKeyPrefixes = {"number", "logging.level"}) - private void onChange(ConfigChangeEvent changeEvent) { - } - } - - private static class TestApolloConfigChangeListenerWithInterestedKeyPrefixesBean1 { - - static final String SPECIAL_NAMESPACE = "special-namespace-2021"; - - private final BlockingQueue configChangeEventQueue = new ArrayBlockingQueue<>(100); - - @ApolloConfigChangeListener(value = SPECIAL_NAMESPACE, interestedKeyPrefixes = {"number", - "logging.level"}) - private void onChange(ConfigChangeEvent changeEvent) { - this.configChangeEventQueue.add(changeEvent); - } - - public ConfigChangeEvent getConfigChangeEvent() throws InterruptedException { - return this.configChangeEventQueue.poll(5, TimeUnit.SECONDS); - } - } - - static class TestApolloConfigChangeListenerWithYamlFile { - - private SettableFuture configChangeEventFuture = SettableFuture.create(); - - @ApolloConfig(APPLICATION_YAML_NAMESPACE) - private Config yamlConfig; - - @ApolloConfigChangeListener(APPLICATION_YAML_NAMESPACE) - private void onChange(ConfigChangeEvent event) { - configChangeEventFuture.set(event); - } - - public SettableFuture getConfigChangeEventFuture() { - return configChangeEventFuture; - } - - public Config getYamlConfig() { - return yamlConfig; - } - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/JavaConfigPlaceholderAutoUpdateTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/JavaConfigPlaceholderAutoUpdateTest.java deleted file mode 100644 index 2182b6e3471..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/JavaConfigPlaceholderAutoUpdateTest.java +++ /dev/null @@ -1,1379 +0,0 @@ -/* - * Copyright 2022 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; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.internals.SimpleConfig; -import com.ctrip.framework.apollo.internals.YamlConfigFile; -import com.ctrip.framework.apollo.spring.JavaConfigPlaceholderTest.JsonBean; -import com.ctrip.framework.apollo.spring.XmlConfigPlaceholderTest.TestXmlBean; -import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue; -import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.primitives.Ints; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Properties; -import java.util.concurrent.TimeUnit; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.ComponentScan.Filter; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.FilterType; -import org.springframework.context.annotation.ImportResource; -import org.springframework.stereotype.Component; - -public class JavaConfigPlaceholderAutoUpdateTest extends AbstractSpringIntegrationTest { - - private static final String TIMEOUT_PROPERTY = "timeout"; - private static final int DEFAULT_TIMEOUT = 100; - private static final String BATCH_PROPERTY = "batch"; - private static final int DEFAULT_BATCH = 200; - private static final String FX_APOLLO_NAMESPACE = "FX.apollo"; - private static final String SOME_KEY_PROPERTY = "someKey"; - private static final String ANOTHER_KEY_PROPERTY = "anotherKey"; - - @Test - public void testAutoUpdateWithOneNamespace() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY, - String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = - assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(newBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithOneYamlFile() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - YamlConfigFile configFile = prepareYamlConfigFile("application.yaml", - readYamlContentAsConfigFileProperties("case1.yaml")); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig12.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case1-new.yaml")); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(newBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithValueAndXmlProperty() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY, - String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig8.class); - - TestJavaConfigBean javaConfigBean = context.getBean(TestJavaConfigBean.class); - TestXmlBean xmlBean = context.getBean(TestXmlBean.class); - - assertEquals(initialTimeout, javaConfigBean.getTimeout()); - assertEquals(initialBatch, javaConfigBean.getBatch()); - assertEquals(initialTimeout, xmlBean.getTimeout()); - assertEquals(initialBatch, xmlBean.getBatch()); - - Properties newProperties = - assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(newTimeout, javaConfigBean.getTimeout()); - assertEquals(newBatch, javaConfigBean.getBatch()); - assertEquals(newTimeout, xmlBean.getTimeout()); - assertEquals(newBatch, xmlBean.getBatch()); - } - - @Test - public void testAutoUpdateWithYamlFileWithValueAndXmlProperty() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - YamlConfigFile configFile = prepareYamlConfigFile("application.yaml", - readYamlContentAsConfigFileProperties("case1.yaml")); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig13.class); - - TestJavaConfigBean javaConfigBean = context.getBean(TestJavaConfigBean.class); - TestXmlBean xmlBean = context.getBean(TestXmlBean.class); - - assertEquals(initialTimeout, javaConfigBean.getTimeout()); - assertEquals(initialBatch, javaConfigBean.getBatch()); - assertEquals(initialTimeout, xmlBean.getTimeout()); - assertEquals(initialBatch, xmlBean.getBatch()); - - configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case1-new.yaml")); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(newTimeout, javaConfigBean.getTimeout()); - assertEquals(newBatch, javaConfigBean.getBatch()); - assertEquals(newTimeout, xmlBean.getTimeout()); - assertEquals(newBatch, xmlBean.getBatch()); - } - - @Test - public void testAutoUpdateDisabled() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - MockConfigUtil mockConfigUtil = new MockConfigUtil(); - mockConfigUtil.setAutoUpdateInjectedSpringProperties(false); - - MockInjector.setInstance(ConfigUtil.class, mockConfigUtil); - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY, - String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = - assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithMultipleNamespaces() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout)); - Properties fxApolloProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(initialBatch)); - - SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties); - SimpleConfig fxApolloConfig = prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig2.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout)); - - applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newFxApolloProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(newBatch)); - - fxApolloConfig.onRepositoryChange(FX_APOLLO_NAMESPACE, newFxApolloProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(newBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithMultipleNamespacesWithSameProperties() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - int anotherBatch = 3000; - int someNewTimeout = 1001; - int someNewBatch = 2001; - - Properties applicationProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(someBatch)); - Properties fxApolloProperties = - assembleProperties(TIMEOUT_PROPERTY, String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch)); - - prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties); - SimpleConfig fxApolloConfig = prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig2.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(someTimeout, bean.getTimeout()); - assertEquals(someBatch, bean.getBatch()); - - Properties newFxApolloProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(someNewTimeout), - BATCH_PROPERTY, String.valueOf(someNewBatch)); - - fxApolloConfig.onRepositoryChange(FX_APOLLO_NAMESPACE, newFxApolloProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(someNewTimeout, bean.getTimeout()); - assertEquals(someBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithMultipleNamespacesWithSamePropertiesWithYamlFile() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - int anotherBatch = 3000; - int someNewBatch = 2001; - - YamlConfigFile configFile = prepareYamlConfigFile("application.yml", - readYamlContentAsConfigFileProperties("case2.yml")); - Properties fxApolloProperties = - assembleProperties(TIMEOUT_PROPERTY, String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch)); - - prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig14.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(someTimeout, bean.getTimeout()); - assertEquals(someBatch, bean.getBatch()); - - configFile.onRepositoryChange("application.yml", readYamlContentAsConfigFileProperties("case2-new.yml")); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(someTimeout, bean.getTimeout()); - assertEquals(someNewBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithNewProperties() throws Exception { - int initialTimeout = 1000; - int newTimeout = 1001; - int newBatch = 2001; - - Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout)); - - SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(DEFAULT_BATCH, bean.getBatch()); - - Properties newApplicationProperties = - assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch)); - - applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(newBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithNewPropertiesWithYamlFile() throws Exception { - int initialTimeout = 1000; - int newTimeout = 1001; - int newBatch = 2001; - - YamlConfigFile configFile = prepareYamlConfigFile("application.yaml", - readYamlContentAsConfigFileProperties("case3.yaml")); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig12.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(DEFAULT_BATCH, bean.getBatch()); - - configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case3-new.yaml")); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(newBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithIrrelevantProperties() throws Exception { - int initialTimeout = 1000; - - String someIrrelevantKey = "someIrrelevantKey"; - String someIrrelevantValue = "someIrrelevantValue"; - - String anotherIrrelevantKey = "anotherIrrelevantKey"; - String anotherIrrelevantValue = "anotherIrrelevantValue"; - - Properties applicationProperties = - assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), someIrrelevantKey, someIrrelevantValue); - - SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(DEFAULT_BATCH, bean.getBatch()); - - Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), - anotherIrrelevantKey, anotherIrrelevantValue); - - applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(DEFAULT_BATCH, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithDeletedProperties() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY, - String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = new Properties(); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(DEFAULT_TIMEOUT, bean.getTimeout()); - assertEquals(DEFAULT_BATCH, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithDeletedPropertiesWithYamlFile() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - - YamlConfigFile configFile = prepareYamlConfigFile("application.yaml", - readYamlContentAsConfigFileProperties("case4.yaml")); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig12.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case4-new.yaml")); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(DEFAULT_TIMEOUT, bean.getTimeout()); - assertEquals(DEFAULT_BATCH, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithMultipleNamespacesWithSamePropertiesDeleted() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - int anotherBatch = 3000; - - Properties applicationProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(someBatch)); - Properties fxApolloProperties = - assembleProperties(TIMEOUT_PROPERTY, String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch)); - - SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties); - prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig2.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(someTimeout, bean.getTimeout()); - assertEquals(someBatch, bean.getBatch()); - - Properties newProperties = new Properties(); - - applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(someTimeout, bean.getTimeout()); - assertEquals(anotherBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithDeletedPropertiesWithNoDefaultValue() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY, - String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig6.class); - - TestJavaConfigBean5 bean = context.getBean(TestJavaConfigBean5.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(300); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithTypeMismatch() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - String newBatch = "newBatch"; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY, - String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig1.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = - assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, newBatch); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(300); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithTypeMismatchWithYamlFile() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - - YamlConfigFile configFile = prepareYamlConfigFile("application.yaml", - readYamlContentAsConfigFileProperties("case5.yaml")); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig12.class); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - configFile.onRepositoryChange("application.yaml", readYamlContentAsConfigFileProperties("case5-new.yaml")); - - TimeUnit.MILLISECONDS.sleep(300); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithValueInjectedAsParameter() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY, - String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig3.class); - - TestJavaConfigBean2 bean = context.getBean(TestJavaConfigBean2.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = - assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - // Does not support this scenario - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - } - - @Test - public void testApplicationPropertySourceWithValueInjectedInConfiguration() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY, - String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig7.class); - - TestJavaConfigBean2 bean = context.getBean(TestJavaConfigBean2.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = - assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - // Does not support this scenario - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithValueInjectedAsConstructorArgs() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY, - String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig4.class); - - TestJavaConfigBean3 bean = context.getBean(TestJavaConfigBean3.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = - assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - // Does not support this scenario - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithInvalidSetter() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), BATCH_PROPERTY, - String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig5.class); - - TestJavaConfigBean4 bean = context.getBean(TestJavaConfigBean4.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = - assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - // Does not support this scenario - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithNestedProperty() throws Exception { - String someKeyValue = "someKeyValue"; - String anotherKeyValue = "anotherKeyValue"; - String newKeyValue = "newKeyValue"; - int someValue = 1234; - int someNewValue = 2345; - - Properties properties = assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY, anotherKeyValue, - String.format("%s.%s", someKeyValue, anotherKeyValue), String.valueOf(someValue)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig1.class); - - TestNestedPropertyBean bean = context.getBean(TestNestedPropertyBean.class); - - assertEquals(someValue, bean.getNestedProperty()); - - Properties newProperties = assembleProperties(SOME_KEY_PROPERTY, newKeyValue, ANOTHER_KEY_PROPERTY, anotherKeyValue, - String.format("%s.%s", newKeyValue, anotherKeyValue), String.valueOf(someNewValue)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(someNewValue, bean.getNestedProperty()); - } - - @Test - public void testAutoUpdateWithNotSupportedNestedProperty() throws Exception { - String someKeyValue = "someKeyValue"; - String anotherKeyValue = "anotherKeyValue"; - int someValue = 1234; - int someNewValue = 2345; - - Properties properties = assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY, anotherKeyValue, - String.format("%s.%s", someKeyValue, anotherKeyValue), String.valueOf(someValue)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig1.class); - - TestNestedPropertyBean bean = context.getBean(TestNestedPropertyBean.class); - - assertEquals(someValue, bean.getNestedProperty()); - - Properties newProperties = assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY, - anotherKeyValue, String.format("%s.%s", someKeyValue, anotherKeyValue), String.valueOf(someNewValue)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - // Does not support this scenario - assertEquals(someValue, bean.getNestedProperty()); - } - - @Test - public void testAutoUpdateWithNestedPropertyWithDefaultValue() throws Exception { - String someKeyValue = "someKeyValue"; - String someNewKeyValue = "someNewKeyValue"; - int someValue = 1234; - int someNewValue = 2345; - - Properties properties = - assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY, String.valueOf(someValue)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig2.class); - - TestNestedPropertyBeanWithDefaultValue bean = context.getBean(TestNestedPropertyBeanWithDefaultValue.class); - - assertEquals(someValue, bean.getNestedProperty()); - - Properties newProperties = assembleProperties(SOME_KEY_PROPERTY, someNewKeyValue, ANOTHER_KEY_PROPERTY, - String.valueOf(someValue), someNewKeyValue, String.valueOf(someNewValue)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(someNewValue, bean.getNestedProperty()); - } - - @Test - public void testAutoUpdateWithMultipleNestedProperty() throws Exception { - String someKeyValue = "someKeyValue"; - String someNewKeyValue = "someNewKeyValue"; - String anotherKeyValue = "anotherKeyValue"; - String someNestedKey = "someNestedKey"; - String someNestedPlaceholder = String.format("${%s}", someNestedKey); - String anotherNestedKey = "anotherNestedKey"; - String anotherNestedPlaceholder = String.format("${%s}", anotherNestedKey); - int someValue = 1234; - int someNewValue = 2345; - - Properties properties = assembleProperties(SOME_KEY_PROPERTY, someKeyValue, ANOTHER_KEY_PROPERTY, anotherKeyValue, - someKeyValue, someNestedPlaceholder); - - properties.setProperty(someNestedKey, String.valueOf(someValue)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig2.class); - - TestNestedPropertyBeanWithDefaultValue bean = context.getBean(TestNestedPropertyBeanWithDefaultValue.class); - - assertEquals(someValue, bean.getNestedProperty()); - - Properties newProperties = assembleProperties(SOME_KEY_PROPERTY, someNewKeyValue, ANOTHER_KEY_PROPERTY, - anotherKeyValue, someNewKeyValue, anotherNestedPlaceholder); - - newProperties.setProperty(anotherNestedKey, String.valueOf(someNewValue)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(someNewValue, bean.getNestedProperty()); - } - - @Test - public void testAutoUpdateWithAllKindsOfDataTypes() throws Exception { - int someInt = 1000; - int someNewInt = 1001; - int[] someIntArray = {1, 2, 3, 4}; - int[] someNewIntArray = {5, 6, 7, 8}; - long someLong = 2000L; - long someNewLong = 2001L; - short someShort = 3000; - short someNewShort = 3001; - float someFloat = 1.2F; - float someNewFloat = 2.2F; - double someDouble = 3.10D; - double someNewDouble = 4.10D; - byte someByte = 123; - byte someNewByte = 124; - boolean someBoolean = true; - boolean someNewBoolean = !someBoolean; - String someString = "someString"; - String someNewString = "someNewString"; - String someJsonProperty = "[{\"a\":\"astring\", \"b\":10},{\"a\":\"astring2\", \"b\":20}]"; - String someNewJsonProperty = "[{\"a\":\"newString\", \"b\":20},{\"a\":\"astring2\", \"b\":20}]"; - - String someDateFormat = "yyyy-MM-dd HH:mm:ss.SSS"; - Date someDate = assembleDate(2018, 2, 23, 20, 1, 2, 123); - Date someNewDate = assembleDate(2018, 2, 23, 21, 2, 3, 345); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(someDateFormat, Locale.US); - - Properties properties = new Properties(); - properties.setProperty("intProperty", String.valueOf(someInt)); - properties.setProperty("intArrayProperty", Ints.join(", ", someIntArray)); - properties.setProperty("longProperty", String.valueOf(someLong)); - properties.setProperty("shortProperty", String.valueOf(someShort)); - properties.setProperty("floatProperty", String.valueOf(someFloat)); - properties.setProperty("doubleProperty", String.valueOf(someDouble)); - properties.setProperty("byteProperty", String.valueOf(someByte)); - properties.setProperty("booleanProperty", String.valueOf(someBoolean)); - properties.setProperty("stringProperty", someString); - properties.setProperty("dateFormat", someDateFormat); - properties.setProperty("dateProperty", simpleDateFormat.format(someDate)); - properties.setProperty("jsonProperty", someJsonProperty); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig9.class); - - TestAllKindsOfDataTypesBean bean = context.getBean(TestAllKindsOfDataTypesBean.class); - - assertEquals(someInt, bean.getIntProperty()); - assertArrayEquals(someIntArray, bean.getIntArrayProperty()); - assertEquals(someLong, bean.getLongProperty()); - assertEquals(someShort, bean.getShortProperty()); - assertEquals(someFloat, bean.getFloatProperty(), 0.001F); - assertEquals(someDouble, bean.getDoubleProperty(), 0.001D); - assertEquals(someByte, bean.getByteProperty()); - assertEquals(someBoolean, bean.getBooleanProperty()); - assertEquals(someString, bean.getStringProperty()); - assertEquals(someDate, bean.getDateProperty()); - assertEquals("astring", bean.getJsonBeanList().get(0).getA()); - assertEquals(10, bean.getJsonBeanList().get(0).getB()); - - Properties newProperties = new Properties(); - newProperties.setProperty("intProperty", String.valueOf(someNewInt)); - newProperties.setProperty("intArrayProperty", Ints.join(", ", someNewIntArray)); - newProperties.setProperty("longProperty", String.valueOf(someNewLong)); - newProperties.setProperty("shortProperty", String.valueOf(someNewShort)); - newProperties.setProperty("floatProperty", String.valueOf(someNewFloat)); - newProperties.setProperty("doubleProperty", String.valueOf(someNewDouble)); - newProperties.setProperty("byteProperty", String.valueOf(someNewByte)); - newProperties.setProperty("booleanProperty", String.valueOf(someNewBoolean)); - newProperties.setProperty("stringProperty", someNewString); - newProperties.setProperty("dateFormat", someDateFormat); - newProperties.setProperty("dateProperty", simpleDateFormat.format(someNewDate)); - newProperties.setProperty("jsonProperty", someNewJsonProperty); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(someNewInt, bean.getIntProperty()); - assertArrayEquals(someNewIntArray, bean.getIntArrayProperty()); - assertEquals(someNewLong, bean.getLongProperty()); - assertEquals(someNewShort, bean.getShortProperty()); - assertEquals(someNewFloat, bean.getFloatProperty(), 0.001F); - assertEquals(someNewDouble, bean.getDoubleProperty(), 0.001D); - assertEquals(someNewByte, bean.getByteProperty()); - assertEquals(someNewBoolean, bean.getBooleanProperty()); - assertEquals(someNewString, bean.getStringProperty()); - assertEquals(someNewDate, bean.getDateProperty()); - assertEquals("newString", bean.getJsonBeanList().get(0).getA()); - assertEquals(20, bean.getJsonBeanList().get(0).getB()); - } - - @Test - public void testAutoUpdateJsonValueWithInvalidValue() throws Exception { - String someValidValue = "{\"a\":\"someString\", \"b\":10}"; - String someInvalidValue = "someInvalidValue"; - - Properties properties = assembleProperties("jsonProperty", someValidValue); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig10.class); - - TestApolloJsonValue bean = context.getBean(TestApolloJsonValue.class); - - JsonBean jsonBean = bean.getJsonBean(); - - assertEquals("someString", jsonBean.getA()); - assertEquals(10, jsonBean.getB()); - - Properties newProperties = assembleProperties("jsonProperty", someInvalidValue); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(300); - - // should not change anything - assertTrue(jsonBean == bean.getJsonBean()); - } - - @Test - public void testAutoUpdateJsonValueWithNoValueAndNoDefaultValue() throws Exception { - String someValidValue = "{\"a\":\"someString\", \"b\":10}"; - - Properties properties = assembleProperties("jsonProperty", someValidValue); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig10.class); - - TestApolloJsonValue bean = context.getBean(TestApolloJsonValue.class); - - JsonBean jsonBean = bean.getJsonBean(); - - assertEquals("someString", jsonBean.getA()); - assertEquals(10, jsonBean.getB()); - - Properties newProperties = new Properties(); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(300); - - // should not change anything - assertTrue(jsonBean == bean.getJsonBean()); - } - - @Test - public void testAutoUpdateJsonValueWithNoValueAndDefaultValue() throws Exception { - String someValidValue = "{\"a\":\"someString\", \"b\":10}"; - - Properties properties = assembleProperties("jsonProperty", someValidValue); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig11.class); - - TestApolloJsonValueWithDefaultValue bean = context.getBean(TestApolloJsonValueWithDefaultValue.class); - - JsonBean jsonBean = bean.getJsonBean(); - - assertEquals("someString", jsonBean.getA()); - assertEquals(10, jsonBean.getB()); - - Properties newProperties = new Properties(); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - JsonBean newJsonBean = bean.getJsonBean(); - - assertEquals("defaultString", newJsonBean.getA()); - assertEquals(1, newJsonBean.getB()); - } - - @Configuration - @EnableApolloConfig - static class AppConfig1 { - @Bean - TestJavaConfigBean testJavaConfigBean() { - return new TestJavaConfigBean(); - } - } - - @Configuration - @EnableApolloConfig({"application", "FX.apollo"}) - static class AppConfig2 { - @Bean - TestJavaConfigBean testJavaConfigBean() { - return new TestJavaConfigBean(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig3 { - /** - * This case won't get auto updated - */ - @Bean - TestJavaConfigBean2 testJavaConfigBean2(@Value("${timeout:100}") int timeout, @Value("${batch:200}") int batch) { - TestJavaConfigBean2 bean = new TestJavaConfigBean2(); - - bean.setTimeout(timeout); - bean.setBatch(batch); - - return bean; - } - } - - @Configuration - @ComponentScan(includeFilters = {@Filter(type = FilterType.ANNOTATION, value = {Component.class})}, - excludeFilters = {@Filter(type = FilterType.ANNOTATION, value = {Configuration.class})}) - @EnableApolloConfig - static class AppConfig4 { - } - - @Configuration - @EnableApolloConfig - static class AppConfig5 { - @Bean - TestJavaConfigBean4 testJavaConfigBean() { - return new TestJavaConfigBean4(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig6 { - @Bean - TestJavaConfigBean5 testJavaConfigBean() { - return new TestJavaConfigBean5(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig7 { - - @Value("${batch}") - private int batch; - - @Bean - @Value("${timeout}") - TestJavaConfigBean2 testJavaConfigBean2(int timeout) { - TestJavaConfigBean2 bean = new TestJavaConfigBean2(); - - bean.setTimeout(timeout); - bean.setBatch(batch); - - return bean; - } - } - - @Configuration - @EnableApolloConfig - @ImportResource("spring/XmlConfigPlaceholderTest1.xml") - static class AppConfig8 { - @Bean - TestJavaConfigBean testJavaConfigBean() { - return new TestJavaConfigBean(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig9 { - @Bean - TestAllKindsOfDataTypesBean testAllKindsOfDataTypesBean() { - return new TestAllKindsOfDataTypesBean(); - } - } - - @Configuration - @EnableApolloConfig - static class NestedPropertyConfig1 { - @Bean - TestNestedPropertyBean testNestedPropertyBean() { - return new TestNestedPropertyBean(); - } - } - - @Configuration - @EnableApolloConfig - static class NestedPropertyConfig2 { - @Bean - TestNestedPropertyBeanWithDefaultValue testNestedPropertyBean() { - return new TestNestedPropertyBeanWithDefaultValue(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig10 { - - @Bean - TestApolloJsonValue testApolloJsonValue() { - return new TestApolloJsonValue(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig11 { - - @Bean - TestApolloJsonValueWithDefaultValue testApolloJsonValue() { - return new TestApolloJsonValueWithDefaultValue(); - } - } - - @Configuration - @EnableApolloConfig("application.yaMl") - static class AppConfig12 { - @Bean - TestJavaConfigBean testJavaConfigBean() { - return new TestJavaConfigBean(); - } - } - - @Configuration - @EnableApolloConfig("application.yaml") - @ImportResource("spring/XmlConfigPlaceholderTest11.xml") - static class AppConfig13 { - @Bean - TestJavaConfigBean testJavaConfigBean() { - return new TestJavaConfigBean(); - } - } - - @Configuration - @EnableApolloConfig({"application.yml", "FX.apollo"}) - static class AppConfig14 { - @Bean - TestJavaConfigBean testJavaConfigBean() { - return new TestJavaConfigBean(); - } - } - - static class TestJavaConfigBean { - - @Value("${timeout:100}") - private int timeout; - private int batch; - - @Value("${batch:200}") - public void setBatch(int batch) { - this.batch = batch; - } - - public int getTimeout() { - return timeout; - } - - public int getBatch() { - return batch; - } - } - - static class TestJavaConfigBean2 { - private int timeout; - private int batch; - - public int getTimeout() { - return timeout; - } - - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - public int getBatch() { - return batch; - } - - public void setBatch(int batch) { - this.batch = batch; - } - } - - /** - * This case won't get auto updated - */ - @Component - static class TestJavaConfigBean3 { - private final int timeout; - private final int batch; - - @Autowired - public TestJavaConfigBean3(@Value("${timeout:100}") int timeout, @Value("${batch:200}") int batch) { - this.timeout = timeout; - this.batch = batch; - } - - public int getTimeout() { - return timeout; - } - - public int getBatch() { - return batch; - } - } - - /** - * This case won't get auto updated - */ - static class TestJavaConfigBean4 { - - private int timeout; - private int batch; - - @Value("${batch:200}") - public void setValues(int batch, @Value("${timeout:100}") int timeout) { - this.batch = batch; - this.timeout = timeout; - } - - public int getTimeout() { - return timeout; - } - - public int getBatch() { - return batch; - } - } - - static class TestJavaConfigBean5 { - - @Value("${timeout}") - private int timeout; - private int batch; - - @Value("${batch}") - public void setBatch(int batch) { - this.batch = batch; - } - - public int getTimeout() { - return timeout; - } - - public int getBatch() { - return batch; - } - } - - static class TestNestedPropertyBean { - - @Value("${${someKey}.${anotherKey}}") - private int nestedProperty; - - public int getNestedProperty() { - return nestedProperty; - } - } - - static class TestNestedPropertyBeanWithDefaultValue { - - @Value("${${someKey}:${anotherKey}}") - private int nestedProperty; - - public int getNestedProperty() { - return nestedProperty; - } - } - - static class TestAllKindsOfDataTypesBean { - - @Value("${intProperty}") - private int intProperty; - - @Value("${intArrayProperty}") - private int[] intArrayProperty; - - @Value("${longProperty}") - private long longProperty; - - @Value("${shortProperty}") - private short shortProperty; - - @Value("${floatProperty}") - private float floatProperty; - - @Value("${doubleProperty}") - private double doubleProperty; - - @Value("${byteProperty}") - private byte byteProperty; - - @Value("${booleanProperty}") - private boolean booleanProperty; - - @Value("${stringProperty}") - private String stringProperty; - - @Value("#{new java.text.SimpleDateFormat('${dateFormat}').parse('${dateProperty}')}") - private Date dateProperty; - - @ApolloJsonValue("${jsonProperty}") - private List jsonBeanList; - - public int getIntProperty() { - return intProperty; - } - - public int[] getIntArrayProperty() { - return intArrayProperty; - } - - public long getLongProperty() { - return longProperty; - } - - public short getShortProperty() { - return shortProperty; - } - - public float getFloatProperty() { - return floatProperty; - } - - public double getDoubleProperty() { - return doubleProperty; - } - - public byte getByteProperty() { - return byteProperty; - } - - public boolean getBooleanProperty() { - return booleanProperty; - } - - public String getStringProperty() { - return stringProperty; - } - - public Date getDateProperty() { - return dateProperty; - } - - public List getJsonBeanList() { - return jsonBeanList; - } - } - - static class TestApolloJsonValue { - - @ApolloJsonValue("${jsonProperty}") - private JsonBean jsonBean; - - public JsonBean getJsonBean() { - return jsonBean; - } - } - - static class TestApolloJsonValueWithDefaultValue { - - @ApolloJsonValue("${jsonProperty:{\"a\":\"defaultString\", \"b\":1}}") - private JsonBean jsonBean; - - public JsonBean getJsonBean() { - return jsonBean; - } - } - -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/JavaConfigPlaceholderTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/JavaConfigPlaceholderTest.java deleted file mode 100644 index ef165ddae5e..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/JavaConfigPlaceholderTest.java +++ /dev/null @@ -1,675 +0,0 @@ -/* - * Copyright 2022 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; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.PropertiesCompatibleConfigFile; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue; -import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; -import java.util.List; -import java.util.Properties; -import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ComponentScan; -import org.springframework.context.annotation.ComponentScan.Filter; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.FilterType; -import org.springframework.stereotype.Component; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class JavaConfigPlaceholderTest extends AbstractSpringIntegrationTest { - private static final String TIMEOUT_PROPERTY = "timeout"; - private static final int DEFAULT_TIMEOUT = 100; - private static final String BATCH_PROPERTY = "batch"; - private static final int DEFAULT_BATCH = 200; - private static final String FX_APOLLO_NAMESPACE = "FX.apollo"; - private static final String JSON_PROPERTY = "jsonProperty"; - private static final String OTHER_JSON_PROPERTY = "otherJsonProperty"; - - @Test - public void testPropertySourceWithNoNamespace() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - - Config config = mock(Config.class); - when(config.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someTimeout)); - when(config.getProperty(eq(BATCH_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someBatch)); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - check(someTimeout, someBatch, AppConfig1.class); - } - - @Test - public void testPropertySourceWithNoConfig() throws Exception { - Config config = mock(Config.class); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - check(DEFAULT_TIMEOUT, DEFAULT_BATCH, AppConfig1.class); - } - - @Test - public void testApplicationPropertySource() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - - Config config = mock(Config.class); - when(config.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someTimeout)); - when(config.getProperty(eq(BATCH_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someBatch)); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - check(someTimeout, someBatch, AppConfig2.class); - } - - @Test - public void testPropertiesCompatiblePropertySource() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - Properties properties = mock(Properties.class); - - when(properties.getProperty(TIMEOUT_PROPERTY)).thenReturn(String.valueOf(someTimeout)); - when(properties.getProperty(BATCH_PROPERTY)).thenReturn(String.valueOf(someBatch)); - PropertiesCompatibleConfigFile configFile = mock(PropertiesCompatibleConfigFile.class); - when(configFile.asProperties()).thenReturn(properties); - - mockConfigFile("application.yaml", configFile); - - check(someTimeout, someBatch, AppConfig9.class); - } - - @Test - public void testPropertiesCompatiblePropertySourceWithNonNormalizedCase() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - Properties properties = mock(Properties.class); - - when(properties.getProperty(TIMEOUT_PROPERTY)).thenReturn(String.valueOf(someTimeout)); - when(properties.getProperty(BATCH_PROPERTY)).thenReturn(String.valueOf(someBatch)); - PropertiesCompatibleConfigFile configFile = mock(PropertiesCompatibleConfigFile.class); - when(configFile.asProperties()).thenReturn(properties); - - mockConfigFile("application.yaml", configFile); - - check(someTimeout, someBatch, AppConfig10.class); - } - - @Test - public void testMultiplePropertySources() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - - Config application = mock(Config.class); - when(application.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someTimeout)); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, application); - - Config fxApollo = mock(Config.class); - when(application.getProperty(eq(BATCH_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someBatch)); - mockConfig(FX_APOLLO_NAMESPACE, fxApollo); - - check(someTimeout, someBatch, AppConfig3.class); - } - - @Test - public void testMultiplePropertiesCompatiblePropertySourcesWithSameProperties() throws Exception { - int someTimeout = 1000; - int anotherTimeout = someTimeout + 1; - int someBatch = 2000; - - Properties properties = mock(Properties.class); - - when(properties.getProperty(TIMEOUT_PROPERTY)).thenReturn(String.valueOf(someTimeout)); - when(properties.getProperty(BATCH_PROPERTY)).thenReturn(String.valueOf(someBatch)); - PropertiesCompatibleConfigFile configFile = mock(PropertiesCompatibleConfigFile.class); - when(configFile.asProperties()).thenReturn(properties); - - mockConfigFile("application.yml", configFile); - - Config fxApollo = mock(Config.class); - when(fxApollo.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(anotherTimeout)); - mockConfig(FX_APOLLO_NAMESPACE, fxApollo); - - check(someTimeout, someBatch, AppConfig11.class); - } - - @Test - public void testMultiplePropertySourcesCoverWithSameProperties() throws Exception { - //Multimap does not maintain the strict input order of namespace. - int someTimeout = 1000; - int anotherTimeout = someTimeout + 1; - int someBatch = 2000; - - Config fxApollo = mock(Config.class); - when(fxApollo.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someTimeout)); - when(fxApollo.getProperty(eq(BATCH_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someBatch)); - mockConfig(FX_APOLLO_NAMESPACE, fxApollo); - - Config application = mock(Config.class); - when(application.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(anotherTimeout)); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, application); - - check(someTimeout, someBatch, AppConfig6.class); - } - - @Test - public void testMultiplePropertySourcesCoverWithSamePropertiesWithPropertiesCompatiblePropertySource() throws Exception { - //Multimap does not maintain the strict input order of namespace. - int someTimeout = 1000; - int anotherTimeout = someTimeout + 1; - int someBatch = 2000; - - Config fxApollo = mock(Config.class); - when(fxApollo.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someTimeout)); - when(fxApollo.getProperty(eq(BATCH_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someBatch)); - mockConfig(FX_APOLLO_NAMESPACE, fxApollo); - - Config application = mock(Config.class); - when(application.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(anotherTimeout)); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, application); - - check(someTimeout, someBatch, AppConfig6.class); - } - - @Test - public void testMultiplePropertySourcesWithSamePropertiesWithWeight() throws Exception { - int someTimeout = 1000; - int anotherTimeout = someTimeout + 1; - int someBatch = 2000; - - Config application = mock(Config.class); - when(application.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someTimeout)); - when(application.getProperty(eq(BATCH_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someBatch)); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, application); - - Config fxApollo = mock(Config.class); - when(fxApollo.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(anotherTimeout)); - mockConfig(FX_APOLLO_NAMESPACE, fxApollo); - - check(anotherTimeout, someBatch, AppConfig2.class, AppConfig4.class); - } - - @Test - public void testApplicationPropertySourceWithValueInjectedAsParameter() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - - Config config = mock(Config.class); - when(config.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someTimeout)); - when(config.getProperty(eq(BATCH_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someBatch)); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig5.class); - - TestJavaConfigBean2 bean = context.getBean(TestJavaConfigBean2.class); - - assertEquals(someTimeout, bean.getTimeout()); - assertEquals(someBatch, bean.getBatch()); - } - - @Test - public void testApplicationPropertySourceWithValueInjectedAsConstructorArgs() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - - Config config = mock(Config.class); - when(config.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someTimeout)); - when(config.getProperty(eq(BATCH_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someBatch)); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig7.class); - - TestJavaConfigBean3 bean = context.getBean(TestJavaConfigBean3.class); - - assertEquals(someTimeout, bean.getTimeout()); - assertEquals(someBatch, bean.getBatch()); - } - - @Test - public void testNestedProperty() throws Exception { - String a = "a"; - String b = "b"; - int someValue = 1234; - - Config config = mock(Config.class); - when(config.getProperty(eq(a), Mockito.nullable(String.class))).thenReturn(a); - when(config.getProperty(eq(b), Mockito.nullable(String.class))).thenReturn(b); - when(config.getProperty(eq(String.format("%s.%s", a, b)), Mockito.nullable(String.class))) - .thenReturn(String.valueOf(someValue)); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig1.class); - - TestNestedPropertyBean bean = context.getBean(TestNestedPropertyBean.class); - - assertEquals(someValue, bean.getNestedProperty()); - } - - @Test - public void testNestedPropertyWithDefaultValue() throws Exception { - String a = "a"; - String b = "b"; - String c = "c"; - int someValue = 1234; - - Config config = mock(Config.class); - when(config.getProperty(eq(a), Mockito.nullable(String.class))).thenReturn(a); - when(config.getProperty(eq(b), Mockito.nullable(String.class))).thenReturn(b); - when(config.getProperty(eq(c), Mockito.nullable(String.class))).thenReturn(String.valueOf(someValue)); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig1.class); - - TestNestedPropertyBean bean = context.getBean(TestNestedPropertyBean.class); - - assertEquals(someValue, bean.getNestedProperty()); - } - - @Test - public void testNestedPropertyWithNestedDefaultValue() throws Exception { - String a = "a"; - String b = "b"; - - Config config = mock(Config.class); - when(config.getProperty(eq(a), Mockito.nullable(String.class))).thenReturn(a); - when(config.getProperty(eq(b), Mockito.nullable(String.class))).thenReturn(b); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig1.class); - - TestNestedPropertyBean bean = context.getBean(TestNestedPropertyBean.class); - - assertEquals(100, bean.getNestedProperty()); - } - - @Test - public void testMultipleNestedProperty() throws Exception { - String a = "a"; - String b = "b"; - String nestedKey = "c.d"; - String nestedProperty = String.format("${%s}", nestedKey); - int someValue = 1234; - - Config config = mock(Config.class); - when(config.getProperty(eq(a), Mockito.nullable(String.class))).thenReturn(a); - when(config.getProperty(eq(b), Mockito.nullable(String.class))).thenReturn(b); - when(config.getProperty(eq(String.format("%s.%s", a, b)), Mockito.nullable(String.class))).thenReturn(nestedProperty); - when(config.getProperty(eq(nestedKey), Mockito.nullable(String.class))).thenReturn(String.valueOf(someValue)); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig1.class); - - TestNestedPropertyBean bean = context.getBean(TestNestedPropertyBean.class); - - assertEquals(someValue, bean.getNestedProperty()); - } - - @Test - public void testMultipleNestedPropertyWithDefaultValue() throws Exception { - String a = "a"; - String b = "b"; - String nestedKey = "c.d"; - int someValue = 1234; - String nestedProperty = String.format("${%s:%d}", nestedKey, someValue); - - Config config = mock(Config.class); - when(config.getProperty(eq(a), Mockito.nullable(String.class))).thenReturn(a); - when(config.getProperty(eq(b), Mockito.nullable(String.class))).thenReturn(b); - when(config.getProperty(eq(String.format("%s.%s", a, b)), Mockito.nullable(String.class))).thenReturn(nestedProperty); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(NestedPropertyConfig1.class); - - TestNestedPropertyBean bean = context.getBean(TestNestedPropertyBean.class); - - assertEquals(someValue, bean.getNestedProperty()); - } - - @Test - public void testApolloJsonValue() { - String someJson = "[{\"a\":\"astring\", \"b\":10},{\"a\":\"astring2\", \"b\":20}]"; - String otherJson = "[{\"a\":\"otherString\", \"b\":10},{\"a\":\"astring2\", \"b\":20}]"; - - Config config = mock(Config.class); - when(config.getProperty(eq(JSON_PROPERTY), Mockito.nullable(String.class))).thenReturn(someJson); - when(config.getProperty(eq(OTHER_JSON_PROPERTY), Mockito.nullable(String.class))).thenReturn(otherJson); - when(config.getProperty(eq("a"), Mockito.nullable(String.class))).thenReturn(JSON_PROPERTY); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( - AppConfig8.class); - - TestJsonPropertyBean testJsonPropertyBean = context.getBean(TestJsonPropertyBean.class); - assertEquals(2, testJsonPropertyBean.getJsonBeanList().size()); - assertEquals("astring", testJsonPropertyBean.getJsonBeanList().get(0).getA()); - assertEquals(10, testJsonPropertyBean.getJsonBeanList().get(0).getB()); - assertEquals("astring2", testJsonPropertyBean.getJsonBeanList().get(1).getA()); - assertEquals(20, testJsonPropertyBean.getJsonBeanList().get(1).getB()); - assertEquals(testJsonPropertyBean.getJsonBeanList(), testJsonPropertyBean.getEmbeddedJsonBeanList()); - assertEquals("otherString", testJsonPropertyBean.getOtherJsonBeanList().get(0).getA()); - assertEquals(10, testJsonPropertyBean.getOtherJsonBeanList().get(0).getB()); - assertEquals("astring2", testJsonPropertyBean.getOtherJsonBeanList().get(1).getA()); - assertEquals(20, testJsonPropertyBean.getOtherJsonBeanList().get(1).getB()); - } - - @Test(expected = BeanCreationException.class) - public void testApolloJsonValueWithInvalidJson() throws Exception { - String someInvalidJson = "someInvalidJson"; - - Config config = mock(Config.class); - when(config.getProperty(eq(JSON_PROPERTY), Mockito.nullable(String.class))).thenReturn(someInvalidJson); - when(config.getProperty(eq(OTHER_JSON_PROPERTY), Mockito.nullable(String.class))).thenReturn(someInvalidJson); - when(config.getProperty(eq("a"), Mockito.nullable(String.class))).thenReturn(JSON_PROPERTY); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - new AnnotationConfigApplicationContext(AppConfig8.class).getBean(TestJsonPropertyBean.class); - } - - @Test(expected = BeanCreationException.class) - public void testApolloJsonValueWithNoPropertyValue() throws Exception { - Config config = mock(Config.class); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - new AnnotationConfigApplicationContext(AppConfig8.class); - } - - private void check(int expectedTimeout, int expectedBatch, Class... annotatedClasses) { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(annotatedClasses); - - TestJavaConfigBean bean = context.getBean(TestJavaConfigBean.class); - - assertEquals(expectedTimeout, bean.getTimeout()); - assertEquals(expectedBatch, bean.getBatch()); - } - - @Configuration - @EnableApolloConfig - static class AppConfig1 { - @Bean - TestJavaConfigBean testJavaConfigBean() { - return new TestJavaConfigBean(); - } - } - - @Configuration - @EnableApolloConfig("application") - static class AppConfig2 { - @Bean - TestJavaConfigBean testJavaConfigBean() { - return new TestJavaConfigBean(); - } - } - - @Configuration - @EnableApolloConfig({"application", "FX.apollo"}) - static class AppConfig3 { - @Bean - TestJavaConfigBean testJavaConfigBean() { - return new TestJavaConfigBean(); - } - } - - @Configuration - @EnableApolloConfig(value = "FX.apollo", order = 10) - static class AppConfig4 { - } - - @Configuration - @EnableApolloConfig - static class AppConfig5 { - @Bean - TestJavaConfigBean2 testJavaConfigBean2(@Value("${timeout:100}") int timeout, @Value("${batch:200}") int batch) { - TestJavaConfigBean2 bean = new TestJavaConfigBean2(); - - bean.setTimeout(timeout); - bean.setBatch(batch); - - return bean; - } - } - - @Configuration - @EnableApolloConfig({"FX.apollo", "application"}) - static class AppConfig6 { - @Bean - TestJavaConfigBean testJavaConfigBean() { - return new TestJavaConfigBean(); - } - } - - @Configuration - @ComponentScan( - includeFilters = {@Filter(type = FilterType.ANNOTATION, value = {Component.class})}, - excludeFilters = {@Filter(type = FilterType.ANNOTATION, value = {Configuration.class})}) - @EnableApolloConfig - static class AppConfig7 { - } - - @Configuration - @EnableApolloConfig - static class NestedPropertyConfig1 { - @Bean - TestNestedPropertyBean testNestedPropertyBean() { - return new TestNestedPropertyBean(); - } - } - - @Configuration - @EnableApolloConfig - static class AppConfig8 { - - @Bean - TestJsonPropertyBean testJavaConfigBean() { - return new TestJsonPropertyBean(); - } - } - - @Configuration - @EnableApolloConfig("application.yaml") - static class AppConfig9 { - @Bean - TestJavaConfigBean testJavaConfigBean() { - return new TestJavaConfigBean(); - } - } - - @Configuration - @EnableApolloConfig("application.yaMl") - static class AppConfig10 { - @Bean - TestJavaConfigBean testJavaConfigBean() { - return new TestJavaConfigBean(); - } - } - - @Configuration - @EnableApolloConfig({"application.yml", "FX.apollo"}) - static class AppConfig11 { - @Bean - TestJavaConfigBean testJavaConfigBean() { - return new TestJavaConfigBean(); - } - } - - @Component - static class TestJavaConfigBean { - @Value("${timeout:100}") - private int timeout; - private int batch; - - @Value("${batch:200}") - public void setBatch(int batch) { - this.batch = batch; - } - - public int getTimeout() { - return timeout; - } - - public int getBatch() { - return batch; - } - } - - static class TestJavaConfigBean2 { - private int timeout; - private int batch; - - public int getTimeout() { - return timeout; - } - - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - public int getBatch() { - return batch; - } - - public void setBatch(int batch) { - this.batch = batch; - } - } - - @Component - static class TestJavaConfigBean3 { - private final int timeout; - private final int batch; - - @Autowired - public TestJavaConfigBean3(@Value("${timeout:100}") int timeout, - @Value("${batch:200}") int batch) { - this.timeout = timeout; - this.batch = batch; - } - - public int getTimeout() { - return timeout; - } - - public int getBatch() { - return batch; - } - } - - static class TestNestedPropertyBean { - - @Value("${${a}.${b}:${c:100}}") - private int nestedProperty; - - public int getNestedProperty() { - return nestedProperty; - } - } - - - static class TestJsonPropertyBean { - - @ApolloJsonValue("${jsonProperty}") - private List jsonBeanList; - - private List otherJsonBeanList; - - @ApolloJsonValue("${${a}}") - private List embeddedJsonBeanList; - - - public List getJsonBeanList() { - return jsonBeanList; - } - - @ApolloJsonValue("${otherJsonProperty}") - public void setOtherJsonBeanList(List otherJsonBeanList) { - this.otherJsonBeanList = otherJsonBeanList; - } - - public List getOtherJsonBeanList() { - return otherJsonBeanList; - } - - public List getEmbeddedJsonBeanList() { - return embeddedJsonBeanList; - } - } - - - static class JsonBean { - - private String a; - private int b; - - String getA() { - return a; - } - - public void setA(String a) { - this.a = a; - } - - int getB() { - return b; - } - - public void setB(int b) { - this.b = b; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - JsonBean jsonBean = (JsonBean) o; - - if (b != jsonBean.b) { - return false; - } - return a != null ? a.equals(jsonBean.a) : jsonBean.a == null; - } - - @Override - public int hashCode() { - int result = a != null ? a.hashCode() : 0; - result = 31 * result + b; - return result; - } - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/XMLConfigAnnotationTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/XMLConfigAnnotationTest.java deleted file mode 100644 index 09fd566a28a..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/XMLConfigAnnotationTest.java +++ /dev/null @@ -1,274 +0,0 @@ -/* - * Copyright 2022 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; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - -import com.google.common.collect.Sets; -import java.util.Collections; -import java.util.List; - -import java.util.Set; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.springframework.beans.factory.BeanCreationException; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import com.ctrip.framework.apollo.spring.annotation.ApolloConfig; -import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener; -import com.google.common.collect.Lists; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class XMLConfigAnnotationTest extends AbstractSpringIntegrationTest { - private static final String FX_APOLLO_NAMESPACE = "FX.apollo"; - - @Test - public void testApolloConfig() throws Exception { - Config applicationConfig = mock(Config.class); - Config fxApolloConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); - - TestApolloConfigBean1 bean = getBean("spring/XmlConfigAnnotationTest1.xml", TestApolloConfigBean1.class); - - assertEquals(applicationConfig, bean.getConfig()); - assertEquals(applicationConfig, bean.getAnotherConfig()); - assertEquals(fxApolloConfig, bean.getYetAnotherConfig()); - } - - @Test(expected = BeanCreationException.class) - public void testApolloConfigWithWrongFieldType() throws Exception { - Config applicationConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - - getBean("spring/XmlConfigAnnotationTest2.xml", TestApolloConfigBean2.class); - } - - @Test - public void testApolloConfigChangeListener() throws Exception { - Config applicationConfig = mock(Config.class); - Config fxApolloConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); - - final List applicationListeners = Lists.newArrayList(); - final List fxApolloListeners = Lists.newArrayList(); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - applicationListeners.add(invocation.getArgument(0, ConfigChangeListener.class)); - - return Void.class; - } - }).when(applicationConfig).addChangeListener(any(ConfigChangeListener.class)); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - fxApolloListeners.add(invocation.getArgument(0, ConfigChangeListener.class)); - - return Void.class; - } - }).when(fxApolloConfig).addChangeListener(any(ConfigChangeListener.class)); - - ConfigChangeEvent someEvent = mock(ConfigChangeEvent.class); - ConfigChangeEvent anotherEvent = mock(ConfigChangeEvent.class); - - TestApolloConfigChangeListenerBean1 bean = getBean("spring/XmlConfigAnnotationTest3.xml", - TestApolloConfigChangeListenerBean1.class); - - //PropertySourcesProcessor add listeners to listen config changed of all namespace - assertEquals(4, applicationListeners.size()); - assertEquals(1, fxApolloListeners.size()); - - for (ConfigChangeListener listener : applicationListeners) { - listener.onChange(someEvent); - } - - assertEquals(someEvent, bean.getChangeEvent1()); - assertEquals(someEvent, bean.getChangeEvent2()); - assertEquals(someEvent, bean.getChangeEvent3()); - - for (ConfigChangeListener listener : fxApolloListeners) { - listener.onChange(anotherEvent); - } - - assertEquals(someEvent, bean.getChangeEvent1()); - assertEquals(someEvent, bean.getChangeEvent2()); - assertEquals(anotherEvent, bean.getChangeEvent3()); - } - - @Test(expected = BeanCreationException.class) - public void testApolloConfigChangeListenerWithWrongParamType() throws Exception { - Config applicationConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - - getBean("spring/XmlConfigAnnotationTest4.xml", TestApolloConfigChangeListenerBean2.class); - } - - @Test(expected = BeanCreationException.class) - public void testApolloConfigChangeListenerWithWrongParamCount() throws Exception { - Config applicationConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - - getBean("spring/XmlConfigAnnotationTest5.xml", TestApolloConfigChangeListenerBean3.class); - } - - @Test - public void testApolloConfigChangeListenerWithInterestedKeys() throws Exception { - Config applicationConfig = mock(Config.class); - Config fxApolloConfig = mock(Config.class); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationConfig); - mockConfig(FX_APOLLO_NAMESPACE, fxApolloConfig); - - TestApolloConfigChangeListenerWithInterestedKeysBean bean = getBean( - "spring/XmlConfigAnnotationTest6.xml", TestApolloConfigChangeListenerWithInterestedKeysBean.class); - - final ArgumentCaptor applicationConfigInterestedKeys = ArgumentCaptor.forClass(Set.class); - final ArgumentCaptor fxApolloConfigInterestedKeys = ArgumentCaptor.forClass(Set.class); - - verify(applicationConfig, times(2)) - .addChangeListener(any(ConfigChangeListener.class), applicationConfigInterestedKeys.capture(), Mockito.nullable(Set.class)); - - verify(fxApolloConfig, times(1)) - .addChangeListener(any(ConfigChangeListener.class), fxApolloConfigInterestedKeys.capture(), Mockito.nullable(Set.class)); - - assertEquals(2, applicationConfigInterestedKeys.getAllValues().size()); - - Set result = Sets.newHashSet(); - for (Set interestedKeys : applicationConfigInterestedKeys.getAllValues()) { - result.addAll(interestedKeys); - } - assertEquals(Sets.newHashSet("someKey", "anotherKey"), result); - - assertEquals(1, fxApolloConfigInterestedKeys.getAllValues().size()); - - assertEquals(Collections.singletonList(Sets.newHashSet("anotherKey")), fxApolloConfigInterestedKeys.getAllValues()); - } - - private T getBean(String xmlLocation, Class beanClass) { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(xmlLocation); - - return context.getBean(beanClass); - } - - public static class TestApolloConfigBean1 { - @ApolloConfig - private Config config; - @ApolloConfig(ConfigConsts.NAMESPACE_APPLICATION) - private Config anotherConfig; - @ApolloConfig(FX_APOLLO_NAMESPACE) - private Config yetAnotherConfig; - - public Config getConfig() { - return config; - } - - public Config getAnotherConfig() { - return anotherConfig; - } - - public Config getYetAnotherConfig() { - return yetAnotherConfig; - } - } - - public static class TestApolloConfigBean2 { - @ApolloConfig - private String config; - } - - public static class TestApolloConfigChangeListenerBean1 { - private ConfigChangeEvent changeEvent1; - private ConfigChangeEvent changeEvent2; - private ConfigChangeEvent changeEvent3; - - @ApolloConfigChangeListener - private void onChange1(ConfigChangeEvent changeEvent) { - this.changeEvent1 = changeEvent; - } - - @ApolloConfigChangeListener(ConfigConsts.NAMESPACE_APPLICATION) - private void onChange2(ConfigChangeEvent changeEvent) { - this.changeEvent2 = changeEvent; - } - - @ApolloConfigChangeListener({ConfigConsts.NAMESPACE_APPLICATION, FX_APOLLO_NAMESPACE}) - private void onChange3(ConfigChangeEvent changeEvent) { - this.changeEvent3 = changeEvent; - } - - public ConfigChangeEvent getChangeEvent1() { - return changeEvent1; - } - - public ConfigChangeEvent getChangeEvent2() { - return changeEvent2; - } - - public ConfigChangeEvent getChangeEvent3() { - return changeEvent3; - } - } - - public static class TestApolloConfigChangeListenerBean2 { - @ApolloConfigChangeListener - private void onChange(String event) { - - } - } - - public static class TestApolloConfigChangeListenerBean3 { - @ApolloConfigChangeListener - private void onChange(ConfigChangeEvent event, String someParam) { - - } - } - - static class TestApolloConfigChangeListenerWithInterestedKeysBean { - - @ApolloConfigChangeListener(interestedKeys = {"someKey"}) - private void someOnChange(ConfigChangeEvent changeEvent) {} - - @ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, FX_APOLLO_NAMESPACE}, - interestedKeys = {"anotherKey"}) - private void anotherOnChange(ConfigChangeEvent changeEvent) { - - } - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/XmlConfigPlaceholderAutoUpdateTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/XmlConfigPlaceholderAutoUpdateTest.java deleted file mode 100644 index 109e334f005..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/XmlConfigPlaceholderAutoUpdateTest.java +++ /dev/null @@ -1,653 +0,0 @@ -/* - * Copyright 2022 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; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.internals.SimpleConfig; -import com.ctrip.framework.apollo.spring.XmlConfigPlaceholderTest.TestXmlBean; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.primitives.Ints; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; -import java.util.Properties; -import java.util.concurrent.TimeUnit; -import org.junit.Test; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class XmlConfigPlaceholderAutoUpdateTest extends AbstractSpringIntegrationTest { - private static final String TIMEOUT_PROPERTY = "timeout"; - private static final int DEFAULT_TIMEOUT = 100; - private static final String BATCH_PROPERTY = "batch"; - private static final int DEFAULT_BATCH = 200; - private static final String FX_APOLLO_NAMESPACE = "FX.apollo"; - - @Test - public void testAutoUpdateWithOneNamespace() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), - BATCH_PROPERTY, String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml"); - - TestXmlBean bean = context.getBean(TestXmlBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), - BATCH_PROPERTY, String.valueOf(newBatch)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(newBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateDisabled() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - MockConfigUtil mockConfigUtil = new MockConfigUtil(); - mockConfigUtil.setAutoUpdateInjectedSpringProperties(false); - - MockInjector.setInstance(ConfigUtil.class, mockConfigUtil); - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), - BATCH_PROPERTY, String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml"); - - TestXmlBean bean = context.getBean(TestXmlBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), - BATCH_PROPERTY, String.valueOf(newBatch)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithMultipleNamespaces() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY, - String.valueOf(initialTimeout)); - Properties fxApolloProperties = assembleProperties(BATCH_PROPERTY, - String.valueOf(initialBatch)); - - SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, - applicationProperties); - SimpleConfig fxApolloConfig = prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest3.xml"); - - TestXmlBean bean = context.getBean(TestXmlBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY, - String.valueOf(newTimeout)); - - applicationConfig - .onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newFxApolloProperties = assembleProperties(BATCH_PROPERTY, String.valueOf(newBatch)); - - fxApolloConfig.onRepositoryChange(FX_APOLLO_NAMESPACE, newFxApolloProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(newBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithMultipleNamespacesWithSameProperties() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - int anotherBatch = 3000; - int someNewTimeout = 1001; - int someNewBatch = 2001; - - Properties applicationProperties = assembleProperties(BATCH_PROPERTY, - String.valueOf(someBatch)); - Properties fxApolloProperties = assembleProperties(TIMEOUT_PROPERTY, - String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch)); - - prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, applicationProperties); - SimpleConfig fxApolloConfig = prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest3.xml"); - - TestXmlBean bean = context.getBean(TestXmlBean.class); - - assertEquals(someTimeout, bean.getTimeout()); - assertEquals(someBatch, bean.getBatch()); - - Properties newFxApolloProperties = assembleProperties(TIMEOUT_PROPERTY, - String.valueOf(someNewTimeout), BATCH_PROPERTY, String.valueOf(someNewBatch)); - - fxApolloConfig.onRepositoryChange(FX_APOLLO_NAMESPACE, newFxApolloProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(someNewTimeout, bean.getTimeout()); - assertEquals(someBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithNewProperties() throws Exception { - int initialTimeout = 1000; - int newTimeout = 1001; - int newBatch = 2001; - - Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY, - String.valueOf(initialTimeout)); - - SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, - applicationProperties); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml"); - - TestXmlBean bean = context.getBean(TestXmlBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(DEFAULT_BATCH, bean.getBatch()); - - Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY, - String.valueOf(newTimeout), BATCH_PROPERTY, String.valueOf(newBatch)); - - applicationConfig - .onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(newBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithIrrelevantProperties() throws Exception { - int initialTimeout = 1000; - - String someIrrelevantKey = "someIrrelevantKey"; - String someIrrelevantValue = "someIrrelevantValue"; - - String anotherIrrelevantKey = "anotherIrrelevantKey"; - String anotherIrrelevantValue = "anotherIrrelevantValue"; - - Properties applicationProperties = assembleProperties(TIMEOUT_PROPERTY, - String.valueOf(initialTimeout), someIrrelevantKey, someIrrelevantValue); - - SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, - applicationProperties); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml"); - - TestXmlBean bean = context.getBean(TestXmlBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(DEFAULT_BATCH, bean.getBatch()); - - Properties newApplicationProperties = assembleProperties(TIMEOUT_PROPERTY, - String.valueOf(initialTimeout), anotherIrrelevantKey, anotherIrrelevantValue); - - applicationConfig - .onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newApplicationProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(DEFAULT_BATCH, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithDeletedProperties() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), - BATCH_PROPERTY, String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml"); - - TestXmlBean bean = context.getBean(TestXmlBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = new Properties(); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(DEFAULT_TIMEOUT, bean.getTimeout()); - assertEquals(DEFAULT_BATCH, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithMultipleNamespacesWithSamePropertiesDeleted() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - int anotherBatch = 3000; - - Properties applicationProperties = assembleProperties(BATCH_PROPERTY, - String.valueOf(someBatch)); - Properties fxApolloProperties = assembleProperties(TIMEOUT_PROPERTY, - String.valueOf(someTimeout), BATCH_PROPERTY, String.valueOf(anotherBatch)); - - SimpleConfig applicationConfig = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, - applicationProperties); - prepareConfig(FX_APOLLO_NAMESPACE, fxApolloProperties); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest3.xml"); - - TestXmlBean bean = context.getBean(TestXmlBean.class); - - assertEquals(someTimeout, bean.getTimeout()); - assertEquals(someBatch, bean.getBatch()); - - Properties newProperties = new Properties(); - - applicationConfig.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(someTimeout, bean.getTimeout()); - assertEquals(anotherBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithDeletedPropertiesWithNoDefaultValue() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), - BATCH_PROPERTY, String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest7.xml"); - - TestXmlBean bean = context.getBean(TestXmlBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(300); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithTypeMismatch() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - String newBatch = "newBatch"; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), - BATCH_PROPERTY, String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest1.xml"); - - TestXmlBean bean = context.getBean(TestXmlBean.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), - BATCH_PROPERTY, newBatch); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(300); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithValueInjectedAsConstructorArgs() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), - BATCH_PROPERTY, String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest8.xml"); - - TestXmlBeanWithConstructorArgs bean = context.getBean(TestXmlBeanWithConstructorArgs.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), - BATCH_PROPERTY, String.valueOf(newBatch)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - // Does not support this scenario - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithValueAndProperty() throws Exception { - int initialTimeout = 1000; - int initialBatch = 2000; - int newTimeout = 1001; - int newBatch = 2001; - - Properties properties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(initialTimeout), - BATCH_PROPERTY, String.valueOf(initialBatch)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest9.xml"); - - TestXmlBeanWithInjectedValue bean = context.getBean(TestXmlBeanWithInjectedValue.class); - - assertEquals(initialTimeout, bean.getTimeout()); - assertEquals(initialBatch, bean.getBatch()); - - Properties newProperties = assembleProperties(TIMEOUT_PROPERTY, String.valueOf(newTimeout), - BATCH_PROPERTY, String.valueOf(newBatch)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(newTimeout, bean.getTimeout()); - assertEquals(newBatch, bean.getBatch()); - } - - @Test - public void testAutoUpdateWithAllKindsOfDataTypes() throws Exception { - int someInt = 1000; - int someNewInt = 1001; - int[] someIntArray = {1, 2, 3, 4}; - int[] someNewIntArray = {5, 6, 7, 8}; - long someLong = 2000L; - long someNewLong = 2001L; - short someShort = 3000; - short someNewShort = 3001; - float someFloat = 1.2F; - float someNewFloat = 2.2F; - double someDouble = 3.10D; - double someNewDouble = 4.10D; - byte someByte = 123; - byte someNewByte = 124; - boolean someBoolean = true; - boolean someNewBoolean = !someBoolean; - String someString = "someString"; - String someNewString = "someNewString"; - - String someDateFormat = "yyyy-MM-dd HH:mm:ss.SSS"; - Date someDate = assembleDate(2018, 2, 23, 20, 1, 2, 123); - Date someNewDate = assembleDate(2018, 2, 23, 21, 2, 3, 345); - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(someDateFormat, Locale.US); - - Properties properties = new Properties(); - properties.setProperty("intProperty", String.valueOf(someInt)); - properties.setProperty("intArrayProperty", Ints.join(", ", someIntArray)); - properties.setProperty("longProperty", String.valueOf(someLong)); - properties.setProperty("shortProperty", String.valueOf(someShort)); - properties.setProperty("floatProperty", String.valueOf(someFloat)); - properties.setProperty("doubleProperty", String.valueOf(someDouble)); - properties.setProperty("byteProperty", String.valueOf(someByte)); - properties.setProperty("booleanProperty", String.valueOf(someBoolean)); - properties.setProperty("stringProperty", someString); - properties.setProperty("dateFormat", someDateFormat); - properties.setProperty("dateProperty", simpleDateFormat.format(someDate)); - - SimpleConfig config = prepareConfig(ConfigConsts.NAMESPACE_APPLICATION, properties); - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/XmlConfigPlaceholderTest10.xml"); - - TestAllKindsOfDataTypesBean bean = context.getBean(TestAllKindsOfDataTypesBean.class); - - assertEquals(someInt, bean.getIntProperty()); - assertArrayEquals(someIntArray, bean.getIntArrayProperty()); - assertEquals(someLong, bean.getLongProperty()); - assertEquals(someShort, bean.getShortProperty()); - assertEquals(someFloat, bean.getFloatProperty(), 0.001F); - assertEquals(someDouble, bean.getDoubleProperty(), 0.001D); - assertEquals(someByte, bean.getByteProperty()); - assertEquals(someBoolean, bean.getBooleanProperty()); - assertEquals(someString, bean.getStringProperty()); - assertEquals(someDate, bean.getDateProperty()); - - Properties newProperties = new Properties(); - newProperties.setProperty("intProperty", String.valueOf(someNewInt)); - newProperties.setProperty("intArrayProperty", Ints.join(", ", someNewIntArray)); - newProperties.setProperty("longProperty", String.valueOf(someNewLong)); - newProperties.setProperty("shortProperty", String.valueOf(someNewShort)); - newProperties.setProperty("floatProperty", String.valueOf(someNewFloat)); - newProperties.setProperty("doubleProperty", String.valueOf(someNewDouble)); - newProperties.setProperty("byteProperty", String.valueOf(someNewByte)); - newProperties.setProperty("booleanProperty", String.valueOf(someNewBoolean)); - newProperties.setProperty("stringProperty", someNewString); - newProperties.setProperty("dateFormat", someDateFormat); - newProperties.setProperty("dateProperty", simpleDateFormat.format(someNewDate)); - - config.onRepositoryChange(ConfigConsts.NAMESPACE_APPLICATION, newProperties); - - TimeUnit.MILLISECONDS.sleep(100); - - assertEquals(someNewInt, bean.getIntProperty()); - assertArrayEquals(someNewIntArray, bean.getIntArrayProperty()); - assertEquals(someNewLong, bean.getLongProperty()); - assertEquals(someNewShort, bean.getShortProperty()); - assertEquals(someNewFloat, bean.getFloatProperty(), 0.001F); - assertEquals(someNewDouble, bean.getDoubleProperty(), 0.001D); - assertEquals(someNewByte, bean.getByteProperty()); - assertEquals(someNewBoolean, bean.getBooleanProperty()); - assertEquals(someNewString, bean.getStringProperty()); - assertEquals(someNewDate, bean.getDateProperty()); - } - - public static class TestXmlBeanWithConstructorArgs { - private final int timeout; - private final int batch; - - public TestXmlBeanWithConstructorArgs(int timeout, int batch) { - this.timeout = timeout; - this.batch = batch; - } - - public int getTimeout() { - return timeout; - } - - public int getBatch() { - return batch; - } - } - - public static class TestXmlBeanWithInjectedValue { - @Value("${timeout}") - private int timeout; - private int batch; - - public void setBatch(int batch) { - this.batch = batch; - } - - public int getTimeout() { - return timeout; - } - - public int getBatch() { - return batch; - } - } - - static class TestAllKindsOfDataTypesBean { - - private int intProperty; - - private int[] intArrayProperty; - - private long longProperty; - - private short shortProperty; - - private float floatProperty; - - private double doubleProperty; - - private byte byteProperty; - - private boolean booleanProperty; - - private String stringProperty; - - private Date dateProperty; - - public void setDateProperty(Date dateProperty) { - this.dateProperty = dateProperty; - } - - public void setIntProperty(int intProperty) { - this.intProperty = intProperty; - } - - public void setIntArrayProperty(int[] intArrayProperty) { - this.intArrayProperty = intArrayProperty; - } - - public void setLongProperty(long longProperty) { - this.longProperty = longProperty; - } - - public void setShortProperty(short shortProperty) { - this.shortProperty = shortProperty; - } - - public void setFloatProperty(float floatProperty) { - this.floatProperty = floatProperty; - } - - public void setDoubleProperty(double doubleProperty) { - this.doubleProperty = doubleProperty; - } - - public void setByteProperty(byte byteProperty) { - this.byteProperty = byteProperty; - } - - public void setBooleanProperty(boolean booleanProperty) { - this.booleanProperty = booleanProperty; - } - - public void setStringProperty(String stringProperty) { - this.stringProperty = stringProperty; - } - - public int getIntProperty() { - return intProperty; - } - - public int[] getIntArrayProperty() { - return intArrayProperty; - } - - public long getLongProperty() { - return longProperty; - } - - public short getShortProperty() { - return shortProperty; - } - - public float getFloatProperty() { - return floatProperty; - } - - public double getDoubleProperty() { - return doubleProperty; - } - - public byte getByteProperty() { - return byteProperty; - } - - public boolean getBooleanProperty() { - return booleanProperty; - } - - public String getStringProperty() { - return stringProperty; - } - - public Date getDateProperty() { - return dateProperty; - } - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/XmlConfigPlaceholderTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/XmlConfigPlaceholderTest.java deleted file mode 100644 index 5227734ca92..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/XmlConfigPlaceholderTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright 2022 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; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.core.ConfigConsts; -import org.junit.After; -import org.junit.Test; -import org.mockito.Mockito; -import org.springframework.beans.FatalBeanException; -import org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class XmlConfigPlaceholderTest extends AbstractSpringIntegrationTest { - - private static final String TIMEOUT_PROPERTY = "timeout"; - private static final int DEFAULT_TIMEOUT = 100; - private static final String BATCH_PROPERTY = "batch"; - private static final int DEFAULT_BATCH = 200; - private static final String FX_APOLLO_NAMESPACE = "FX.apollo"; - - /** - * forbidden to override the method {@link super#tearDown()}. - */ - @After - public void XmlConfigPlaceholderTestTearDown() { - // clear the system properties - System.clearProperty(SystemPropertyKeyConstants.XXX_FROM_SYSTEM_PROPERTY); - System.clearProperty(SystemPropertyKeyConstants.YYY_FROM_SYSTEM_PROPERTY); - } - - @Test - public void testPropertySourceWithNoNamespace() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - - Config config = mock(Config.class); - when(config.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))) - .thenReturn(String.valueOf(someTimeout)); - when(config.getProperty(eq(BATCH_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someBatch)); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - check("spring/XmlConfigPlaceholderTest1.xml", someTimeout, someBatch); - } - - @Test - public void testPropertySourceWithNoConfig() throws Exception { - Config config = mock(Config.class); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - check("spring/XmlConfigPlaceholderTest1.xml", DEFAULT_TIMEOUT, DEFAULT_BATCH); - } - - @Test - public void testApplicationPropertySource() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - - Config config = mock(Config.class); - when(config.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))) - .thenReturn(String.valueOf(someTimeout)); - when(config.getProperty(eq(BATCH_PROPERTY), Mockito.nullable(String.class))).thenReturn(String.valueOf(someBatch)); - - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, config); - - check("spring/XmlConfigPlaceholderTest2.xml", someTimeout, someBatch); - } - - @Test - public void testMultiplePropertySources() throws Exception { - int someTimeout = 1000; - int someBatch = 2000; - - Config application = mock(Config.class); - when(application.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))) - .thenReturn(String.valueOf(someTimeout)); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, application); - - Config fxApollo = mock(Config.class); - when(application.getProperty(eq(BATCH_PROPERTY), Mockito.nullable(String.class))) - .thenReturn(String.valueOf(someBatch)); - mockConfig(FX_APOLLO_NAMESPACE, fxApollo); - - check("spring/XmlConfigPlaceholderTest3.xml", someTimeout, someBatch); - } - - private void prepare(int someTimeout, int anotherTimeout, int someBatch) { - Config application = mock(Config.class); - when(application.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))) - .thenReturn(String.valueOf(someTimeout)); - when(application.getProperty(eq(BATCH_PROPERTY), Mockito.nullable(String.class))) - .thenReturn(String.valueOf(someBatch)); - mockConfig(ConfigConsts.NAMESPACE_APPLICATION, application); - - Config fxApollo = mock(Config.class); - when(fxApollo.getProperty(eq(TIMEOUT_PROPERTY), Mockito.nullable(String.class))) - .thenReturn(String.valueOf(anotherTimeout)); - mockConfig(FX_APOLLO_NAMESPACE, fxApollo); - } - - @Test - public void testMultiplePropertySourcesWithSameProperties() throws Exception { - int someTimeout = 1000; - int anotherTimeout = someTimeout + 1; - int someBatch = 2000; - this.prepare(someTimeout, anotherTimeout, someBatch); - - check("spring/XmlConfigPlaceholderTest3.xml", someTimeout, someBatch); - } - - @Test - public void testMultiplePropertySourcesWithSameProperties2() throws Exception { - int someTimeout = 1000; - int anotherTimeout = someTimeout + 1; - int someBatch = 2000; - this.prepare(someTimeout, anotherTimeout, someBatch); - - check("spring/XmlConfigPlaceholderTest6.xml", anotherTimeout, someBatch); - } - - @Test - public void testMultiplePropertySourcesWithSamePropertiesWithWeight() throws Exception { - int someTimeout = 1000; - int anotherTimeout = someTimeout + 1; - int someBatch = 2000; - this.prepare(someTimeout, anotherTimeout, someBatch); - - check("spring/XmlConfigPlaceholderTest4.xml", anotherTimeout, someBatch); - } - - @Test(expected = XmlBeanDefinitionStoreException.class) - public void testWithInvalidWeight() throws Exception { - check("spring/XmlConfigPlaceholderTest5.xml", DEFAULT_TIMEOUT, DEFAULT_BATCH); - } - - - @Test - public void testResolveNamespacesWithDefaultValue() throws Exception { - int someTimeout = 1000; - int anotherTimeout = someTimeout + 1; - int someBatch = 2000; - this.prepare(someTimeout, anotherTimeout, someBatch); - - check("spring/config.namespace.placeholder.with.default.value.xml", anotherTimeout, someBatch); - } - - @Test - public void testResolveNamespacesFromSystemProperty() throws Exception { - System.setProperty(SystemPropertyKeyConstants.XXX_FROM_SYSTEM_PROPERTY, ConfigConsts.NAMESPACE_APPLICATION); - System.setProperty(SystemPropertyKeyConstants.YYY_FROM_SYSTEM_PROPERTY, "FX.apollo"); - int someTimeout = 1000; - int anotherTimeout = someTimeout + 1; - int someBatch = 2000; - this.prepare(someTimeout, anotherTimeout, someBatch); - - check("spring/config.namespace.placeholder.xml", anotherTimeout, someBatch); - } - - @Test(expected = FatalBeanException.class) - public void testUnresolvedNamespaces() { - int someTimeout = 1000; - int anotherTimeout = someTimeout + 1; - int someBatch = 2000; - this.prepare(someTimeout, anotherTimeout, someBatch); - - check("spring/config.namespace.placeholder.xml", anotherTimeout, someBatch); - } - - private static void check(String xmlLocation, int expectedTimeout, int expectedBatch) { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(xmlLocation); - - TestXmlBean bean = context.getBean(TestXmlBean.class); - - assertEquals(expectedTimeout, bean.getTimeout()); - assertEquals(expectedBatch, bean.getBatch()); - } - - private static class SystemPropertyKeyConstants { - - static final String XXX_FROM_SYSTEM_PROPERTY = "xxx.from.system.property"; - static final String YYY_FROM_SYSTEM_PROPERTY = "yyy.from.system.property"; - } - - public static class TestXmlBean { - - private int timeout; - private int batch; - - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - public int getTimeout() { - return timeout; - } - - public int getBatch() { - return batch; - } - - public void setBatch(int batch) { - this.batch = batch; - } - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializerTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializerTest.java deleted file mode 100644 index d128f8f6448..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/boot/ApolloApplicationContextInitializerTest.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright 2022 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.boot; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.spring.config.CachedCompositePropertySource; -import com.ctrip.framework.apollo.spring.config.PropertySourcesConstants; -import com.ctrip.framework.apollo.util.ConfigUtil; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.springframework.core.env.ConfigurableEnvironment; -import org.springframework.core.env.MutablePropertySources; -import org.springframework.core.env.PropertiesPropertySource; -import org.springframework.core.env.StandardEnvironment; - -import java.util.Properties; - -public class ApolloApplicationContextInitializerTest { - - private ApolloApplicationContextInitializer apolloApplicationContextInitializer; - - @Before - public void setUp() throws Exception { - apolloApplicationContextInitializer = new ApolloApplicationContextInitializer(); - } - - @After - public void tearDown() throws Exception { - System.clearProperty(ApolloClientSystemConsts.APP_ID); - System.clearProperty(ConfigConsts.APOLLO_CLUSTER_KEY); - System.clearProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR); - System.clearProperty(ConfigConsts.APOLLO_META_KEY); - - MockInjector.reset(); - } - - @Test - public void testFillFromEnvironment() throws Exception { - String someAppId = "someAppId"; - String someCluster = "someCluster"; - String someCacheDir = "someCacheDir"; - String someApolloMeta = "someApolloMeta"; - - ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class); - - when(environment.getProperty(ApolloClientSystemConsts.APP_ID)).thenReturn(someAppId); - when(environment.getProperty(ConfigConsts.APOLLO_CLUSTER_KEY)).thenReturn(someCluster); - when(environment.getProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR)).thenReturn(someCacheDir); - when(environment.getProperty(ConfigConsts.APOLLO_META_KEY)).thenReturn(someApolloMeta); - - apolloApplicationContextInitializer.initializeSystemProperty(environment); - - assertEquals(someAppId, System.getProperty(ApolloClientSystemConsts.APP_ID)); - assertEquals(someCluster, System.getProperty(ConfigConsts.APOLLO_CLUSTER_KEY)); - assertEquals(someCacheDir, System.getProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR)); - assertEquals(someApolloMeta, System.getProperty(ConfigConsts.APOLLO_META_KEY)); - } - - @Test - public void testFillFromEnvironmentWithSystemPropertyAlreadyFilled() throws Exception { - String someAppId = "someAppId"; - String someCluster = "someCluster"; - String someCacheDir = "someCacheDir"; - String someApolloMeta = "someApolloMeta"; - - System.setProperty(ApolloClientSystemConsts.APP_ID, someAppId); - System.setProperty(ConfigConsts.APOLLO_CLUSTER_KEY, someCluster); - System.setProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR, someCacheDir); - System.setProperty(ConfigConsts.APOLLO_META_KEY, someApolloMeta); - - String anotherAppId = "anotherAppId"; - String anotherCluster = "anotherCluster"; - String anotherCacheDir = "anotherCacheDir"; - String anotherApolloMeta = "anotherApolloMeta"; - - ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class); - - when(environment.getProperty(ApolloClientSystemConsts.APP_ID)).thenReturn(anotherAppId); - when(environment.getProperty(ConfigConsts.APOLLO_CLUSTER_KEY)).thenReturn(anotherCluster); - when(environment.getProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR)).thenReturn(anotherCacheDir); - when(environment.getProperty(ConfigConsts.APOLLO_META_KEY)).thenReturn(anotherApolloMeta); - - apolloApplicationContextInitializer.initializeSystemProperty(environment); - - assertEquals(someAppId, System.getProperty(ApolloClientSystemConsts.APP_ID)); - assertEquals(someCluster, System.getProperty(ConfigConsts.APOLLO_CLUSTER_KEY)); - assertEquals(someCacheDir, System.getProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR)); - assertEquals(someApolloMeta, System.getProperty(ConfigConsts.APOLLO_META_KEY)); - } - - @Test - public void testFillFromEnvironmentWithNoPropertyFromEnvironment() throws Exception { - ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class); - - apolloApplicationContextInitializer.initializeSystemProperty(environment); - - assertNull(System.getProperty(ApolloClientSystemConsts.APP_ID)); - assertNull(System.getProperty(ConfigConsts.APOLLO_CLUSTER_KEY)); - assertNull(System.getProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR)); - assertNull(System.getProperty(ConfigConsts.APOLLO_META_KEY)); - } - - @Test - public void testPropertyNamesCacheEnabled() { - ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class); - MutablePropertySources propertySources = new MutablePropertySources(); - when(environment.getPropertySources()).thenReturn(propertySources); - when(environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, - ConfigConsts.NAMESPACE_APPLICATION)).thenReturn(""); - - apolloApplicationContextInitializer.initialize(environment); - - assertTrue(propertySources.contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)); - assertFalse(propertySources.iterator().next() instanceof CachedCompositePropertySource); - - ConfigUtil configUtil = new ConfigUtil(); - configUtil = spy(configUtil); - when(configUtil.isPropertyNamesCacheEnabled()).thenReturn(true); - MockInjector.setInstance(ConfigUtil.class, configUtil); - apolloApplicationContextInitializer = new ApolloApplicationContextInitializer(); - propertySources.remove(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME); - - apolloApplicationContextInitializer.initialize(environment); - - assertTrue(propertySources.contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)); - assertTrue(propertySources.iterator().next() instanceof CachedCompositePropertySource); - } - - @Test - public void testOverrideSystemProperties() { - Properties properties = new Properties(); - properties.setProperty("server.port", "8080"); - ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class); - - MutablePropertySources propertySources = new MutablePropertySources(); - propertySources.addLast(new PropertiesPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, properties)); - - when(environment.getPropertySources()).thenReturn(propertySources); - when(environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, - ConfigConsts.NAMESPACE_APPLICATION)).thenReturn(""); - ConfigUtil configUtil = new ConfigUtil(); - configUtil = spy(configUtil); - when(configUtil.isOverrideSystemProperties()).thenReturn(false); - MockInjector.setInstance(ConfigUtil.class, configUtil); - - apolloApplicationContextInitializer.initialize(environment); - - assertTrue(propertySources.contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)); - assertEquals(propertySources.iterator().next().getName(), StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/config/CachedCompositePropertySourceTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/config/CachedCompositePropertySourceTest.java deleted file mode 100644 index 9d6e11f84f4..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/config/CachedCompositePropertySourceTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2022 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.config; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import org.assertj.core.util.Arrays; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; -import org.springframework.core.env.PropertySource; - -/** - * @author Shawyeok (shawyeok@outlook.com) - */ -@RunWith(MockitoJUnitRunner.class) -public class CachedCompositePropertySourceTest { - - private CachedCompositePropertySource compositeSource; - - @Mock - private ConfigPropertySource configPropertySource; - - private List listeners; - - @Before - public void setUp() throws Exception { - compositeSource = new CachedCompositePropertySource("testCompositeSource"); - listeners = new LinkedList<>(); - Mockito.doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ConfigChangeListener listener = invocation.getArgument(0, ConfigChangeListener.class); - listeners.add(listener); - return Void.class; - } - }).when(configPropertySource).addChangeListener(any(ConfigChangeListener.class)); - compositeSource.addPropertySource(configPropertySource); - } - - @Test - public void testGetPropertyNames() { - String[] propertyNames = Arrays.array("propertyName"); - String[] anotherPropertyNames = Arrays.array("propertyName", "anotherPropertyName"); - - when(configPropertySource.getPropertyNames()).thenReturn(propertyNames, anotherPropertyNames); - - String[] returnedPropertyNames = compositeSource.getPropertyNames(); - assertArrayEquals(propertyNames, returnedPropertyNames); - assertSame(returnedPropertyNames, compositeSource.getPropertyNames()); - - listeners.get(0).onChange(new ConfigChangeEvent(null, null)); - - returnedPropertyNames = compositeSource.getPropertyNames(); - assertArrayEquals(anotherPropertyNames, returnedPropertyNames); - assertSame(returnedPropertyNames, compositeSource.getPropertyNames()); - } - - @Test - public void testAddPropertySource() { - verify(configPropertySource, times(1)) - .addChangeListener(any(CachedCompositePropertySource.class)); - assertEquals(1, listeners.size()); - assertTrue(compositeSource.getPropertySources().contains(configPropertySource)); - } - - @Test - public void testAddFirstPropertySource() { - ConfigPropertySource anotherSource = mock(ConfigPropertySource.class); - final List anotherListenerList = new LinkedList<>(); - Mockito.doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - ConfigChangeListener listener = invocation.getArgument(0, ConfigChangeListener.class); - anotherListenerList.add(listener); - return Void.class; - } - }).when(anotherSource).addChangeListener(any(ConfigChangeListener.class)); - compositeSource.addFirstPropertySource(anotherSource); - - Collection> propertySources = compositeSource.getPropertySources(); - Iterator> it = propertySources.iterator(); - - assertEquals(2, propertySources.size()); - assertEquals(1, anotherListenerList.size()); - assertSame(anotherSource, it.next()); - assertSame(configPropertySource, it.next()); - } -} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/config/ConfigPropertySourceTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/config/ConfigPropertySourceTest.java deleted file mode 100644 index f67d66a48a3..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/config/ConfigPropertySourceTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2022 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.config; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import java.util.List; -import java.util.Set; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.junit.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; - -@RunWith(MockitoJUnitRunner.class) -public class ConfigPropertySourceTest { - - private ConfigPropertySource configPropertySource; - - @Mock - private Config someConfig; - - @Before - public void setUp() throws Exception { - String someName = "someName"; - configPropertySource = new ConfigPropertySource(someName, someConfig); - } - - @Test - public void testGetPropertyNames() throws Exception { - String somePropertyName = "somePropertyName"; - String anotherPropertyName = "anotherPropertyName"; - Set somePropertyNames = Sets.newHashSet(somePropertyName, anotherPropertyName); - - when(someConfig.getPropertyNames()).thenReturn(somePropertyNames); - - String[] result = configPropertySource.getPropertyNames(); - - verify(someConfig, times(1)).getPropertyNames(); - - assertEquals(somePropertyNames, Sets.newHashSet(result)); - } - - @Test - public void testGetEmptyPropertyNames() throws Exception { - when(someConfig.getPropertyNames()).thenReturn(Sets.newHashSet()); - - assertEquals(0, configPropertySource.getPropertyNames().length); - } - - @Test - public void testGetProperty() throws Exception { - String somePropertyName = "somePropertyName"; - - String someValue = "someValue"; - - when(someConfig.getProperty(somePropertyName, null)).thenReturn(someValue); - - assertEquals(someValue, configPropertySource.getProperty(somePropertyName)); - - verify(someConfig, times(1)).getProperty(somePropertyName, null); - } - - @Test - public void testAddChangeListener() throws Exception { - ConfigChangeListener someListener = mock(ConfigChangeListener.class); - ConfigChangeListener anotherListener = mock(ConfigChangeListener.class); - - final List listeners = Lists.newArrayList(); - - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - listeners.add(invocation.getArgument(0, ConfigChangeListener.class)); - - return Void.class; - } - }).when(someConfig).addChangeListener(any(ConfigChangeListener.class)); - - configPropertySource.addChangeListener(someListener); - configPropertySource.addChangeListener(anotherListener); - - assertEquals(2, listeners.size()); - assertTrue(listeners.containsAll(Lists.newArrayList(someListener, anotherListener))); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/config/PropertySourcesProcessorTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/config/PropertySourcesProcessorTest.java deleted file mode 100644 index be6ec4bffdc..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/config/PropertySourcesProcessorTest.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright 2022 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.config; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import com.ctrip.framework.apollo.spring.AbstractSpringIntegrationTest; -import com.ctrip.framework.apollo.spring.events.ApolloConfigChangeEvent; -import com.ctrip.framework.apollo.util.ConfigUtil; -import com.google.common.collect.Lists; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.context.ApplicationEventPublisher; -import org.springframework.core.env.*; - -import java.util.Properties; - -public class PropertySourcesProcessorTest extends AbstractSpringIntegrationTest { - - private ConfigurableEnvironment environment; - private ConfigurableListableBeanFactory beanFactory; - private PropertySourcesProcessor processor; - private MutablePropertySources propertySources; - private ApplicationEventPublisher applicationEventPublisher; - - @Override - @Before - public void setUp() throws Exception { - super.setUp(); - propertySources = mock(MutablePropertySources.class); - environment = mock(ConfigurableEnvironment.class); - when(environment.getPropertySources()).thenReturn(propertySources); - beanFactory = mock(ConfigurableListableBeanFactory.class); - applicationEventPublisher = mock(ApplicationEventPublisher.class); - processor = new PropertySourcesProcessor(); - processor.setEnvironment(environment); - processor.setApplicationEventPublisher(applicationEventPublisher); - } - - @Override - @After - public void tearDown() throws Exception { - super.tearDown(); - PropertySourcesProcessor.reset(); - } - - @Test - public void testInitializePropertySources() { - String namespaceName = "someNamespace"; - String anotherNamespaceName = "anotherNamespace"; - Config config = mock(Config.class); - Config anotherConfig = mock(Config.class); - mockConfig(namespaceName, config); - mockConfig(anotherNamespaceName, anotherConfig); - PropertySourcesProcessor.addNamespaces(Lists.newArrayList(namespaceName, anotherNamespaceName), - 0); - - processor.postProcessBeanFactory(beanFactory); - - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass( - CompositePropertySource.class); - verify(propertySources).addFirst(argumentCaptor.capture()); - - CompositePropertySource compositePropertySource = argumentCaptor.getValue(); - assertEquals(2, compositePropertySource.getPropertySources().size()); - - ConfigPropertySource propertySource = (ConfigPropertySource) Lists.newArrayList( - compositePropertySource.getPropertySources()).get(0); - ConfigPropertySource anotherPropertySource = (ConfigPropertySource) Lists.newArrayList( - compositePropertySource.getPropertySources()).get(1); - - assertEquals(namespaceName, propertySource.getName()); - assertSame(config, propertySource.getSource()); - assertEquals(anotherNamespaceName, anotherPropertySource.getName()); - assertSame(anotherConfig, anotherPropertySource.getSource()); - } - - @Test - public void testApplicationEvent() { - String namespaceName = "someNamespace"; - Config config = mock(Config.class); - mockConfig(namespaceName, config); - PropertySourcesProcessor.addNamespaces(Lists.newArrayList(namespaceName), 0); - ConfigChangeEvent someConfigChangeEvent = mock(ConfigChangeEvent.class); - - processor.postProcessBeanFactory(beanFactory); - - ArgumentCaptor argumentCaptor = ArgumentCaptor.forClass( - ConfigChangeListener.class); - verify(config).addChangeListener(argumentCaptor.capture()); - - ConfigChangeListener listener = argumentCaptor.getValue(); - listener.onChange(someConfigChangeEvent); - - ArgumentCaptor eventCaptor = ArgumentCaptor.forClass( - ApolloConfigChangeEvent.class); - verify(applicationEventPublisher).publishEvent(eventCaptor.capture()); - - ApolloConfigChangeEvent event = eventCaptor.getValue(); - assertSame(someConfigChangeEvent, event.getConfigChangeEvent()); - } - - - @Test - public void testOverrideSystemProperties() { - Properties properties = new Properties(); - properties.setProperty("server.port", "8080"); - properties.setProperty(ApolloClientSystemConsts.APOLLO_OVERRIDE_SYSTEM_PROPERTIES, "false"); - ConfigurableEnvironment environment = mock(ConfigurableEnvironment.class); - - MutablePropertySources propertySources = new MutablePropertySources(); - propertySources.addLast(new PropertiesPropertySource(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, properties)); - - when(environment.getPropertySources()).thenReturn(propertySources); - when(environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, - ConfigConsts.NAMESPACE_APPLICATION)).thenReturn(""); - - ConfigUtil configUtil = new ConfigUtil(); - configUtil = spy(configUtil); - when(configUtil.isOverrideSystemProperties()).thenReturn(false); - MockInjector.setInstance(ConfigUtil.class, configUtil); - - processor.setEnvironment(environment); - processor.postProcessBeanFactory(beanFactory); - - assertTrue(propertySources.contains(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME)); - assertEquals(propertySources.iterator().next().getName(), StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/property/PlaceholderHelperTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/property/PlaceholderHelperTest.java deleted file mode 100644 index 15df10ccf13..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/property/PlaceholderHelperTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2022 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 static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.common.collect.Sets; -import org.junit.Before; -import org.junit.Test; - -public class PlaceholderHelperTest { - - private PlaceholderHelper placeholderHelper; - - @Before - public void setUp() throws Exception { - placeholderHelper = new PlaceholderHelper(); - } - - @Test - public void testExtractPlaceholderKeys() throws Exception { - check("${some.key}", "some.key"); - check("${some.key:100}", "some.key"); - check("${some.key:${some.other.key}}", "some.key", "some.other.key"); - check("${some.key:${some.other.key:100}}", "some.key", "some.other.key"); - - check("${some.key}/xx", "some.key"); - check("${some.key:100}/xx", "some.key"); - check("${some.key:${some.other.key}/xx}/yy", "some.key", "some.other.key"); - check("${some.key:${some.other.key:100}/xx}/yy", "some.key", "some.other.key"); - } - - @Test - public void testExtractNestedPlaceholderKeys() throws Exception { - check("${${some.key}}", "some.key"); - check("${${some.key:other.key}}", "some.key"); - check("${${some.key}:100}", "some.key"); - check("${${some.key}:${another.key}}", "some.key", "another.key"); - - check("${${some.key}/xx}/xx", "some.key"); - check("${${some.key:other.key/xx}/xx}/xx", "some.key"); - check("${${some.key}/xx:100}/xx", "some.key"); - check("${${some.key}/xx:${another.key}/xx}xx", "some.key", "another.key"); - - } - - @Test - public void testExtractComplexNestedPlaceholderKeys() throws Exception { - check("${${a}1${b}:3.${c:${d:100}}}", "a", "b", "c", "d"); - check("${1${a}2${b}3:4.${c:5${d:100}6}7}", "a", "b", "c", "d"); - - check("${${a}1${b}:3.${c:${d:100}}}/xx", "a", "b", "c", "d"); - check("${1${a}2${b}3:4.${c:5${d:100}6}7}/xx", "a", "b", "c", "d"); - } - - @Test - public void testExtractPlaceholderKeysFromExpression() throws Exception { - check("#{new java.text.SimpleDateFormat('${some.key}').parse('${another.key}')}", "some.key", "another.key"); - check("#{new java.text.SimpleDateFormat('${some.key:abc}').parse('${another.key:100}')}", "some.key", "another.key"); - check("#{new java.text.SimpleDateFormat('${some.key:${some.other.key}}').parse('${another.key}')}", "some.key", "another.key", "some.other.key"); - check("#{new java.text.SimpleDateFormat('${some.key:${some.other.key:abc}}').parse('${another.key}')}", "some.key", "another.key", "some.other.key"); - check("#{new java.text.SimpleDateFormat('${${some.key}}').parse('${${another.key:other.key}}')}", "some.key", "another.key"); - - check("#{new java.text.SimpleDateFormat('${some.key}/xx').parse('${another.key}/xx')}", "some.key", "another.key"); - check("#{new java.text.SimpleDateFormat('${some.key:abc}/xx').parse('${another.key:100}/xx')}", "some.key", "another.key"); - check("#{new java.text.SimpleDateFormat('${some.key:${some.other.key}/xx}/xx').parse('${another.key}/xx')}", "some.key", "another.key", "some.other.key"); - check("#{new java.text.SimpleDateFormat('${some.key:${some.other.key:abc}/xx}/xx').parse('${another.key}/xx')}", "some.key", "another.key", "some.other.key"); - check("#{new java.text.SimpleDateFormat('${${some.key}/xx}').parse('${${another.key:other.key}/xx}/xx')}", "some.key", "another.key"); - - - assertTrue(placeholderHelper.extractPlaceholderKeys("#{systemProperties[some.key] ?: 123}").isEmpty()); - assertTrue(placeholderHelper.extractPlaceholderKeys("#{ T(java.lang.Math).random() * 100.0 }").isEmpty()); - } - - @Test - public void testExtractInvalidPlaceholderKeys() throws Exception { - assertTrue(placeholderHelper.extractPlaceholderKeys("some.key").isEmpty()); - assertTrue(placeholderHelper.extractPlaceholderKeys("some.key:100").isEmpty()); - } - - private void check(String propertyString, String... expectedPlaceholders) { - assertEquals(Sets.newHashSet(expectedPlaceholders), placeholderHelper.extractPlaceholderKeys(propertyString)); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/ApolloConfigRegistrarHelperTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/ApolloConfigRegistrarHelperTest.java deleted file mode 100644 index e2a31d2806f..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/ApolloConfigRegistrarHelperTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import static org.springframework.test.util.AssertionErrors.assertEquals; - -import com.ctrip.framework.apollo.spring.annotation.ApolloConfigRegistrar; -import java.lang.reflect.Field; -import org.junit.Test; -import org.springframework.util.ReflectionUtils; - -public class ApolloConfigRegistrarHelperTest { - - @Test - public void testHelperLoadingOrder() { - ApolloConfigRegistrar apolloConfigRegistrar = new ApolloConfigRegistrar(); - - Field field = ReflectionUtils.findField(ApolloConfigRegistrar.class, "helper"); - ReflectionUtils.makeAccessible(field); - Object helper = ReflectionUtils.getField(field, apolloConfigRegistrar); - - assertEquals("helper is not TestRegistrarHelper instance", TestRegistrarHelper.class, helper.getClass()); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/ConfigPropertySourcesProcessorHelperTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/ConfigPropertySourcesProcessorHelperTest.java deleted file mode 100644 index a365dec62df..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/ConfigPropertySourcesProcessorHelperTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import static org.springframework.test.util.AssertionErrors.assertEquals; - -import com.ctrip.framework.apollo.spring.config.ConfigPropertySourcesProcessor; -import java.lang.reflect.Field; -import org.junit.Test; -import org.springframework.util.ReflectionUtils; - -public class ConfigPropertySourcesProcessorHelperTest { - - @Test - public void testHelperLoadingOrder() { - ConfigPropertySourcesProcessor processor = new ConfigPropertySourcesProcessor(); - - Field field = ReflectionUtils.findField(ConfigPropertySourcesProcessor.class, "helper"); - ReflectionUtils.makeAccessible(field); - Object helper = ReflectionUtils.getField(field, processor); - - assertEquals("helper is not TestProcessorHelper instance", TestProcessorHelper.class, helper.getClass()); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/TestProcessorHelper.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/TestProcessorHelper.java deleted file mode 100644 index 9f0533846b4..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/TestProcessorHelper.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; - -public class TestProcessorHelper extends DefaultConfigPropertySourcesProcessorHelper { - - @Override - public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) - throws BeansException { - super.postProcessBeanDefinitionRegistry(registry); - } - - @Override - public int getOrder() { - return 0; - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/TestRegistrarHelper.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/TestRegistrarHelper.java deleted file mode 100644 index 3345842fdcd..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/spi/TestRegistrarHelper.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.core.type.AnnotationMetadata; - -public class TestRegistrarHelper extends DefaultApolloConfigRegistrarHelper { - - @Override - public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, - BeanDefinitionRegistry registry) { - super.registerBeanDefinitions(importingClassMetadata, registry); - } - - @Override - public int getOrder() { - return 0; - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/util/BeanRegistrationUtilTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/util/BeanRegistrationUtilTest.java deleted file mode 100644 index 98a3a2e285d..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/spring/util/BeanRegistrationUtilTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2022 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.util; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.support.SimpleBeanDefinitionRegistry; - -@RunWith(MockitoJUnitRunner.class) -public class BeanRegistrationUtilTest { - - @InjectMocks - private BeanRegistrationUtil beanRegistrationUtil; - private BeanDefinitionRegistry someRegistry; - private String someBeanName = "someBean"; - - @Before - public void setUp() { - someRegistry = new SimpleBeanDefinitionRegistry(); - } - - @Test - public void registerBeanDefinitionIfNotExistsTest() { - someRegistry.registerBeanDefinition(someBeanName, Mockito.mock(BeanDefinition.class)); - assertFalse(BeanRegistrationUtil.registerBeanDefinitionIfNotExists(someRegistry, someBeanName, - getClass(), null)); - assertFalse(BeanRegistrationUtil.registerBeanDefinitionIfNotExists(someRegistry, someBeanName, - getClass())); - } - - @Test - public void registerBeanDefinitionIfNotExistsBeanNotPresentTest() { - someRegistry.registerBeanDefinition("someAnotherBean", Mockito.mock(BeanDefinition.class)); - assertTrue(BeanRegistrationUtil.registerBeanDefinitionIfNotExists(someRegistry, someBeanName, - getClass(), null)); - } - - @Test - public void registerBeanDefinitionIfNotExistsWithExtPropTest() { - someRegistry.registerBeanDefinition("someAnotherBean", Mockito.mock(BeanDefinition.class)); - Map extraPropertyValues = new ConcurrentHashMap<>(); - extraPropertyValues.put(someBeanName, "someProperty"); - assertTrue(BeanRegistrationUtil.registerBeanDefinitionIfNotExists(someRegistry, someBeanName, - getClass(), extraPropertyValues)); - } - - @Test - public void registerBeanDefinitionIfNotExistsWithoutBeanNameTest() { - someRegistry.registerBeanDefinition(BeanDefinition.class.getName(), Mockito.mock(BeanDefinition.class)); - assertFalse(BeanRegistrationUtil.registerBeanDefinitionIfNotExists(someRegistry, BeanDefinition.class)); - } - - @Test - public void registerBeanDefinitionIfNotExistsWithoutBeanNameWithExtPropTest() { - Map extraPropertyValues = new ConcurrentHashMap<>(); - extraPropertyValues.put(someBeanName, "someProperty"); - someRegistry.registerBeanDefinition(BeanDefinition.class.getName(), Mockito.mock(BeanDefinition.class)); - assertFalse(BeanRegistrationUtil.registerBeanDefinitionIfNotExists(someRegistry, BeanDefinition.class, - extraPropertyValues)); - } - -} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/ConfigUtilTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/util/ConfigUtilTest.java deleted file mode 100644 index 23a373625fa..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/ConfigUtilTest.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright 2022 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.util; - -import com.ctrip.framework.apollo.core.ConfigConsts; - -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.util.factory.PropertiesFactory; -import java.io.File; -import org.junit.After; -import org.junit.Test; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.spy; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ConfigUtilTest { - - @After - public void tearDown() throws Exception { - System.clearProperty(ConfigConsts.APOLLO_CLUSTER_KEY); - System.clearProperty("apollo.connectTimeout"); - System.clearProperty("apollo.readTimeout"); - System.clearProperty("apollo.refreshInterval"); - System.clearProperty("apollo.loadConfigQPS"); - System.clearProperty("apollo.longPollQPS"); - System.clearProperty("apollo.configCacheSize"); - System.clearProperty("apollo.longPollingInitialDelayInMills"); - System.clearProperty("apollo.autoUpdateInjectedSpringProperties"); - System.clearProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR); - System.clearProperty(PropertiesFactory.APOLLO_PROPERTY_ORDER_ENABLE); - System.clearProperty(ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE); - } - - @Test - public void testApolloCluster() throws Exception { - String someCluster = "someCluster"; - System.setProperty(ConfigConsts.APOLLO_CLUSTER_KEY, someCluster); - - ConfigUtil configUtil = new ConfigUtil(); - - assertEquals(someCluster, configUtil.getCluster()); - } - - @Test - public void testCustomizeConnectTimeout() throws Exception { - int someConnectTimeout = 1; - System.setProperty("apollo.connectTimeout", String.valueOf(someConnectTimeout)); - - ConfigUtil configUtil = new ConfigUtil(); - - assertEquals(someConnectTimeout, configUtil.getConnectTimeout()); - } - - @Test - public void testCustomizeInvalidConnectTimeout() throws Exception { - String someInvalidConnectTimeout = "a"; - System.setProperty("apollo.connectTimeout", someInvalidConnectTimeout); - - ConfigUtil configUtil = new ConfigUtil(); - - assertTrue(configUtil.getConnectTimeout() > 0); - } - - @Test - public void testCustomizeReadTimeout() throws Exception { - int someReadTimeout = 1; - System.setProperty("apollo.readTimeout", String.valueOf(someReadTimeout)); - - ConfigUtil configUtil = new ConfigUtil(); - - assertEquals(someReadTimeout, configUtil.getReadTimeout()); - } - - @Test - public void testCustomizeInvalidReadTimeout() throws Exception { - String someInvalidReadTimeout = "a"; - System.setProperty("apollo.readTimeout", someInvalidReadTimeout); - - ConfigUtil configUtil = new ConfigUtil(); - - assertTrue(configUtil.getReadTimeout() > 0); - } - - @Test - public void testCustomizeRefreshInterval() throws Exception { - int someRefreshInterval = 1; - System.setProperty("apollo.refreshInterval", String.valueOf(someRefreshInterval)); - - ConfigUtil configUtil = new ConfigUtil(); - - assertEquals(someRefreshInterval, configUtil.getRefreshInterval()); - } - - @Test - public void testCustomizeInvalidRefreshInterval() throws Exception { - String someInvalidRefreshInterval = "a"; - System.setProperty("apollo.refreshInterval", someInvalidRefreshInterval); - - ConfigUtil configUtil = new ConfigUtil(); - - assertTrue(configUtil.getRefreshInterval() > 0); - } - - @Test - public void testCustomizeLoadConfigQPS() throws Exception { - int someQPS = 1; - System.setProperty("apollo.loadConfigQPS", String.valueOf(someQPS)); - - ConfigUtil configUtil = new ConfigUtil(); - - assertEquals(someQPS, configUtil.getLoadConfigQPS()); - } - - @Test - public void testCustomizeInvalidLoadConfigQPS() throws Exception { - String someInvalidQPS = "a"; - System.setProperty("apollo.loadConfigQPS", someInvalidQPS); - - ConfigUtil configUtil = new ConfigUtil(); - - assertTrue(configUtil.getLoadConfigQPS() > 0); - } - - @Test - public void testCustomizeLongPollQPS() throws Exception { - int someQPS = 1; - System.setProperty("apollo.longPollQPS", String.valueOf(someQPS)); - - ConfigUtil configUtil = new ConfigUtil(); - - assertEquals(someQPS, configUtil.getLongPollQPS()); - } - - @Test - public void testCustomizeInvalidLongPollQPS() throws Exception { - String someInvalidQPS = "a"; - System.setProperty("apollo.longPollQPS", someInvalidQPS); - - ConfigUtil configUtil = new ConfigUtil(); - - assertTrue(configUtil.getLongPollQPS() > 0); - } - - @Test - public void testCustomizeMaxConfigCacheSize() throws Exception { - long someCacheSize = 1; - System.setProperty("apollo.configCacheSize", String.valueOf(someCacheSize)); - - ConfigUtil configUtil = new ConfigUtil(); - - assertEquals(someCacheSize, configUtil.getMaxConfigCacheSize()); - } - - @Test - public void testCustomizeInvalidMaxConfigCacheSize() throws Exception { - String someInvalidCacheSize = "a"; - System.setProperty("apollo.configCacheSize", someInvalidCacheSize); - - ConfigUtil configUtil = new ConfigUtil(); - - assertTrue(configUtil.getMaxConfigCacheSize() > 0); - } - - @Test - public void testCustomizeLongPollingInitialDelayInMills() throws Exception { - long someLongPollingDelayInMills = 1; - System.setProperty("apollo.longPollingInitialDelayInMills", - String.valueOf(someLongPollingDelayInMills)); - - ConfigUtil configUtil = new ConfigUtil(); - - assertEquals(someLongPollingDelayInMills, configUtil.getLongPollingInitialDelayInMills()); - } - - @Test - public void testCustomizeInvalidLongPollingInitialDelayInMills() throws Exception { - String someInvalidLongPollingDelayInMills = "a"; - System.setProperty("apollo.longPollingInitialDelayInMills", someInvalidLongPollingDelayInMills); - - ConfigUtil configUtil = new ConfigUtil(); - - assertTrue(configUtil.getLongPollingInitialDelayInMills() > 0); - } - - @Test - public void testCustomizeAutoUpdateInjectedSpringProperties() throws Exception { - boolean someAutoUpdateInjectedSpringProperties = false; - System.setProperty("apollo.autoUpdateInjectedSpringProperties", - String.valueOf(someAutoUpdateInjectedSpringProperties)); - - ConfigUtil configUtil = new ConfigUtil(); - - assertEquals(someAutoUpdateInjectedSpringProperties, - configUtil.isAutoUpdateInjectedSpringPropertiesEnabled()); - } - - @Test - public void testLocalCacheDirWithSystemProperty() throws Exception { - String someCacheDir = "someCacheDir"; - String someAppId = "someAppId"; - - System.setProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR, someCacheDir); - - ConfigUtil configUtil = spy(new ConfigUtil()); - - doReturn(someAppId).when(configUtil).getAppId(); - - assertEquals(someCacheDir + File.separator + someAppId, configUtil.getDefaultLocalCacheDir()); - } - - @Test - public void testDefaultLocalCacheDir() throws Exception { - String someAppId = "someAppId"; - - ConfigUtil configUtil = spy(new ConfigUtil()); - - doReturn(someAppId).when(configUtil).getAppId(); - - doReturn(true).when(configUtil).isOSWindows(); - - assertEquals("C:\\opt\\data\\" + someAppId, configUtil.getDefaultLocalCacheDir()); - - doReturn(false).when(configUtil).isOSWindows(); - - assertEquals("/opt/data/" + someAppId, configUtil.getDefaultLocalCacheDir()); - } - - @Test - public void testCustomizePropertiesOrdered() { - boolean propertiesOrdered = true; - System.setProperty(PropertiesFactory.APOLLO_PROPERTY_ORDER_ENABLE, - String.valueOf(propertiesOrdered)); - - ConfigUtil configUtil = new ConfigUtil(); - - assertEquals(propertiesOrdered, - configUtil.isPropertiesOrderEnabled()); - } - - @Test - public void test() { - ConfigUtil configUtil = new ConfigUtil(); - assertFalse(configUtil.isPropertyNamesCacheEnabled()); - - System.setProperty(ApolloClientSystemConsts.APOLLO_PROPERTY_NAMES_CACHE_ENABLE, "true"); - configUtil = new ConfigUtil(); - assertTrue(configUtil.isPropertyNamesCacheEnabled()); - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/ExceptionUtilTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/util/ExceptionUtilTest.java deleted file mode 100644 index 1077c41abe6..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/ExceptionUtilTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2022 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.util; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ExceptionUtilTest { - - @Test - public void testGetDetailMessageWithNoCause() throws Exception { - String someMessage = "some message"; - Throwable ex = new Throwable(someMessage); - assertEquals(someMessage, ExceptionUtil.getDetailMessage(ex)); - } - - @Test - public void testGetDetailMessageWithCauses() throws Exception { - String causeMsg1 = "some cause"; - String causeMsg2 = "another cause"; - String someMessage = "some message"; - - Throwable cause2 = new Throwable(causeMsg2); - Throwable cause1 = new Throwable(causeMsg1, cause2); - Throwable ex = new Throwable(someMessage, cause1); - - String expected = someMessage + " [Cause: " + causeMsg1 + " [Cause: " + causeMsg2 + "]]"; - assertEquals(expected, ExceptionUtil.getDetailMessage(ex)); - } - - @Test - public void testGetDetailMessageWithCauseMessageNull() throws Exception { - String someMessage = "some message"; - Throwable cause = new Throwable(); - Throwable ex = new Throwable(someMessage, cause); - - assertEquals(someMessage, ExceptionUtil.getDetailMessage(ex)); - } - - @Test - public void testGetDetailMessageWithNullMessage() throws Exception { - Throwable ex = new Throwable(); - - assertEquals("", ExceptionUtil.getDetailMessage(ex)); - assertEquals("", ExceptionUtil.getDetailMessage(null)); - - } -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/OrderedPropertiesTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/util/OrderedPropertiesTest.java deleted file mode 100644 index 2d7123c710d..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/OrderedPropertiesTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2022 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.util; - -import static org.junit.Assert.*; - -import java.util.Collection; -import java.util.Enumeration; -import java.util.Properties; -import org.junit.Before; -import org.junit.Test; - -public class OrderedPropertiesTest { - - private OrderedProperties orderedProperties; - - @Before - public void setUp() { - orderedProperties = new OrderedProperties(); - orderedProperties.setProperty("key1", "value1"); - orderedProperties.setProperty("key2", "value2"); - } - - @Test - public void testOrderedPropertiesInvokedAsLegacyProperties() { - Properties legacyProperties = orderedProperties; - assertEquals(orderedProperties.size(), legacyProperties.size()); - - legacyProperties.put("key3", "value3"); - assertEquals(orderedProperties.size(), legacyProperties.size()); - - assertEquals(orderedProperties.getProperty("key3"), legacyProperties.getProperty("key3")); - assertEquals(orderedProperties.get("key3"), legacyProperties.get("key3")); - - assertEquals(orderedProperties.containsKey("key2"), legacyProperties.containsKey("key2")); - assertEquals(orderedProperties.containsValue("key2"), legacyProperties.containsValue("key2")); - assertEquals(orderedProperties.containsValue("value2"), - legacyProperties.containsValue("value2")); - - assertEquals(orderedProperties.entrySet(), legacyProperties.entrySet()); - assertEquals(orderedProperties.keySet(), legacyProperties.keySet()); - - } - - @Test - public void testClear() { - orderedProperties.clear(); - assertEquals(0, orderedProperties.size()); - assertTrue(orderedProperties.isEmpty()); - } - - @Test - public void testClone() { - OrderedProperties clone = (OrderedProperties) orderedProperties.clone(); - - assertNotSame(clone, orderedProperties); - assertEquals(orderedProperties, clone); - } - - @Test - public void testRemove() { - Object value1 = orderedProperties.remove("key1"); - assertEquals("value1", value1); - - value1 = orderedProperties.remove("key1"); - assertNull(value1); - - assertNull(orderedProperties.get("key1")); - assertFalse(orderedProperties.containsKey("key1")); - } - - @Test - public void testValues() { - Collection values = orderedProperties.values(); - assertEquals(2, values.size()); - assertTrue(values.contains("value1")); - assertTrue(values.contains("value2")); - } - - - @Test(expected = NullPointerException.class) - public void testPutNull() { - orderedProperties.put("key3", null); - } - - @Test - public void testPropertyNames() { - Enumeration propertyNames = orderedProperties.propertyNames(); - assertEquals("key1", propertyNames.nextElement()); - assertEquals("key2", propertyNames.nextElement()); - } - - - @Test - public void testKeys() { - Enumeration keys = orderedProperties.keys(); - assertTrue(keys.hasMoreElements()); - assertEquals("key1", keys.nextElement()); - assertTrue(keys.hasMoreElements()); - assertEquals("key2", keys.nextElement()); - - } - -} diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/parser/DateParserTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/util/parser/DateParserTest.java deleted file mode 100644 index 62d47f80d58..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/parser/DateParserTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2022 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.util.parser; - -import static org.junit.Assert.assertEquals; - -import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.Locale; - -import org.junit.Test; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class DateParserTest { - private Parsers.DateParser dateParser = Parsers.forDate(); - - private String shortDateText = "2016-09-28"; - private String mediumDateText = "2016-09-28 15:10:10"; - private String longDateText = "2016-09-28 15:10:10.123"; - - @Test - public void testParseShortFormat() throws Exception { - String format = "yyyy-MM-dd"; - Date expected = assembleDate(2016, 9, 28, 0, 0, 0, 0); - - checkWithFormat(expected, shortDateText, format); - checkWithFormat(expected, mediumDateText, format); - checkWithFormat(expected, longDateText, format); - } - - @Test - public void testParseMediumFormat() throws Exception { - String format = "yyyy-MM-dd HH:mm:ss"; - Date expected = assembleDate(2016, 9, 28, 15, 10, 10, 0); - - checkWithFormat(expected, mediumDateText, format); - checkWithFormat(expected, longDateText, format); - } - - @Test - public void testParseLongFormat() throws Exception { - String format = "yyyy-MM-dd HH:mm:ss.SSS"; - Date expected = assembleDate(2016, 9, 28, 15, 10, 10, 123); - - checkWithFormat(expected, longDateText, format); - } - - @Test - public void testParseWithNoFormat() throws Exception { - Date shortDate = assembleDate(2016, 9, 28, 0, 0, 0, 0); - Date mediumDate = assembleDate(2016, 9, 28, 15, 10, 10, 0); - Date longDate = assembleDate(2016, 9, 28, 15, 10, 10, 123); - - check(shortDate, shortDateText); - check(mediumDate, mediumDateText); - check(longDate, longDateText); - } - - @Test - public void testParseWithFormatAndLocale() throws Exception { - Date someDate = assembleDate(2016, 9, 28, 15, 10, 10, 123); - Locale someLocale = Locale.FRENCH; - String someFormat = "EEE, d MMM yyyy HH:mm:ss.SSS Z"; - SimpleDateFormat someDateFormat = new SimpleDateFormat(someFormat, someLocale); - String dateText = someDateFormat.format(someDate); - - checkWithFormatAndLocale(someDate, dateText, someFormat, someLocale); - } - - @Test(expected = ParserException.class) - public void testParseError() throws Exception { - String someInvalidDate = "someInvalidDate"; - String format = "yyyy-MM-dd"; - - dateParser.parse(someInvalidDate, format); - } - - private void check(Date expected, String text) throws Exception { - assertEquals(expected, dateParser.parse(text)); - } - - private void checkWithFormat(Date expected, String text, String format) throws Exception { - assertEquals(expected, dateParser.parse(text, format)); - } - - private void checkWithFormatAndLocale(Date expected, String text, String format, Locale locale) throws Exception { - assertEquals(expected, dateParser.parse(text, format, locale)); - } - - private Date assembleDate(int year, int month, int day, int hour, int minute, int second, int millisecond) { - Calendar date = Calendar.getInstance(); - date.set(year, month - 1, day, hour, minute, second); //Month in Calendar is 0 based - date.set(Calendar.MILLISECOND, millisecond); - - return date.getTime(); - } -} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/parser/DurationParserTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/util/parser/DurationParserTest.java deleted file mode 100644 index 2cf5a19382d..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/parser/DurationParserTest.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2022 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.util.parser; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class DurationParserTest { - private Parsers.DurationParser durationParser = Parsers.forDuration(); - - @Test - public void testParseMilliSeconds() throws Exception { - String text = "345MS"; - long expected = 345; - - checkParseToMillis(expected, text); - } - - @Test - public void testParseMilliSecondsWithNoSuffix() throws Exception { - String text = "123"; - long expected = 123; - - checkParseToMillis(expected, text); - } - - @Test - public void testParseSeconds() throws Exception { - String text = "20S"; - long expected = 20 * 1000; - - checkParseToMillis(expected, text); - } - - @Test - public void testParseMinutes() throws Exception { - String text = "15M"; - long expected = 15 * 60 * 1000; - - checkParseToMillis(expected, text); - } - - @Test - public void testParseHours() throws Exception { - String text = "10H"; - long expected = 10 * 3600 * 1000; - - checkParseToMillis(expected, text); - } - - @Test - public void testParseDays() throws Exception { - String text = "2D"; - long expected = 2 * 24 * 3600 * 1000; - - checkParseToMillis(expected, text); - } - - @Test - public void testParseFullText() throws Exception { - String text = "2D3H4M5S123MS"; - long expected = 2 * 24 * 3600 * 1000 + 3 * 3600 * 1000 + 4 * 60 * 1000 + 5 * 1000 + 123; - - checkParseToMillis(expected, text); - } - - @Test - public void testParseFullTextWithLowerCase() throws Exception { - String text = "2d3h4m5s123ms"; - long expected = 2 * 24 * 3600 * 1000 + 3 * 3600 * 1000 + 4 * 60 * 1000 + 5 * 1000 + 123; - - checkParseToMillis(expected, text); - } - - @Test - public void testParseFullTextWithNoMS() throws Exception { - String text = "2D3H4M5S123"; - long expected = 2 * 24 * 3600 * 1000 + 3 * 3600 * 1000 + 4 * 60 * 1000 + 5 * 1000 + 123; - - checkParseToMillis(expected, text); - } - - @Test(expected = ParserException.class) - public void testParseException() throws Exception { - String text = "someInvalidText"; - - durationParser.parseToMillis(text); - } - - private void checkParseToMillis(long expected, String text) throws Exception { - assertEquals(expected, durationParser.parseToMillis(text)); - } -} \ No newline at end of file diff --git a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/yaml/YamlParserTest.java b/apollo-client/src/test/java/com/ctrip/framework/apollo/util/yaml/YamlParserTest.java deleted file mode 100644 index b634c25431b..00000000000 --- a/apollo-client/src/test/java/com/ctrip/framework/apollo/util/yaml/YamlParserTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright 2022 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.util.yaml; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.build.MockInjector; -import com.ctrip.framework.apollo.util.OrderedProperties; -import com.ctrip.framework.apollo.util.factory.PropertiesFactory; -import com.google.common.base.Charsets; -import com.google.common.io.Files; -import java.io.File; -import java.io.IOException; -import java.util.Properties; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; -import org.springframework.core.io.ByteArrayResource; -import org.yaml.snakeyaml.constructor.ConstructorException; -import org.yaml.snakeyaml.constructor.DuplicateKeyException; -import org.yaml.snakeyaml.parser.ParserException; - -public class YamlParserTest { - - private YamlParser parser; - - @Before - public void setUp() throws Exception { - parser = new YamlParser(); - } - - @After - public void tearDown() throws Exception { - MockInjector.reset(); - } - - @Test - public void testValidCases() throws Exception { - test("case1.yaml"); - test("case3.yaml"); - test("case4.yaml"); - test("case5.yaml"); - test("case6.yaml"); - test("case7.yaml"); - } - - @Test(expected = DuplicateKeyException.class) - public void testcase2() throws Exception { - testInvalid("case2.yaml"); - } - - @Test(expected = ParserException.class) - public void testcase8() throws Exception { - testInvalid("case8.yaml"); - } - - @Test(expected = ConstructorException.class) - public void testcase9() throws Exception { - testInvalid("case9.yaml"); - } - - @Test - public void testOrderProperties() throws IOException { - String yamlContent = loadYaml("orderedcase.yaml"); - - Properties nonOrderedProperties = parser.yamlToProperties(yamlContent); - - PropertiesFactory propertiesFactory = mock(PropertiesFactory.class); - when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer() { - @Override - public Properties answer(InvocationOnMock invocation) { - return new OrderedProperties(); - } - }); - MockInjector.setInstance(PropertiesFactory.class, propertiesFactory); - - parser = new YamlParser(); - - Properties orderedProperties = parser.yamlToProperties(yamlContent); - - assertTrue(orderedProperties instanceof OrderedProperties); - - checkPropertiesEquals(nonOrderedProperties, orderedProperties); - - String[] propertyNames = orderedProperties.stringPropertyNames().toArray(new String[0]); - - assertEquals("k2", propertyNames[0]); - assertEquals("k4", propertyNames[1]); - assertEquals("k1", propertyNames[2]); - } - - private void test(String caseName) throws Exception { - String yamlContent = loadYaml(caseName); - - check(yamlContent); - } - - private String loadYaml(String caseName) throws IOException { - File file = new File("src/test/resources/yaml/" + caseName); - - return Files.asCharSource(file, Charsets.UTF_8).read(); - } - - private void testInvalid(String caseName) throws Exception { - File file = new File("src/test/resources/yaml/" + caseName); - - String yamlContent = Files.asCharSource(file, Charsets.UTF_8).read(); - - parser.yamlToProperties(yamlContent); - } - - private void check(String yamlContent) { - YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean(); - yamlPropertiesFactoryBean.setResources(new ByteArrayResource(yamlContent.getBytes())); - Properties expected = yamlPropertiesFactoryBean.getObject(); - - Properties actual = parser.yamlToProperties(yamlContent); - - assertTrue("expected: " + expected + " actual: " + actual, checkPropertiesEquals(expected, actual)); - } - - private boolean checkPropertiesEquals(Properties expected, Properties actual) { - if (expected == actual) - return true; - - if (expected.size() != actual.size()) - return false; - - for (Object key : expected.keySet()) { - if (!expected.getProperty((String) key).equals(actual.getProperty((String) key))) { - return false; - } - } - - return true; - } -} diff --git a/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.internals.Injector b/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.internals.Injector deleted file mode 100644 index cf034c4d4fa..00000000000 --- a/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.internals.Injector +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.build.MockInjector \ No newline at end of file diff --git a/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer b/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer deleted file mode 100644 index 42602228c64..00000000000 --- a/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.spi.ApolloInjectorCustomizer +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.build.MockInjector$InjectCustomizer \ No newline at end of file diff --git a/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.spring.spi.ApolloConfigRegistrarHelper b/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.spring.spi.ApolloConfigRegistrarHelper deleted file mode 100644 index b51082c31b6..00000000000 --- a/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.spring.spi.ApolloConfigRegistrarHelper +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.spring.spi.TestRegistrarHelper diff --git a/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.spring.spi.ConfigPropertySourcesProcessorHelper b/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.spring.spi.ConfigPropertySourcesProcessorHelper deleted file mode 100644 index 64d7bb6109e..00000000000 --- a/apollo-client/src/test/resources/META-INF/services/com.ctrip.framework.apollo.spring.spi.ConfigPropertySourcesProcessorHelper +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.spring.spi.TestProcessorHelper diff --git a/apollo-client/src/test/resources/log4j2.xml b/apollo-client/src/test/resources/log4j2.xml deleted file mode 100644 index 477f40615cd..00000000000 --- a/apollo-client/src/test/resources/log4j2.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest1.xml b/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest1.xml deleted file mode 100644 index 6d0b8702818..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest1.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest2.xml b/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest2.xml deleted file mode 100644 index 4736d90b0d1..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest2.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest3.xml b/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest3.xml deleted file mode 100644 index 6a0b7239827..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest3.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest4.xml b/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest4.xml deleted file mode 100644 index d8b49114623..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest4.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest5.xml b/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest5.xml deleted file mode 100644 index fb6d4a7a4c8..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest5.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest6.xml b/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest6.xml deleted file mode 100644 index 1d49785d184..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigAnnotationTest6.xml +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest1.xml b/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest1.xml deleted file mode 100644 index 1174006161c..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest1.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest10.xml b/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest10.xml deleted file mode 100644 index c2e660901df..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest10.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest11.xml b/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest11.xml deleted file mode 100644 index 081ffaf1699..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest11.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest2.xml b/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest2.xml deleted file mode 100644 index 39bc1d58493..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest2.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest3.xml b/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest3.xml deleted file mode 100644 index eeb6e0fd846..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest3.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest4.xml b/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest4.xml deleted file mode 100644 index a9e5ff03642..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest4.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest5.xml b/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest5.xml deleted file mode 100644 index 1e6d6fa18f6..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest5.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest6.xml b/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest6.xml deleted file mode 100644 index cbd5ab40aec..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest6.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest7.xml b/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest7.xml deleted file mode 100644 index 58f0bb6272a..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest7.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest8.xml b/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest8.xml deleted file mode 100644 index 77c3a2802fb..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest8.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest9.xml b/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest9.xml deleted file mode 100644 index 47a31533cd3..00000000000 --- a/apollo-client/src/test/resources/spring/XmlConfigPlaceholderTest9.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/config.namespace.placeholder.with.default.value.xml b/apollo-client/src/test/resources/spring/config.namespace.placeholder.with.default.value.xml deleted file mode 100644 index 3ff4a2374e9..00000000000 --- a/apollo-client/src/test/resources/spring/config.namespace.placeholder.with.default.value.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/config.namespace.placeholder.xml b/apollo-client/src/test/resources/spring/config.namespace.placeholder.xml deleted file mode 100644 index 1e25ca82cdf..00000000000 --- a/apollo-client/src/test/resources/spring/config.namespace.placeholder.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - diff --git a/apollo-client/src/test/resources/spring/yaml/case1-new.yaml b/apollo-client/src/test/resources/spring/yaml/case1-new.yaml deleted file mode 100644 index d0427e56b4f..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case1-new.yaml +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright 2022 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. -# -timeout: 1001 -batch: 2001 diff --git a/apollo-client/src/test/resources/spring/yaml/case1.yaml b/apollo-client/src/test/resources/spring/yaml/case1.yaml deleted file mode 100644 index 84719bbd5f6..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case1.yaml +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright 2022 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. -# -timeout: 1000 -batch: 2000 diff --git a/apollo-client/src/test/resources/spring/yaml/case2-new.yml b/apollo-client/src/test/resources/spring/yaml/case2-new.yml deleted file mode 100644 index 9377025e989..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case2-new.yml +++ /dev/null @@ -1,16 +0,0 @@ -# -# Copyright 2022 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. -# -batch: 2001 diff --git a/apollo-client/src/test/resources/spring/yaml/case2.yml b/apollo-client/src/test/resources/spring/yaml/case2.yml deleted file mode 100644 index 72c1078acf2..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case2.yml +++ /dev/null @@ -1,16 +0,0 @@ -# -# Copyright 2022 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. -# -batch: 2000 diff --git a/apollo-client/src/test/resources/spring/yaml/case3-new.yaml b/apollo-client/src/test/resources/spring/yaml/case3-new.yaml deleted file mode 100644 index d0427e56b4f..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case3-new.yaml +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright 2022 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. -# -timeout: 1001 -batch: 2001 diff --git a/apollo-client/src/test/resources/spring/yaml/case3.yaml b/apollo-client/src/test/resources/spring/yaml/case3.yaml deleted file mode 100644 index f25be7b525c..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case3.yaml +++ /dev/null @@ -1,16 +0,0 @@ -# -# Copyright 2022 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. -# -timeout: 1000 diff --git a/apollo-client/src/test/resources/spring/yaml/case4-new.yaml b/apollo-client/src/test/resources/spring/yaml/case4-new.yaml deleted file mode 100644 index f3943a83517..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case4-new.yaml +++ /dev/null @@ -1,15 +0,0 @@ -# -# Copyright 2022 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. -# diff --git a/apollo-client/src/test/resources/spring/yaml/case4.yaml b/apollo-client/src/test/resources/spring/yaml/case4.yaml deleted file mode 100644 index 84719bbd5f6..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case4.yaml +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright 2022 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. -# -timeout: 1000 -batch: 2000 diff --git a/apollo-client/src/test/resources/spring/yaml/case5-new.yaml b/apollo-client/src/test/resources/spring/yaml/case5-new.yaml deleted file mode 100644 index b4162fd79b8..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case5-new.yaml +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright 2022 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. -# -timeout: 1001 -batch: newBatch diff --git a/apollo-client/src/test/resources/spring/yaml/case5.yaml b/apollo-client/src/test/resources/spring/yaml/case5.yaml deleted file mode 100644 index 84719bbd5f6..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case5.yaml +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright 2022 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. -# -timeout: 1000 -batch: 2000 diff --git a/apollo-client/src/test/resources/spring/yaml/case6.yml b/apollo-client/src/test/resources/spring/yaml/case6.yml deleted file mode 100644 index 0db1ff1cc63..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case6.yml +++ /dev/null @@ -1,16 +0,0 @@ -# -# Copyright 2022 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. -# -apollo.test.testBean: true diff --git a/apollo-client/src/test/resources/spring/yaml/case7.yml b/apollo-client/src/test/resources/spring/yaml/case7.yml deleted file mode 100644 index 36dbe22ba36..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case7.yml +++ /dev/null @@ -1,16 +0,0 @@ -# -# Copyright 2022 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. -# -apollo.test.testBean:false diff --git a/apollo-client/src/test/resources/spring/yaml/case8.yml b/apollo-client/src/test/resources/spring/yaml/case8.yml deleted file mode 100644 index f3943a83517..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case8.yml +++ /dev/null @@ -1,15 +0,0 @@ -# -# Copyright 2022 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. -# diff --git a/apollo-client/src/test/resources/spring/yaml/case9-new.yml b/apollo-client/src/test/resources/spring/yaml/case9-new.yml deleted file mode 100644 index 3f5ac3a9a09..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case9-new.yml +++ /dev/null @@ -1,16 +0,0 @@ -# -# Copyright 2022 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. -# -someKey: anotherValue diff --git a/apollo-client/src/test/resources/spring/yaml/case9.yml b/apollo-client/src/test/resources/spring/yaml/case9.yml deleted file mode 100644 index 440e3976620..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/case9.yml +++ /dev/null @@ -1,16 +0,0 @@ -# -# Copyright 2022 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. -# -someKey: someValue diff --git a/apollo-client/src/test/resources/spring/yaml/resolve.from.self.yml b/apollo-client/src/test/resources/spring/yaml/resolve.from.self.yml deleted file mode 100644 index ff0705f4bcb..00000000000 --- a/apollo-client/src/test/resources/spring/yaml/resolve.from.self.yml +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright 2022 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. -# -# value must as same as file name -i.can.resolve.from.self: resolve.from.self.yml \ No newline at end of file diff --git a/apollo-client/src/test/resources/yaml/case1.yaml b/apollo-client/src/test/resources/yaml/case1.yaml deleted file mode 100644 index c45fa7f5e2b..00000000000 --- a/apollo-client/src/test/resources/yaml/case1.yaml +++ /dev/null @@ -1,40 +0,0 @@ -# -# Copyright 2022 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. -# -root: - key1: "someValue" - key2: 100 - key3: - key4: - key5: '(%sender%) %message%' - key6: '* %sender% %message%' -# commented: "xxx" - list: - - 'item 1' - - 'item 2' - intList: - - 100 - - 200 - listOfMap: - - key: '#mychannel' - value: '' - - key: '#myprivatechannel' - value: 'mypassword' - listOfList: - - - 'a1' - - 'a2' - - - 'b1' - - 'b2' - listOfList2: [ ['a1', 'a2'], ['b1', 'b2'] ] diff --git a/apollo-client/src/test/resources/yaml/case2.yaml b/apollo-client/src/test/resources/yaml/case2.yaml deleted file mode 100644 index 67c8ba171bb..00000000000 --- a/apollo-client/src/test/resources/yaml/case2.yaml +++ /dev/null @@ -1,19 +0,0 @@ -# -# Copyright 2022 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. -# -root: - key1: "someValue" - key2: 100 - key1: "anotherValue" diff --git a/apollo-client/src/test/resources/yaml/case3.yaml b/apollo-client/src/test/resources/yaml/case3.yaml deleted file mode 100644 index 5621abdb042..00000000000 --- a/apollo-client/src/test/resources/yaml/case3.yaml +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright 2022 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. -# -root: -key1: "someValue" -key2: 100 diff --git a/apollo-client/src/test/resources/yaml/case4.yaml b/apollo-client/src/test/resources/yaml/case4.yaml deleted file mode 100644 index a85bbd5598a..00000000000 --- a/apollo-client/src/test/resources/yaml/case4.yaml +++ /dev/null @@ -1,163 +0,0 @@ -# -# Copyright 2022 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. -# ---- # document start - -# Comments in YAML look like this. - -################ -# SCALAR TYPES # -################ - -# Our root object (which continues for the entire document) will be a map, -# which is equivalent to a dictionary, hash or object in other languages. -key: value -another_key: Another value goes here. -a_number_value: 100 -scientific_notation: 1e+12 -# The number 1 will be interpreted as a number, not a boolean. if you want -# it to be interpreted as a boolean, use true -boolean: true -null_value: null -key with spaces: value -# Notice that strings don't need to be quoted. However, they can be. -however: 'A string, enclosed in quotes.' -'Keys can be quoted too.': "Useful if you want to put a ':' in your key." -single quotes: 'have ''one'' escape pattern' -double quotes: "have many: \", \0, \t, \u263A, \x0d\x0a == \r\n, and more." - -# Multiple-line strings can be written either as a 'literal block' (using |), -# or a 'folded block' (using '>'). -literal_block: | - This entire block of text will be the value of the 'literal_block' key, - with line breaks being preserved. - - The literal continues until de-dented, and the leading indentation is - stripped. - - Any lines that are 'more-indented' keep the rest of their indentation - - these lines will be indented by 4 spaces. -folded_style: > - This entire block of text will be the value of 'folded_style', but this - time, all newlines will be replaced with a single space. - - Blank lines, like above, are converted to a newline character. - - 'More-indented' lines keep their newlines, too - - this text will appear over two lines. - -#################### -# COLLECTION TYPES # -#################### - -# Nesting uses indentation. 2 space indent is preferred (but not required). -a_nested_map: - key: value - another_key: Another Value - another_nested_map: - hello: hello - -# Maps don't have to have string keys. -0.25: a float key - -# Keys can also be complex, like multi-line objects -# We use ? followed by a space to indicate the start of a complex key. -? | - This is a key - that has multiple lines -: and this is its value - -# YAML also allows mapping between sequences with the complex key syntax -# Some language parsers might complain -# An example -? - Manchester United - - Real Madrid -: [2001-01-01, 2002-02-02] - -# Sequences (equivalent to lists or arrays) look like this -# (note that the '-' counts as indentation): -a_sequence: - - Item 1 - - Item 2 - - 0.5 # sequences can contain disparate types. - - Item 4 - - key: value - another_key: another_value - - - - This is a sequence - - inside another sequence - - - - Nested sequence indicators - - can be collapsed - -# Since YAML is a superset of JSON, you can also write JSON-style maps and -# sequences: -json_map: {"key": "value"} -json_seq: [3, 2, 1, "takeoff"] -and quotes are optional: {key: [3, 2, 1, takeoff]} - -####################### -# EXTRA YAML FEATURES # -####################### - -# YAML also has a handy feature called 'anchors', which let you easily duplicate -# content across your document. Both of these keys will have the same value: -anchored_content: &anchor_name This string will appear as the value of two keys. -other_anchor: *anchor_name - -# Anchors can be used to duplicate/inherit properties -base: &base - name: Everyone has same name - -# The regexp << is called Merge Key Language-Independent Type. It is used to -# indicate that all the keys of one or more specified maps should be inserted -# into the current map. - -foo: &foo - <<: *base - age: 10 - -bar: &bar - <<: *base - age: 20 - -# foo and bar would also have name: Everyone has same name - -# YAML also has tags, which you can use to explicitly declare types. -explicit_string: !!str 0.5 - -#################### -# EXTRA YAML TYPES # -#################### - -# Strings and numbers aren't the only scalars that YAML can understand. -# ISO-formatted date and datetime literals are also parsed. -datetime: 2001-12-15T02:59:43.1Z -datetime_with_spaces: 2001-12-14 21:59:43.10 -5 -date: 2002-12-14 - -# YAML also has a set type, which looks like this: -set: - ? item1 - ? item2 - ? item3 -or: {item1, item2, item3} - -# Sets are just maps with null values; the above is equivalent to: -set2: - item1: null - item2: null - item3: null - -... # document end diff --git a/apollo-client/src/test/resources/yaml/case5.yaml b/apollo-client/src/test/resources/yaml/case5.yaml deleted file mode 100644 index 18001294318..00000000000 --- a/apollo-client/src/test/resources/yaml/case5.yaml +++ /dev/null @@ -1,57 +0,0 @@ -# -# Copyright 2022 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. -# ---- -- Ada -- APL -- ASP - -- Assembly -- Awk ---- -- Basic ---- -- C -- C# # Note that comments are denoted with ' #' (space and #). -- C++ -- Cold Fusion - -- - - HTML - - LaTeX - - SGML - - VRML - - XML - - YAML -- - - BSD - - GNU Hurd - - Linux - -- 1.1 -- - 2.1 - - 2.2 -- - - 3.1 - - 3.2 - - 3.3 - -- name: PyYAML - status: 4 - license: MIT - language: Python -- name: PySyck - status: 5 - license: BSD - language: Python diff --git a/apollo-client/src/test/resources/yaml/case6.yaml b/apollo-client/src/test/resources/yaml/case6.yaml deleted file mode 100644 index b1f00dbcf21..00000000000 --- a/apollo-client/src/test/resources/yaml/case6.yaml +++ /dev/null @@ -1,51 +0,0 @@ -# -# Copyright 2022 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. -# -left hand: -- Ring of Teleportation -- Ring of Speed - -right hand: -- Ring of Resist Fire -- Ring of Resist Cold -- Ring of Resist Poison -base armor class: 0 -base damage: [4,4] -plus to-hit: 12 -plus to-dam: 16 -plus to-ac: 0 -hero: - hp: 34 - sp: 8 - level: 4 -orc: - hp: 12 - sp: 0 - level: 2 - -plain: Scroll of Remove Curse -single-quoted: 'EASY_KNOW' -double-quoted: "?" -literal: | # Borrowed from http://www.kersbergen.com/flump/religion.html - by hjw ___ - __ /.-.\ - / )_____________\\ Y - /_ /=== == === === =\ _\_ - ( /)=== == === === == Y \ - `-------------------( o ) - \___/ -folded: > - It removes all ordinary curses from all equipped items. - Heavy or permanent curses are unaffected. diff --git a/apollo-client/src/test/resources/yaml/case7.yaml b/apollo-client/src/test/resources/yaml/case7.yaml deleted file mode 100644 index 1450dc1ffd7..00000000000 --- a/apollo-client/src/test/resources/yaml/case7.yaml +++ /dev/null @@ -1,16 +0,0 @@ -# -# Copyright 2022 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. -# -xxx diff --git a/apollo-client/src/test/resources/yaml/case8.yaml b/apollo-client/src/test/resources/yaml/case8.yaml deleted file mode 100644 index 1ded3269de9..00000000000 --- a/apollo-client/src/test/resources/yaml/case8.yaml +++ /dev/null @@ -1,16 +0,0 @@ -# -# Copyright 2022 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. -# -, diff --git a/apollo-client/src/test/resources/yaml/case9.yaml b/apollo-client/src/test/resources/yaml/case9.yaml deleted file mode 100644 index e2c07d55ccd..00000000000 --- a/apollo-client/src/test/resources/yaml/case9.yaml +++ /dev/null @@ -1,20 +0,0 @@ -# -# Copyright 2022 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. -# -!!javax.script.ScriptEngineManager [ - !!java.net.URLClassLoader [[ - !!java.net.URL ["http://localhost"] - ]] -] \ No newline at end of file diff --git a/apollo-client/src/test/resources/yaml/orderedcase.yaml b/apollo-client/src/test/resources/yaml/orderedcase.yaml deleted file mode 100644 index 98e2850b63f..00000000000 --- a/apollo-client/src/test/resources/yaml/orderedcase.yaml +++ /dev/null @@ -1,18 +0,0 @@ -# -# Copyright 2022 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. -# -k2: "someValue" -k4: "anotherValue" -k1: "yetAnotherValue" \ No newline at end of file diff --git a/apollo-core/pom.xml b/apollo-core/pom.xml deleted file mode 100644 index b82ac72e78d..00000000000 --- a/apollo-core/pom.xml +++ /dev/null @@ -1,75 +0,0 @@ - - - - - com.ctrip.framework.apollo - apollo - ${revision} - ../pom.xml - - 4.0.0 - apollo-core - Apollo Core - jar - - ${project.artifactId} - - - - com.dianping.cat - cat-client - true - - - - com.google.code.gson - gson - - - - - com.google.guava - guava - - - - - org.slf4j - slf4j-api - - - - - org.eclipse.jetty - jetty-server - test - - - org.apache.logging.log4j - log4j-slf4j-impl - test - - - org.apache.logging.log4j - log4j-core - test - - - - diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/Apollo.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/Apollo.java deleted file mode 100644 index 46fdc7a55b4..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/Apollo.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2022 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; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class Apollo { - public final static String VERSION = - "java-" + Apollo.class.getPackage().getImplementationVersion(); -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ApolloClientSystemConsts.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ApolloClientSystemConsts.java deleted file mode 100644 index 0fa0550a52b..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ApolloClientSystemConsts.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright 2022 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; - -/** - * @author vdisk - */ -public class ApolloClientSystemConsts { - - /** - * apollo client app id - */ - public static final String APP_ID = "app.id"; - - /** - * apollo client app label - */ - public static final String APOLLO_LABEL = "apollo.label"; - - /** - * apollo client app id environment variables - */ - public static final String APP_ID_ENVIRONMENT_VARIABLES = "APP_ID"; - - /** - * apollo client app label environment variables - */ - public static final String APOLLO_LABEL_ENVIRONMENT_VARIABLES = "APOLLO_LABEL"; - - /** - * cluster name - */ - public static final String APOLLO_CLUSTER = ConfigConsts.APOLLO_CLUSTER_KEY; - - /** - * cluster name environment variables - */ - public static final String APOLLO_CLUSTER_ENVIRONMENT_VARIABLES = "APOLLO_CLUSTER"; - - /** - * local cache directory - */ - public static final String APOLLO_CACHE_DIR = "apollo.cache-dir"; - - /** - * local cache directory - */ - @Deprecated - public static final String DEPRECATED_APOLLO_CACHE_DIR = "apollo.cacheDir"; - - /** - * local cache directory environment variables - */ - public static final String APOLLO_CACHE_DIR_ENVIRONMENT_VARIABLES = "APOLLO_CACHE_DIR"; - - /** - * local cache directory environment variables - */ - @Deprecated - public static final String DEPRECATED_APOLLO_CACHE_DIR_ENVIRONMENT_VARIABLES = "APOLLO_CACHEDIR"; - - /** - * apollo client access key - */ - public static final String APOLLO_ACCESS_KEY_SECRET = "apollo.access-key.secret"; - - /** - * apollo client access key - */ - @Deprecated - public static final String DEPRECATED_APOLLO_ACCESS_KEY_SECRET = "apollo.accesskey.secret"; - - /** - * apollo client access key environment variables - */ - public static final String APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES = "APOLLO_ACCESS_KEY_SECRET"; - - /** - * apollo client access key environment variables - */ - @Deprecated - public static final String DEPRECATED_APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES = "APOLLO_ACCESSKEY_SECRET"; - - /** - * apollo meta server address - */ - public static final String APOLLO_META = ConfigConsts.APOLLO_META_KEY; - - /** - * apollo meta server address environment variables - */ - public static final String APOLLO_META_ENVIRONMENT_VARIABLES = "APOLLO_META"; - - /** - * apollo config service address - */ - public static final String APOLLO_CONFIG_SERVICE = "apollo.config-service"; - - /** - * apollo config service address - */ - @Deprecated - public static final String DEPRECATED_APOLLO_CONFIG_SERVICE = "apollo.configService"; - - /** - * apollo config service address environment variables - */ - public static final String APOLLO_CONFIG_SERVICE_ENVIRONMENT_VARIABLES = "APOLLO_CONFIG_SERVICE"; - - /** - * apollo config service address environment variables - */ - @Deprecated - public static final String DEPRECATED_APOLLO_CONFIG_SERVICE_ENVIRONMENT_VARIABLES = "APOLLO_CONFIGSERVICE"; - - /** - * enable property order - */ - public static final String APOLLO_PROPERTY_ORDER_ENABLE = "apollo.property.order.enable"; - - /** - * enable property order environment variables - */ - public static final String APOLLO_PROPERTY_ORDER_ENABLE_ENVIRONMENT_VARIABLES = "APOLLO_PROPERTY_ORDER_ENABLE"; - - /** - * enable property names cache - */ - public static final String APOLLO_PROPERTY_NAMES_CACHE_ENABLE = "apollo.property.names.cache.enable"; - - /** - * enable property names cache environment variables - */ - public static final String APOLLO_PROPERTY_NAMES_CACHE_ENABLE_ENVIRONMENT_VARIABLES = "APOLLO_PROPERTY_NAMES_CACHE_ENABLE"; - - /** - * enable property names cache - */ - public static final String APOLLO_CACHE_FILE_ENABLE = "apollo.cache.file.enable"; - - /** - * enable property names cache environment variables - */ - public static final String APOLLO_CACHE_FILE_ENABLE_ENVIRONMENT_VARIABLES = "APOLLO_CACHE_FILE_ENABLE"; - - /** - * enable apollo overrideSystemProperties - */ - public static final String APOLLO_OVERRIDE_SYSTEM_PROPERTIES = "apollo.override-system-properties"; -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ConfigConsts.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ConfigConsts.java deleted file mode 100644 index a6108dfb942..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ConfigConsts.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2022 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; - -public interface ConfigConsts { - String NAMESPACE_APPLICATION = "application"; - String CLUSTER_NAME_DEFAULT = "default"; - String CLUSTER_NAMESPACE_SEPARATOR = "+"; - String APOLLO_CLUSTER_KEY = "apollo.cluster"; - String APOLLO_META_KEY = "apollo.meta"; - String CONFIG_FILE_CONTENT_KEY = "content"; - String NO_APPID_PLACEHOLDER = "ApolloNoAppIdPlaceHolder"; - long NOTIFICATION_ID_PLACEHOLDER = -1; -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/MetaDomainConsts.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/MetaDomainConsts.java deleted file mode 100644 index c678898318d..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/MetaDomainConsts.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.core.enums.Env; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import com.ctrip.framework.apollo.core.spi.Ordered; -import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; -import org.slf4j.Logger; - -import com.ctrip.framework.apollo.core.spi.MetaServerProvider; -import com.ctrip.framework.apollo.core.utils.ApolloThreadFactory; -import com.ctrip.framework.apollo.core.utils.NetUtil; -import com.ctrip.framework.apollo.tracer.Tracer; -import com.ctrip.framework.apollo.tracer.spi.Transaction; -import com.ctrip.framework.foundation.internals.ServiceBootstrap; -import com.google.common.base.Strings; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -/** - * The meta domain will try to load the meta server address from MetaServerProviders, the default - * ones are: - * - *
    - *
  • com.ctrip.framework.apollo.core.internals.LegacyMetaServerProvider
  • - *
- *

- * If no provider could provide the meta server url, the default meta url will be used(http://apollo.meta). - *
- *

- * 3rd party MetaServerProvider could be injected by typical Java Service Loader pattern. - * - * @see com.ctrip.framework.apollo.core.internals.LegacyMetaServerProvider - */ -public class MetaDomainConsts { - - public static final String DEFAULT_META_URL = "http://apollo.meta"; - - // env -> meta server address cache - private static final Map metaServerAddressCache = Maps.newConcurrentMap(); - private static volatile List metaServerProviders = null; - - private static final long REFRESH_INTERVAL_IN_SECOND = 60;// 1 min - private static final Logger logger = DeferredLoggerFactory.getLogger(MetaDomainConsts.class); - // comma separated meta server address -> selected single meta server address cache - private static final Map selectedMetaServerAddressCache = Maps.newConcurrentMap(); - private static final AtomicBoolean periodicRefreshStarted = new AtomicBoolean(false); - - private static final Object LOCK = new Object(); - - /** - * Return one meta server address. If multiple meta server addresses are configured, will select - * one. - */ - public static String getDomain(Env env) { - String metaServerAddress = getMetaServerAddress(env); - // if there is more than one address, need to select one - if (metaServerAddress.contains(",")) { - return selectMetaServerAddress(metaServerAddress); - } - return metaServerAddress; - } - - /** - * Return meta server address. If multiple meta server addresses are configured, will return the - * comma separated string. - */ - public static String getMetaServerAddress(Env env) { - if (!metaServerAddressCache.containsKey(env)) { - initMetaServerAddress(env); - } - - return metaServerAddressCache.get(env); - } - - private static void initMetaServerAddress(Env env) { - if (metaServerProviders == null) { - synchronized (LOCK) { - if (metaServerProviders == null) { - metaServerProviders = initMetaServerProviders(); - } - } - } - - String metaAddress = null; - - for (MetaServerProvider provider : metaServerProviders) { - metaAddress = provider.getMetaServerAddress(env); - if (!Strings.isNullOrEmpty(metaAddress)) { - logger.info("Located meta server address {} for env {} from {}", metaAddress, env, - provider.getClass().getName()); - break; - } - } - - if (Strings.isNullOrEmpty(metaAddress)) { - // Fallback to default meta address - metaAddress = DEFAULT_META_URL; - logger.warn( - "Meta server address fallback to {} for env {}, because it is not available in all MetaServerProviders", - metaAddress, env); - } - - metaServerAddressCache.put(env, metaAddress.trim()); - } - - private static List initMetaServerProviders() { - Iterator metaServerProviderIterator = ServiceBootstrap - .loadAll(MetaServerProvider.class); - - List metaServerProviders = Lists.newArrayList(metaServerProviderIterator); - - // the smaller order has higher priority - metaServerProviders.sort(Comparator.comparingInt(Ordered::getOrder)); - - return metaServerProviders; - } - - /** - * Select one available meta server from the comma separated meta server addresses, e.g. - * http://1.2.3.4:8080,http://2.3.4.5:8080 - *

- *
- *

- * In production environment, we still suggest using one single domain like - * http://config.xxx.com(backed by software load balancers like nginx) instead of multiple ip - * addresses - */ - private static String selectMetaServerAddress(String metaServerAddresses) { - String metaAddressSelected = selectedMetaServerAddressCache.get(metaServerAddresses); - if (metaAddressSelected == null) { - // initialize - if (periodicRefreshStarted.compareAndSet(false, true)) { - schedulePeriodicRefresh(); - } - updateMetaServerAddresses(metaServerAddresses); - metaAddressSelected = selectedMetaServerAddressCache.get(metaServerAddresses); - } - - return metaAddressSelected; - } - - private static void updateMetaServerAddresses(String metaServerAddresses) { - logger.debug("Selecting meta server address for: {}", metaServerAddresses); - - Transaction transaction = Tracer - .newTransaction("Apollo.MetaService", "refreshMetaServerAddress"); - transaction.addData("Url", metaServerAddresses); - - try { - List metaServers = Lists.newArrayList(metaServerAddresses.split(",")); - // random load balancing - Collections.shuffle(metaServers); - - boolean serverAvailable = false; - - for (String address : metaServers) { - address = address.trim(); - //check whether /services/config is accessible - if (NetUtil.pingUrl(address + "/services/config")) { - // select the first available meta server - selectedMetaServerAddressCache.put(metaServerAddresses, address); - serverAvailable = true; - logger.debug("Selected meta server address {} for {}", address, metaServerAddresses); - break; - } - } - - // we need to make sure the map is not empty, e.g. the first update might be failed - if (!selectedMetaServerAddressCache.containsKey(metaServerAddresses)) { - selectedMetaServerAddressCache.put(metaServerAddresses, metaServers.get(0).trim()); - } - - if (!serverAvailable) { - logger.warn( - "Could not find available meta server for configured meta server addresses: {}, fallback to: {}", - metaServerAddresses, selectedMetaServerAddressCache.get(metaServerAddresses)); - } - - transaction.setStatus(Transaction.SUCCESS); - } catch (Throwable ex) { - transaction.setStatus(ex); - throw ex; - } finally { - transaction.complete(); - } - } - - private static void schedulePeriodicRefresh() { - ScheduledExecutorService scheduledExecutorService = - Executors.newScheduledThreadPool(1, ApolloThreadFactory.create("MetaServiceLocator", true)); - - scheduledExecutorService.scheduleAtFixedRate(new Runnable() { - @Override - public void run() { - try { - for (String metaServerAddresses : selectedMetaServerAddressCache.keySet()) { - updateMetaServerAddresses(metaServerAddresses); - } - } catch (Throwable ex) { - logger - .warn(String.format("Refreshing meta server address failed, will retry in %d seconds", - REFRESH_INTERVAL_IN_SECOND), ex); - } - } - }, REFRESH_INTERVAL_IN_SECOND, REFRESH_INTERVAL_IN_SECOND, TimeUnit.SECONDS); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ServiceNameConsts.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ServiceNameConsts.java deleted file mode 100644 index 9e2b1a11237..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/ServiceNameConsts.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2022 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; - -public interface ServiceNameConsts { - - String APOLLO_METASERVICE = "apollo-metaservice"; - - String APOLLO_CONFIGSERVICE = "apollo-configservice"; - - String APOLLO_ADMINSERVICE = "apollo-adminservice"; - - String APOLLO_PORTAL = "apollo-portal"; -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/dto/ApolloConfig.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/dto/ApolloConfig.java deleted file mode 100644 index 6ae5584fe87..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/dto/ApolloConfig.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2022 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; - -import java.util.Map; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ApolloConfig { - - private String appId; - - private String cluster; - - private String namespaceName; - - private Map configurations; - - private String releaseKey; - - public ApolloConfig() { - } - - public ApolloConfig(String appId, - String cluster, - String namespaceName, - String releaseKey) { - this.appId = appId; - this.cluster = cluster; - this.namespaceName = namespaceName; - this.releaseKey = releaseKey; - } - - public String getAppId() { - return appId; - } - - public String getCluster() { - return cluster; - } - - public String getNamespaceName() { - return namespaceName; - } - - public String getReleaseKey() { - return releaseKey; - } - - public Map getConfigurations() { - return configurations; - } - - public void setAppId(String appId) { - this.appId = appId; - } - - public void setCluster(String cluster) { - this.cluster = cluster; - } - - public void setNamespaceName(String namespaceName) { - this.namespaceName = namespaceName; - } - - public void setReleaseKey(String releaseKey) { - this.releaseKey = releaseKey; - } - - public void setConfigurations(Map configurations) { - this.configurations = configurations; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("ApolloConfig{"); - sb.append("appId='").append(appId).append('\''); - sb.append(", cluster='").append(cluster).append('\''); - sb.append(", namespaceName='").append(namespaceName).append('\''); - sb.append(", configurations=").append(configurations); - sb.append(", releaseKey='").append(releaseKey).append('\''); - sb.append('}'); - return sb.toString(); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/dto/ApolloConfigNotification.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/dto/ApolloConfigNotification.java deleted file mode 100644 index aaaa444757a..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/dto/ApolloConfigNotification.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2022 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(song_s@ctrip.com) - */ -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 + - '}'; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/dto/ApolloNotificationMessages.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/dto/ApolloNotificationMessages.java deleted file mode 100644 index 0e1967a5155..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/dto/ApolloNotificationMessages.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2022 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; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; - -import java.util.Map; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ApolloNotificationMessages { - private Map details; - - public ApolloNotificationMessages() { - this(Maps.newTreeMap()); - } - - private ApolloNotificationMessages(Map details) { - this.details = details; - } - - public void put(String key, long notificationId) { - details.put(key, notificationId); - } - - public Long get(String key) { - return this.details.get(key); - } - - public boolean has(String key) { - return this.details.containsKey(key); - } - - public boolean isEmpty() { - return this.details.isEmpty(); - } - - public Map getDetails() { - return details; - } - - public void setDetails(Map details) { - this.details = details; - } - - public void mergeFrom(ApolloNotificationMessages source) { - if (source == null) { - return; - } - - for (Map.Entry entry : source.getDetails().entrySet()) { - //to make sure the notification id always grows bigger - if (this.has(entry.getKey()) && - this.get(entry.getKey()) >= entry.getValue()) { - continue; - } - this.put(entry.getKey(), entry.getValue()); - } - } - - public ApolloNotificationMessages clone() { - return new ApolloNotificationMessages(ImmutableMap.copyOf(this.details)); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/dto/ServiceDTO.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/dto/ServiceDTO.java deleted file mode 100644 index e0d625c96ac..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/dto/ServiceDTO.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2022 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; - -public class ServiceDTO { - - private String appName; - - private String instanceId; - - private String homepageUrl; - - public String getAppName() { - return appName; - } - - public String getHomepageUrl() { - return homepageUrl; - } - - public String getInstanceId() { - return instanceId; - } - - public void setAppName(String appName) { - this.appName = appName; - } - - public void setHomepageUrl(String homepageUrl) { - this.homepageUrl = homepageUrl; - } - - public void setInstanceId(String instanceId) { - this.instanceId = instanceId; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("ServiceDTO{"); - sb.append("appName='").append(appName).append('\''); - sb.append(", instanceId='").append(instanceId).append('\''); - sb.append(", homepageUrl='").append(homepageUrl).append('\''); - sb.append('}'); - return sb.toString(); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/enums/ConfigFileFormat.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/enums/ConfigFileFormat.java deleted file mode 100644 index 8a445739a9a..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/enums/ConfigFileFormat.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2022 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.enums; - -import com.ctrip.framework.apollo.core.utils.StringUtils; -import java.util.stream.Stream; - -/** - * This enum represents all the possible Configuration file formats apollo currently supports. - *

- * Currently the following formats are supported: - *

    - *
  • {@link ConfigFileFormat#Properties}
  • - *
  • {@link ConfigFileFormat#XML}
  • - *
  • {@link ConfigFileFormat#JSON}
  • - *
  • {@link ConfigFileFormat#YML}
  • - *
  • {@link ConfigFileFormat#YAML}
  • - *
  • {@link ConfigFileFormat#TXT}
  • - *
- * - * @author Jason Song(song_s@ctrip.com) - * @author Diego Krupitza(info@diegokrupitza.com) - */ -public enum ConfigFileFormat { - Properties("properties"), XML("xml"), JSON("json"), YML("yml"), YAML("yaml"), TXT("txt"); - - private final String value; - - ConfigFileFormat(String value) { - this.value = value; - } - - /** - * Cleans a given configFilename so it does not contain leading or trailing spaces and is always - * lowercase. - *

- * For example: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
BeforeAfter
"Properties ""properties"
" """
- * - * @param configFileName the name we want to clean - * @return the cleansed configFileName - */ - private static String getWellFormedName(String configFileName) { - if (StringUtils.isBlank(configFileName)) { - return ""; - } - return configFileName.trim().toLowerCase(); - } - - /** - * Transforms a given string to its matching {@link ConfigFileFormat}. - * - * @param value the string that matches - * @return the matching {@link ConfigFileFormat} - * @throws IllegalArgumentException in case the value is empty or there is no - * matching {@link ConfigFileFormat} - */ - public static ConfigFileFormat fromString(String value) { - if (StringUtils.isEmpty(value)) { - throw new IllegalArgumentException("value can not be empty"); - } - - final String cleansedName = getWellFormedName(value); - - return Stream.of(ConfigFileFormat.values()) - .filter(item -> cleansedName.equalsIgnoreCase(item.getValue())) - .findFirst() - .orElseThrow(() -> new IllegalArgumentException(value + " can not map enum")); - } - - /** - * Checks if a given string is a valid {@link ConfigFileFormat}. - * - * @param value the string to check on - * @return is it a valid format - */ - public static boolean isValidFormat(String value) { - try { - fromString(value); - return true; - } catch (IllegalArgumentException e) { - return false; - } - } - - /** - * Checks whether a given {@link ConfigFileFormat} is compatible with {@link - * ConfigFileFormat#Properties} - * - * @param format the format to check its compatibility - * @return is it compatible with {@link ConfigFileFormat#Properties} - */ - public static boolean isPropertiesCompatible(ConfigFileFormat format) { - return format == YAML || format == YML || format == Properties; - } - - /** - * @return The string representation of the given {@link ConfigFileFormat} - */ - public String getValue() { - return value; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/enums/Env.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/enums/Env.java deleted file mode 100644 index 71a682e51a4..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/enums/Env.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2022 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.enums; - -import com.google.common.base.Preconditions; - -/** - * Here is the brief description for all the predefined environments: - *

    - *
  • LOCAL: Local Development environment, assume you are working at the beach with no network access
  • - *
  • DEV: Development environment
  • - *
  • FWS: Feature Web Service Test environment
  • - *
  • FAT: Feature Acceptance Test environment
  • - *
  • UAT: User Acceptance Test environment
  • - *
  • LPT: Load and Performance Test environment
  • - *
  • PRO: Production environment
  • - *
  • TOOLS: Tooling environment, a special area in production environment which allows - * access to test environment, e.g. Apollo Portal should be deployed in tools environment
  • - *
- * - * @author Jason Song(song_s@ctrip.com) - */ -public enum Env{ - LOCAL, DEV, FWS, FAT, UAT, LPT, PRO, TOOLS, UNKNOWN; - - public static Env fromString(String env) { - Env environment = EnvUtils.transformEnv(env); - Preconditions.checkArgument(environment != UNKNOWN, String.format("Env %s is invalid", env)); - return environment; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/enums/EnvUtils.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/enums/EnvUtils.java deleted file mode 100644 index 87f23f1b7ba..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/enums/EnvUtils.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright 2022 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.enums; - -import com.ctrip.framework.apollo.core.utils.StringUtils; - -/** - * A utility class for the {@link Env} enum. - *

- * The class provides simple functionalities that extend the capabilities of {@link Env} - * - * @author Diego Krupitza(info@diegokrupitza.com) - */ -public final class EnvUtils { - - /** - * Transforms a given String to its matching {@link Env} - * - * @param envName the String to convert - * @return the matching {@link Env} for the given String - */ - public static Env transformEnv(String envName) { - if (StringUtils.isBlank(envName)) { - return Env.UNKNOWN; - } - - String cleanedEnvName = envName.trim().toUpperCase(); - - // fix up in case there is a typo - // like prod/pro - if (cleanedEnvName.equals("PROD")) { - return Env.PRO; - } - - if (cleanedEnvName.equals("FWS")) { - // special case that FAT & FWS - // should return the same - return Env.FAT; - } - - try { - return Env.valueOf(cleanedEnvName); - } catch (IllegalArgumentException e) { - // the name could not be found - // or there is a typo we dont handle - return Env.UNKNOWN; - } - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProvider.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProvider.java deleted file mode 100644 index 7004b543594..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProvider.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2022 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.internals; - -import com.ctrip.framework.apollo.core.enums.Env; -import com.ctrip.framework.apollo.core.spi.MetaServerProvider; -import com.ctrip.framework.apollo.core.utils.ResourceUtils; -import com.google.common.base.Strings; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -/** - * For legacy meta server configuration use, i.e. apollo-env.properties - */ -public class LegacyMetaServerProvider implements MetaServerProvider { - - // make it as lowest as possible, yet not the lowest - public static final int ORDER = MetaServerProvider.LOWEST_PRECEDENCE - 1; - private static final Map domains = new HashMap<>(); - - public LegacyMetaServerProvider() { - initialize(); - } - - private void initialize() { - Properties prop = new Properties(); - prop = ResourceUtils.readConfigFile("apollo-env.properties", prop); - - domains.put(Env.LOCAL, getMetaServerAddress(prop, "local_meta", "local.meta")); - domains.put(Env.DEV, getMetaServerAddress(prop, "dev_meta", "dev.meta")); - domains.put(Env.FAT, getMetaServerAddress(prop, "fat_meta", "fat.meta")); - domains.put(Env.UAT, getMetaServerAddress(prop, "uat_meta", "uat.meta")); - domains.put(Env.LPT, getMetaServerAddress(prop, "lpt_meta", "lpt.meta")); - domains.put(Env.PRO, getMetaServerAddress(prop, "pro_meta", "pro.meta")); - } - - private String getMetaServerAddress(Properties prop, String sourceName, String propName) { - // 1. Get from System Property. - String metaAddress = System.getProperty(sourceName); - if (Strings.isNullOrEmpty(metaAddress)) { - // 2. Get from OS environment variable, which could not contain dot and is normally in UPPER case,like DEV_META. - metaAddress = System.getenv(sourceName.toUpperCase()); - } - if (Strings.isNullOrEmpty(metaAddress)) { - // 3. Get from properties file. - metaAddress = prop.getProperty(propName); - } - return metaAddress; - } - - @Override - public String getMetaServerAddress(Env targetEnv) { - String metaServerAddress = domains.get(targetEnv); - return metaServerAddress == null ? null : metaServerAddress.trim(); - } - - @Override - public int getOrder() { - return ORDER; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/schedule/ExponentialSchedulePolicy.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/schedule/ExponentialSchedulePolicy.java deleted file mode 100644 index 4cdf9faf252..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/schedule/ExponentialSchedulePolicy.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2022 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.schedule; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ExponentialSchedulePolicy implements SchedulePolicy { - private final long delayTimeLowerBound; - private final long delayTimeUpperBound; - private long lastDelayTime; - - public ExponentialSchedulePolicy(long delayTimeLowerBound, long delayTimeUpperBound) { - this.delayTimeLowerBound = delayTimeLowerBound; - this.delayTimeUpperBound = delayTimeUpperBound; - } - - @Override - public long fail() { - long delayTime = lastDelayTime; - - if (delayTime == 0) { - delayTime = delayTimeLowerBound; - } else { - delayTime = Math.min(lastDelayTime << 1, delayTimeUpperBound); - } - - lastDelayTime = delayTime; - - return delayTime; - } - - @Override - public void success() { - lastDelayTime = 0; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/schedule/SchedulePolicy.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/schedule/SchedulePolicy.java deleted file mode 100644 index baba0d5f791..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/schedule/SchedulePolicy.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2022 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.schedule; - -/** - * Schedule policy - * @author Jason Song(song_s@ctrip.com) - */ -public interface SchedulePolicy { - long fail(); - - void success(); -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/signature/HmacSha1Utils.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/signature/HmacSha1Utils.java deleted file mode 100644 index 8689e399458..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/signature/HmacSha1Utils.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2022 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.signature; - -import com.google.common.io.BaseEncoding; -import java.io.UnsupportedEncodingException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -/** - * @author nisiyong - */ -public class HmacSha1Utils { - - private static final String ALGORITHM_NAME = "HmacSHA1"; - private static final String ENCODING = "UTF-8"; - - public static String signString(String stringToSign, String accessKeySecret) { - try { - Mac mac = Mac.getInstance(ALGORITHM_NAME); - mac.init(new SecretKeySpec( - accessKeySecret.getBytes(ENCODING), - ALGORITHM_NAME - )); - byte[] signData = mac.doFinal(stringToSign.getBytes(ENCODING)); - return BaseEncoding.base64().encode(signData); - } catch (NoSuchAlgorithmException | UnsupportedEncodingException | InvalidKeyException e) { - throw new IllegalArgumentException(e.toString()); - } - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/signature/Signature.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/signature/Signature.java deleted file mode 100644 index 2c9924234c8..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/signature/Signature.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2022 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.signature; - -import com.google.common.collect.Maps; -import com.google.common.net.HttpHeaders; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Map; - -/** - * @author nisiyong - */ -public class Signature { - - /** - * Authorization=Apollo {appId}:{sign} - */ - private static final String AUTHORIZATION_FORMAT = "Apollo %s:%s"; - private static final String DELIMITER = "\n"; - - public static final String HTTP_HEADER_TIMESTAMP = "Timestamp"; - - public static String signature(String timestamp, String pathWithQuery, String secret) { - String stringToSign = timestamp + DELIMITER + pathWithQuery; - return HmacSha1Utils.signString(stringToSign, secret); - } - - public static Map buildHttpHeaders(String url, String appId, String secret) { - long currentTimeMillis = System.currentTimeMillis(); - String timestamp = String.valueOf(currentTimeMillis); - - String pathWithQuery = url2PathWithQuery(url); - String signature = signature(timestamp, pathWithQuery, secret); - - Map headers = Maps.newHashMap(); - headers.put(HttpHeaders.AUTHORIZATION, String.format(AUTHORIZATION_FORMAT, appId, signature)); - headers.put(HTTP_HEADER_TIMESTAMP, timestamp); - return headers; - } - - private static String url2PathWithQuery(String urlString) { - try { - URL url = new URL(urlString); - String path = url.getPath(); - String query = url.getQuery(); - - String pathWithQuery = path; - if (query != null && query.length() > 0) { - pathWithQuery += "?" + query; - } - return pathWithQuery; - } catch (MalformedURLException e) { - throw new IllegalArgumentException("Invalid url pattern: " + urlString, e); - } - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/spi/MetaServerProvider.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/spi/MetaServerProvider.java deleted file mode 100644 index 44e3d94e643..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/spi/MetaServerProvider.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import com.ctrip.framework.apollo.core.enums.Env; - -/** - * @since 1.0.0 - */ -public interface MetaServerProvider extends Ordered { - - /** - * Provide the Apollo meta server address, could be a domain url or comma separated ip addresses, like http://1.2.3.4:8080,http://2.3.4.5:8080. - *
- * In production environment, we suggest using one single domain like http://config.xxx.com(backed by software load balancers like nginx) instead of multiple ip addresses - */ - String getMetaServerAddress(Env targetEnv); -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/spi/Ordered.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/spi/Ordered.java deleted file mode 100644 index 40950c305d9..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/spi/Ordered.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2022 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.spi; - -/** - * {@code Ordered} is an interface that can be implemented by objects that - * should be orderable, for example in a {@code Collection}. - * - *

The actual {@link #getOrder() order} can be interpreted as prioritization, - * with the first object (with the lowest order value) having the highest - * priority. - * - * @since 1.0.0 - */ -public interface Ordered { - /** - * Useful constant for the highest precedence value. - * @see java.lang.Integer#MIN_VALUE - */ - int HIGHEST_PRECEDENCE = Integer.MIN_VALUE; - - /** - * Useful constant for the lowest precedence value. - * @see java.lang.Integer#MAX_VALUE - */ - int LOWEST_PRECEDENCE = Integer.MAX_VALUE; - - - /** - * Get the order value of this object. - *

Higher values are interpreted as lower priority. As a consequence, - * the object with the lowest value has the highest priority (somewhat - * analogous to Servlet {@code load-on-startup} values). - *

Same order values will result in arbitrary sort positions for the - * affected objects. - * @return the order value - * @see #HIGHEST_PRECEDENCE - * @see #LOWEST_PRECEDENCE - */ - int getOrder(); -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ApolloThreadFactory.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ApolloThreadFactory.java deleted file mode 100644 index c4e67a79ee8..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ApolloThreadFactory.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -public class ApolloThreadFactory implements ThreadFactory { - private static Logger log = LoggerFactory.getLogger(ApolloThreadFactory.class); - - private final AtomicLong threadNumber = new AtomicLong(1); - - private final String namePrefix; - - private final boolean daemon; - - private static final ThreadGroup threadGroup = new ThreadGroup("Apollo"); - - public static ThreadGroup getThreadGroup() { - return threadGroup; - } - - public static ThreadFactory create(String namePrefix, boolean daemon) { - return new ApolloThreadFactory(namePrefix, daemon); - } - - public static boolean waitAllShutdown(int timeoutInMillis) { - ThreadGroup group = getThreadGroup(); - Thread[] activeThreads = new Thread[group.activeCount()]; - group.enumerate(activeThreads); - Set alives = new HashSet<>(Arrays.asList(activeThreads)); - Set dies = new HashSet<>(); - log.info("Current ACTIVE thread count is: {}", alives.size()); - long expire = System.currentTimeMillis() + timeoutInMillis; - while (System.currentTimeMillis() < expire) { - classify(alives, dies, new ClassifyStandard() { - @Override - public boolean satisfy(Thread thread) { - return !thread.isAlive() || thread.isInterrupted() || thread.isDaemon(); - } - }); - if (alives.size() > 0) { - log.info("Alive apollo threads: {}", alives); - try { - TimeUnit.SECONDS.sleep(2); - } catch (InterruptedException ex) { - // ignore - } - } else { - log.info("All apollo threads are shutdown."); - return true; - } - } - log.warn("Some apollo threads are still alive but expire time has reached, alive threads: {}", - alives); - return false; - } - - private interface ClassifyStandard { - boolean satisfy(T thread); - } - - private static void classify(Set src, Set des, ClassifyStandard standard) { - Set set = new HashSet<>(); - for (T t : src) { - if (standard.satisfy(t)) { - set.add(t); - } - } - src.removeAll(set); - des.addAll(set); - } - - private ApolloThreadFactory(String namePrefix, boolean daemon) { - this.namePrefix = namePrefix; - this.daemon = daemon; - } - - public Thread newThread(Runnable runnable) { - Thread thread = new Thread(threadGroup, runnable,// - threadGroup.getName() + "-" + namePrefix + "-" + threadNumber.getAndIncrement()); - thread.setDaemon(daemon); - if (thread.getPriority() != Thread.NORM_PRIORITY) { - thread.setPriority(Thread.NORM_PRIORITY); - } - return thread; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ByteUtil.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ByteUtil.java deleted file mode 100644 index fe4530b92c5..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ByteUtil.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2022 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.utils; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ByteUtil { - private static final char[] HEX_CHARS = new char[] { - '0', '1', '2', '3', '4', '5', '6', '7', - '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; - - public static byte int3(final int x) { - return (byte) (x >> 24); - } - - public static byte int2(final int x) { - return (byte) (x >> 16); - } - - public static byte int1(final int x) { - return (byte) (x >> 8); - } - - public static byte int0(final int x) { - return (byte) (x); - } - - public static String toHexString(byte[] bytes) { - char[] chars = new char[bytes.length * 2]; - int i = 0; - for (byte b : bytes) { - chars[i++] = HEX_CHARS[b >> 4 & 0xF]; - chars[i++] = HEX_CHARS[b & 0xF]; - } - return new String(chars); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ClassLoaderUtil.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ClassLoaderUtil.java deleted file mode 100644 index 2528e482360..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ClassLoaderUtil.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import com.google.common.base.Strings; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.net.URL; -import java.net.URLDecoder; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ClassLoaderUtil { - private static final Logger logger = LoggerFactory.getLogger(ClassLoaderUtil.class); - - private static ClassLoader loader = Thread.currentThread().getContextClassLoader(); - private static String classPath = ""; - - static { - if (loader == null) { - logger.warn("Using system class loader"); - loader = ClassLoader.getSystemClassLoader(); - } - - try { - URL url = loader.getResource(""); - // get class path - if (url != null) { - classPath = url.getPath(); - classPath = URLDecoder.decode(classPath, "utf-8"); - } - - // 如果是jar包内的,则返回当前路径 - if (Strings.isNullOrEmpty(classPath) || classPath.contains(".jar!")) { - classPath = System.getProperty("user.dir"); - } - } catch (Throwable ex) { - classPath = System.getProperty("user.dir"); - logger.warn("Failed to locate class path, fallback to user.dir: {}", classPath, ex); - } - } - - public static ClassLoader getLoader() { - return loader; - } - - public static String getClassPath() { - return classPath; - } - - public static boolean isClassPresent(String className) { - try { - Class.forName(className); - return true; - } catch (ClassNotFoundException ex) { - // ignore expected exception - return false; - } catch (LinkageError ex) { - // unexpected error, need to let the user know the actual error - logger.error("Failed to load class: {}", className, ex); - return false; - } - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DNSUtil.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DNSUtil.java deleted file mode 100644 index 9abada200c1..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DNSUtil.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.List; - -public class DNSUtil { - - public static List resolve(String domainName) throws UnknownHostException { - List result = new ArrayList<>(); - - InetAddress[] addresses = InetAddress.getAllByName(domainName); - if (addresses != null) { - for (InetAddress addr : addresses) { - result.add(addr.getHostAddress()); - } - } - - return result; - } - -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DeferredLogCache.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DeferredLogCache.java deleted file mode 100644 index 7ebd74e7268..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DeferredLogCache.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import com.google.common.cache.Cache; -import com.google.common.cache.CacheBuilder; -import org.slf4j.Logger; -import org.slf4j.event.Level; - -import java.util.concurrent.atomic.AtomicInteger; - -/** - * Delayed log printing utility class, used only for logging when Apollo is initialized - * - * @author kl (http://kailing.pub) - * @since 2021/5/11 - */ -final class DeferredLogCache { - - public static final int MAX_LOG_SIZE = 1000; - private static final AtomicInteger LOG_INDEX = new AtomicInteger(0); - private static final Cache LOG_CACHE = CacheBuilder.newBuilder() - .maximumSize(MAX_LOG_SIZE) - .build(); - - private DeferredLogCache() { - } - - - public static void debug(Logger logger, String message, Throwable throwable) { - add(logger, Level.DEBUG, message, null, throwable); - } - - public static void debug(Logger logger, String message, Object... objects) { - add(logger, Level.DEBUG, message, objects, null); - } - - public static void info(Logger logger, String message, Throwable throwable) { - add(logger, Level.INFO, message, null, throwable); - } - - public static void info(Logger logger, String message, Object... objects) { - add(logger, Level.INFO, message, objects, null); - } - - public static void warn(Logger logger, String message, Object... objects) { - add(logger, Level.WARN, message, objects, null); - } - - public static void warn(Logger logger, String message, Throwable throwable) { - add(logger, Level.WARN, message, null, throwable); - } - - - public static void error(Logger logger, String message, Throwable throwable) { - add(logger, Level.ERROR, message, null, throwable); - } - - public static void error(Logger logger, String message, Object... objects) { - add(logger, Level.ERROR, message, objects, null); - } - - private static void add(Logger logger, Level level, String message, Object[] objects, - Throwable throwable) { - Line logLine = new Line(level, message, objects, throwable, logger); - LOG_CACHE.put(LOG_INDEX.incrementAndGet(), logLine); - } - - static void replayTo() { - for (int i = 1; i <= LOG_INDEX.get(); i++) { - Line logLine = LOG_CACHE.getIfPresent(i); - if (logLine == null) { - continue; - } - Logger logger = logLine.getLogger(); - Level level = logLine.getLevel(); - String message = logLine.getMessage(); - Object[] objects = logLine.getObjects(); - Throwable throwable = logLine.getThrowable(); - logTo(logger, level, message, objects, throwable); - } - clear(); - } - - static void clear() { - LOG_CACHE.invalidateAll(); - LOG_INDEX.set(0); - } - - static long logSize() { - return LOG_CACHE.size(); - } - - static void logTo(Logger logger, Level level, String message, Object[] objects, - Throwable throwable) { - switch (level) { - case DEBUG: - if (throwable != null) { - logger.debug(message, throwable); - } else { - logger.debug(message, objects); - } - return; - case INFO: - if (throwable != null) { - logger.info(message, throwable); - } else { - logger.info(message, objects); - } - return; - case WARN: - if (throwable != null) { - logger.warn(message, throwable); - } else { - logger.warn(message, objects); - } - return; - case ERROR: - if (throwable != null) { - logger.error(message, throwable); - } else { - logger.error(message, objects); - } - break; - default: - throw new IllegalStateException("Unexpected value: " + level); - } - } - - private static class Line { - - private final Level level; - - private final String message; - - private final Object[] objects; - - private final Throwable throwable; - - private final Logger logger; - - Line(Level level, String message, Object[] objects, Throwable throwable, Logger logger) { - this.level = level; - this.message = message; - this.objects = objects; - this.throwable = throwable; - this.logger = logger; - } - - public Object[] getObjects() { - return objects; - } - - public Logger getLogger() { - return logger; - } - - Level getLevel() { - return this.level; - } - - String getMessage() { - return this.message; - } - - Throwable getThrowable() { - return this.throwable; - } - - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DeferredLogger.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DeferredLogger.java deleted file mode 100644 index 8f7c7e2fffa..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DeferredLogger.java +++ /dev/null @@ -1,464 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import java.util.concurrent.atomic.AtomicInteger; -import org.slf4j.Logger; -import org.slf4j.Marker; - -/** - * Only the following methods implement the delayed log function - *

- *  public void debug(String s);
- *  public void debug(String s, Object o);
- *  public void debug(String s, Object... objects);
- *  public void debug(String s, Object o, Object o1);
- *  public void debug(String s, Throwable throwable);
- *  public void info(String s);
- *  public void info(String s, Object o);
- *  public void info(String s, Object... objects);
- *  public void info(String s, Object o, Object o1);
- *  public void info(String s, Throwable throwable);
- *  public void warn(String s);
- *  public void warn(String s, Object o);
- *  public void warn(String s, Object... objects);
- *  public void warn(String s, Object o, Object o1);
- *  public void warn(String s, Throwable throwable)
- *  public void error(String s);
- *  public void error(String s, Object o);
- *  public void error(String s, Object o, Object o1);
- *  public void error(String s, Object... objects);
- *  public void error(String s, Throwable throwable);
- * 
- * - * @author kl (http://kailing.pub) - * @since 2021/5/19 - */ -public class DeferredLogger implements Logger { - - private final Logger logger; - /** - * Delay the opening state of the log -1: Uninitialized 0: Disable 1: Enabled - */ - private static final AtomicInteger state = new AtomicInteger(-1); - - public static void enable() { - state.compareAndSet(-1, 1); - } - - public static void disable() { - state.set(0); - } - - public static boolean isEnabled() { - return state.get() == 1; - } - - public static void replayTo() { - disable(); - DeferredLogCache.replayTo(); - } - - public DeferredLogger(Logger logger) { - this.logger = logger; - } - - @Override - public String getName() { - return logger.getName(); - } - - @Override - public boolean isTraceEnabled() { - return logger.isTraceEnabled(); - } - - @Override - public void trace(String s) { - logger.trace(s); - } - - @Override - public void trace(String s, Object o) { - logger.trace(s, o); - } - - @Override - public void trace(String s, Object o, Object o1) { - logger.trace(s, o, o1); - } - - @Override - public void trace(String s, Object... objects) { - logger.trace(s, objects); - } - - @Override - public void trace(String s, Throwable throwable) { - logger.trace(s, throwable); - } - - @Override - public boolean isTraceEnabled(Marker marker) { - return logger.isTraceEnabled(marker); - } - - @Override - public void trace(Marker marker, String s) { - logger.trace(marker, s); - } - - @Override - public void trace(Marker marker, String s, Object o) { - logger.trace(marker, s, o); - } - - @Override - public void trace(Marker marker, String s, Object o, Object o1) { - logger.trace(marker, s, o, o1); - } - - @Override - public void trace(Marker marker, String s, Object... objects) { - logger.trace(marker, s, objects); - } - - @Override - public void trace(Marker marker, String s, Throwable throwable) { - logger.trace(marker, s, throwable); - } - - @Override - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } - - @Override - public void debug(String s) { - if (isEnabled()) { - DeferredLogCache.debug(logger, s); - } else { - logger.debug(s); - } - } - - @Override - public void debug(String s, Object o) { - if (isEnabled()) { - DeferredLogCache.debug(logger, s, o); - } else { - logger.debug(s, o); - } - } - - @Override - public void debug(String s, Object o, Object o1) { - if (isEnabled()) { - DeferredLogCache.debug(logger, s, o, o1); - } else { - logger.debug(s, o, o1); - } - } - - @Override - public void debug(String s, Object... objects) { - if (isEnabled()) { - DeferredLogCache.debug(logger, s, objects); - } else { - logger.debug(s, objects); - } - } - - @Override - public void debug(String s, Throwable throwable) { - if (isEnabled()) { - DeferredLogCache.debug(logger, s, throwable); - } else { - logger.debug(s, throwable); - } - } - - @Override - public boolean isDebugEnabled(Marker marker) { - return logger.isDebugEnabled(marker); - } - - @Override - public void debug(Marker marker, String s) { - logger.debug(marker, s); - } - - @Override - public void debug(Marker marker, String s, Object o) { - logger.debug(marker, s, o); - } - - @Override - public void debug(Marker marker, String s, Object o, Object o1) { - logger.debug(marker, s, o, o1); - } - - @Override - public void debug(Marker marker, String s, Object... objects) { - logger.debug(marker, s, objects); - } - - @Override - public void debug(Marker marker, String s, Throwable throwable) { - logger.debug(marker, s, throwable); - } - - @Override - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } - - @Override - public void info(String s) { - if (isEnabled()) { - DeferredLogCache.info(logger, s); - } else { - logger.info(s); - } - } - - @Override - public void info(String s, Object o) { - if (isEnabled()) { - DeferredLogCache.info(logger, s, o); - } else { - logger.info(s, o); - } - } - - @Override - public void info(String s, Object o, Object o1) { - if (isEnabled()) { - DeferredLogCache.info(logger, s, o, o1); - } else { - logger.info(s, o, o1); - } - } - - @Override - public void info(String s, Object... objects) { - if (isEnabled()) { - DeferredLogCache.info(logger, s, objects); - } else { - logger.info(s, objects); - } - } - - @Override - public void info(String s, Throwable throwable) { - if (isEnabled()) { - DeferredLogCache.info(logger, s, throwable); - } else { - logger.info(s, throwable); - } - } - - @Override - public boolean isInfoEnabled(Marker marker) { - return logger.isInfoEnabled(marker); - } - - @Override - public void info(Marker marker, String s) { - logger.info(marker, s); - } - - @Override - public void info(Marker marker, String s, Object o) { - logger.info(marker, s, o); - } - - @Override - public void info(Marker marker, String s, Object o, Object o1) { - logger.info(marker, s, o, o1); - } - - @Override - public void info(Marker marker, String s, Object... objects) { - logger.info(marker, s, objects); - } - - @Override - public void info(Marker marker, String s, Throwable throwable) { - logger.info(marker, s, throwable); - } - - @Override - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } - - @Override - public void warn(String s) { - if (isEnabled()) { - DeferredLogCache.warn(logger, s); - } else { - logger.warn(s); - } - } - - @Override - public void warn(String s, Object o) { - if (isEnabled()) { - DeferredLogCache.warn(logger, s, o); - } else { - logger.warn(s, o); - } - } - - @Override - public void warn(String s, Object... objects) { - if (isEnabled()) { - DeferredLogCache.warn(logger, s, objects); - } else { - logger.warn(s, objects); - } - } - - @Override - public void warn(String s, Object o, Object o1) { - if (isEnabled()) { - DeferredLogCache.warn(logger, s, o, o1); - } else { - logger.warn(s, o, o1); - } - } - - @Override - public void warn(String s, Throwable throwable) { - if (isEnabled()) { - DeferredLogCache.warn(logger, s, throwable); - } else { - logger.warn(s, throwable); - } - } - - @Override - public boolean isWarnEnabled(Marker marker) { - return logger.isWarnEnabled(marker); - } - - @Override - public void warn(Marker marker, String s) { - logger.warn(marker, s); - } - - @Override - public void warn(Marker marker, String s, Object o) { - logger.warn(marker, s, o); - } - - @Override - public void warn(Marker marker, String s, Object o, Object o1) { - logger.warn(marker, s, o, o1); - } - - @Override - public void warn(Marker marker, String s, Object... objects) { - logger.warn(marker, s, objects); - } - - @Override - public void warn(Marker marker, String s, Throwable throwable) { - logger.warn(marker, s, throwable); - } - - @Override - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); - } - - @Override - public void error(String s) { - if (isEnabled()) { - DeferredLogCache.error(logger, s); - } else { - logger.error(s); - } - } - - @Override - public void error(String s, Object o) { - if (isEnabled()) { - DeferredLogCache.error(logger, s, o); - } else { - logger.error(s, o); - } - } - - @Override - public void error(String s, Object o, Object o1) { - if (isEnabled()) { - DeferredLogCache.error(logger, s, o, o1); - } else { - logger.error(s, o, o1); - } - } - - @Override - public void error(String s, Object... objects) { - if (isEnabled()) { - DeferredLogCache.error(logger, s, objects); - } else { - logger.error(s, objects); - } - } - - @Override - public void error(String s, Throwable throwable) { - if (isEnabled()) { - DeferredLogCache.error(logger, s, throwable); - } else { - logger.error(s, throwable); - } - } - - @Override - public boolean isErrorEnabled(Marker marker) { - return logger.isErrorEnabled(marker); - } - - @Override - public void error(Marker marker, String s) { - logger.error(marker, s); - } - - @Override - public void error(Marker marker, String s, Object o) { - logger.error(marker, s, o); - } - - @Override - public void error(Marker marker, String s, Object o, Object o1) { - logger.error(marker, s, o, o1); - } - - @Override - public void error(Marker marker, String s, Object... objects) { - logger.error(marker, s, objects); - } - - @Override - public void error(Marker marker, String s, Throwable throwable) { - logger.error(marker, s, throwable); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DeferredLoggerFactory.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DeferredLoggerFactory.java deleted file mode 100644 index 3a3c6a56f63..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DeferredLoggerFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author kl (http://kailing.pub) - * @since 2021/5/19 - */ -public class DeferredLoggerFactory { - - private DeferredLoggerFactory() { - } - - public static Logger getLogger(Class clazz) { - Logger logger = LoggerFactory.getLogger(clazz); - return new DeferredLogger(logger); - } - - public static Logger getLogger(String name) { - Logger logger = LoggerFactory.getLogger(name); - return new DeferredLogger(logger); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DeprecatedPropertyNotifyUtil.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DeprecatedPropertyNotifyUtil.java deleted file mode 100644 index d39fbeeda4a..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/DeprecatedPropertyNotifyUtil.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import org.slf4j.Logger; - -/** - * @author vdisk - */ -public class DeprecatedPropertyNotifyUtil { - - private static final Logger log = DeferredLoggerFactory - .getLogger(DeprecatedPropertyNotifyUtil.class); - - public static void warn(String deprecatedProperty, String insteadProperty) { - log.warn("[{}] is deprecated since 1.9.0 and will be removed in a future version, please use the [{}] instead.", deprecatedProperty, insteadProperty); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/MachineUtil.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/MachineUtil.java deleted file mode 100644 index f356eae1942..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/MachineUtil.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.net.NetworkInterface; -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; -import java.security.SecureRandom; -import java.util.Enumeration; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class MachineUtil { - private static final Logger logger = LoggerFactory.getLogger(MachineUtil.class); - private static final int MACHINE_IDENTIFIER = createMachineIdentifier(); - - public static int getMachineIdentifier() { - return MACHINE_IDENTIFIER; - } - - /** - * Get the machine identifier from mac address - * - * @see ObjectId.java - */ - private static int createMachineIdentifier() { - // build a 2-byte machine piece based on NICs info - int machinePiece; - try { - StringBuilder sb = new StringBuilder(); - Enumeration e = NetworkInterface.getNetworkInterfaces(); - - if (e != null){ - while (e.hasMoreElements()) { - NetworkInterface ni = e.nextElement(); - sb.append(ni.toString()); - byte[] mac = ni.getHardwareAddress(); - if (mac != null) { - ByteBuffer bb = ByteBuffer.wrap(mac); - try { - sb.append(bb.getChar()); - sb.append(bb.getChar()); - sb.append(bb.getChar()); - } catch (BufferUnderflowException shortHardwareAddressException) { //NOPMD - // mac with less than 6 bytes. continue - } - } - } - } - - machinePiece = sb.toString().hashCode(); - } catch (Throwable ex) { - // exception sometimes happens with IBM JVM, use random - machinePiece = (new SecureRandom().nextInt()); - logger.warn( - "Failed to get machine identifier from network interface, using random number instead", - ex); - } - return machinePiece; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/NetUtil.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/NetUtil.java deleted file mode 100644 index 4142b13b823..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/NetUtil.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import com.google.common.io.CharStreams; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; - -/** - * Created by gl49 on 2018/6/8. - */ -public class NetUtil { - - private static final int DEFAULT_TIMEOUT_IN_SECONDS = 5000; - - /** - * ping the url, return true if ping ok, false otherwise - */ - public static boolean pingUrl(String address) { - try { - URL urlObj = new URL(address); - HttpURLConnection connection = (HttpURLConnection) urlObj.openConnection(); - connection.setRequestMethod("GET"); - connection.setUseCaches(false); - connection.setConnectTimeout(DEFAULT_TIMEOUT_IN_SECONDS); - connection.setReadTimeout(DEFAULT_TIMEOUT_IN_SECONDS); - int statusCode = connection.getResponseCode(); - cleanUpConnection(connection); - return (200 <= statusCode && statusCode <= 399); - } catch (Throwable ignore) { - } - return false; - } - - /** - * according to https://docs.oracle.com/javase/7/docs/technotes/guides/net/http-keepalive.html, we should clean up the - * connection by reading the response body so that the connection could be reused. - */ - private static void cleanUpConnection(HttpURLConnection conn) { - InputStreamReader isr = null; - InputStreamReader esr = null; - try { - isr = new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8); - CharStreams.toString(isr); - } catch (IOException e) { - InputStream errorStream = conn.getErrorStream(); - - if (errorStream != null) { - esr = new InputStreamReader(errorStream, StandardCharsets.UTF_8); - try { - CharStreams.toString(esr); - } catch (IOException ioe) { - //ignore - } - } - } finally { - if (isr != null) { - try { - isr.close(); - } catch (IOException ex) { - // ignore - } - } - - if (esr != null) { - try { - esr.close(); - } catch (IOException ex) { - // ignore - } - } - } - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/PropertiesUtil.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/PropertiesUtil.java deleted file mode 100644 index deb5243740f..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/PropertiesUtil.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import java.io.IOException; -import java.io.StringWriter; -import java.util.Properties; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class PropertiesUtil { - /** - * Transform the properties to string format - * @param properties the properties object - * @return the string containing the properties - * @throws IOException - */ - public static String toString(Properties properties) throws IOException { - StringWriter writer = new StringWriter(); - properties.store(writer, null); - StringBuffer stringBuffer = writer.getBuffer(); - filterPropertiesComment(stringBuffer); - return stringBuffer.toString(); - } - - /** - * filter out the first comment line - * @param stringBuffer the string buffer - * @return true if filtered successfully, false otherwise - */ - static boolean filterPropertiesComment(StringBuffer stringBuffer) { - //check whether has comment in the first line - if (stringBuffer.charAt(0) != '#') { - return false; - } - int commentLineIndex = stringBuffer.indexOf("\n"); - if (commentLineIndex == -1) { - return false; - } - stringBuffer.delete(0, commentLineIndex + 1); - return true; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ResourceUtils.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ResourceUtils.java deleted file mode 100644 index 2c1dca0abda..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/ResourceUtils.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import java.net.URL; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.FileNotFoundException; -import java.nio.file.Paths; -import java.util.Properties; - -public class ResourceUtils { - - private static final Logger logger = LoggerFactory.getLogger(ResourceUtils.class); - private static final String[] DEFAULT_FILE_SEARCH_LOCATIONS = new String[]{"./config/", "./"}; - - @SuppressWarnings("unchecked") - public static Properties readConfigFile(String configPath, Properties defaults) { - Properties props = new Properties(); - if (defaults != null) { - props.putAll(defaults); - } - - InputStream in = loadConfigFileFromDefaultSearchLocations(configPath); - - try { - if (in != null) { - props.load(in); - } - } catch (IOException ex) { - logger.warn("Reading config failed: {}", ex.getMessage()); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException ex) { - logger.warn("Close config failed: {}", ex.getMessage()); - } - } - } - - if (logger.isDebugEnabled()) { - StringBuilder sb = new StringBuilder(); - for (String propertyName : props.stringPropertyNames()) { - sb.append(propertyName).append('=').append(props.getProperty(propertyName)).append('\n'); - - } - if (sb.length() > 0) { - logger.debug("Reading properties: \n" + sb); - } else { - logger.warn("No available properties: {}", configPath); - } - } - return props; - } - - private static InputStream loadConfigFileFromDefaultSearchLocations(String configPath) { - try { - // load from default search locations - for (String searchLocation : DEFAULT_FILE_SEARCH_LOCATIONS) { - File candidate = Paths.get(searchLocation, configPath).toFile(); - if (candidate.exists() && candidate.isFile() && candidate.canRead()) { - logger.debug("Reading config from resource {}", candidate.getAbsolutePath()); - return new FileInputStream(candidate); - } - } - - // load from classpath - URL url = ClassLoaderUtil.getLoader().getResource(configPath); - - if (url != null) { - InputStream in = getResourceAsStream(url); - - if (in != null) { - logger.debug("Reading config from resource {}", url.getPath()); - return in; - } - } - - // load outside resource under current user path - File candidate = new File(System.getProperty("user.dir"), configPath); - if (candidate.exists() && candidate.isFile() && candidate.canRead()) { - logger.debug("Reading config from resource {}", candidate.getAbsolutePath()); - return new FileInputStream(candidate); - } - } catch (FileNotFoundException e) { - //ignore - } - return null; - } - - private static InputStream getResourceAsStream(URL url) { - try { - return url != null ? url.openStream() : null; - } catch (IOException e) { - return null; - } - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/StringUtils.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/StringUtils.java deleted file mode 100644 index 4ffde2c5533..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/core/utils/StringUtils.java +++ /dev/null @@ -1,347 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import java.util.Collection; -import java.util.Iterator; - -public class StringUtils { - - public static final String EMPTY = ""; - - /** - *

- * Checks if a String is empty ("") or null. - *

- * - *
-   * StringUtils.isEmpty(null)      = true
-   * StringUtils.isEmpty("")        = true
-   * StringUtils.isEmpty(" ")       = false
-   * StringUtils.isEmpty("bob")     = false
-   * StringUtils.isEmpty("  bob  ") = false
-   * 
- * - *

- * NOTE: This method changed in Lang version 2.0. It no longer trims the String. That functionality is available in isBlank(). - *

- * - * @param str the String to check, may be null - * @return true if the String is empty or null - */ - public static boolean isEmpty(String str) { - return str == null || str.length() == 0; - } - - - public static boolean isContainEmpty(String... args){ - if (args == null){ - return false; - } - - for (String arg: args){ - if (arg == null || "".equals(arg)){ - return true; - } - } - - return false; - } - /** - *

- * Checks if a String is whitespace, empty ("") or null. - *

- * - *
-   * StringUtils.isBlank(null)      = true
-   * StringUtils.isBlank("")        = true
-   * StringUtils.isBlank(" ")       = true
-   * StringUtils.isBlank("bob")     = false
-   * StringUtils.isBlank("  bob  ") = false
-   * 
- * - * @param str the String to check, may be null - * @return true if the String is null, empty or whitespace - */ - public static boolean isBlank(String str) { - int strLen; - if (str == null || (strLen = str.length()) == 0) { - return true; - } - for (int i = 0; i < strLen; i++) { - if (!Character.isWhitespace(str.charAt(i))) { - return false; - } - } - return true; - } - - /** - *

- * Removes control characters (char <= 32) from both ends of this String returning null if the String is empty - * ("") after the trim or if it is null. - * - *

- * The String is trimmed using {@link String#trim()}. Trim removes start and end characters <= 32. To strip whitespace use - * {@link #stripToNull(String)}. - *

- * - *
-   * StringUtils.trimToNull(null)          = null
-   * StringUtils.trimToNull("")            = null
-   * StringUtils.trimToNull("     ")       = null
-   * StringUtils.trimToNull("abc")         = "abc"
-   * StringUtils.trimToNull("    abc    ") = "abc"
-   * 
- * - * @param str the String to be trimmed, may be null - * @return the trimmed String, null if only chars <= 32, empty or null String input - * @since 2.0 - */ - public static String trimToNull(String str) { - String ts = trim(str); - return isEmpty(ts) ? null : ts; - } - - /** - *

- * Removes control characters (char <= 32) from both ends of this String returning an empty String ("") if the String is empty - * ("") after the trim or if it is null. - * - *

- * The String is trimmed using {@link String#trim()}. Trim removes start and end characters <= 32. To strip whitespace use - * {@link #stripToEmpty(String)}. - *

- * - *
-   * StringUtils.trimToEmpty(null)          = ""
-   * StringUtils.trimToEmpty("")            = ""
-   * StringUtils.trimToEmpty("     ")       = ""
-   * StringUtils.trimToEmpty("abc")         = "abc"
-   * StringUtils.trimToEmpty("    abc    ") = "abc"
-   * 
- * - * @param str the String to be trimmed, may be null - * @return the trimmed String, or an empty String if null input - * @since 2.0 - */ - public static String trimToEmpty(String str) { - return str == null ? EMPTY : str.trim(); - } - - /** - *

- * Removes control characters (char <= 32) from both ends of this String, handling null by returning - * null. - *

- * - *

- * The String is trimmed using {@link String#trim()}. Trim removes start and end characters <= 32. To strip whitespace use - * {@link #strip(String)}. - *

- * - *

- * To trim your choice of characters, use the {@link #strip(String, String)} methods. - *

- * - *
-   * StringUtils.trim(null)          = null
-   * StringUtils.trim("")            = ""
-   * StringUtils.trim("     ")       = ""
-   * StringUtils.trim("abc")         = "abc"
-   * StringUtils.trim("    abc    ") = "abc"
-   * 
- * - * @param str the String to be trimmed, may be null - * @return the trimmed string, null if null String input - */ - public static String trim(String str) { - return str == null ? null : str.trim(); - } - - /** - *

- * Compares two Strings, returning true if they are equal. - *

- * - *

- * nulls are handled without exceptions. Two null references are considered to be equal. The comparison - * is case sensitive. - *

- * - *
-   * StringUtils.equals(null, null)   = true
-   * StringUtils.equals(null, "abc")  = false
-   * StringUtils.equals("abc", null)  = false
-   * StringUtils.equals("abc", "abc") = true
-   * StringUtils.equals("abc", "ABC") = false
-   * 
- * - * @param str1 the first String, may be null - * @param str2 the second String, may be null - * @return true if the Strings are equal, case sensitive, or both null - * @see java.lang.String#equals(Object) - */ - public static boolean equals(String str1, String str2) { - return str1 == null ? str2 == null : str1.equals(str2); - } - - /** - *

- * Compares two Strings, returning true if they are equal ignoring the case. - *

- * - *

- * nulls are handled without exceptions. Two null references are considered equal. Comparison is case - * insensitive. - *

- * - *
-   * StringUtils.equalsIgnoreCase(null, null)   = true
-   * StringUtils.equalsIgnoreCase(null, "abc")  = false
-   * StringUtils.equalsIgnoreCase("abc", null)  = false
-   * StringUtils.equalsIgnoreCase("abc", "abc") = true
-   * StringUtils.equalsIgnoreCase("abc", "ABC") = true
-   * 
- * - * @param str1 the first String, may be null - * @param str2 the second String, may be null - * @return true if the Strings are equal, case insensitive, or both null - * @see java.lang.String#equalsIgnoreCase(String) - */ - public static boolean equalsIgnoreCase(String str1, String str2) { - return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2); - } - - /** - *

- * Check if a String starts with a specified prefix. - *

- * - *

- * nulls are handled without exceptions. Two null references are considered to be equal. The comparison - * is case sensitive. - *

- * - *
-   * StringUtils.startsWith(null, null)      = true
-   * StringUtils.startsWith(null, "abc")     = false
-   * StringUtils.startsWith("abcdef", null)  = false
-   * StringUtils.startsWith("abcdef", "abc") = true
-   * StringUtils.startsWith("ABCDEF", "abc") = false
-   * 
- * - * @param str the String to check, may be null - * @param prefix the prefix to find, may be null - * @return true if the String starts with the prefix, case sensitive, or both null - * @see java.lang.String#startsWith(String) - * @since 2.4 - */ - public static boolean startsWith(String str, String prefix) { - return startsWith(str, prefix, false); - } - - /** - *

- * Check if a String starts with a specified prefix (optionally case insensitive). - *

- * - * @param str the String to check, may be null - * @param prefix the prefix to find, may be null - * @param ignoreCase inidicates whether the compare should ignore case (case insensitive) or not. - * @return true if the String starts with the prefix or both null - * @see java.lang.String#startsWith(String) - */ - private static boolean startsWith(String str, String prefix, boolean ignoreCase) { - if (str == null || prefix == null) { - return str == null && prefix == null; - } - if (prefix.length() > str.length()) { - return false; - } - return str.regionMatches(ignoreCase, 0, prefix, 0, prefix.length()); - } - - /** - *

- * Case insensitive check if a String starts with a specified prefix. - *

- * - *

- * nulls are handled without exceptions. Two null references are considered to be equal. The comparison - * is case insensitive. - *

- * - *
-   * StringUtils.startsWithIgnoreCase(null, null)      = true
-   * StringUtils.startsWithIgnoreCase(null, "abc")     = false
-   * StringUtils.startsWithIgnoreCase("abcdef", null)  = false
-   * StringUtils.startsWithIgnoreCase("abcdef", "abc") = true
-   * StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
-   * 
- * - * @param str the String to check, may be null - * @param prefix the prefix to find, may be null - * @return true if the String starts with the prefix, case insensitive, or both null - * @see java.lang.String#startsWith(String) - * @since 2.4 - */ - public static boolean startsWithIgnoreCase(String str, String prefix) { - return startsWith(str, prefix, true); - } - - /** - *

- * Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false. - *

- * - *

- * null will return false. An empty String (length()=0) will return true. - *

- * - *
-   * StringUtils.isNumeric(null)   = false
-   * StringUtils.isNumeric("")     = true
-   * StringUtils.isNumeric("  ")   = false
-   * StringUtils.isNumeric("123")  = true
-   * StringUtils.isNumeric("12 3") = false
-   * StringUtils.isNumeric("ab2c") = false
-   * StringUtils.isNumeric("12-3") = false
-   * StringUtils.isNumeric("12.3") = false
-   * 
- * - * @param str the String to check, may be null - * @return true if only contains digits, and is non-null - */ - public static boolean isNumeric(String str) { - if (str == null) { - return false; - } - int sz = str.length(); - for (int i = 0; i < sz; i++) { - if (!Character.isDigit(str.charAt(i))) { - return false; - } - } - return true; - } - - public interface StringFormatter { - String format(T obj); - } - -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/Tracer.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/Tracer.java deleted file mode 100644 index e7818eac62f..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/Tracer.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2022 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.tracer; - -import com.ctrip.framework.apollo.tracer.internals.NullMessageProducerManager; -import com.ctrip.framework.apollo.tracer.spi.MessageProducer; -import com.ctrip.framework.apollo.tracer.spi.MessageProducerManager; -import com.ctrip.framework.apollo.tracer.spi.Transaction; - -import com.ctrip.framework.foundation.internals.ServiceBootstrap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public abstract class Tracer { - private static final Logger logger = LoggerFactory.getLogger(Tracer.class); - private static final MessageProducerManager NULL_MESSAGE_PRODUCER_MANAGER = - new NullMessageProducerManager(); - private static volatile MessageProducerManager producerManager; - private static Object lock = new Object(); - - static { - getProducer(); - } - - private static MessageProducer getProducer() { - try { - if (producerManager == null) { - synchronized (lock) { - if (producerManager == null) { - producerManager = ServiceBootstrap.loadFirst(MessageProducerManager.class); - } - } - } - } catch (Throwable ex) { - logger.error( - "Failed to initialize message producer manager, use null message producer manager.", ex); - producerManager = NULL_MESSAGE_PRODUCER_MANAGER; - } - return producerManager.getProducer(); - } - - public static void logError(String message, Throwable cause) { - try { - getProducer().logError(message, cause); - } catch (Throwable ex) { - logger.warn("Failed to log error for message: {}, cause: {}", message, cause, ex); - } - } - - public static void logError(Throwable cause) { - try { - getProducer().logError(cause); - } catch (Throwable ex) { - logger.warn("Failed to log error for cause: {}", cause, ex); - } - } - - public static void logEvent(String type, String name) { - try { - getProducer().logEvent(type, name); - } catch (Throwable ex) { - logger.warn("Failed to log event for type: {}, name: {}", type, name, ex); - } - } - - public static void logEvent(String type, String name, String status, String nameValuePairs) { - try { - getProducer().logEvent(type, name, status, nameValuePairs); - } catch (Throwable ex) { - logger.warn("Failed to log event for type: {}, name: {}, status: {}, nameValuePairs: {}", - type, name, status, nameValuePairs, ex); - } - } - - public static Transaction newTransaction(String type, String name) { - try { - return getProducer().newTransaction(type, name); - } catch (Throwable ex) { - logger.warn("Failed to create transaction for type: {}, name: {}", type, name, ex); - return NULL_MESSAGE_PRODUCER_MANAGER.getProducer().newTransaction(type, name); - } - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManager.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManager.java deleted file mode 100644 index 2490abdbb26..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManager.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2022 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.tracer.internals; - -import com.ctrip.framework.apollo.core.utils.ClassLoaderUtil; -import com.ctrip.framework.apollo.tracer.internals.cat.CatMessageProducer; -import com.ctrip.framework.apollo.tracer.internals.cat.CatNames; -import com.ctrip.framework.apollo.tracer.spi.MessageProducer; -import com.ctrip.framework.apollo.tracer.spi.MessageProducerManager; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class DefaultMessageProducerManager implements MessageProducerManager { - private static MessageProducer producer; - - public DefaultMessageProducerManager() { - if (ClassLoaderUtil.isClassPresent(CatNames.CAT_CLASS)) { - producer = new CatMessageProducer(); - } else { - producer = new NullMessageProducerManager().getProducer(); - } - } - - @Override - public MessageProducer getProducer() { - return producer; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/NullMessageProducer.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/NullMessageProducer.java deleted file mode 100644 index 76673141bad..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/NullMessageProducer.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2022 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.tracer.internals; - -import com.ctrip.framework.apollo.tracer.spi.MessageProducer; -import com.ctrip.framework.apollo.tracer.spi.Transaction; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class NullMessageProducer implements MessageProducer { - private static final Transaction NULL_TRANSACTION = new NullTransaction(); - - @Override - public void logError(Throwable cause) { - } - - @Override - public void logError(String message, Throwable cause) { - } - - @Override - public void logEvent(String type, String name) { - } - - @Override - public void logEvent(String type, String name, String status, String nameValuePairs) { - } - - @Override - public Transaction newTransaction(String type, String name) { - return NULL_TRANSACTION; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/NullMessageProducerManager.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/NullMessageProducerManager.java deleted file mode 100644 index ae50d9d9fad..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/NullMessageProducerManager.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2022 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.tracer.internals; - -import com.ctrip.framework.apollo.tracer.spi.MessageProducer; -import com.ctrip.framework.apollo.tracer.spi.MessageProducerManager; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class NullMessageProducerManager implements MessageProducerManager { - private static final MessageProducer producer = new NullMessageProducer(); - - @Override - public MessageProducer getProducer() { - return producer; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/NullTransaction.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/NullTransaction.java deleted file mode 100644 index e1c2ba5f4f0..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/NullTransaction.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2022 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.tracer.internals; - -import com.ctrip.framework.apollo.tracer.spi.Transaction; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class NullTransaction implements Transaction { - @Override - public void setStatus(String status) { - } - - @Override - public void setStatus(Throwable e) { - } - - @Override - public void addData(String key, Object value) { - } - - @Override - public void complete() { - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatMessageProducer.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatMessageProducer.java deleted file mode 100644 index cb525f909bf..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatMessageProducer.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2022 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.tracer.internals.cat; - -import com.ctrip.framework.apollo.tracer.spi.MessageProducer; -import com.ctrip.framework.apollo.tracer.spi.Transaction; -import com.dianping.cat.Cat; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class CatMessageProducer implements MessageProducer { - @Override - public void logError(Throwable cause) { - Cat.logError(cause); - } - - @Override - public void logError(String message, Throwable cause) { - Cat.logError(message, cause); - } - - @Override - public void logEvent(String type, String name) { - Cat.logEvent(type, name); - } - - @Override - public void logEvent(String type, String name, String status, String nameValuePairs) { - Cat.logEvent(type, name, - status, nameValuePairs); - } - - @Override - public Transaction newTransaction(String type, String name) { - return new CatTransaction(Cat.newTransaction(type, name)); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatNames.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatNames.java deleted file mode 100644 index 6835a1ede43..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatNames.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2022 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.tracer.internals.cat; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface CatNames { - String CAT_CLASS = "com.dianping.cat.Cat"; -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatTransaction.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatTransaction.java deleted file mode 100644 index bccdb5e9c55..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/internals/cat/CatTransaction.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2022 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.tracer.internals.cat; - -import com.ctrip.framework.apollo.tracer.spi.Transaction; - -import java.lang.reflect.Method; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class CatTransaction implements Transaction { - - private com.dianping.cat.message.Transaction catTransaction; - - public CatTransaction(com.dianping.cat.message.Transaction catTransaction) { - this.catTransaction = catTransaction; - } - - @Override - public void setStatus(String status) { - catTransaction.setStatus(status); - } - - @Override - public void setStatus(Throwable status) { - catTransaction.setStatus(status); - } - - @Override - public void addData(String key, Object value) { - catTransaction.addData(key, value); - } - - @Override - public void complete() { - catTransaction.complete(); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducer.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducer.java deleted file mode 100644 index 61eb8040b63..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducer.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2022 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.tracer.spi; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface MessageProducer { - /** - * Log an error. - * - * @param cause root cause exception - */ - void logError(Throwable cause); - - /** - * Log an error. - * - * @param cause root cause exception - */ - void logError(String message, Throwable cause); - - /** - * Log an event in one shot with SUCCESS status. - * - * @param type event type - * @param name event name - */ - void logEvent(String type, String name); - - /** - * Log an event in one shot. - * - * @param type event type - * @param name event name - * @param status "0" means success, otherwise means error code - * @param nameValuePairs name value pairs in the format of "a=1&b=2&..." - */ - void logEvent(String type, String name, String status, String nameValuePairs); - - /** - * Create a new transaction with given type and name. - * - * @param type transaction type - * @param name transaction name - */ - Transaction newTransaction(String type, String name); -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducerManager.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducerManager.java deleted file mode 100644 index 2d174dd7f8e..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/MessageProducerManager.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2022 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.tracer.spi; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface MessageProducerManager { - /** - * @return the message producer - */ - MessageProducer getProducer(); -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/Transaction.java b/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/Transaction.java deleted file mode 100644 index ed3679375ce..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/apollo/tracer/spi/Transaction.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2022 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.tracer.spi; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public interface Transaction { - String SUCCESS = "0"; - - /** - * Set the message status. - * - * @param status message status. "0" means success, otherwise error code. - */ - void setStatus(String status); - - /** - * Set the message status with exception class name. - * - * @param e exception. - */ - void setStatus(Throwable e); - - /** - * add one key-value pair to the message. - */ - void addData(String key, Object value); - - /** - * Complete the message construction. - */ - void complete(); -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/Foundation.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/Foundation.java deleted file mode 100644 index 7bd1f150500..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/Foundation.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.foundation.internals.NullProviderManager; -import com.ctrip.framework.foundation.internals.ServiceBootstrap; -import com.ctrip.framework.foundation.spi.ProviderManager; -import com.ctrip.framework.foundation.spi.provider.ApplicationProvider; -import com.ctrip.framework.foundation.spi.provider.NetworkProvider; -import com.ctrip.framework.foundation.spi.provider.ServerProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public abstract class Foundation { - - private static final Logger logger = LoggerFactory.getLogger(Foundation.class); - private static final Object LOCK = new Object(); - - private static volatile ProviderManager s_manager; - - // Encourage early initialization and fail early if it happens. - static { - getManager(); - } - - private static ProviderManager getManager() { - try { - if (s_manager == null) { - // Double locking to make sure only one thread initializes ProviderManager. - synchronized (LOCK) { - if (s_manager == null) { - s_manager = ServiceBootstrap.loadPrimary(ProviderManager.class); - } - } - } - - return s_manager; - } catch (Throwable ex) { - s_manager = new NullProviderManager(); - logger.error("Initialize ProviderManager failed.", ex); - return s_manager; - } - } - - public static String getProperty(String name, String defaultValue) { - try { - return getManager().getProperty(name, defaultValue); - } catch (Throwable ex) { - logger.error("getProperty for {} failed.", name, ex); - return defaultValue; - } - } - - public static NetworkProvider net() { - try { - return getManager().provider(NetworkProvider.class); - } catch (Exception ex) { - logger.error("Initialize NetworkProvider failed.", ex); - return NullProviderManager.provider; - } - } - - public static ServerProvider server() { - try { - return getManager().provider(ServerProvider.class); - } catch (Exception ex) { - logger.error("Initialize ServerProvider failed.", ex); - return NullProviderManager.provider; - } - } - - public static ApplicationProvider app() { - try { - return getManager().provider(ApplicationProvider.class); - } catch (Exception ex) { - logger.error("Initialize ApplicationProvider failed.", ex); - return NullProviderManager.provider; - } - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/DefaultProviderManager.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/DefaultProviderManager.java deleted file mode 100644 index b6dded27a3e..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/DefaultProviderManager.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2022 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; - -import java.util.LinkedHashMap; -import java.util.Map; - -import com.ctrip.framework.foundation.internals.provider.DefaultApplicationProvider; -import com.ctrip.framework.foundation.internals.provider.DefaultNetworkProvider; -import com.ctrip.framework.foundation.internals.provider.DefaultServerProvider; -import com.ctrip.framework.foundation.spi.ProviderManager; -import com.ctrip.framework.foundation.spi.provider.Provider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class DefaultProviderManager implements ProviderManager { - private static final Logger logger = LoggerFactory.getLogger(DefaultProviderManager.class); - private Map, Provider> m_providers = new LinkedHashMap<>(); - - public DefaultProviderManager() { - // Load per-application configuration, like app id, from classpath://META-INF/app.properties - Provider applicationProvider = new DefaultApplicationProvider(); - applicationProvider.initialize(); - register(applicationProvider); - - // Load network parameters - Provider networkProvider = new DefaultNetworkProvider(); - networkProvider.initialize(); - register(networkProvider); - - // Load environment (fat, fws, uat, prod ...) and dc, from /opt/settings/server.properties, JVM property and/or OS - // environment variables. - Provider serverProvider = new DefaultServerProvider(); - serverProvider.initialize(); - register(serverProvider); - } - - public synchronized void register(Provider provider) { - m_providers.put(provider.getType(), provider); - } - - @Override - @SuppressWarnings("unchecked") - public T provider(Class clazz) { - Provider provider = m_providers.get(clazz); - - if (provider != null) { - return (T) provider; - } - logger.error("No provider [{}] found in DefaultProviderManager, please make sure it is registered in DefaultProviderManager ", - clazz.getName()); - return (T) NullProviderManager.provider; - } - - @Override - public String getProperty(String name, String defaultValue) { - for (Provider provider : m_providers.values()) { - String value = provider.getProperty(name, null); - - if (value != null) { - return value; - } - } - - return defaultValue; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(512); - if (null != m_providers) { - for (Map.Entry, Provider> entry : m_providers.entrySet()) { - sb.append(entry.getValue()).append("\n"); - } - } - sb.append("(DefaultProviderManager)").append("\n"); - return sb.toString(); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/NetworkInterfaceManager.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/NetworkInterfaceManager.java deleted file mode 100644 index b93610b50c7..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/NetworkInterfaceManager.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2022 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; - -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Enumeration; -import java.util.List; - -public enum NetworkInterfaceManager { - INSTANCE; - - private InetAddress m_local; - - private InetAddress m_localHost; - - NetworkInterfaceManager() { - load(); - } - - public InetAddress findValidateIp(List addresses) { - InetAddress local = null; - int maxWeight = -1; - for (InetAddress address : addresses) { - if (address instanceof Inet4Address) { - int weight = 0; - - if (address.isSiteLocalAddress()) { - weight += 8; - } - - if (address.isLinkLocalAddress()) { - weight += 4; - } - - if (address.isLoopbackAddress()) { - weight += 2; - } - - /** - * The following logic is removed as we will sort the network interfaces according to the index asc to determine - * the priorities between network interfaces, see https://github.com/ctripcorp/apollo/pull/1986 - */ - // has host name - /* - if (!Objects.equals(address.getHostName(), address.getHostAddress())) { - weight += 1; - } - */ - - if (weight > maxWeight) { - maxWeight = weight; - local = address; - } - } - } - return local; - } - - public String getLocalHostAddress() { - return m_local.getHostAddress(); - } - - public String getLocalHostName() { - try { - if (null == m_localHost) { - m_localHost = InetAddress.getLocalHost(); - } - return m_localHost.getHostName(); - } catch (UnknownHostException e) { - return m_local.getHostName(); - } - } - - private String getProperty(String name) { - String value = null; - - value = System.getProperty(name); - - if (value == null) { - value = System.getenv(name); - } - - return value; - } - - private void load() { - String ip = getProperty("host.ip"); - - if (ip != null) { - try { - m_local = InetAddress.getByName(ip); - return; - } catch (Exception e) { - System.err.println(e); - // ignore - } - } - - try { - Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); - if (interfaces == null) { - m_local = InetAddress.getLoopbackAddress(); - return; - } - List nis = Collections.list(interfaces); - //sort the network interfaces according to the index asc - nis.sort(Comparator.comparingInt(NetworkInterface::getIndex)); - List addresses = new ArrayList<>(); - InetAddress local = null; - - try { - for (NetworkInterface ni : nis) { - if (ni.isUp() && !ni.isLoopback()) { - addresses.addAll(Collections.list(ni.getInetAddresses())); - } - } - local = findValidateIp(addresses); - } catch (Exception e) { - // ignore - } - if (local != null) { - m_local = local; - return; - } - } catch (SocketException e) { - // ignore it - } - - m_local = InetAddress.getLoopbackAddress(); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/NullProviderManager.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/NullProviderManager.java deleted file mode 100644 index 6ced0e58626..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/NullProviderManager.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.foundation.internals.provider.NullProvider; -import com.ctrip.framework.foundation.spi.ProviderManager; - -public class NullProviderManager implements ProviderManager { - public static final NullProvider provider = new NullProvider(); - - @Override - public String getProperty(String name, String defaultValue) { - return defaultValue; - } - - @Override - public NullProvider provider(Class clazz) { - return provider; - } - - @Override - public String toString() { - return provider.toString(); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/ServiceBootstrap.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/ServiceBootstrap.java deleted file mode 100644 index 28273afd117..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/ServiceBootstrap.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.core.spi.Ordered; -import com.google.common.collect.Lists; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.ServiceLoader; - -public class ServiceBootstrap { - public static S loadFirst(Class clazz) { - Iterator iterator = loadAll(clazz); - if (!iterator.hasNext()) { - throw new IllegalStateException(String.format( - "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!", - clazz.getName())); - } - return iterator.next(); - } - - public static Iterator loadAll(Class clazz) { - ServiceLoader loader = ServiceLoader.load(clazz); - - return loader.iterator(); - } - - public static List loadAllOrdered(Class clazz) { - Iterator iterator = loadAll(clazz); - List candidates = Lists.newArrayList(iterator); - // the smaller order has higher priority - candidates.sort(Comparator.comparingInt(Ordered::getOrder)); - - return candidates; - } - - public static S loadPrimary(Class clazz) { - List candidates = loadAllOrdered(clazz); - - if (candidates.isEmpty()) { - throw new IllegalStateException(String.format( - "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!", - clazz.getName())); - } - - - return candidates.get(0); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/Utils.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/Utils.java deleted file mode 100755 index 1eeaff3225e..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/Utils.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2022 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; - -import com.google.common.base.Strings; - -public class Utils { - public static boolean isBlank(String str) { - return Strings.nullToEmpty(str).trim().isEmpty(); - } - - public static boolean isOSWindows() { - String osName = System.getProperty("os.name"); - if (Utils.isBlank(osName)) { - return false; - } - return osName.startsWith("Windows"); - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/io/BOMInputStream.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/io/BOMInputStream.java deleted file mode 100644 index ce27aeb7f1d..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/io/BOMInputStream.java +++ /dev/null @@ -1,391 +0,0 @@ -/* - * Copyright 2022 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. - * - */ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE - * file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file - * to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ctrip.framework.foundation.internals.io; - - -import static com.ctrip.framework.foundation.internals.io.IOUtils.EOF; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; - -/** - * This class is used to wrap a stream that includes an encoded {@link ByteOrderMark} as its first bytes. - * - * This class detects these bytes and, if required, can automatically skip them and return the subsequent byte as the - * first byte in the stream. - * - * The {@link ByteOrderMark} implementation has the following pre-defined BOMs: - *
    - *
  • UTF-8 - {@link ByteOrderMark#UTF_8}
  • - *
  • UTF-16BE - {@link ByteOrderMark#UTF_16LE}
  • - *
  • UTF-16LE - {@link ByteOrderMark#UTF_16BE}
  • - *
  • UTF-32BE - {@link ByteOrderMark#UTF_32LE}
  • - *
  • UTF-32LE - {@link ByteOrderMark#UTF_32BE}
  • - *
- * - * - *

Example 1 - Detect and exclude a UTF-8 BOM

- * - *
- * BOMInputStream bomIn = new BOMInputStream(in);
- * if (bomIn.hasBOM()) {
- *   // has a UTF-8 BOM
- * }
- * 
- * - *

Example 2 - Detect a UTF-8 BOM (but don't exclude it)

- * - *
- * boolean include = true;
- * BOMInputStream bomIn = new BOMInputStream(in, include);
- * if (bomIn.hasBOM()) {
- *   // has a UTF-8 BOM
- * }
- * 
- * - *

Example 3 - Detect Multiple BOMs

- * - *
- * BOMInputStream bomIn = new BOMInputStream(in, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_32LE,
- *     ByteOrderMark.UTF_32BE);
- * if (bomIn.hasBOM() == false) {
- *   // No BOM found
- * } else if (bomIn.hasBOM(ByteOrderMark.UTF_16LE)) {
- *   // has a UTF-16LE BOM
- * } else if (bomIn.hasBOM(ByteOrderMark.UTF_16BE)) {
- *   // has a UTF-16BE BOM
- * } else if (bomIn.hasBOM(ByteOrderMark.UTF_32LE)) {
- *   // has a UTF-32LE BOM
- * } else if (bomIn.hasBOM(ByteOrderMark.UTF_32BE)) {
- *   // has a UTF-32BE BOM
- * }
- * 
- * - * @see ByteOrderMark - * @see Wikipedia - Byte Order Mark - * @version $Id: BOMInputStream.java 1686527 2015-06-20 06:31:39Z krosenvold $ - * @since 2.0 - */ -public class BOMInputStream extends ProxyInputStream { - private final boolean include; - /** - * BOMs are sorted from longest to shortest. - */ - private final List boms; - private ByteOrderMark byteOrderMark; - private int[] firstBytes; - private int fbLength; - private int fbIndex; - private int markFbIndex; - private boolean markedAtStart; - - /** - * Constructs a new BOM InputStream that excludes a {@link ByteOrderMark#UTF_8} BOM. - * - * @param delegate the InputStream to delegate to - */ - public BOMInputStream(final InputStream delegate) { - this(delegate, false, ByteOrderMark.UTF_8); - } - - /** - * Constructs a new BOM InputStream that detects a a {@link ByteOrderMark#UTF_8} and optionally includes it. - * - * @param delegate the InputStream to delegate to - * @param include true to include the UTF-8 BOM or false to exclude it - */ - public BOMInputStream(final InputStream delegate, final boolean include) { - this(delegate, include, ByteOrderMark.UTF_8); - } - - /** - * Constructs a new BOM InputStream that excludes the specified BOMs. - * - * @param delegate the InputStream to delegate to - * @param boms The BOMs to detect and exclude - */ - public BOMInputStream(final InputStream delegate, final ByteOrderMark... boms) { - this(delegate, false, boms); - } - - /** - * Compares ByteOrderMark objects in descending length order. - */ - private static final Comparator ByteOrderMarkLengthComparator = new Comparator() { - - public int compare(final ByteOrderMark bom1, final ByteOrderMark bom2) { - final int len1 = bom1.length(); - final int len2 = bom2.length(); - if (len1 > len2) { - return EOF; - } - if (len2 > len1) { - return 1; - } - return 0; - } - }; - - /** - * Constructs a new BOM InputStream that detects the specified BOMs and optionally includes them. - * - * @param delegate the InputStream to delegate to - * @param include true to include the specified BOMs or false to exclude them - * @param boms The BOMs to detect and optionally exclude - */ - public BOMInputStream(final InputStream delegate, final boolean include, final ByteOrderMark... boms) { - super(delegate); - if (boms == null || boms.length == 0) { - throw new IllegalArgumentException("No BOMs specified"); - } - this.include = include; - // Sort the BOMs to match the longest BOM first because some BOMs have the same starting two bytes. - Arrays.sort(boms, ByteOrderMarkLengthComparator); - this.boms = Arrays.asList(boms); - - } - - /** - * Indicates whether the stream contains one of the specified BOMs. - * - * @return true if the stream has one of the specified BOMs, otherwise false if it does not - * @throws IOException if an error reading the first bytes of the stream occurs - */ - public boolean hasBOM() throws IOException { - return getBOM() != null; - } - - /** - * Indicates whether the stream contains the specified BOM. - * - * @param bom The BOM to check for - * @return true if the stream has the specified BOM, otherwise false if it does not - * @throws IllegalArgumentException if the BOM is not one the stream is configured to detect - * @throws IOException if an error reading the first bytes of the stream occurs - */ - public boolean hasBOM(final ByteOrderMark bom) throws IOException { - if (!boms.contains(bom)) { - throw new IllegalArgumentException("Stream not configure to detect " + bom); - } - getBOM(); - return byteOrderMark != null && byteOrderMark.equals(bom); - } - - /** - * Return the BOM (Byte Order Mark). - * - * @return The BOM or null if none - * @throws IOException if an error reading the first bytes of the stream occurs - */ - public ByteOrderMark getBOM() throws IOException { - if (firstBytes == null) { - fbLength = 0; - // BOMs are sorted from longest to shortest - final int maxBomSize = boms.get(0).length(); - firstBytes = new int[maxBomSize]; - // Read first maxBomSize bytes - for (int i = 0; i < firstBytes.length; i++) { - firstBytes[i] = in.read(); - fbLength++; - if (firstBytes[i] < 0) { - break; - } - } - // match BOM in firstBytes - byteOrderMark = find(); - if (byteOrderMark != null) { - if (!include) { - if (byteOrderMark.length() < firstBytes.length) { - fbIndex = byteOrderMark.length(); - } else { - fbLength = 0; - } - } - } - } - return byteOrderMark; - } - - /** - * Return the BOM charset Name - {@link ByteOrderMark#getCharsetName()}. - * - * @return The BOM charset Name or null if no BOM found - * @throws IOException if an error reading the first bytes of the stream occurs - * - */ - public String getBOMCharsetName() throws IOException { - getBOM(); - return byteOrderMark == null ? null : byteOrderMark.getCharsetName(); - } - - /** - * This method reads and either preserves or skips the first bytes in the stream. It behaves like the single-byte - * read() method, either returning a valid byte or -1 to indicate that the initial bytes have been - * processed already. - * - * @return the byte read (excluding BOM) or -1 if the end of stream - * @throws IOException if an I/O error occurs - */ - private int readFirstBytes() throws IOException { - getBOM(); - return fbIndex < fbLength ? firstBytes[fbIndex++] : EOF; - } - - /** - * Find a BOM with the specified bytes. - * - * @return The matched BOM or null if none matched - */ - private ByteOrderMark find() { - for (final ByteOrderMark bom : boms) { - if (matches(bom)) { - return bom; - } - } - return null; - } - - /** - * Check if the bytes match a BOM. - * - * @param bom The BOM - * @return true if the bytes match the bom, otherwise false - */ - private boolean matches(final ByteOrderMark bom) { - // if (bom.length() != fbLength) { - // return false; - // } - // firstBytes may be bigger than the BOM bytes - for (int i = 0; i < bom.length(); i++) { - if (bom.get(i) != firstBytes[i]) { - return false; - } - } - return true; - } - - // ---------------------------------------------------------------------------- - // Implementation of InputStream - // ---------------------------------------------------------------------------- - - /** - * Invokes the delegate's read() method, detecting and optionally skipping BOM. - * - * @return the byte read (excluding BOM) or -1 if the end of stream - * @throws IOException if an I/O error occurs - */ - @Override - public int read() throws IOException { - final int b = readFirstBytes(); - return b >= 0 ? b : in.read(); - } - - /** - * Invokes the delegate's read(byte[], int, int) method, detecting and optionally skipping BOM. - * - * @param buf the buffer to read the bytes into - * @param off The start offset - * @param len The number of bytes to read (excluding BOM) - * @return the number of bytes read or -1 if the end of stream - * @throws IOException if an I/O error occurs - */ - @Override - public int read(final byte[] buf, int off, int len) throws IOException { - int firstCount = 0; - int b = 0; - while (len > 0 && b >= 0) { - b = readFirstBytes(); - if (b >= 0) { - buf[off++] = (byte) (b & 0xFF); - len--; - firstCount++; - } - } - final int secondCount = in.read(buf, off, len); - return secondCount < 0 ? firstCount > 0 ? firstCount : EOF : firstCount + secondCount; - } - - /** - * Invokes the delegate's read(byte[]) method, detecting and optionally skipping BOM. - * - * @param buf the buffer to read the bytes into - * @return the number of bytes read (excluding BOM) or -1 if the end of stream - * @throws IOException if an I/O error occurs - */ - @Override - public int read(final byte[] buf) throws IOException { - return read(buf, 0, buf.length); - } - - /** - * Invokes the delegate's mark(int) method. - * - * @param readlimit read ahead limit - */ - @Override - public synchronized void mark(final int readlimit) { - markFbIndex = fbIndex; - markedAtStart = firstBytes == null; - in.mark(readlimit); - } - - /** - * Invokes the delegate's reset() method. - * - * @throws IOException if an I/O error occurs - */ - @Override - public synchronized void reset() throws IOException { - fbIndex = markFbIndex; - if (markedAtStart) { - firstBytes = null; - } - - in.reset(); - } - - /** - * Invokes the delegate's skip(long) method, detecting and optionallyskipping BOM. - * - * @param n the number of bytes to skip - * @return the number of bytes to skipped or -1 if the end of stream - * @throws IOException if an I/O error occurs - */ - @Override - public long skip(long n) throws IOException { - int skipped = 0; - while ((n > skipped) && (readFirstBytes() >= 0)) { - skipped++; - } - return in.skip(n - skipped) + skipped; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/io/ByteOrderMark.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/io/ByteOrderMark.java deleted file mode 100644 index 236a57ea29d..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/io/ByteOrderMark.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright 2022 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. - * - */ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE - * file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file - * to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ctrip.framework.foundation.internals.io; - -import java.io.Serializable; - -/** - * Byte Order Mark (BOM) representation - see {@link BOMInputStream}. - * - * @see BOMInputStream - * @see Wikipedia: Byte Order Mark - * @see W3C: Autodetection of Character Encodings - * (Non-Normative) - * @version $Id: ByteOrderMark.java 1586504 2014-04-10 23:34:37Z ggregory $ - * @since 2.0 - */ -public class ByteOrderMark implements Serializable { - - private static final long serialVersionUID = 1L; - - /** UTF-8 BOM */ - public static final ByteOrderMark UTF_8 = new ByteOrderMark("UTF-8", 0xEF, 0xBB, 0xBF); - - /** UTF-16BE BOM (Big-Endian) */ - public static final ByteOrderMark UTF_16BE = new ByteOrderMark("UTF-16BE", 0xFE, 0xFF); - - /** UTF-16LE BOM (Little-Endian) */ - public static final ByteOrderMark UTF_16LE = new ByteOrderMark("UTF-16LE", 0xFF, 0xFE); - - /** - * UTF-32BE BOM (Big-Endian) - * - * @since 2.2 - */ - public static final ByteOrderMark UTF_32BE = new ByteOrderMark("UTF-32BE", 0x00, 0x00, 0xFE, 0xFF); - - /** - * UTF-32LE BOM (Little-Endian) - * - * @since 2.2 - */ - public static final ByteOrderMark UTF_32LE = new ByteOrderMark("UTF-32LE", 0xFF, 0xFE, 0x00, 0x00); - - /** - * Unicode BOM character; external form depends on the encoding. - * - * @see Byte Order Mark (BOM) FAQ - * @since 2.5 - */ - public static final char UTF_BOM = '\uFEFF'; - - private final String charsetName; - private final int[] bytes; - - /** - * Construct a new BOM. - * - * @param charsetName The name of the charset the BOM represents - * @param bytes The BOM's bytes - * @throws IllegalArgumentException if the charsetName is null or zero length - * @throws IllegalArgumentException if the bytes are null or zero length - */ - public ByteOrderMark(final String charsetName, final int... bytes) { - if (charsetName == null || charsetName.isEmpty()) { - throw new IllegalArgumentException("No charsetName specified"); - } - if (bytes == null || bytes.length == 0) { - throw new IllegalArgumentException("No bytes specified"); - } - this.charsetName = charsetName; - this.bytes = new int[bytes.length]; - System.arraycopy(bytes, 0, this.bytes, 0, bytes.length); - } - - /** - * Return the name of the {@link java.nio.charset.Charset} the BOM represents. - * - * @return the character set name - */ - public String getCharsetName() { - return charsetName; - } - - /** - * Return the length of the BOM's bytes. - * - * @return the length of the BOM's bytes - */ - public int length() { - return bytes.length; - } - - /** - * The byte at the specified position. - * - * @param pos The position - * @return The specified byte - */ - public int get(final int pos) { - return bytes[pos]; - } - - /** - * Return a copy of the BOM's bytes. - * - * @return a copy of the BOM's bytes - */ - public byte[] getBytes() { - final byte[] copy = new byte[bytes.length]; - for (int i = 0; i < bytes.length; i++) { - copy[i] = (byte) bytes[i]; - } - return copy; - } - - /** - * Indicates if this BOM's bytes equals another. - * - * @param obj The object to compare to - * @return true if the bom's bytes are equal, otherwise false - */ - @Override - public boolean equals(final Object obj) { - if (!(obj instanceof ByteOrderMark)) { - return false; - } - final ByteOrderMark bom = (ByteOrderMark) obj; - if (bytes.length != bom.length()) { - return false; - } - for (int i = 0; i < bytes.length; i++) { - if (bytes[i] != bom.get(i)) { - return false; - } - } - return true; - } - - /** - * Return the hashcode for this BOM. - * - * @return the hashcode for this BOM. - * @see Object#hashCode() - */ - @Override - public int hashCode() { - int hashCode = getClass().hashCode(); - for (final int b : bytes) { - hashCode += b; - } - return hashCode; - } - - /** - * Provide a String representation of the BOM. - * - * @return the length of the BOM's bytes - */ - @Override - public String toString() { - final StringBuilder builder = new StringBuilder(); - builder.append(getClass().getSimpleName()); - builder.append('['); - builder.append(charsetName); - builder.append(": "); - for (int i = 0; i < bytes.length; i++) { - if (i > 0) { - builder.append(","); - } - builder.append("0x"); - builder.append(Integer.toHexString(0xFF & bytes[i]).toUpperCase()); - } - builder.append(']'); - return builder.toString(); - } - -} - - diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/io/IOUtils.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/io/IOUtils.java deleted file mode 100644 index a46d5d3c762..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/io/IOUtils.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2022 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; -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/io/ProxyInputStream.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/io/ProxyInputStream.java deleted file mode 100644 index f8d972cf26b..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/io/ProxyInputStream.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright 2022 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. - * - */ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE - * file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file - * to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the - * License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - */ -package com.ctrip.framework.foundation.internals.io; - -import static com.ctrip.framework.foundation.internals.io.IOUtils.EOF; - -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; - -/** - * A Proxy stream which acts as expected, that is it passes the method calls on to the proxied stream and doesn't change - * which methods are being called. - *

- * It is an alternative base class to FilterInputStream to increase reusability, because FilterInputStream changes the - * methods being called, such as read(byte[]) to read(byte[], int, int). - *

- * See the protected methods for ways in which a subclass can easily decorate a stream with custom pre-, post- or error - * processing functionality. - * - * @version $Id: ProxyInputStream.java 1603493 2014-06-18 15:46:07Z ggregory $ - */ -public abstract class ProxyInputStream extends FilterInputStream { - - /** - * Constructs a new ProxyInputStream. - * - * @param proxy the InputStream to delegate to - */ - public ProxyInputStream(final InputStream proxy) { - super(proxy); - // the proxy is stored in a protected superclass variable named 'in' - } - - /** - * Invokes the delegate's read() method. - * - * @return the byte read or -1 if the end of stream - * @throws IOException if an I/O error occurs - */ - @Override - public int read() throws IOException { - try { - beforeRead(1); - final int b = in.read(); - afterRead(b != EOF ? 1 : EOF); - return b; - } catch (final IOException e) { - handleIOException(e); - return EOF; - } - } - - /** - * Invokes the delegate's read(byte[]) method. - * - * @param bts the buffer to read the bytes into - * @return the number of bytes read or EOF if the end of stream - * @throws IOException if an I/O error occurs - */ - @Override - public int read(final byte[] bts) throws IOException { - try { - beforeRead(bts != null ? bts.length : 0); - final int n = in.read(bts); - afterRead(n); - return n; - } catch (final IOException e) { - handleIOException(e); - return EOF; - } - } - - /** - * Invokes the delegate's read(byte[], int, int) method. - * - * @param bts the buffer to read the bytes into - * @param off The start offset - * @param len The number of bytes to read - * @return the number of bytes read or -1 if the end of stream - * @throws IOException if an I/O error occurs - */ - @Override - public int read(final byte[] bts, final int off, final int len) throws IOException { - try { - beforeRead(len); - final int n = in.read(bts, off, len); - afterRead(n); - return n; - } catch (final IOException e) { - handleIOException(e); - return EOF; - } - } - - /** - * Invokes the delegate's skip(long) method. - * - * @param ln the number of bytes to skip - * @return the actual number of bytes skipped - * @throws IOException if an I/O error occurs - */ - @Override - public long skip(final long ln) throws IOException { - try { - return in.skip(ln); - } catch (final IOException e) { - handleIOException(e); - return 0; - } - } - - /** - * Invokes the delegate's available() method. - * - * @return the number of available bytes - * @throws IOException if an I/O error occurs - */ - @Override - public int available() throws IOException { - try { - return super.available(); - } catch (final IOException e) { - handleIOException(e); - return 0; - } - } - - /** - * Invokes the delegate's close() method. - * - * @throws IOException if an I/O error occurs - */ - @Override - public void close() throws IOException { - try { - in.close(); - } catch (final IOException e) { - handleIOException(e); - } - } - - /** - * Invokes the delegate's mark(int) method. - * - * @param readlimit read ahead limit - */ - @Override - public synchronized void mark(final int readlimit) { - in.mark(readlimit); - } - - /** - * Invokes the delegate's reset() method. - * - * @throws IOException if an I/O error occurs - */ - @Override - public synchronized void reset() throws IOException { - try { - in.reset(); - } catch (final IOException e) { - handleIOException(e); - } - } - - /** - * Invokes the delegate's markSupported() method. - * - * @return true if mark is supported, otherwise false - */ - @Override - public boolean markSupported() { - return in.markSupported(); - } - - /** - * Invoked by the read methods before the call is proxied. The number of bytes that the caller wanted to read (1 for - * the {@link #read()} method, buffer length for {@link #read(byte[])}, etc.) is given as an argument. - *

- * Subclasses can override this method to add common pre-processing functionality without having to override all the - * read methods. The default implementation does nothing. - *

- * Note this method is not called from {@link #skip(long)} or {@link #reset()}. You need to explicitly - * override those methods if you want to add pre-processing steps also to them. - * - * @since 2.0 - * @param n number of bytes that the caller asked to be read - * @throws IOException if the pre-processing fails - */ - protected void beforeRead(final int n) throws IOException { - // no-op - } - - /** - * Invoked by the read methods after the proxied call has returned successfully. The number of bytes returned to the - * caller (or -1 if the end of stream was reached) is given as an argument. - *

- * Subclasses can override this method to add common post-processing functionality without having to override all the - * read methods. The default implementation does nothing. - *

- * Note this method is not called from {@link #skip(long)} or {@link #reset()}. You need to explicitly - * override those methods if you want to add post-processing steps also to them. - * - * @since 2.0 - * @param n number of bytes read, or -1 if the end of stream was reached - * @throws IOException if the post-processing fails - */ - protected void afterRead(final int n) throws IOException { - // no-op - } - - /** - * Handle any IOExceptions thrown. - *

- * This method provides a point to implement custom exception handling. The default behaviour is to re-throw the - * exception. - * - * @param e The IOException thrown - * @throws IOException if an I/O error occurs - * @since 2.0 - */ - protected void handleIOException(final IOException e) throws IOException { - throw e; - } - -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/DefaultApplicationProvider.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/DefaultApplicationProvider.java deleted file mode 100644 index aaf8808511b..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/DefaultApplicationProvider.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright 2022 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.provider; - -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; -import com.ctrip.framework.apollo.core.utils.DeprecatedPropertyNotifyUtil; -import com.ctrip.framework.foundation.internals.Utils; -import com.ctrip.framework.foundation.internals.io.BOMInputStream; -import com.ctrip.framework.foundation.spi.provider.ApplicationProvider; -import com.ctrip.framework.foundation.spi.provider.Provider; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.Properties; -import org.slf4j.Logger; - -public class DefaultApplicationProvider implements ApplicationProvider { - - private static final Logger logger = DeferredLoggerFactory - .getLogger(DefaultApplicationProvider.class); - public static final String APP_PROPERTIES_CLASSPATH = "/META-INF/app.properties"; - private Properties m_appProperties = new Properties(); - - private String m_appId; - private String m_appLabel; - private String accessKeySecret; - - @Override - public void initialize() { - try { - InputStream in = Thread.currentThread().getContextClassLoader() - .getResourceAsStream(APP_PROPERTIES_CLASSPATH.substring(1)); - if (in == null) { - in = DefaultApplicationProvider.class.getResourceAsStream(APP_PROPERTIES_CLASSPATH); - } - - initialize(in); - } catch (Throwable ex) { - logger.error("Initialize DefaultApplicationProvider failed.", ex); - } - } - - @Override - public void initialize(InputStream in) { - try { - if (in != null) { - try { - m_appProperties - .load(new InputStreamReader(new BOMInputStream(in), StandardCharsets.UTF_8)); - } finally { - in.close(); - } - } - - initAppId(); - initAppLabel(); - initAccessKey(); - } catch (Throwable ex) { - logger.error("Initialize DefaultApplicationProvider failed.", ex); - } - } - - @Override - public String getAppId() { - return m_appId; - } - - @Override - public String getApolloLabel() { - return m_appLabel; - } - - @Override - public String getAccessKeySecret() { - return accessKeySecret; - } - - @Override - public boolean isAppIdSet() { - return !Utils.isBlank(m_appId); - } - - @Override - public String getProperty(String name, String defaultValue) { - if (ApolloClientSystemConsts.APP_ID.equals(name)) { - String val = getAppId(); - return val == null ? defaultValue : val; - } - - if (ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET.equals(name)) { - String val = getAccessKeySecret(); - return val == null ? defaultValue : val; - } - - String val = m_appProperties.getProperty(name, defaultValue); - return val == null ? defaultValue : val; - } - - @Override - public Class getType() { - return ApplicationProvider.class; - } - - private void initAppId() { - // 1. Get app.id from System Property - m_appId = System.getProperty(ApolloClientSystemConsts.APP_ID); - if (!Utils.isBlank(m_appId)) { - m_appId = m_appId.trim(); - logger.info("App ID is set to {} by app.id property from System Property", m_appId); - return; - } - - //2. Try to get app id from OS environment variable - m_appId = System.getenv(ApolloClientSystemConsts.APP_ID_ENVIRONMENT_VARIABLES); - if (!Utils.isBlank(m_appId)) { - m_appId = m_appId.trim(); - logger.info("App ID is set to {} by APP_ID property from OS environment variable", m_appId); - return; - } - - // 3. Try to get app id from app.properties. - m_appId = m_appProperties.getProperty(ApolloClientSystemConsts.APP_ID); - if (!Utils.isBlank(m_appId)) { - m_appId = m_appId.trim(); - logger.info("App ID is set to {} by app.id property from {}", m_appId, - APP_PROPERTIES_CLASSPATH); - return; - } - - m_appId = null; - logger.warn("app.id is not available from System Property and {}. It is set to null", - APP_PROPERTIES_CLASSPATH); - } - - private void initAppLabel() { - // 1. Get app.label from System Property - m_appLabel = System.getProperty(ApolloClientSystemConsts.APOLLO_LABEL); - if (!Utils.isBlank(m_appLabel)) { - m_appLabel = m_appLabel.trim(); - logger.info("App Label is set to {} by app.label property from System Property", m_appLabel); - return; - } - - //2. Try to get app label from OS environment variable - m_appLabel = System.getenv(ApolloClientSystemConsts.APOLLO_LABEL_ENVIRONMENT_VARIABLES); - if (!Utils.isBlank(m_appLabel)) { - m_appLabel = m_appLabel.trim(); - logger.info("App Label is set to {} by APP_LABEL property from OS environment variable", m_appLabel); - return; - } - - // 3. Try to get app label from app.properties. - m_appLabel = m_appProperties.getProperty(ApolloClientSystemConsts.APOLLO_LABEL); - if (!Utils.isBlank(m_appLabel)) { - m_appLabel = m_appLabel.trim(); - logger.info("App Label is set to {} by app.label property from {}", m_appLabel, - APP_PROPERTIES_CLASSPATH); - return; - } - - m_appLabel = null; - logger.warn("app.label is not available from System Property and {}. It is set to null", - APP_PROPERTIES_CLASSPATH); - } - - private void initAccessKey() { - // 1. Get ACCESS KEY SECRET from System Property - accessKeySecret = System.getProperty(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET); - if (!Utils.isBlank(accessKeySecret)) { - accessKeySecret = accessKeySecret.trim(); - logger - .info("ACCESS KEY SECRET is set by apollo.access-key.secret property from System Property"); - return; - } - - //2. Try to get ACCESS KEY SECRET from OS environment variable - accessKeySecret = System.getenv(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES); - if (!Utils.isBlank(accessKeySecret)) { - accessKeySecret = accessKeySecret.trim(); - logger.info( - "ACCESS KEY SECRET is set by APOLLO_ACCESS_KEY_SECRET property from OS environment variable"); - return; - } - - // 3. Try to get ACCESS KEY SECRET from app.properties. - accessKeySecret = m_appProperties.getProperty(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET); - if (!Utils.isBlank(accessKeySecret)) { - accessKeySecret = accessKeySecret.trim(); - logger.info("ACCESS KEY SECRET is set by apollo.access-key.secret property from {}", - APP_PROPERTIES_CLASSPATH); - return; - } - - // 4. Try to get ACCESS KEY SECRET from deprecated config. - accessKeySecret = initDeprecatedAccessKey(); - if (!Utils.isBlank(accessKeySecret)) { - return; - } - accessKeySecret = null; - } - - @SuppressWarnings("deprecation") - private String initDeprecatedAccessKey() { - // 1. Get ACCESS KEY SECRET from System Property - String accessKeySecret = System - .getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET); - if (!Utils.isBlank(accessKeySecret)) { - accessKeySecret = accessKeySecret.trim(); - logger.info( - "ACCESS KEY SECRET is set by apollo.accesskey.secret property from System Property"); - DeprecatedPropertyNotifyUtil - .warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET, - ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET); - return accessKeySecret; - } - - //2. Try to get ACCESS KEY SECRET from OS environment variable - accessKeySecret = System - .getenv(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES); - if (!Utils.isBlank(accessKeySecret)) { - accessKeySecret = accessKeySecret.trim(); - logger.info( - "ACCESS KEY SECRET is set by APOLLO_ACCESSKEY_SECRET property from OS environment variable"); - DeprecatedPropertyNotifyUtil - .warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES, - ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET_ENVIRONMENT_VARIABLES); - return accessKeySecret; - } - - // 3. Try to get ACCESS KEY SECRET from app.properties. - accessKeySecret = m_appProperties - .getProperty(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET); - if (!Utils.isBlank(accessKeySecret)) { - accessKeySecret = accessKeySecret.trim(); - logger.info("ACCESS KEY SECRET is set by apollo.accesskey.secret property from {}", - APP_PROPERTIES_CLASSPATH); - DeprecatedPropertyNotifyUtil - .warn(ApolloClientSystemConsts.DEPRECATED_APOLLO_ACCESS_KEY_SECRET, - ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET); - return accessKeySecret; - } - return null; - } - - @Override - public String toString() { - return "appId [" + getAppId() + "] properties: " + m_appProperties - + " (DefaultApplicationProvider)"; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/DefaultNetworkProvider.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/DefaultNetworkProvider.java deleted file mode 100644 index 46c15a945d4..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/DefaultNetworkProvider.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2022 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.provider; - -import com.ctrip.framework.foundation.internals.NetworkInterfaceManager; -import com.ctrip.framework.foundation.spi.provider.NetworkProvider; -import com.ctrip.framework.foundation.spi.provider.Provider; - -public class DefaultNetworkProvider implements NetworkProvider { - @Override - public String getProperty(String name, String defaultValue) { - if ("host.address".equalsIgnoreCase(name)) { - String val = getHostAddress(); - return val == null ? defaultValue : val; - } - if ("host.name".equalsIgnoreCase(name)) { - String val = getHostName(); - return val == null ? defaultValue : val; - } - return defaultValue; - } - - @Override - public void initialize() { - - } - - @Override - public String getHostAddress() { - return NetworkInterfaceManager.INSTANCE.getLocalHostAddress(); - } - - @Override - public String getHostName() { - return NetworkInterfaceManager.INSTANCE.getLocalHostName(); - } - - @Override - public Class getType() { - return NetworkProvider.class; - } - - @Override - public String toString() { - return "hostName [" + getHostName() + "] hostIP [" + getHostAddress() + "] (DefaultNetworkProvider)"; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/DefaultServerProvider.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/DefaultServerProvider.java deleted file mode 100644 index 076d7406c97..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/DefaultServerProvider.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Copyright 2022 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. - * - */ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package com.ctrip.framework.foundation.internals.provider; - -import com.ctrip.framework.apollo.core.utils.DeferredLoggerFactory; -import com.google.common.base.Strings; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.Properties; - -import com.ctrip.framework.foundation.internals.Utils; -import com.ctrip.framework.foundation.internals.io.BOMInputStream; -import com.ctrip.framework.foundation.spi.provider.Provider; -import com.ctrip.framework.foundation.spi.provider.ServerProvider; -import org.slf4j.Logger; - -public class DefaultServerProvider implements ServerProvider { - - private static final Logger logger = DeferredLoggerFactory.getLogger(DefaultServerProvider.class); - - static final String DEFAULT_SERVER_PROPERTIES_PATH_ON_LINUX = "/opt/settings/server.properties"; - static final String DEFAULT_SERVER_PROPERTIES_PATH_ON_WINDOWS = "C:/opt/settings/server.properties"; - private String m_env; - private String m_dc; - - private final Properties m_serverProperties = new Properties(); - - String getServerPropertiesPath() { - final String serverPropertiesPath = getCustomizedServerPropertiesPath(); - - if (!Strings.isNullOrEmpty(serverPropertiesPath)) { - return serverPropertiesPath; - } - - return Utils.isOSWindows() ? DEFAULT_SERVER_PROPERTIES_PATH_ON_WINDOWS - : DEFAULT_SERVER_PROPERTIES_PATH_ON_LINUX; - } - - private String getCustomizedServerPropertiesPath() { - // 1. Get from System Property - final String serverPropertiesPathFromSystemProperty = System - .getProperty("apollo.path.server.properties"); - if (!Strings.isNullOrEmpty(serverPropertiesPathFromSystemProperty)) { - return serverPropertiesPathFromSystemProperty; - } - - // 2. Get from OS environment variable - final String serverPropertiesPathFromEnvironment = System - .getenv("APOLLO_PATH_SERVER_PROPERTIES"); - if (!Strings.isNullOrEmpty(serverPropertiesPathFromEnvironment)) { - return serverPropertiesPathFromEnvironment; - } - - // last, return null if there is no custom value - return null; - } - - @Override - public void initialize() { - try { - File file = new File(this.getServerPropertiesPath()); - if (file.exists() && file.canRead()) { - logger.info("Loading {}", file.getAbsolutePath()); - FileInputStream fis = new FileInputStream(file); - initialize(fis); - return; - } - - initialize(null); - } catch (Throwable ex) { - logger.error("Initialize DefaultServerProvider failed.", ex); - } - } - - @Override - public void initialize(InputStream in) { - try { - if (in != null) { - try { - m_serverProperties - .load(new InputStreamReader(new BOMInputStream(in), StandardCharsets.UTF_8)); - } finally { - in.close(); - } - } - - initEnvType(); - initDataCenter(); - } catch (Throwable ex) { - logger.error("Initialize DefaultServerProvider failed.", ex); - } - } - - @Override - public String getDataCenter() { - return m_dc; - } - - @Override - public boolean isDataCenterSet() { - return m_dc != null; - } - - @Override - public String getEnvType() { - return m_env; - } - - @Override - public boolean isEnvTypeSet() { - return m_env != null; - } - - @Override - public String getProperty(String name, String defaultValue) { - if ("env".equalsIgnoreCase(name)) { - String val = getEnvType(); - return val == null ? defaultValue : val; - } - if ("dc".equalsIgnoreCase(name)) { - String val = getDataCenter(); - return val == null ? defaultValue : val; - } - String val = m_serverProperties.getProperty(name, defaultValue); - return val == null ? defaultValue : val.trim(); - } - - @Override - public Class getType() { - return ServerProvider.class; - } - - private void initEnvType() { - // 1. Try to get environment from JVM system property - m_env = System.getProperty("env"); - if (!Utils.isBlank(m_env)) { - m_env = m_env.trim(); - logger.info("Environment is set to [{}] by JVM system property 'env'.", m_env); - return; - } - - // 2. Try to get environment from OS environment variable - m_env = System.getenv("ENV"); - if (!Utils.isBlank(m_env)) { - m_env = m_env.trim(); - logger.info("Environment is set to [{}] by OS env variable 'ENV'.", m_env); - return; - } - - // 3. Try to get environment from file "server.properties" - m_env = m_serverProperties.getProperty("env"); - if (!Utils.isBlank(m_env)) { - m_env = m_env.trim(); - logger.info("Environment is set to [{}] by property 'env' in server.properties.", m_env); - return; - } - - // 4. Set environment to null. - m_env = null; - logger.info( - "Environment is set to null. Because it is not available in either (1) JVM system property 'env', (2) OS env variable 'ENV' nor (3) property 'env' from the properties InputStream."); - } - - private void initDataCenter() { - // 1. Try to get environment from JVM system property - m_dc = System.getProperty("idc"); - if (!Utils.isBlank(m_dc)) { - m_dc = m_dc.trim(); - logger.info("Data Center is set to [{}] by JVM system property 'idc'.", m_dc); - return; - } - - // 2. Try to get idc from OS environment variable - m_dc = System.getenv("IDC"); - if (!Utils.isBlank(m_dc)) { - m_dc = m_dc.trim(); - logger.info("Data Center is set to [{}] by OS env variable 'IDC'.", m_dc); - return; - } - - // 3. Try to get idc from from file "server.properties" - m_dc = m_serverProperties.getProperty("idc"); - if (!Utils.isBlank(m_dc)) { - m_dc = m_dc.trim(); - logger.info("Data Center is set to [{}] by property 'idc' in server.properties.", m_dc); - return; - } - - // 4. Set Data Center to null. - m_dc = null; - logger.debug( - "Data Center is set to null. Because it is not available in either (1) JVM system property 'idc', (2) OS env variable 'IDC' nor (3) property 'idc' from the properties InputStream."); - } - - @Override - public String toString() { - return "environment [" + getEnvType() + "] data center [" + getDataCenter() + "] properties: " - + m_serverProperties - + " (DefaultServerProvider)"; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/NullProvider.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/NullProvider.java deleted file mode 100644 index 838dbaddbdf..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/internals/provider/NullProvider.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2022 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.provider; - -import java.io.InputStream; - -import com.ctrip.framework.foundation.spi.provider.ApplicationProvider; -import com.ctrip.framework.foundation.spi.provider.NetworkProvider; -import com.ctrip.framework.foundation.spi.provider.Provider; -import com.ctrip.framework.foundation.spi.provider.ServerProvider; - -public class NullProvider implements ApplicationProvider, NetworkProvider, ServerProvider { - @Override - public Class getType() { - return null; - } - - @Override - public String getProperty(String name, String defaultValue) { - return defaultValue; - } - - @Override - public void initialize() { - - } - - @Override - public String getAppId() { - return null; - } - - @Override - public String getApolloLabel() { - return null; - } - - @Override - public String getAccessKeySecret() { - return null; - } - - @Override - public boolean isAppIdSet() { - return false; - } - - @Override - public String getEnvType() { - return null; - } - - @Override - public boolean isEnvTypeSet() { - return false; - } - - @Override - public String getDataCenter() { - return null; - } - - @Override - public boolean isDataCenterSet() { - return false; - } - - @Override - public void initialize(InputStream in) { - - } - - @Override - public String getHostAddress() { - return null; - } - - @Override - public String getHostName() { - return null; - } - - @Override - public String toString() { - return "(NullProvider)"; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/ProviderManager.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/ProviderManager.java deleted file mode 100644 index 72a4e571f1e..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/ProviderManager.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2022 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.spi; - -import com.ctrip.framework.apollo.core.spi.Ordered; -import com.ctrip.framework.foundation.spi.provider.Provider; - -public interface ProviderManager extends Ordered { - - String getProperty(String name, String defaultValue); - - T provider(Class clazz); - - @Override - default int getOrder() { - return Ordered.LOWEST_PRECEDENCE; - } -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/provider/ApplicationProvider.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/provider/ApplicationProvider.java deleted file mode 100644 index 17275e2d5b1..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/provider/ApplicationProvider.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2022 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.spi.provider; - -import java.io.InputStream; - -/** - * Provider for application related properties - */ -public interface ApplicationProvider extends Provider { - /** - * @return the application's app id - */ - String getAppId(); - - /** - * @return the application's app label - */ - String getApolloLabel(); - - /** - * @return the application's access key secret - */ - String getAccessKeySecret(); - - /** - * @return whether the application's app id is set or not - */ - boolean isAppIdSet(); - - /** - * Initialize the application provider with the specified input stream - */ - void initialize(InputStream in); -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/provider/NetworkProvider.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/provider/NetworkProvider.java deleted file mode 100644 index f14ad3a676b..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/provider/NetworkProvider.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2022 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.spi.provider; - -/** - * Provider for network related properties - */ -public interface NetworkProvider extends Provider { - /** - * @return the host address, i.e. ip - */ - String getHostAddress(); - - /** - * @return the host name - */ - String getHostName(); -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/provider/Provider.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/provider/Provider.java deleted file mode 100644 index e0922ad0c1b..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/provider/Provider.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2022 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.spi.provider; - -public interface Provider { - /** - * @return the current provider's type - */ - Class getType(); - - /** - * Return the property value with the given name, or {@code defaultValue} if the name doesn't exist. - * - * @param name the property name - * @param defaultValue the default value when name is not found or any error occurred - * @return the property value - */ - String getProperty(String name, String defaultValue); - - /** - * Initialize the provider - */ - void initialize(); -} diff --git a/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/provider/ServerProvider.java b/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/provider/ServerProvider.java deleted file mode 100644 index 8cd051dff7d..00000000000 --- a/apollo-core/src/main/java/com/ctrip/framework/foundation/spi/provider/ServerProvider.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2022 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.spi.provider; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Provider for server related properties - */ -public interface ServerProvider extends Provider { - /** - * @return current environment or {@code null} if not set - */ - String getEnvType(); - - /** - * @return whether current environment is set or not - */ - boolean isEnvTypeSet(); - - /** - * @return current data center or {@code null} if not set - */ - String getDataCenter(); - - /** - * @return whether data center is set or not - */ - boolean isDataCenterSet(); - - /** - * Initialize server provider with the specified input stream - * - * @throws IOException - */ - void initialize(InputStream in) throws IOException; -} diff --git a/apollo-core/src/main/resources/META-INF/services/com.ctrip.framework.apollo.core.spi.MetaServerProvider b/apollo-core/src/main/resources/META-INF/services/com.ctrip.framework.apollo.core.spi.MetaServerProvider deleted file mode 100644 index 43484be9585..00000000000 --- a/apollo-core/src/main/resources/META-INF/services/com.ctrip.framework.apollo.core.spi.MetaServerProvider +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.core.internals.LegacyMetaServerProvider diff --git a/apollo-core/src/main/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager b/apollo-core/src/main/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager deleted file mode 100644 index eab7be59c50..00000000000 --- a/apollo-core/src/main/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.tracer.internals.DefaultMessageProducerManager \ No newline at end of file diff --git a/apollo-core/src/main/resources/META-INF/services/com.ctrip.framework.foundation.spi.ProviderManager b/apollo-core/src/main/resources/META-INF/services/com.ctrip.framework.foundation.spi.ProviderManager deleted file mode 100644 index 7c3cec046ba..00000000000 --- a/apollo-core/src/main/resources/META-INF/services/com.ctrip.framework.foundation.spi.ProviderManager +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.foundation.internals.DefaultProviderManager \ No newline at end of file diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/BaseIntegrationTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/BaseIntegrationTest.java deleted file mode 100644 index 6fa5a37b945..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/BaseIntegrationTest.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright 2022 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; - -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.tracer.internals.MockMessageProducerManager; -import com.ctrip.framework.apollo.tracer.spi.MessageProducer; -import com.ctrip.framework.apollo.tracer.spi.Transaction; -import java.io.IOException; -import java.net.ServerSocket; -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.Server; -import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.server.handler.ContextHandler; -import org.eclipse.jetty.server.handler.ContextHandlerCollection; -import org.junit.After; -import org.junit.Before; - -public abstract class BaseIntegrationTest { - protected static final int PORT = findFreePort(); - private Server server; - - /** - * init and start a jetty server, remember to call server.stop when the task is finished - */ - protected Server startServerWithHandlers(ContextHandler... handlers) throws Exception { - server = new Server(PORT); - - ContextHandlerCollection contexts = new ContextHandlerCollection(); - contexts.setHandlers(handlers); - - server.setHandler(contexts); - server.start(); - - return server; - } - - - @Before - public void setUp() throws Exception { - MessageProducer someProducer = mock(MessageProducer.class); - MockMessageProducerManager.setProducer(someProducer); - - Transaction someTransaction = mock(Transaction.class); - - when(someProducer.newTransaction(anyString(), anyString())).thenReturn(someTransaction); - } - - @After - public void tearDown() throws Exception { - if (server != null && server.isStarted()) { - server.stop(); - } - } - - protected ContextHandler mockServerHandler(final int statusCode, final String response) { - ContextHandler context = new ContextHandler("/"); - context.setHandler(new AbstractHandler() { - - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, - HttpServletResponse response) throws IOException, ServletException { - - response.setContentType("text/plain;charset=UTF-8"); - response.setStatus(statusCode); - response.getWriter().println(response); - baseRequest.setHandled(true); - } - }); - return context; - } - - /** - * Returns a free port number on localhost. - * - * Heavily inspired from org.eclipse.jdt.launching.SocketUtil (to avoid a dependency to JDT just because of this). - * Slightly improved with close() missing in JDT. And throws exception instead of returning -1. - * - * @return a free port number on localhost - * @throws IllegalStateException if unable to find a free port - */ - protected static int findFreePort() { - ServerSocket socket = null; - try { - socket = new ServerSocket(0); - socket.setReuseAddress(true); - int port = socket.getLocalPort(); - try { - socket.close(); - } catch (IOException e) { - // Ignore IOException on close() - } - return port; - } catch (IOException e) { - } finally { - if (socket != null) { - try { - socket.close(); - } catch (IOException e) { - } - } - } - throw new IllegalStateException("Could not find a free TCP/IP port to start embedded Jetty HTTP Server on"); - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/MetaDomainTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/MetaDomainTest.java deleted file mode 100644 index c64cebc5c90..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/MetaDomainTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2022 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; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.ctrip.framework.apollo.BaseIntegrationTest; -import com.ctrip.framework.apollo.core.enums.Env; -import com.ctrip.framework.apollo.core.internals.LegacyMetaServerProvider; -import com.ctrip.framework.apollo.core.spi.MetaServerProvider; -import com.google.common.collect.Maps; -import java.util.Map; -import javax.servlet.http.HttpServletResponse; -import org.junit.After; -import org.junit.Test; - -public class MetaDomainTest extends BaseIntegrationTest { - - @Override - @After - public void tearDown() throws Exception { - super.tearDown(); - MockMetaServerProvider.clear(); - } - - @Test - public void testGetMetaDomain() { - assertEquals("http://localhost:8080", MetaDomainConsts.getDomain(Env.LOCAL)); - assertEquals("http://dev:8080", MetaDomainConsts.getDomain(Env.DEV)); - assertEquals(MetaDomainConsts.DEFAULT_META_URL, MetaDomainConsts.getDomain(Env.PRO)); - } - - @Test - public void testGetValidAddress() throws Exception { - String someResponse = "some response"; - startServerWithHandlers(mockServerHandler(HttpServletResponse.SC_OK, someResponse)); - - String validServer = " http://localhost:" + PORT + " "; - String invalidServer = "http://localhost:" + findFreePort(); - - MockMetaServerProvider.mock(Env.FAT, validServer + "," + invalidServer); - MockMetaServerProvider.mock(Env.UAT, invalidServer + "," + validServer); - - assertEquals(validServer.trim(), MetaDomainConsts.getDomain(Env.FAT)); - assertEquals(validServer.trim(), MetaDomainConsts.getDomain(Env.UAT)); - } - - @Test - public void testInvalidAddress() throws Exception { - String invalidServer = "http://localhost:" + findFreePort() + " "; - String anotherInvalidServer = "http://localhost:" + findFreePort() + " "; - - MockMetaServerProvider.mock(Env.LPT, invalidServer + "," + anotherInvalidServer); - - String metaServer = MetaDomainConsts.getDomain(Env.LPT); - - assertTrue(metaServer.equals(invalidServer.trim()) || metaServer.equals(anotherInvalidServer.trim())); - } - - public static class MockMetaServerProvider implements MetaServerProvider { - - private static Map mockMetaServerAddress = Maps.newHashMap(); - - private static void mock(Env env, String metaServerAddress) { - mockMetaServerAddress.put(env, metaServerAddress); - } - - private static void clear() { - mockMetaServerAddress.clear(); - } - - @Override - public String getMetaServerAddress(Env targetEnv) { - return mockMetaServerAddress.get(targetEnv); - } - - @Override - public int getOrder() { - return LegacyMetaServerProvider.ORDER - 1;// just in front of LegacyMetaServerProvider - } - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/enums/ConfigFileFormatTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/enums/ConfigFileFormatTest.java deleted file mode 100644 index f33c362df56..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/enums/ConfigFileFormatTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2022 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.enums; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.jupiter.api.Assertions.assertFalse; - -import java.util.ArrayList; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; - -/** - * Tests the {@link ConfigFileFormat} enum. - * - * @author Diego Krupitza(info@diegokrupitza.com) - */ -public class ConfigFileFormatTest { - - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - @Test - public void testFromStringEqualsOriginal() { - assertEquals(ConfigFileFormat.Properties, - ConfigFileFormat.fromString(ConfigFileFormat.Properties.getValue())); - assertEquals(ConfigFileFormat.XML, - ConfigFileFormat.fromString(ConfigFileFormat.XML.getValue())); - assertEquals(ConfigFileFormat.JSON, - ConfigFileFormat.fromString(ConfigFileFormat.JSON.getValue())); - assertEquals(ConfigFileFormat.YML, - ConfigFileFormat.fromString(ConfigFileFormat.YML.getValue())); - assertEquals(ConfigFileFormat.YAML, - ConfigFileFormat.fromString(ConfigFileFormat.YAML.getValue())); - assertEquals(ConfigFileFormat.TXT, - ConfigFileFormat.fromString(ConfigFileFormat.TXT.getValue())); - } - - @Test - public void testNonExistingValueFromString() { - expectedEx.expect(IllegalArgumentException.class); - expectedEx.expectMessage("thisShouldNotExistPropertiesXML can not map enum"); - - ConfigFileFormat.fromString("thisShouldNotExistPropertiesXML"); - } - - @Test - public void testEmptyValueFromString() { - expectedEx.expect(IllegalArgumentException.class); - expectedEx.expectMessage("value can not be empty"); - - ConfigFileFormat.fromString(""); - } - - @Test - public void testSpacedValueFromString() { - expectedEx.expect(IllegalArgumentException.class); - expectedEx.expectMessage(" can not map enum"); - - ConfigFileFormat.fromString(" "); - } - - @Test - public void testSpecialCharsValueFromString() { - ArrayList specialChars = new ArrayList<>(); - specialChars.add(" "); - specialChars.add("\t"); - specialChars.add(" \t"); - specialChars.add(" \t "); - specialChars.add("\t "); - - specialChars.forEach(item -> { - assertEquals(ConfigFileFormat.Properties, - ConfigFileFormat.fromString(item + ConfigFileFormat.Properties.getValue() + item)); - assertEquals(ConfigFileFormat.XML, - ConfigFileFormat.fromString(item + ConfigFileFormat.XML.getValue() + item)); - assertEquals(ConfigFileFormat.JSON, - ConfigFileFormat.fromString(item + ConfigFileFormat.JSON.getValue() + item)); - assertEquals(ConfigFileFormat.YML, - ConfigFileFormat.fromString(item + ConfigFileFormat.YML.getValue() + item)); - assertEquals(ConfigFileFormat.YAML, - ConfigFileFormat.fromString(item + ConfigFileFormat.YAML.getValue() + item)); - assertEquals(ConfigFileFormat.TXT, - ConfigFileFormat.fromString(item + ConfigFileFormat.TXT.getValue() + item)); - }); - } - - @Test - public void testIsValidFormatForOriginalContent() { - assertTrue(ConfigFileFormat.isValidFormat(ConfigFileFormat.Properties.getValue())); - assertTrue(ConfigFileFormat.isValidFormat(ConfigFileFormat.XML.getValue())); - assertTrue(ConfigFileFormat.isValidFormat(ConfigFileFormat.JSON.getValue())); - assertTrue(ConfigFileFormat.isValidFormat(ConfigFileFormat.YML.getValue())); - assertTrue(ConfigFileFormat.isValidFormat(ConfigFileFormat.YAML.getValue())); - assertTrue(ConfigFileFormat.isValidFormat(ConfigFileFormat.TXT.getValue())); - - assertTrue( - ConfigFileFormat.isValidFormat(ConfigFileFormat.Properties.getValue().toUpperCase())); - assertTrue(ConfigFileFormat.isValidFormat(ConfigFileFormat.XML.getValue().toUpperCase())); - assertTrue(ConfigFileFormat.isValidFormat(ConfigFileFormat.JSON.getValue().toUpperCase())); - assertTrue(ConfigFileFormat.isValidFormat(ConfigFileFormat.YML.getValue().toUpperCase())); - assertTrue(ConfigFileFormat.isValidFormat(ConfigFileFormat.YAML.getValue().toUpperCase())); - assertTrue(ConfigFileFormat.isValidFormat(ConfigFileFormat.TXT.getValue().toUpperCase())); - } - - @Test - public void testIsValidFormatForInvalid() { - assertFalse(ConfigFileFormat.isValidFormat("thisshouldnotexist")); - } - - @Test - public void testIfPropertiesCompatible() { - assertTrue(ConfigFileFormat.isPropertiesCompatible(ConfigFileFormat.YAML)); - assertTrue(ConfigFileFormat.isPropertiesCompatible(ConfigFileFormat.YML)); - assertTrue(ConfigFileFormat.isPropertiesCompatible(ConfigFileFormat.Properties)); - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/enums/EnvUtilsTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/enums/EnvUtilsTest.java deleted file mode 100644 index f839da8c4c9..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/enums/EnvUtilsTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2022 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.enums; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class EnvUtilsTest { - - @Test - public void testTransformEnv() throws Exception { - assertEquals(Env.DEV, EnvUtils.transformEnv(Env.DEV.name())); - assertEquals(Env.FAT, EnvUtils.transformEnv(Env.FAT.name().toLowerCase())); - assertEquals(Env.UAT, EnvUtils.transformEnv(" " + Env.UAT.name().toUpperCase() + "")); - assertEquals(Env.UNKNOWN, EnvUtils.transformEnv("someInvalidEnv")); - } - - @Test - public void testFromString() throws Exception { - assertEquals(Env.DEV, Env.fromString(Env.DEV.name())); - assertEquals(Env.FAT, Env.fromString(Env.FAT.name().toLowerCase())); - assertEquals(Env.UAT, Env.fromString(" " + Env.UAT.name().toUpperCase() + "")); - } - - @Test(expected = IllegalArgumentException.class) - public void testFromInvalidString() throws Exception { - Env.fromString("someInvalidEnv"); - } - - @Test - public void fixTypoInProductionTest() { - Env prod = Env.fromString("PROD"); - assertEquals(prod, Env.PRO); - } - - @Test(expected = IllegalArgumentException.class) - public void fromBlankStringTest() { - Env.fromString(""); - } - - @Test(expected = IllegalArgumentException.class) - public void fromSpacesStringTest() { - Env.fromString(" "); - } - - @Test(expected = IllegalArgumentException.class) - public void fromNullStringTest() { - Env.fromString(null); - } - -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProviderTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProviderTest.java deleted file mode 100644 index b8ba4f701da..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProviderTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2022 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.internals; - -import static org.junit.Assert.assertEquals; - -import com.ctrip.framework.apollo.core.enums.Env; -import org.junit.After; -import org.junit.Test; - -public class LegacyMetaServerProviderTest { - - @After - public void tearDown() throws Exception { - System.clearProperty("dev_meta"); - } - - @Test - public void testFromPropertyFile() { - LegacyMetaServerProvider legacyMetaServerProvider = new LegacyMetaServerProvider(); - assertEquals("http://localhost:8080", legacyMetaServerProvider.getMetaServerAddress(Env.LOCAL)); - assertEquals("http://dev:8080", legacyMetaServerProvider.getMetaServerAddress(Env.DEV)); - assertEquals(null, legacyMetaServerProvider.getMetaServerAddress(Env.PRO)); - } - - @Test - public void testWithSystemProperty() throws Exception { - String someDevMetaAddress = "someMetaAddress"; - String someFatMetaAddress = "someFatMetaAddress"; - System.setProperty("dev_meta", someDevMetaAddress); - System.setProperty("fat_meta", someFatMetaAddress); - - LegacyMetaServerProvider legacyMetaServerProvider = new LegacyMetaServerProvider(); - - assertEquals(someDevMetaAddress, legacyMetaServerProvider.getMetaServerAddress(Env.DEV)); - assertEquals(someFatMetaAddress, legacyMetaServerProvider.getMetaServerAddress(Env.FAT)); - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/signature/HmacSha1UtilsTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/signature/HmacSha1UtilsTest.java deleted file mode 100644 index 89048127f60..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/signature/HmacSha1UtilsTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2022 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.signature; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -/** - * @author nisiyong - */ -public class HmacSha1UtilsTest { - - @Test - public void testSignString() { - String stringToSign = "1576478257344\n/configs/100004458/default/application?ip=10.0.0.1"; - String accessKeySecret = "df23df3f59884980844ff3dada30fa97"; - - String actualSignature = HmacSha1Utils.signString(stringToSign, accessKeySecret); - - String expectedSignature = "EoKyziXvKqzHgwx+ijDJwgVTDgE="; - assertEquals(expectedSignature, actualSignature); - } -} \ No newline at end of file diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/signature/SignatureTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/signature/SignatureTest.java deleted file mode 100644 index 99a9e061f85..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/signature/SignatureTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2022 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.signature; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import com.google.common.net.HttpHeaders; -import java.util.Map; -import org.junit.Test; - -/** - * @author nisiyong - */ -public class SignatureTest { - - @Test - public void testSignature() { - String timestamp = "1576478257344"; - String pathWithQuery = "/configs/100004458/default/application?ip=10.0.0.1"; - String secret = "df23df3f59884980844ff3dada30fa97"; - - String actualSignature = Signature.signature(timestamp, pathWithQuery, secret); - - String expectedSignature = "EoKyziXvKqzHgwx+ijDJwgVTDgE="; - assertEquals(expectedSignature, actualSignature); - } - - @Test - public void testBuildHttpHeaders() { - String url = "http://10.0.0.1:8080/configs/100004458/default/application?ip=10.0.0.1"; - String appId = "100004458"; - String secret = "df23df3f59884980844ff3dada30fa97"; - - Map actualHttpHeaders = Signature.buildHttpHeaders(url, appId, secret); - - assertTrue(actualHttpHeaders.containsKey(HttpHeaders.AUTHORIZATION)); - assertTrue(actualHttpHeaders.containsKey(Signature.HTTP_HEADER_TIMESTAMP)); - } -} \ No newline at end of file diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/ByteUtilTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/ByteUtilTest.java deleted file mode 100644 index e04dccb9f85..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/ByteUtilTest.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import com.ctrip.framework.apollo.core.utils.ByteUtil; -import org.junit.Assert; -import org.junit.Test; - -public class ByteUtilTest { - - @Test - public void testInt3() { - Assert.assertEquals((byte)0, ByteUtil.int3(0)); - Assert.assertEquals((byte)0, ByteUtil.int3(1)); - } - - @Test - public void testInt2() { - Assert.assertEquals((byte)0, ByteUtil.int2(0)); - Assert.assertEquals((byte)0, ByteUtil.int2(1)); - } - - @Test - public void testInt1() { - Assert.assertEquals((byte)0, ByteUtil.int1(0)); - Assert.assertEquals((byte)0, ByteUtil.int1(1)); - } - - @Test - public void testInt0() { - Assert.assertEquals((byte)0, ByteUtil.int0(0)); - Assert.assertEquals((byte)1, ByteUtil.int0(1)); - } - - @Test - public void testToHexString() { - Assert.assertEquals("", ByteUtil.toHexString(new byte[] {})); - Assert.assertEquals("98", ByteUtil.toHexString(new byte[] {(byte)-104})); - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/ClassLoaderUtilTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/ClassLoaderUtilTest.java deleted file mode 100644 index 8635d5c42dd..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/ClassLoaderUtilTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class ClassLoaderUtilTest { - private static boolean shouldFailInInitialization = false; - @Test - public void testGetClassLoader() { - assertNotNull(ClassLoaderUtil.getLoader()); - } - - @Test - public void testIsClassPresent() { - assertTrue(ClassLoaderUtil.isClassPresent("java.lang.String")); - } - - @Test - public void testIsClassPresentWithClassNotFound() { - assertFalse(ClassLoaderUtil.isClassPresent("java.lang.StringNotFound")); - } - - @Test - public void testIsClassPresentWithLinkageError() { - shouldFailInInitialization = true; - assertFalse(ClassLoaderUtil.isClassPresent(ClassWithInitializationError.class.getName())); - } - - public static class ClassWithInitializationError { - static { - if (ClassLoaderUtilTest.shouldFailInInitialization) { - throw new RuntimeException("Some initialization exception"); - } - } - } -} \ No newline at end of file diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/DeferredLogCacheTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/DeferredLogCacheTest.java deleted file mode 100644 index f54733c5e61..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/DeferredLogCacheTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import com.ctrip.framework.test.tools.AloneRunner; -import com.ctrip.framework.test.tools.AloneWith; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author kl (http://kailing.pub) - * @since 2021/5/20 - */ -@RunWith(AloneRunner.class) -@AloneWith(JUnit4.class) -public class DeferredLogCacheTest { - - private final Logger logger = LoggerFactory.getLogger(getClass()); - private static final String logMsg = "hello kl"; - - @Test - public void testDeferredLogCacheMaxLogSize() { - for (int i = 0; i < 20000; i++) { - DeferredLogCache.info(logger, "DeferredLogUtilTest"); - } - Assert.assertEquals(DeferredLogCache.logSize(), DeferredLogCache.MAX_LOG_SIZE); - } - - @Test - public void testDisableDeferred() { - DeferredLogCache.clear(); - DeferredLogger.disable(); - final Logger defaultLogger = DeferredLoggerFactory.getLogger(DeferredLoggerTest.class); - defaultLogger.info(logMsg); - defaultLogger.debug(logMsg); - defaultLogger.warn(logMsg); - Assert.assertEquals(0, DeferredLogCache.logSize()); - - } - - @Test - public void testEnableDeferred() { - final Logger defaultLogger = DeferredLoggerFactory.getLogger(DeferredLoggerTest.class); - DeferredLogger.enable(); - - defaultLogger.info(logMsg); - defaultLogger.debug(logMsg); - defaultLogger.warn(logMsg); - Assert.assertEquals(3, DeferredLogCache.logSize()); - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/DeferredLoggerStateTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/DeferredLoggerStateTest.java deleted file mode 100644 index e4deed31283..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/DeferredLoggerStateTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import com.ctrip.framework.test.tools.AloneRunner; -import com.ctrip.framework.test.tools.AloneWith; -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; - -/** - * @author kl (http://kailing.pub) - * @since 2021/5/21 - */ -@RunWith(AloneRunner.class) -@AloneWith(JUnit4.class) -public class DeferredLoggerStateTest { - - @Test - public void testDeferredState() { - Assert.assertFalse(DeferredLogger.isEnabled()); - - DeferredLogger.enable(); - Assert.assertTrue(DeferredLogger.isEnabled()); - - DeferredLogger.replayTo(); - Assert.assertFalse(DeferredLogger.isEnabled()); - - DeferredLogger.enable(); - Assert.assertFalse(DeferredLogger.isEnabled()); - } - -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/DeferredLoggerTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/DeferredLoggerTest.java deleted file mode 100644 index ac161e0678b..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/DeferredLoggerTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import com.ctrip.framework.test.tools.AloneRunner; -import com.ctrip.framework.test.tools.AloneWith; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.JUnit4; -import org.slf4j.Logger; - -/** - * @author kl (http://kailing.pub) - * @since 2021/5/11 - */ -@RunWith(AloneRunner.class) -@AloneWith(JUnit4.class) -public class DeferredLoggerTest { - - private static ByteArrayOutputStream outContent; - private static Logger logger = null; - private static PrintStream printStream; - - @BeforeClass - public static void init() throws NoSuchFieldException, IllegalAccessException { - DeferredLoggerTest.outContent = new ByteArrayOutputStream(); - DeferredLoggerTest.printStream = new PrintStream(DeferredLoggerTest.outContent); - System.setOut(DeferredLoggerTest.printStream); - DeferredLoggerTest.logger = DeferredLoggerFactory.getLogger("DeferredLoggerTest"); - } - - @Test - public void testErrorLog() { - DeferredLoggerTest.logger.error("errorLogger"); - Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("errorLogger")); - } - - @Test - public void testInfoLog() { - DeferredLoggerTest.logger.info("inFoLogger"); - Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("inFoLogger")); - } - - @Test - public void testWarnLog() { - DeferredLoggerTest.logger.warn("warnLogger"); - Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("warnLogger")); - } - - @Test - public void testDebugLog() { - DeferredLoggerTest.logger.warn("debugLogger"); - Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("debugLogger")); - } - - @Test - public void testDeferredLog() { - DeferredLogger.enable(); - - DeferredLoggerTest.logger.error("errorLogger_testDeferredLog"); - DeferredLoggerTest.logger.info("inFoLogger_testDeferredLog"); - DeferredLoggerTest.logger.warn("warnLogger_testDeferredLog"); - DeferredLoggerTest.logger.debug("debugLogger_testDeferredLog"); - - Assert.assertFalse(DeferredLoggerTest.outContent.toString().contains("errorLogger_testDeferredLog")); - Assert.assertFalse(DeferredLoggerTest.outContent.toString().contains("inFoLogger_testDeferredLog")); - Assert.assertFalse(DeferredLoggerTest.outContent.toString().contains("warnLogger_testDeferredLog")); - Assert.assertFalse(DeferredLoggerTest.outContent.toString().contains("debugLogger_testDeferredLog")); - - DeferredLogCache.replayTo(); - - Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("errorLogger_testDeferredLog")); - Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("inFoLogger_testDeferredLog")); - Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("warnLogger_testDeferredLog")); - Assert.assertTrue(DeferredLoggerTest.outContent.toString().contains("debugLogger_testDeferredLog")); - - } - -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/NetUtilTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/NetUtilTest.java deleted file mode 100644 index 1e8c960eeb2..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/NetUtilTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.ctrip.framework.apollo.BaseIntegrationTest; -import javax.servlet.http.HttpServletResponse; -import org.eclipse.jetty.server.handler.ContextHandler; -import org.junit.Test; - -/** - * Created by gl49 on 2018/6/8. - */ -public class NetUtilTest extends BaseIntegrationTest { - - @Test - public void testPingUrlWithStatusCode200() throws Exception { - String someResponse = "some response"; - ContextHandler handler = mockServerHandler(HttpServletResponse.SC_OK, someResponse); - startServerWithHandlers(handler); - - assertTrue(NetUtil.pingUrl("http://localhost:" + PORT)); - } - - @Test - public void testPingUrlWithStatusCode404() throws Exception { - String someResponse = "some response"; - startServerWithHandlers(mockServerHandler(HttpServletResponse.SC_NOT_FOUND, someResponse)); - - assertFalse(NetUtil.pingUrl("http://localhost:" + PORT)); - } - - @Test - public void testPingUrlWithServerNotStarted() throws Exception { - assertFalse(NetUtil.pingUrl("http://localhost:" + PORT)); - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/PropertiesUtilTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/PropertiesUtilTest.java deleted file mode 100644 index ad54fd3589d..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/PropertiesUtilTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - - -import java.io.IOException; -import java.util.Properties; - - -public class PropertiesUtilTest { - - - @Test - public void testToString() throws IOException { - - assertEquals("", PropertiesUtil.toString(new Properties())); - assertNotEquals(" ", PropertiesUtil.toString(new Properties())); - - Properties properties = new Properties(); - properties.put("a", "aaa"); - assertEquals("a=aaa" + System.lineSeparator(), PropertiesUtil.toString(properties)); - } - - @Test - public void testFilterPropertiesComment() { - - StringBuffer sb1 = new StringBuffer(System.lineSeparator()); - PropertiesUtil.filterPropertiesComment(sb1); - boolean equals = "".equals(sb1.toString()); - assertEquals(false, equals); - - StringBuffer sb2 = new StringBuffer("#aaa" + System.lineSeparator()); - PropertiesUtil.filterPropertiesComment(sb2); - assertEquals("", sb2.toString()); - - StringBuffer sb3 = new StringBuffer("#aaaaa" + System.lineSeparator() + "bbb"); - PropertiesUtil.filterPropertiesComment(sb3); - assertEquals("bbb", sb3.toString()); - assertNotEquals("#aaaaa" + System.lineSeparator() + "bbb", sb3.toString()); - - StringBuffer sb4 = new StringBuffer("#aaaa"); - PropertiesUtil.filterPropertiesComment(sb4); - assertEquals("#aaaa", sb4.toString()); - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/StringUtilsTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/StringUtilsTest.java deleted file mode 100644 index 5b9ab8a08a9..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/core/utils/StringUtilsTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import org.junit.Assert; -import org.junit.Test; - -import java.util.ArrayList; - -public class StringUtilsTest { - - @Test - public void testEqualsIgnoreCase() { - Assert.assertFalse(StringUtils.equalsIgnoreCase(",", "foo")); - Assert.assertFalse(StringUtils.equalsIgnoreCase(null, "??")); - Assert.assertTrue(StringUtils.equalsIgnoreCase(null, null)); - Assert.assertTrue(StringUtils.equalsIgnoreCase("foo", "Foo")); - } - - @Test - public void testEquals() { - Assert.assertFalse(StringUtils.equals(null, "")); - Assert.assertTrue(StringUtils.equals(null, null)); - Assert.assertTrue(StringUtils.equals("3", "3")); - } - - @Test - public void testIsBlank() { - Assert.assertFalse(StringUtils.isBlank("\'")); - Assert.assertTrue(StringUtils.isBlank("")); - Assert.assertTrue(StringUtils.isBlank(null)); - } - - @Test - public void testIsContainEmpty() { - Assert.assertFalse(StringUtils.isContainEmpty(null)); - Assert.assertFalse(StringUtils.isContainEmpty(new String[] {})); - Assert.assertFalse(StringUtils.isContainEmpty(new String[] {"1"})); - Assert.assertTrue(StringUtils.isContainEmpty(new String[] {null})); - } - - @Test - public void testIsEmpty() { - Assert.assertFalse(StringUtils.isEmpty("1")); - Assert.assertTrue(StringUtils.isEmpty(null)); - Assert.assertTrue(StringUtils.isEmpty("")); - } - - @Test - public void testIsNumeric() { - Assert.assertFalse(StringUtils.isNumeric(null)); - Assert.assertFalse(StringUtils.isNumeric("\'")); - Assert.assertTrue(StringUtils.isNumeric("1")); - } - - @Test - public void testStartsWithIgnoreCase() { - Assert.assertFalse(StringUtils.startsWithIgnoreCase("A1B2C3", "BAZ")); - Assert.assertFalse(StringUtils.startsWithIgnoreCase(",", "BAZ")); - Assert.assertTrue(StringUtils.startsWithIgnoreCase("bar", "BAR")); - } - - @Test - public void testStartsWith() { - Assert.assertFalse(StringUtils.startsWith("1234", "1a 2b 3c")); - Assert.assertTrue(StringUtils.startsWith("1a 2b 3c", "1a 2b 3c")); - Assert.assertTrue(StringUtils.startsWith(null, null)); - } - - @Test - public void testTrim() { - Assert.assertEquals("1234", StringUtils.trim("1234")); - Assert.assertNull(StringUtils.trim(null)); - } - - @Test - public void testTrimToEmpty() { - Assert.assertEquals("1234", StringUtils.trimToEmpty("1234")); - Assert.assertEquals("", StringUtils.trimToEmpty(null)); - } - - @Test - public void trimToNull() { - Assert.assertNull(StringUtils.trimToNull(null)); - Assert.assertEquals("foo", StringUtils.trimToNull("foo")); - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/TracerTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/TracerTest.java deleted file mode 100644 index 598babc9460..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/TracerTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright 2022 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.tracer; - -import com.ctrip.framework.apollo.tracer.internals.MockMessageProducerManager; -import com.ctrip.framework.apollo.tracer.internals.NullTransaction; -import com.ctrip.framework.apollo.tracer.spi.MessageProducer; -import com.ctrip.framework.apollo.tracer.spi.Transaction; - -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doThrow; -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(song_s@ctrip.com) - */ -public class TracerTest { - private MessageProducer someProducer; - - @Before - public void setUp() throws Exception { - someProducer = mock(MessageProducer.class); - MockMessageProducerManager.setProducer(someProducer); - } - - @Test - public void testLogError() throws Exception { - String someMessage = "someMessage"; - Throwable someCause = mock(Throwable.class); - - Tracer.logError(someMessage, someCause); - - verify(someProducer, times(1)).logError(someMessage, someCause); - } - - @Test - public void testLogErrorWithException() throws Exception { - String someMessage = "someMessage"; - Throwable someCause = mock(Throwable.class); - doThrow(RuntimeException.class).when(someProducer).logError(someMessage, someCause); - - Tracer.logError(someMessage, someCause); - - verify(someProducer, times(1)).logError(someMessage, someCause); - } - - @Test - public void testLogErrorWithOnlyCause() throws Exception { - Throwable someCause = mock(Throwable.class); - - Tracer.logError(someCause); - - verify(someProducer, times(1)).logError(someCause); - } - - @Test - public void testLogErrorWithOnlyCauseWithException() throws Exception { - Throwable someCause = mock(Throwable.class); - doThrow(RuntimeException.class).when(someProducer).logError(someCause); - - Tracer.logError(someCause); - - verify(someProducer, times(1)).logError(someCause); - } - - @Test - public void testLogEvent() throws Exception { - String someType = "someType"; - String someName = "someName"; - - Tracer.logEvent(someType, someName); - - verify(someProducer, times(1)).logEvent(someType, someName); - } - - @Test - public void testLogEventWithException() throws Exception { - String someType = "someType"; - String someName = "someName"; - doThrow(RuntimeException.class).when(someProducer).logEvent(someType, someName); - - Tracer.logEvent(someType, someName); - - verify(someProducer, times(1)).logEvent(someType, someName); - } - - @Test - public void testLogEventWithStatusAndNameValuePairs() throws Exception { - String someType = "someType"; - String someName = "someName"; - String someStatus = "someStatus"; - String someNameValuePairs = "someNameValuePairs"; - - Tracer.logEvent(someType, someName, someStatus, someNameValuePairs); - - verify(someProducer, times(1)).logEvent(someType, someName, someStatus, someNameValuePairs); - } - - @Test - public void testLogEventWithStatusAndNameValuePairsWithException() throws Exception { - String someType = "someType"; - String someName = "someName"; - String someStatus = "someStatus"; - String someNameValuePairs = "someNameValuePairs"; - doThrow(RuntimeException.class).when(someProducer).logEvent(someType, someName, someStatus, - someNameValuePairs); - - Tracer.logEvent(someType, someName, someStatus, someNameValuePairs); - - verify(someProducer, times(1)).logEvent(someType, someName, someStatus, someNameValuePairs); - } - - @Test - public void testNewTransaction() throws Exception { - String someType = "someType"; - String someName = "someName"; - Transaction someTransaction = mock(Transaction.class); - - when(someProducer.newTransaction(someType, someName)).thenReturn(someTransaction); - - Transaction result = Tracer.newTransaction(someType, someName); - - verify(someProducer, times(1)).newTransaction(someType, someName); - assertEquals(someTransaction, result); - } - - @Test - public void testNewTransactionWithException() throws Exception { - String someType = "someType"; - String someName = "someName"; - - when(someProducer.newTransaction(someType, someName)).thenThrow(RuntimeException.class); - - Transaction result = Tracer.newTransaction(someType, someName); - - verify(someProducer, times(1)).newTransaction(someType, someName); - assertTrue(result instanceof NullTransaction); - } -} \ No newline at end of file diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManagerTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManagerTest.java deleted file mode 100644 index ed3314c01d4..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/internals/DefaultMessageProducerManagerTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2022 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.tracer.internals; - -import com.ctrip.framework.apollo.tracer.internals.cat.CatMessageProducer; -import com.ctrip.framework.apollo.tracer.spi.MessageProducerManager; - -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class DefaultMessageProducerManagerTest { - private MessageProducerManager messageProducerManager; - - @Before - public void setUp() throws Exception { - messageProducerManager = new DefaultMessageProducerManager(); - } - - @Test - public void testGetProducer() throws Exception { - assertTrue(messageProducerManager.getProducer() instanceof CatMessageProducer); - } - -} \ No newline at end of file diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/internals/MockMessageProducerManager.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/internals/MockMessageProducerManager.java deleted file mode 100644 index 9177c4801e0..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/internals/MockMessageProducerManager.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2022 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.tracer.internals; - -import com.ctrip.framework.apollo.tracer.spi.MessageProducer; -import com.ctrip.framework.apollo.tracer.spi.MessageProducerManager; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class MockMessageProducerManager implements MessageProducerManager { - private static MessageProducer s_producer; - - @Override - public MessageProducer getProducer() { - return s_producer; - } - - public static void setProducer(MessageProducer producer) { - s_producer = producer; - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/internals/NullMessageProducerManagerTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/internals/NullMessageProducerManagerTest.java deleted file mode 100644 index b74c2b681b8..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/internals/NullMessageProducerManagerTest.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2022 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.tracer.internals; - -import com.ctrip.framework.apollo.tracer.spi.MessageProducerManager; - -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class NullMessageProducerManagerTest { - private MessageProducerManager messageProducerManager; - - @Before - public void setUp() throws Exception { - messageProducerManager = new NullMessageProducerManager(); - } - - @Test - public void testGetProducer() throws Exception { - assertTrue(messageProducerManager.getProducer() instanceof NullMessageProducer); - } -} \ No newline at end of file diff --git a/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/internals/NullMessageProducerTest.java b/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/internals/NullMessageProducerTest.java deleted file mode 100644 index 0960a1f9142..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/apollo/tracer/internals/NullMessageProducerTest.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2022 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.tracer.internals; - -import com.ctrip.framework.apollo.tracer.spi.MessageProducer; - -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.*; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class NullMessageProducerTest { - private MessageProducer messageProducer; - - @Before - public void setUp() throws Exception { - messageProducer = new NullMessageProducer(); - } - - @Test - public void testNewTransaction() throws Exception { - String someType = "someType"; - String someName = "someName"; - assertTrue(messageProducer.newTransaction(someType, someName) instanceof NullTransaction); - } - -} \ No newline at end of file diff --git a/apollo-core/src/test/java/com/ctrip/framework/foundation/FoundationTest.java b/apollo-core/src/test/java/com/ctrip/framework/foundation/FoundationTest.java deleted file mode 100644 index 39ed2f96c6d..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/foundation/FoundationTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2022 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; - -import static org.junit.Assert.assertTrue; - -import com.ctrip.framework.foundation.Foundation; -import com.ctrip.framework.foundation.internals.provider.DefaultApplicationProvider; -import com.ctrip.framework.foundation.internals.provider.DefaultServerProvider; -import org.junit.Assert; -import org.junit.Test; - -public class FoundationTest { - - @Test - public void testApp() { - assertTrue(Foundation.app() instanceof DefaultApplicationProvider); - } - - @Test - public void testServer() { - assertTrue(Foundation.server() instanceof DefaultServerProvider); - } - - @Test - public void testNet() { - // 获取本机IP和HostName - String hostAddress = Foundation.net().getHostAddress(); - String hostName = Foundation.net().getHostName(); - - Assert.assertNotNull("No host address detected.", hostAddress); - Assert.assertNotNull("No host name resolved.", hostName); - } - -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/foundation/internals/ServiceBootstrapTest.java b/apollo-core/src/test/java/com/ctrip/framework/foundation/internals/ServiceBootstrapTest.java deleted file mode 100644 index 1cb35cb3a73..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/foundation/internals/ServiceBootstrapTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.core.spi.Ordered; -import org.junit.Test; - -import java.util.ServiceConfigurationError; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * @author Jason Song(song_s@ctrip.com) - */ -public class ServiceBootstrapTest { - @Test - public void loadFirstSuccessfully() throws Exception { - Interface1 service = ServiceBootstrap.loadFirst(Interface1.class); - assertTrue(service instanceof Interface1Impl); - } - - @Test(expected = IllegalStateException.class) - public void loadFirstWithNoServiceFileDefined() throws Exception { - ServiceBootstrap.loadFirst(Interface2.class); - } - - @Test(expected = IllegalStateException.class) - public void loadFirstWithServiceFileButNoServiceImpl() throws Exception { - ServiceBootstrap.loadFirst(Interface3.class); - } - - @Test(expected = ServiceConfigurationError.class) - public void loadFirstWithWrongServiceImpl() throws Exception { - ServiceBootstrap.loadFirst(Interface4.class); - } - - @Test(expected = ServiceConfigurationError.class) - public void loadFirstWithServiceImplNotExists() throws Exception { - ServiceBootstrap.loadFirst(Interface5.class); - } - - @Test - public void loadAllWithServiceFileButNoServiceImpl() { - assertFalse(ServiceBootstrap.loadAll(Interface7.class).hasNext()); - } - - @Test - public void loadPrimarySuccessfully() { - Interface6 service = ServiceBootstrap.loadPrimary(Interface6.class); - assertTrue(service instanceof Interface6Impl1); - } - - @Test(expected = IllegalStateException.class) - public void loadPrimaryWithServiceFileButNoServiceImpl() { - ServiceBootstrap.loadPrimary(Interface7.class); - } - - @Test - public void loadAllOrderedWithServiceFileButNoServiceImpl() { - assertTrue(ServiceBootstrap.loadAllOrdered(Interface7.class).isEmpty()); - } - - interface Interface1 { - } - - public static class Interface1Impl implements Interface1 { - } - - interface Interface2 { - } - - interface Interface3 { - } - - interface Interface4 { - } - - interface Interface5 { - } - - interface Interface6 extends Ordered { - } - - public static class Interface6Impl1 implements Interface6 { - @Override - public int getOrder() { - return 1; - } - } - - public static class Interface6Impl2 implements Interface6 { - @Override - public int getOrder() { - return 2; - } - } - - interface Interface7 extends Ordered { - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/foundation/internals/UtilsTest.java b/apollo-core/src/test/java/com/ctrip/framework/foundation/internals/UtilsTest.java deleted file mode 100644 index f3d63e3a4f2..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/foundation/internals/UtilsTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2022 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; - -import org.junit.After; -import org.junit.Test; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class UtilsTest { - private final String actualOsName = System.getProperty("os.name"); - - @After - public void tearDown() { - System.setProperty("os.name", actualOsName); - } - - @Test - public void isBlankTrueGivenNull() { - assertTrue(Utils.isBlank(null)); - } - - @Test - public void isBlankTrueGivenEmpty() { - assertTrue(Utils.isBlank("")); - } - - @Test - public void isBlankTrueGivenWhitespace() { - assertTrue(Utils.isBlank(" ")); - } - - @Test - public void isBlankFalseGivenLoremIpsum() { - assertFalse(Utils.isBlank("Lorem Ipsum")); - } - - @Test - public void isBlankFalseGivenWhitespacePadded() { - assertFalse(Utils.isBlank(" Lorem Ipsum ")); - } - - @Test - public void isOsWindowsTrueGivenWindows10() { - System.setProperty("os.name", "Windows 10"); - assertTrue(Utils.isOSWindows()); - } - - @Test - public void isOSWindowsFalseGivenMacOsX() { - System.setProperty("os.name", "Mac OS X"); - assertFalse(Utils.isOSWindows()); - } - - @Test - public void isOSWindowsFalseGivenBlank() { - System.setProperty("os.name", ""); - assertFalse(Utils.isOSWindows()); - } - - // Explicitly calling out case sensitivity; revisit if Microsoft changes naming convention - @Test - public void isOSWindowsFalseGivenAllUppercaseWindows() { - System.setProperty("os.name", "WINDOWS 10"); - assertFalse(Utils.isOSWindows()); - } - - @Test - public void isOSWindowsFalseGivenAllLowercaseWindows() { - System.setProperty("os.name", "windows 10"); - assertFalse(Utils.isOSWindows()); - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/foundation/internals/provider/DefaultApplicationProviderTest.java b/apollo-core/src/test/java/com/ctrip/framework/foundation/internals/provider/DefaultApplicationProviderTest.java deleted file mode 100644 index d220b3a7778..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/foundation/internals/provider/DefaultApplicationProviderTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2022 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.provider; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import java.io.File; -import java.io.FileInputStream; -import org.junit.Before; -import org.junit.Test; - -public class DefaultApplicationProviderTest { - private DefaultApplicationProvider defaultApplicationProvider; - String PREDEFINED_APP_ID = "110402"; - - @Before - public void setUp() throws Exception { - defaultApplicationProvider = new DefaultApplicationProvider(); - } - - @Test - public void testLoadAppProperties() throws Exception { - defaultApplicationProvider.initialize(); - - assertEquals(PREDEFINED_APP_ID, defaultApplicationProvider.getAppId()); - assertTrue(defaultApplicationProvider.isAppIdSet()); - } - - @Test - public void testLoadAppPropertiesWithUTF8Bom() throws Exception { - File baseDir = new File("src/test/resources/META-INF"); - File appProperties = new File(baseDir, "app-with-utf8bom.properties"); - - defaultApplicationProvider.initialize(new FileInputStream(appProperties)); - - assertEquals(PREDEFINED_APP_ID, defaultApplicationProvider.getAppId()); - assertTrue(defaultApplicationProvider.isAppIdSet()); - } - - @Test - public void testLoadAppPropertiesWithSystemProperty() throws Exception { - String someAppId = "someAppId"; - String someSecret = "someSecret"; - System.setProperty(ApolloClientSystemConsts.APP_ID, someAppId); - System.setProperty(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET, someSecret); - defaultApplicationProvider.initialize(); - System.clearProperty(ApolloClientSystemConsts.APP_ID); - System.clearProperty(ApolloClientSystemConsts.APOLLO_ACCESS_KEY_SECRET); - - assertEquals(someAppId, defaultApplicationProvider.getAppId()); - assertTrue(defaultApplicationProvider.isAppIdSet()); - assertEquals(someSecret, defaultApplicationProvider.getAccessKeySecret()); - } - - @Test - public void testLoadAppPropertiesFailed() throws Exception { - File baseDir = new File("src/test/resources/META-INF"); - File appProperties = new File(baseDir, "some-invalid-app.properties"); - - defaultApplicationProvider.initialize(new FileInputStream(appProperties)); - - assertEquals(null, defaultApplicationProvider.getAppId()); - assertFalse(defaultApplicationProvider.isAppIdSet()); - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/foundation/internals/provider/DefaultServerProviderTest.java b/apollo-core/src/test/java/com/ctrip/framework/foundation/internals/provider/DefaultServerProviderTest.java deleted file mode 100644 index 7c4a131d05a..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/foundation/internals/provider/DefaultServerProviderTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2022 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.provider; - -import static com.ctrip.framework.foundation.internals.provider.DefaultServerProvider.DEFAULT_SERVER_PROPERTIES_PATH_ON_LINUX; -import static com.ctrip.framework.foundation.internals.provider.DefaultServerProvider.DEFAULT_SERVER_PROPERTIES_PATH_ON_WINDOWS; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import com.ctrip.framework.foundation.internals.Utils; -import java.io.File; -import java.io.FileInputStream; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import com.ctrip.framework.foundation.internals.provider.DefaultServerProvider; - -public class DefaultServerProviderTest { - private DefaultServerProvider defaultServerProvider; - - @Before - public void setUp() throws Exception { - cleanUp(); - defaultServerProvider = new DefaultServerProvider(); - } - - @After - public void tearDown() throws Exception { - cleanUp(); - } - - private void cleanUp() { - System.clearProperty("env"); - System.clearProperty("idc"); - System.clearProperty("apollo.path.server.properties"); - } - - @Test - public void testGetServerPropertiesPathDefault() { - assertEquals(Utils.isOSWindows() ? DEFAULT_SERVER_PROPERTIES_PATH_ON_WINDOWS - : DEFAULT_SERVER_PROPERTIES_PATH_ON_LINUX, defaultServerProvider.getServerPropertiesPath()); - } - - @Test - public void testGetServerPropertiesPathCustom() { - final String customPath = "/simple/custom/path"; - System.setProperty("apollo.path.server.properties", customPath); - assertEquals(customPath, defaultServerProvider.getServerPropertiesPath()); - } - - @Test - public void testEnvWithSystemProperty() throws Exception { - String someEnv = "someEnv"; - String someDc = "someDc"; - System.setProperty("env", someEnv); - System.setProperty("idc", someDc); - - defaultServerProvider.initialize(null); - - assertEquals(someEnv, defaultServerProvider.getEnvType()); - assertEquals(someDc, defaultServerProvider.getDataCenter()); - } - - @Test - public void testWithPropertiesStream() throws Exception { - File baseDir = new File("src/test/resources/properties"); - File serverProperties = new File(baseDir, "server.properties"); - defaultServerProvider.initialize(new FileInputStream(serverProperties)); - - assertEquals("SHAJQ", defaultServerProvider.getDataCenter()); - assertTrue(defaultServerProvider.isEnvTypeSet()); - assertEquals("DEV", defaultServerProvider.getEnvType()); - } - - @Test - public void testWithUTF8BomPropertiesStream() throws Exception { - File baseDir = new File("src/test/resources/properties"); - File serverProperties = new File(baseDir, "server-with-utf8bom.properties"); - defaultServerProvider.initialize(new FileInputStream(serverProperties)); - - assertEquals("SHAJQ", defaultServerProvider.getDataCenter()); - assertTrue(defaultServerProvider.isEnvTypeSet()); - assertEquals("DEV", defaultServerProvider.getEnvType()); - } - - @Test - public void testWithPropertiesStreamAndEnvFromSystemProperty() throws Exception { - String prodEnv = "pro"; - System.setProperty("env", prodEnv); - - File baseDir = new File("src/test/resources/properties"); - File serverProperties = new File(baseDir, "server.properties"); - defaultServerProvider.initialize(new FileInputStream(serverProperties)); - - String predefinedDataCenter = "SHAJQ"; - - assertEquals(predefinedDataCenter, defaultServerProvider.getDataCenter()); - assertTrue(defaultServerProvider.isEnvTypeSet()); - assertEquals(prodEnv, defaultServerProvider.getEnvType()); - } - - @Test - public void testWithNoPropertiesStream() throws Exception { - defaultServerProvider.initialize(null); - - assertNull(defaultServerProvider.getDataCenter()); - assertFalse(defaultServerProvider.isEnvTypeSet()); - assertNull(defaultServerProvider.getEnvType()); - } -} diff --git a/apollo-core/src/test/java/com/ctrip/framework/test/tools/AloneClassLoader.java b/apollo-core/src/test/java/com/ctrip/framework/test/tools/AloneClassLoader.java deleted file mode 100644 index 50136850e84..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/test/tools/AloneClassLoader.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2022 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.test.tools; - -import java.net.URLClassLoader; - -/** - * @author kl (http://kailing.pub) - * @since 2021/5/21 - */ -public class AloneClassLoader extends URLClassLoader { - - private final ClassLoader appClassLoader; - - public AloneClassLoader() { - super(((URLClassLoader) getSystemClassLoader()).getURLs(), - Thread.currentThread().getContextClassLoader().getParent()); - appClassLoader = Thread.currentThread().getContextClassLoader(); - } - - @Override - public Class loadClass(String name) throws ClassNotFoundException { - if (name.startsWith("org.junit.") || name.startsWith("junit.")) { - return appClassLoader.loadClass(name); - } - - return super.loadClass(name); - } -} \ No newline at end of file diff --git a/apollo-core/src/test/java/com/ctrip/framework/test/tools/AloneRunner.java b/apollo-core/src/test/java/com/ctrip/framework/test/tools/AloneRunner.java deleted file mode 100644 index 361f310a2d4..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/test/tools/AloneRunner.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2022 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.test.tools; - -import org.junit.runner.Description; -import org.junit.runner.Runner; -import org.junit.runner.notification.RunNotifier; -import org.junit.runners.JUnit4; -import org.junit.runners.model.InitializationError; - -/** - * @author kl (http://kailing.pub) - * @since 2021/5/21 - */ -public class AloneRunner extends Runner { - - private static final String CONSTRUCTOR_ERROR_FORMAT = "Custom runner class %s should have a public constructor with signature %s(Class testClass)"; - private final Runner realRunner; - - private final ClassLoader testCaseClassloader; - - public AloneRunner(Class clazz) throws InitializationError { - - AloneWith annotation = clazz.getAnnotation( - AloneWith.class); - - Class realClassRunnerClass = - annotation == null ? JUnit4.class : annotation.value(); - if (AloneRunner.class.isAssignableFrom(realClassRunnerClass)) { - throw new InitializationError("Dead-loop code"); - } - - testCaseClassloader = new AloneClassLoader(); - ClassLoader backupClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(testCaseClassloader); - try { - Class newTestCaseClass = testCaseClassloader.loadClass(clazz.getName()); - Class realRunnerClass = (Class) testCaseClassloader - .loadClass(realClassRunnerClass.getName()); - realRunner = buildRunner(realRunnerClass, newTestCaseClass); - } catch (ReflectiveOperationException e) { - throw new InitializationError(e); - } finally { - Thread.currentThread().setContextClassLoader(backupClassLoader); - } - } - - public Description getDescription() { - return realRunner.getDescription(); - } - - public void run(RunNotifier runNotifier) { - ClassLoader backupClassLoader = Thread.currentThread().getContextClassLoader(); - Thread.currentThread().setContextClassLoader(testCaseClassloader); - - realRunner.run(runNotifier); - - Thread.currentThread().setContextClassLoader(backupClassLoader); - } - - protected Runner buildRunner(Class runnerClass, - Class testClass) throws ReflectiveOperationException, InitializationError { - try { - return runnerClass.getConstructor(Class.class).newInstance(testClass); - } catch (NoSuchMethodException e) { - String simpleName = runnerClass.getSimpleName(); - throw new InitializationError(String.format( - CONSTRUCTOR_ERROR_FORMAT, simpleName, simpleName)); - } - } -} \ No newline at end of file diff --git a/apollo-core/src/test/java/com/ctrip/framework/test/tools/AloneWith.java b/apollo-core/src/test/java/com/ctrip/framework/test/tools/AloneWith.java deleted file mode 100644 index df28246323f..00000000000 --- a/apollo-core/src/test/java/com/ctrip/framework/test/tools/AloneWith.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2022 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.test.tools; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Inherited; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import org.junit.runner.Runner; - -/** - * @author kl (http://kailing.pub) - * @since 2021/5/21 - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) -@Inherited -public @interface AloneWith { - - Class value(); -} \ No newline at end of file diff --git a/apollo-core/src/test/resources/META-INF/app-with-utf8bom.properties b/apollo-core/src/test/resources/META-INF/app-with-utf8bom.properties deleted file mode 100644 index 4ee6867d699..00000000000 --- a/apollo-core/src/test/resources/META-INF/app-with-utf8bom.properties +++ /dev/null @@ -1 +0,0 @@ -app.id=110402 diff --git a/apollo-core/src/test/resources/META-INF/app.properties b/apollo-core/src/test/resources/META-INF/app.properties deleted file mode 100644 index b57d086b74d..00000000000 --- a/apollo-core/src/test/resources/META-INF/app.properties +++ /dev/null @@ -1,16 +0,0 @@ -# -# Copyright 2022 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. -# -app.id=110402 diff --git a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.apollo.core.spi.MetaServerProvider b/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.apollo.core.spi.MetaServerProvider deleted file mode 100644 index bd6d23f18db..00000000000 --- a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.apollo.core.spi.MetaServerProvider +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.core.MetaDomainTest$MockMetaServerProvider diff --git a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager b/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager deleted file mode 100644 index 2899c14e633..00000000000 --- a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.apollo.tracer.spi.MessageProducerManager +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.apollo.tracer.internals.MockMessageProducerManager \ No newline at end of file diff --git a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface1 b/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface1 deleted file mode 100644 index f18a65b80a1..00000000000 --- a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface1 +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface1Impl diff --git a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface3 b/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface3 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface4 b/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface4 deleted file mode 100644 index f18a65b80a1..00000000000 --- a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface4 +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface1Impl diff --git a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface5 b/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface5 deleted file mode 100644 index 9336e3616f7..00000000000 --- a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface5 +++ /dev/null @@ -1 +0,0 @@ -com.ctrip.framework.foundation.internals.ServiceBootstrapTest$SomeImplNotExists diff --git a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface6 b/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface6 deleted file mode 100644 index 7041108b20f..00000000000 --- a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface6 +++ /dev/null @@ -1,2 +0,0 @@ -com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface6Impl1 -com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface6Impl2 diff --git a/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface7 b/apollo-core/src/test/resources/META-INF/services/com.ctrip.framework.foundation.internals.ServiceBootstrapTest$Interface7 deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/apollo-core/src/test/resources/META-INF/some-invalid-app.properties b/apollo-core/src/test/resources/META-INF/some-invalid-app.properties deleted file mode 100644 index 8fdb28977ec..00000000000 --- a/apollo-core/src/test/resources/META-INF/some-invalid-app.properties +++ /dev/null @@ -1,16 +0,0 @@ -# -# Copyright 2022 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. -# -appid=110402 diff --git a/apollo-core/src/test/resources/apollo-env.properties b/apollo-core/src/test/resources/apollo-env.properties deleted file mode 100644 index 22931c84e2d..00000000000 --- a/apollo-core/src/test/resources/apollo-env.properties +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright 2022 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. -# -local.meta=http://localhost:8080 -dev.meta=http://dev:8080 diff --git a/apollo-core/src/test/resources/log4j2.xml b/apollo-core/src/test/resources/log4j2.xml deleted file mode 100644 index ca87727a822..00000000000 --- a/apollo-core/src/test/resources/log4j2.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/apollo-core/src/test/resources/properties/server-with-utf8bom.properties b/apollo-core/src/test/resources/properties/server-with-utf8bom.properties deleted file mode 100644 index ec5bf515514..00000000000 --- a/apollo-core/src/test/resources/properties/server-with-utf8bom.properties +++ /dev/null @@ -1,6 +0,0 @@ -idc=SHAJQ -env=DEV -subenv=Dev123 -bigdata=true -tooling=true -pci=true diff --git a/apollo-core/src/test/resources/properties/server.properties b/apollo-core/src/test/resources/properties/server.properties deleted file mode 100644 index 8e11723aac5..00000000000 --- a/apollo-core/src/test/resources/properties/server.properties +++ /dev/null @@ -1,21 +0,0 @@ -# -# Copyright 2022 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. -# -idc=SHAJQ -env=DEV -subenv=Dev123 -bigdata=true -tooling=true -pci=true diff --git a/apollo-mockserver/pom.xml b/apollo-mockserver/pom.xml deleted file mode 100644 index ecc30fb4016..00000000000 --- a/apollo-mockserver/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - - - apollo - com.ctrip.framework.apollo - ${revision} - - 4.0.0 - - apollo-mockserver - Apollo Mock Server - - - ${project.artifactId} - 4.9.3 - - - - - - com.squareup.okhttp3 - mockwebserver - ${okhttp3.version} - - - com.squareup.okhttp3 - okhttp - ${okhttp3.version} - - - - - - - com.ctrip.framework.apollo - apollo-client - - - com.squareup.okhttp3 - mockwebserver - - - com.squareup.okhttp3 - okhttp - - - org.springframework.boot - spring-boot-starter - test - - - - diff --git a/apollo-mockserver/src/main/java/com/ctrip/framework/apollo/mockserver/EmbeddedApollo.java b/apollo-mockserver/src/main/java/com/ctrip/framework/apollo/mockserver/EmbeddedApollo.java deleted file mode 100644 index 865ad4c2b84..00000000000 --- a/apollo-mockserver/src/main/java/com/ctrip/framework/apollo/mockserver/EmbeddedApollo.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright 2022 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.mockserver; - -import com.ctrip.framework.apollo.build.ApolloInjector; -import com.ctrip.framework.apollo.core.ApolloClientSystemConsts; -import com.ctrip.framework.apollo.core.dto.ApolloConfig; -import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification; -import com.ctrip.framework.apollo.core.utils.ResourceUtils; -import com.ctrip.framework.apollo.internals.ConfigServiceLocator; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import okhttp3.mockwebserver.Dispatcher; -import okhttp3.mockwebserver.MockResponse; -import okhttp3.mockwebserver.MockWebServer; -import okhttp3.mockwebserver.RecordedRequest; -import org.junit.rules.ExternalResource; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Create by zhangzheng on 8/22/18 Email:zhangzheng@youzan.com - */ -public class EmbeddedApollo extends ExternalResource { - - private static final Logger logger = LoggerFactory.getLogger(EmbeddedApollo.class); - private static final Type notificationType = new TypeToken>() { - }.getType(); - - private static Method CONFIG_SERVICE_LOCATOR_CLEAR; - private static ConfigServiceLocator CONFIG_SERVICE_LOCATOR; - - private static final Gson GSON = new Gson(); - private final Map> addedOrModifiedPropertiesOfNamespace = Maps.newConcurrentMap(); - private final Map> deletedKeysOfNamespace = Maps.newConcurrentMap(); - - private MockWebServer server; - - static { - try { - System.setProperty("apollo.longPollingInitialDelayInMills", "0"); - CONFIG_SERVICE_LOCATOR = ApolloInjector.getInstance(ConfigServiceLocator.class); - CONFIG_SERVICE_LOCATOR_CLEAR = ConfigServiceLocator.class.getDeclaredMethod("initConfigServices"); - CONFIG_SERVICE_LOCATOR_CLEAR.setAccessible(true); - } catch (NoSuchMethodException e) { - logger.error(e.getMessage(), e); - } - } - - @Override - protected void before() throws Throwable { - clear(); - server = new MockWebServer(); - final Dispatcher dispatcher = new Dispatcher() { - @Override - public MockResponse dispatch(RecordedRequest request) throws InterruptedException { - if (request.getPath().startsWith("/notifications/v2")) { - String notifications = request.getRequestUrl().queryParameter("notifications"); - return new MockResponse().setResponseCode(200).setBody(mockLongPollBody(notifications)); - } - if (request.getPath().startsWith("/configs")) { - List pathSegments = request.getRequestUrl().pathSegments(); - // appId and cluster might be used in the future - String appId = pathSegments.get(1); - String cluster = pathSegments.get(2); - String namespace = pathSegments.get(3); - return new MockResponse().setResponseCode(200).setBody(loadConfigFor(namespace)); - } - return new MockResponse().setResponseCode(404); - } - }; - - server.setDispatcher(dispatcher); - server.start(); - - mockConfigServiceUrl("http://localhost:" + server.getPort()); - - super.before(); - } - - @Override - protected void after() { - try { - clear(); - server.close(); - } catch (Exception e) { - logger.error("stop apollo server error", e); - } - } - - private void clear() throws Exception { - resetOverriddenProperties(); - } - - private void mockConfigServiceUrl(String url) throws Exception { - System.setProperty(ApolloClientSystemConsts.APOLLO_CONFIG_SERVICE, url); - - CONFIG_SERVICE_LOCATOR_CLEAR.invoke(CONFIG_SERVICE_LOCATOR); - } - - private String loadConfigFor(String namespace) { - String filename = String.format("mockdata-%s.properties", namespace); - final Properties prop = ResourceUtils.readConfigFile(filename, new Properties()); - Map configurations = Maps.newHashMap(); - for (String propertyName : prop.stringPropertyNames()) { - configurations.put(propertyName, prop.getProperty(propertyName)); - } - ApolloConfig apolloConfig = new ApolloConfig("someAppId", "someCluster", namespace, "someReleaseKey"); - - Map mergedConfigurations = mergeOverriddenProperties(namespace, configurations); - apolloConfig.setConfigurations(mergedConfigurations); - return GSON.toJson(apolloConfig); - } - - private String mockLongPollBody(String notificationsStr) { - List oldNotifications = GSON.fromJson(notificationsStr, notificationType); - List newNotifications = new ArrayList<>(); - for (ApolloConfigNotification notification : oldNotifications) { - newNotifications - .add(new ApolloConfigNotification(notification.getNamespaceName(), notification.getNotificationId() + 1)); - } - return GSON.toJson(newNotifications); - } - - /** - * 合并用户对namespace的修改 - */ - private Map mergeOverriddenProperties(String namespace, Map configurations) { - if (addedOrModifiedPropertiesOfNamespace.containsKey(namespace)) { - configurations.putAll(addedOrModifiedPropertiesOfNamespace.get(namespace)); - } - if (deletedKeysOfNamespace.containsKey(namespace)) { - for (String k : deletedKeysOfNamespace.get(namespace)) { - configurations.remove(k); - } - } - return configurations; - } - - /** - * Add new property or update existed property - */ - public void addOrModifyProperty(String namespace, String someKey, String someValue) { - if (addedOrModifiedPropertiesOfNamespace.containsKey(namespace)) { - addedOrModifiedPropertiesOfNamespace.get(namespace).put(someKey, someValue); - } else { - Map m = Maps.newConcurrentMap(); - m.put(someKey, someValue); - addedOrModifiedPropertiesOfNamespace.put(namespace, m); - } - } - - /** - * Delete existed property - */ - public void deleteProperty(String namespace, String someKey) { - if (deletedKeysOfNamespace.containsKey(namespace)) { - deletedKeysOfNamespace.get(namespace).add(someKey); - } else { - Set m = Sets.newConcurrentHashSet(); - m.add(someKey); - deletedKeysOfNamespace.put(namespace, m); - } - } - - /** - * reset overridden properties - */ - public void resetOverriddenProperties() { - addedOrModifiedPropertiesOfNamespace.clear(); - deletedKeysOfNamespace.clear(); - } -} diff --git a/apollo-mockserver/src/test/java/com/ctrip/framework/apollo/mockserver/ApolloMockServerApiTest.java b/apollo-mockserver/src/test/java/com/ctrip/framework/apollo/mockserver/ApolloMockServerApiTest.java deleted file mode 100644 index b129060639b..00000000000 --- a/apollo-mockserver/src/test/java/com/ctrip/framework/apollo/mockserver/ApolloMockServerApiTest.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright 2022 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.mockserver; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import com.ctrip.framework.apollo.Config; -import com.ctrip.framework.apollo.ConfigChangeListener; -import com.ctrip.framework.apollo.ConfigService; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import com.google.common.util.concurrent.SettableFuture; - -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; - -import org.junit.ClassRule; -import org.junit.Test; - -public class ApolloMockServerApiTest { - - private static final String anotherNamespace = "anotherNamespace"; - - @ClassRule - public static EmbeddedApollo embeddedApollo = new EmbeddedApollo(); - - @Test - public void testGetProperty() throws Exception { - Config applicationConfig = ConfigService.getAppConfig(); - - assertEquals("value1", applicationConfig.getProperty("key1", null)); - assertEquals("value2", applicationConfig.getProperty("key2", null)); - } - - @Test - public void testUpdateProperties() throws Exception { - String someNewValue = "someNewValue"; - - Config otherConfig = ConfigService.getConfig(anotherNamespace); - - final SettableFuture future = SettableFuture.create(); - - otherConfig.addChangeListener(new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - future.set(changeEvent); - } - }); - - assertEquals("otherValue1", otherConfig.getProperty("key1", null)); - assertEquals("otherValue2", otherConfig.getProperty("key2", null)); - - embeddedApollo.addOrModifyProperty(anotherNamespace, "key1", someNewValue); - - ConfigChangeEvent changeEvent = future.get(5, TimeUnit.SECONDS); - - assertEquals(someNewValue, otherConfig.getProperty("key1", null)); - assertEquals("otherValue2", otherConfig.getProperty("key2", null)); - assertTrue(changeEvent.isChanged("key1")); - } - - @Test - public void testUpdateSamePropertyTwice() throws Exception { - String someNewValue = "someNewValue"; - - Config otherConfig = ConfigService.getConfig(anotherNamespace); - - final Semaphore changes = new Semaphore(0); - - otherConfig.addChangeListener(new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - changes.release(); - } - }); - - assertEquals("otherValue3", otherConfig.getProperty("key3", null)); - - embeddedApollo.addOrModifyProperty(anotherNamespace, "key3", someNewValue); - embeddedApollo.addOrModifyProperty(anotherNamespace, "key3", someNewValue); - - assertTrue(changes.tryAcquire(5, TimeUnit.SECONDS)); - assertEquals(someNewValue, otherConfig.getProperty("key3", null)); - assertEquals(0, changes.availablePermits()); - } - - @Test - public void testDeleteProperties() throws Exception { - Config otherConfig = ConfigService.getConfig(anotherNamespace); - - final SettableFuture future = SettableFuture.create(); - - otherConfig.addChangeListener(new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - future.set(changeEvent); - } - }); - - assertEquals("otherValue4", otherConfig.getProperty("key4", null)); - assertEquals("otherValue5", otherConfig.getProperty("key5", null)); - - embeddedApollo.deleteProperty(anotherNamespace, "key4"); - - ConfigChangeEvent changeEvent = future.get(5, TimeUnit.SECONDS); - - assertNull(otherConfig.getProperty("key4", null)); - assertEquals("otherValue5", otherConfig.getProperty("key5", null)); - assertTrue(changeEvent.isChanged("key4")); - } - - @Test - public void testDeleteSamePropertyTwice() throws Exception { - Config otherConfig = ConfigService.getConfig(anotherNamespace); - - final Semaphore changes = new Semaphore(0); - - otherConfig.addChangeListener(new ConfigChangeListener() { - @Override - public void onChange(ConfigChangeEvent changeEvent) { - changes.release(); - } - }); - - assertEquals("otherValue6", otherConfig.getProperty("key6", null)); - - embeddedApollo.deleteProperty(anotherNamespace, "key6"); - embeddedApollo.deleteProperty(anotherNamespace, "key6"); - - assertTrue(changes.tryAcquire(5, TimeUnit.SECONDS)); - assertNull(otherConfig.getProperty("key6", null)); - assertEquals(0, changes.availablePermits()); - } -} diff --git a/apollo-mockserver/src/test/java/com/ctrip/framework/apollo/mockserver/ApolloMockServerSpringIntegrationTest.java b/apollo-mockserver/src/test/java/com/ctrip/framework/apollo/mockserver/ApolloMockServerSpringIntegrationTest.java deleted file mode 100644 index de694c62fe0..00000000000 --- a/apollo-mockserver/src/test/java/com/ctrip/framework/apollo/mockserver/ApolloMockServerSpringIntegrationTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright 2022 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.mockserver; - -import com.ctrip.framework.apollo.enums.PropertyChangeType; -import com.ctrip.framework.apollo.mockserver.ApolloMockServerSpringIntegrationTest.TestConfiguration; -import com.ctrip.framework.apollo.model.ConfigChangeEvent; -import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener; -import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig; -import com.google.common.util.concurrent.SettableFuture; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import static org.junit.Assert.assertEquals; - -/** - * Create by zhangzheng on 8/16/18 Email:zhangzheng@youzan.com - */ -@RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = TestConfiguration.class) -public class ApolloMockServerSpringIntegrationTest { - - private static final String otherNamespace = "otherNamespace"; - - @ClassRule - public static EmbeddedApollo embeddedApollo = new EmbeddedApollo(); - - @Autowired - private TestBean testBean; - - @Autowired - private TestInterestedKeyPrefixesBean testInterestedKeyPrefixesBean; - - @Test - @DirtiesContext - public void testPropertyInject() { - assertEquals("value1", testBean.key1); - assertEquals("value2", testBean.key2); - } - - @Test - @DirtiesContext - public void testListenerTriggeredByAdd() throws InterruptedException, ExecutionException, TimeoutException { - embeddedApollo.addOrModifyProperty(otherNamespace, "someKey", "someValue"); - ConfigChangeEvent changeEvent = testBean.futureData.get(5000, TimeUnit.MILLISECONDS); - assertEquals(otherNamespace, changeEvent.getNamespace()); - assertEquals("someValue", changeEvent.getChange("someKey").getNewValue()); - } - - @Test - @DirtiesContext - public void testListenerTriggeredByDel() - throws InterruptedException, ExecutionException, TimeoutException { - embeddedApollo.deleteProperty(otherNamespace, "key1"); - ConfigChangeEvent changeEvent = testBean.futureData.get(5000, TimeUnit.MILLISECONDS); - assertEquals(otherNamespace, changeEvent.getNamespace()); - assertEquals(PropertyChangeType.DELETED, changeEvent.getChange("key1").getChangeType()); - } - - @Test - @DirtiesContext - public void shouldNotifyOnInterestedPatterns() throws Exception { - embeddedApollo.addOrModifyProperty(otherNamespace, "server.port", "8080"); - embeddedApollo.addOrModifyProperty(otherNamespace, "server.path", "/apollo"); - embeddedApollo.addOrModifyProperty(otherNamespace, "spring.application.name", "whatever"); - ConfigChangeEvent changeEvent = testInterestedKeyPrefixesBean.futureData.get(5000, TimeUnit.MILLISECONDS); - assertEquals(otherNamespace, changeEvent.getNamespace()); - assertEquals("8080", changeEvent.getChange("server.port").getNewValue()); - assertEquals("/apollo", changeEvent.getChange("server.path").getNewValue()); - } - - @Test(expected = TimeoutException.class) - @DirtiesContext - public void shouldNotNotifyOnUninterestedPatterns() throws Exception { - embeddedApollo.addOrModifyProperty(otherNamespace, "spring.application.name", "apollo"); - testInterestedKeyPrefixesBean.futureData.get(5000, TimeUnit.MILLISECONDS); - } - - @EnableApolloConfig - @Configuration - static class TestConfiguration { - - @Bean - public TestBean testBean() { - return new TestBean(); - } - - @Bean - public TestInterestedKeyPrefixesBean testInterestedKeyPrefixesBean() { - return new TestInterestedKeyPrefixesBean(); - } - } - - private static class TestBean { - - @Value("${key1:default}") - private String key1; - @Value("${key2:default}") - private String key2; - - private SettableFuture futureData = SettableFuture.create(); - - @ApolloConfigChangeListener(otherNamespace) - private void onChange(ConfigChangeEvent changeEvent) { - futureData.set(changeEvent); - } - } - - private static class TestInterestedKeyPrefixesBean { - private SettableFuture futureData = SettableFuture.create(); - - @ApolloConfigChangeListener(value = otherNamespace, interestedKeyPrefixes = "server.") - private void onChange(ConfigChangeEvent changeEvent) { - futureData.set(changeEvent); - } - } -} diff --git a/apollo-mockserver/src/test/resources/META-INF/app.properties b/apollo-mockserver/src/test/resources/META-INF/app.properties deleted file mode 100644 index 329eca95d46..00000000000 --- a/apollo-mockserver/src/test/resources/META-INF/app.properties +++ /dev/null @@ -1,16 +0,0 @@ -# -# Copyright 2022 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. -# -app.id=someAppId diff --git a/apollo-mockserver/src/test/resources/mockdata-anotherNamespace.properties b/apollo-mockserver/src/test/resources/mockdata-anotherNamespace.properties deleted file mode 100644 index a77c24c9435..00000000000 --- a/apollo-mockserver/src/test/resources/mockdata-anotherNamespace.properties +++ /dev/null @@ -1,21 +0,0 @@ -# -# Copyright 2022 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. -# -key1=otherValue1 -key2=otherValue2 -key3=otherValue3 -key4=otherValue4 -key5=otherValue5 -key6=otherValue6 diff --git a/apollo-mockserver/src/test/resources/mockdata-application.properties b/apollo-mockserver/src/test/resources/mockdata-application.properties deleted file mode 100644 index e4f29807b8e..00000000000 --- a/apollo-mockserver/src/test/resources/mockdata-application.properties +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright 2022 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. -# -key1=value1 -key2=value2 diff --git a/apollo-mockserver/src/test/resources/mockdata-otherNamespace.properties b/apollo-mockserver/src/test/resources/mockdata-otherNamespace.properties deleted file mode 100644 index 4c200cbaa29..00000000000 --- a/apollo-mockserver/src/test/resources/mockdata-otherNamespace.properties +++ /dev/null @@ -1,17 +0,0 @@ -# -# Copyright 2022 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. -# -key1=otherValue1 -key2=otherValue2 diff --git a/apollo-openapi/pom.xml b/apollo-openapi/pom.xml deleted file mode 100644 index 3c55580c58b..00000000000 --- a/apollo-openapi/pom.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - apollo - com.ctrip.framework.apollo - ${revision} - - 4.0.0 - - apollo-openapi - Apollo Open Api - - - ${project.artifactId} - - - - - com.ctrip.framework.apollo - apollo-core - - - org.apache.httpcomponents - httpclient - - - commons-logging - commons-logging - - - - - org.slf4j - jcl-over-slf4j - - - org.apache.logging.log4j - log4j-slf4j-impl - test - - - org.apache.logging.log4j - log4j-core - test - - - - diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/AppOpenApiService.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/AppOpenApiService.java deleted file mode 100644 index 2b4d1c9d65c..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/AppOpenApiService.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2022 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.api; - -import com.ctrip.framework.apollo.openapi.dto.OpenAppDTO; -import com.ctrip.framework.apollo.openapi.dto.OpenEnvClusterDTO; -import java.util.List; - -/** - * @author wxq - */ -public interface AppOpenApiService { - - List getEnvClusterInfo(String appId); - - List getAllApps(); - - List getAppsInfo(List appIds); - - List getAuthorizedApps(); -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/ClusterOpenApiService.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/ClusterOpenApiService.java deleted file mode 100644 index dda685d4ab5..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/ClusterOpenApiService.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright 2022 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.api; - -import com.ctrip.framework.apollo.openapi.dto.OpenClusterDTO; - -/** - * @author wxq - */ -public interface ClusterOpenApiService { - - OpenClusterDTO getCluster(String appId, String env, String clusterName); - - OpenClusterDTO createCluster(String env, OpenClusterDTO openClusterDTO); -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/ItemOpenApiService.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/ItemOpenApiService.java deleted file mode 100644 index f063cd23814..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/ItemOpenApiService.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2022 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.api; - -import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO; -import com.ctrip.framework.apollo.openapi.dto.OpenPageDTO; - -/** - * @author wxq - */ -public interface ItemOpenApiService { - - OpenItemDTO getItem(String appId, String env, String clusterName, String namespaceName, - String key); - - OpenItemDTO createItem(String appId, String env, String clusterName, String namespaceName, - OpenItemDTO itemDTO); - - void updateItem(String appId, String env, String clusterName, String namespaceName, - OpenItemDTO itemDTO); - - void createOrUpdateItem(String appId, String env, String clusterName, String namespaceName, - OpenItemDTO itemDTO); - - void removeItem(String appId, String env, String clusterName, String namespaceName, String key, - String operator); - - OpenPageDTO findItemsByNamespace(String appId, String env, String clusterName, - String namespaceName, int page, int size); - -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/NamespaceOpenApiService.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/NamespaceOpenApiService.java deleted file mode 100644 index 760130fb307..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/NamespaceOpenApiService.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2022 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.api; - -import com.ctrip.framework.apollo.openapi.dto.OpenAppNamespaceDTO; -import com.ctrip.framework.apollo.openapi.dto.OpenNamespaceDTO; -import com.ctrip.framework.apollo.openapi.dto.OpenNamespaceLockDTO; -import java.util.List; - -/** - * @author wxq - */ -public interface NamespaceOpenApiService { - - OpenNamespaceDTO getNamespace(String appId, String env, String clusterName, String namespaceName); - - List getNamespaces(String appId, String env, String clusterName); - - OpenAppNamespaceDTO createAppNamespace(OpenAppNamespaceDTO appNamespaceDTO); - - OpenNamespaceLockDTO getNamespaceLock(String appId, String env, String clusterName, - String namespaceName); -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/ReleaseOpenApiService.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/ReleaseOpenApiService.java deleted file mode 100644 index 3599397dce9..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/api/ReleaseOpenApiService.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2022 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.api; - -import com.ctrip.framework.apollo.openapi.dto.NamespaceReleaseDTO; -import com.ctrip.framework.apollo.openapi.dto.OpenReleaseDTO; - -/** - * @author wxq - */ -public interface ReleaseOpenApiService { - - OpenReleaseDTO publishNamespace(String appId, String env, String clusterName, - String namespaceName, - NamespaceReleaseDTO releaseDTO); - - OpenReleaseDTO getLatestActiveRelease(String appId, String env, String clusterName, - String namespaceName); - - void rollbackRelease(String env, long releaseId, String operator); -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/ApolloOpenApiClient.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/ApolloOpenApiClient.java deleted file mode 100644 index a0688238a44..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/ApolloOpenApiClient.java +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Copyright 2022 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; - -import com.ctrip.framework.apollo.openapi.client.constant.ApolloOpenApiConstants; -import com.ctrip.framework.apollo.openapi.client.service.AppOpenApiService; -import com.ctrip.framework.apollo.openapi.client.service.ClusterOpenApiService; -import com.ctrip.framework.apollo.openapi.client.service.ItemOpenApiService; -import com.ctrip.framework.apollo.openapi.client.service.NamespaceOpenApiService; -import com.ctrip.framework.apollo.openapi.client.service.ReleaseOpenApiService; -import com.ctrip.framework.apollo.openapi.dto.*; -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; -import com.google.common.collect.Lists; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.message.BasicHeader; - -import java.util.List; - -/** - * This class contains collections of methods to access Apollo Open Api. - *
- * For more information, please refer Apollo Wiki. - * - */ -public class ApolloOpenApiClient { - private final String portalUrl; - private final String token; - private final AppOpenApiService appService; - private final ItemOpenApiService itemService; - private final ReleaseOpenApiService releaseService; - private final NamespaceOpenApiService namespaceService; - private final ClusterOpenApiService clusterService; - private static final Gson GSON = new GsonBuilder().setDateFormat(ApolloOpenApiConstants.JSON_DATE_FORMAT).create(); - - private ApolloOpenApiClient(String portalUrl, String token, RequestConfig requestConfig) { - this.portalUrl = portalUrl; - this.token = token; - CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig) - .setDefaultHeaders(Lists.newArrayList(new BasicHeader("Authorization", token))).build(); - - String baseUrl = this.portalUrl + ApolloOpenApiConstants.OPEN_API_V1_PREFIX; - appService = new AppOpenApiService(client, baseUrl, GSON); - clusterService = new ClusterOpenApiService(client, baseUrl, GSON); - namespaceService = new NamespaceOpenApiService(client, baseUrl, GSON); - itemService = new ItemOpenApiService(client, baseUrl, GSON); - releaseService = new ReleaseOpenApiService(client, baseUrl, GSON); - } - - /** - * Get the environment and cluster information - */ - public List getEnvClusterInfo(String appId) { - return appService.getEnvClusterInfo(appId); - } - - /** - * Get all App information - */ - public List getAllApps() { - return appService.getAllApps(); - } - - /** - * Get applications which can be operated by current open api client. - * - * @return app's information - */ - public List getAuthorizedApps() { - return this.appService.getAuthorizedApps(); - } - - /** - * Get App information by app ids - */ - public List getAppsByIds(List appIds) { - return appService.getAppsInfo(appIds); - } - - /** - * Get the namespaces - */ - public List getNamespaces(String appId, String env, String clusterName) { - return namespaceService.getNamespaces(appId, env, clusterName); - } - - /** - * Get the cluster - * - * @since 1.5.0 - */ - public OpenClusterDTO getCluster(String appId, String env, String clusterName) { - return clusterService.getCluster(appId, env, clusterName); - } - - /** - * Create the cluster - * - * @since 1.5.0 - */ - public OpenClusterDTO createCluster(String env, OpenClusterDTO openClusterDTO) { - return clusterService.createCluster(env, openClusterDTO); - } - - /** - * Get the namespace - */ - public OpenNamespaceDTO getNamespace(String appId, String env, String clusterName, String namespaceName) { - return namespaceService.getNamespace(appId, env, clusterName, namespaceName); - } - - /** - * Create the app namespace - */ - public OpenAppNamespaceDTO createAppNamespace(OpenAppNamespaceDTO appNamespaceDTO) { - return namespaceService.createAppNamespace(appNamespaceDTO); - } - - /** - * Get the namespace lock - */ - public OpenNamespaceLockDTO getNamespaceLock(String appId, String env, String clusterName, String namespaceName) { - return namespaceService.getNamespaceLock(appId, env, clusterName, namespaceName); - } - - /** - * Get config - * - * @return the item or null if not exists - * - * @since 1.2.0 - */ - public OpenItemDTO getItem(String appId, String env, String clusterName, String namespaceName, String key) { - return itemService.getItem(appId, env, clusterName, namespaceName, key); - } - - /** - * Paging get configs - */ - public OpenPageDTO findItemsByNamespace(String appId, String env, String clusterName, - String namespaceName, int page, int size) { - return itemService.findItemsByNamespace(appId, env, clusterName, namespaceName, page, size); - } - - /** - * Add config - * @return the created config - */ - public OpenItemDTO createItem(String appId, String env, String clusterName, String namespaceName, - OpenItemDTO itemDTO) { - return itemService.createItem(appId, env, clusterName, namespaceName, itemDTO); - } - - /** - * Update config - */ - public void updateItem(String appId, String env, String clusterName, String namespaceName, OpenItemDTO itemDTO) { - itemService.updateItem(appId, env, clusterName, namespaceName, itemDTO); - } - - /** - * Create config if not exists or update config if already exists - */ - public void createOrUpdateItem(String appId, String env, String clusterName, String namespaceName, OpenItemDTO itemDTO) { - itemService.createOrUpdateItem(appId, env, clusterName, namespaceName, itemDTO); - } - - /** - * Remove config - * - * @param operator the user who removes the item - */ - public void removeItem(String appId, String env, String clusterName, String namespaceName, String key, - String operator) { - itemService.removeItem(appId, env, clusterName, namespaceName, key, operator); - } - - /** - * publish namespace - * @return the released configurations - */ - public OpenReleaseDTO publishNamespace(String appId, String env, String clusterName, String namespaceName, - NamespaceReleaseDTO releaseDTO) { - return releaseService.publishNamespace(appId, env, clusterName, namespaceName, releaseDTO); - } - - /** - * @return the latest active release information or null if not found - */ - public OpenReleaseDTO getLatestActiveRelease(String appId, String env, String clusterName, String namespaceName) { - return releaseService.getLatestActiveRelease(appId, env, clusterName, namespaceName); - } - - /** - * Rollback the release - * - * @param operator the user who rollbacks the release - * @since 1.5.0 - */ - public void rollbackRelease(String env, long releaseId, String operator) { - releaseService.rollbackRelease(env, releaseId, operator); - } - - - public String getPortalUrl() { - return portalUrl; - } - - public String getToken() { - return token; - } - - public static ApolloOpenApiClientBuilder newBuilder() { - return new ApolloOpenApiClientBuilder(); - } - - public static class ApolloOpenApiClientBuilder { - - private String portalUrl; - private String token; - private int connectTimeout = -1; - private int readTimeout = -1; - - /** - * @param portalUrl The apollo portal url, e.g http://localhost:8070 - */ - public ApolloOpenApiClientBuilder withPortalUrl(String portalUrl) { - this.portalUrl = portalUrl; - return this; - } - - /** - * @param token The authorization token, e.g. e16e5cd903fd0c97a116c873b448544b9d086de8 - */ - public ApolloOpenApiClientBuilder withToken(String token) { - this.token = token; - return this; - } - - /** - * @param connectTimeout an int that specifies the connect timeout value in milliseconds - */ - public ApolloOpenApiClientBuilder withConnectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - return this; - } - - /** - * @param readTimeout an int that specifies the timeout value to be used in milliseconds - */ - public ApolloOpenApiClientBuilder withReadTimeout(int readTimeout) { - this.readTimeout = readTimeout; - return this; - } - - public ApolloOpenApiClient build() { - Preconditions.checkArgument(!Strings.isNullOrEmpty(portalUrl), "Portal url should not be null or empty!"); - Preconditions.checkArgument(portalUrl.startsWith("http://") || portalUrl.startsWith("https://"), "Portal url should start with http:// or https://" ); - Preconditions.checkArgument(!Strings.isNullOrEmpty(token), "Token should not be null or empty!"); - - if (connectTimeout < 0) { - connectTimeout = ApolloOpenApiConstants.DEFAULT_CONNECT_TIMEOUT; - } - - if (readTimeout < 0) { - readTimeout = ApolloOpenApiConstants.DEFAULT_READ_TIMEOUT; - } - - RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout) - .setSocketTimeout(readTimeout).build(); - - return new ApolloOpenApiClient(portalUrl, token, requestConfig); - } - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/constant/ApolloOpenApiConstants.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/constant/ApolloOpenApiConstants.java deleted file mode 100644 index 6d45c5b1bc9..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/constant/ApolloOpenApiConstants.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2022 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"; - -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/exception/ApolloOpenApiException.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/exception/ApolloOpenApiException.java deleted file mode 100644 index 8ee8ebc3e1e..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/exception/ApolloOpenApiException.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2022 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.exception; - -public class ApolloOpenApiException extends RuntimeException { - private final int status; - - public ApolloOpenApiException(int status, String reason, String message) { - super(String.format("Request to apollo open api failed, status code: %d, reason: %s, message: %s", status, reason, - message)); - this.status = status; - } - - public int getStatus() { - return status; - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/AbstractOpenApiService.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/AbstractOpenApiService.java deleted file mode 100644 index 811ee890a06..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/AbstractOpenApiService.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2022 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.service; - -import com.ctrip.framework.apollo.openapi.client.exception.ApolloOpenApiException; -import com.ctrip.framework.apollo.openapi.client.url.OpenApiPathBuilder; -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; -import com.google.gson.Gson; -import org.apache.http.HttpResponse; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.*; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.util.EntityUtils; - -import java.io.IOException; - -abstract class AbstractOpenApiService { - private final String baseUrl; - - protected final CloseableHttpClient client; - protected final Gson gson; - - AbstractOpenApiService(CloseableHttpClient client, String baseUrl, Gson gson) { - this.client = client; - this.baseUrl = baseUrl; - this.gson = gson; - } - - protected CloseableHttpResponse get(OpenApiPathBuilder path) throws IOException { - HttpGet get = new HttpGet(path.buildPath(baseUrl)); - - return execute(get); - } - - protected CloseableHttpResponse post(OpenApiPathBuilder path, Object entity) throws IOException { - HttpPost post = new HttpPost(path.buildPath(baseUrl)); - - return execute(post, entity); - } - - protected CloseableHttpResponse put(OpenApiPathBuilder path, Object entity) throws IOException { - HttpPut put = new HttpPut(path.buildPath(baseUrl)); - - return execute(put, entity); - } - - protected CloseableHttpResponse delete(OpenApiPathBuilder path) throws IOException { - HttpDelete delete = new HttpDelete(path.buildPath(baseUrl)); - - return execute(delete); - } - - private CloseableHttpResponse execute(HttpEntityEnclosingRequestBase requestBase, Object entity) throws IOException { - requestBase.setEntity(new StringEntity(gson.toJson(entity), ContentType.APPLICATION_JSON)); - - return execute(requestBase); - } - - private CloseableHttpResponse execute(HttpUriRequest request) throws IOException { - CloseableHttpResponse response = client.execute(request); - - checkHttpResponseStatus(response); - - return response; - } - - private void checkHttpResponseStatus(HttpResponse response) { - if (response.getStatusLine().getStatusCode() == 200) { - return; - } - - StatusLine status = response.getStatusLine(); - String message = ""; - try { - message = EntityUtils.toString(response.getEntity()); - } catch (IOException e) { - //ignore - } - - throw new ApolloOpenApiException(status.getStatusCode(), status.getReasonPhrase(), message); - } - - protected void checkNotEmpty(String value, String name) { - Preconditions.checkArgument(!Strings.isNullOrEmpty(value), name + " should not be null or empty"); - } - - protected void checkPage(int page) { - Preconditions.checkArgument(page >= 0, "page should be positive or 0"); - } - - protected void checkSize(int size) { - Preconditions.checkArgument(size > 0, "size should be positive number"); - } - -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/AppOpenApiService.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/AppOpenApiService.java deleted file mode 100644 index 4fe38911a81..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/AppOpenApiService.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright 2022 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.service; - -import com.ctrip.framework.apollo.openapi.client.url.OpenApiPathBuilder; -import com.ctrip.framework.apollo.openapi.dto.OpenAppDTO; -import com.ctrip.framework.apollo.openapi.dto.OpenEnvClusterDTO; -import com.google.common.base.Joiner; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import java.lang.reflect.Type; -import java.util.List; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.util.EntityUtils; - -public class AppOpenApiService extends AbstractOpenApiService implements - com.ctrip.framework.apollo.openapi.api.AppOpenApiService { - private static final Type OPEN_ENV_CLUSTER_DTO_LIST_TYPE = new TypeToken>() { - }.getType(); - private static final Type OPEN_APP_DTO_LIST_TYPE = new TypeToken>() { - }.getType(); - - public AppOpenApiService(CloseableHttpClient client, String baseUrl, Gson gson) { - super(client, baseUrl, gson); - } - - @Override - public List getEnvClusterInfo(String appId) { - checkNotEmpty(appId, "App id"); - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .appsPathVal(appId) - .customResource("envclusters"); - - try (CloseableHttpResponse response = get(pathBuilder)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OPEN_ENV_CLUSTER_DTO_LIST_TYPE); - } catch (Throwable ex) { - throw new RuntimeException(String.format("Load env cluster information for appId: %s failed", appId), ex); - } - } - - @Override - public List getAllApps() { - return this.getAppsInfo(null); - } - - @Override - public List getAppsInfo(List appIds) { - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .customResource("apps"); - - if (appIds != null && !appIds.isEmpty()) { - String param = Joiner.on(",").join(appIds); - pathBuilder.addParam("appIds", param); - } - - try (CloseableHttpResponse response = get(pathBuilder)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OPEN_APP_DTO_LIST_TYPE); - } catch (Throwable ex) { - throw new RuntimeException(String.format("Load app information for appIds: %s failed", appIds), ex); - } - } - - @Override - public List getAuthorizedApps() { - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .customResource("apps/authorized"); - - try(CloseableHttpResponse response = this.get(pathBuilder)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OPEN_APP_DTO_LIST_TYPE); - } catch (Throwable ex) { - throw new RuntimeException("Load authorized apps failed", ex); - } - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/ClusterOpenApiService.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/ClusterOpenApiService.java deleted file mode 100644 index 3d22abfa039..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/ClusterOpenApiService.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2022 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.service; - -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.openapi.client.url.OpenApiPathBuilder; -import com.ctrip.framework.apollo.openapi.dto.OpenClusterDTO; -import com.google.common.base.Strings; -import com.google.gson.Gson; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.util.EntityUtils; - -public class ClusterOpenApiService extends AbstractOpenApiService implements - com.ctrip.framework.apollo.openapi.api.ClusterOpenApiService { - - public ClusterOpenApiService(CloseableHttpClient client, String baseUrl, Gson gson) { - super(client, baseUrl, gson); - } - - @Override - public OpenClusterDTO getCluster(String appId, String env, String clusterName) { - checkNotEmpty(appId, "App id"); - checkNotEmpty(env, "Env"); - - if (Strings.isNullOrEmpty(clusterName)) { - clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT; - } - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName); - - try (CloseableHttpResponse response = get(pathBuilder)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenClusterDTO.class); - } catch (Throwable ex) { - throw new RuntimeException(String - .format("Get cluster for appId: %s, cluster: %s in env: %s failed", appId, clusterName, env), ex); - } - } - - @Override - public OpenClusterDTO createCluster(String env, OpenClusterDTO openClusterDTO) { - checkNotEmpty(openClusterDTO.getAppId(), "App id"); - checkNotEmpty(env, "Env"); - checkNotEmpty(openClusterDTO.getName(), "Cluster name"); - checkNotEmpty(openClusterDTO.getDataChangeCreatedBy(), "Created by"); - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(openClusterDTO.getAppId()) - .customResource("clusters"); - - try (CloseableHttpResponse response = post(pathBuilder, openClusterDTO)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenClusterDTO.class); - } catch (Throwable ex) { - throw new RuntimeException(String - .format("Create cluster: %s for appId: %s in env: %s failed", openClusterDTO.getName(), - openClusterDTO.getAppId(), env), ex); - } - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/ItemOpenApiService.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/ItemOpenApiService.java deleted file mode 100644 index de5a86a9a5d..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/ItemOpenApiService.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * Copyright 2022 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.service; - -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.openapi.client.exception.ApolloOpenApiException; -import com.ctrip.framework.apollo.openapi.client.url.OpenApiPathBuilder; -import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO; -import com.ctrip.framework.apollo.openapi.dto.OpenPageDTO; -import com.google.common.base.Strings; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.util.EntityUtils; - -import java.lang.reflect.Type; - -public class ItemOpenApiService extends AbstractOpenApiService implements - com.ctrip.framework.apollo.openapi.api.ItemOpenApiService { - - private static final Type OPEN_PAGE_DTO_OPEN_ITEM_DTO_TYPE_REFERENCE = new TypeToken>() { - }.getType(); - - public ItemOpenApiService(CloseableHttpClient client, String baseUrl, Gson gson) { - super(client, baseUrl, gson); - } - - @Override - public OpenItemDTO getItem(String appId, String env, String clusterName, String namespaceName, String key) { - if (Strings.isNullOrEmpty(clusterName)) { - clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT; - } - if (Strings.isNullOrEmpty(namespaceName)) { - namespaceName = ConfigConsts.NAMESPACE_APPLICATION; - } - - checkNotEmpty(appId, "App id"); - checkNotEmpty(env, "Env"); - checkNotEmpty(key, "Item key"); - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .itemsPathVal(key); - - try (CloseableHttpResponse response = get(pathBuilder)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenItemDTO.class); - } catch (Throwable ex) { - // return null if item doesn't exist - if (ex instanceof ApolloOpenApiException && ((ApolloOpenApiException)ex).getStatus() == 404) { - return null; - } - throw new RuntimeException(String - .format("Get item: %s for appId: %s, cluster: %s, namespace: %s in env: %s failed", key, appId, clusterName, - namespaceName, env), ex); - } - } - - @Override - public OpenItemDTO createItem(String appId, String env, String clusterName, String namespaceName, OpenItemDTO itemDTO) { - if (Strings.isNullOrEmpty(clusterName)) { - clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT; - } - if (Strings.isNullOrEmpty(namespaceName)) { - namespaceName = ConfigConsts.NAMESPACE_APPLICATION; - } - - checkNotEmpty(appId, "App id"); - checkNotEmpty(env, "Env"); - checkNotEmpty(itemDTO.getKey(), "Item key"); - checkNotEmpty(itemDTO.getDataChangeCreatedBy(), "Item created by"); - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .customResource("items"); - - try (CloseableHttpResponse response = post(pathBuilder, itemDTO)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenItemDTO.class); - } catch (Throwable ex) { - throw new RuntimeException(String - .format("Create item: %s for appId: %s, cluster: %s, namespace: %s in env: %s failed", itemDTO.getKey(), - appId, clusterName, namespaceName, env), ex); - } - } - - @Override - public void updateItem(String appId, String env, String clusterName, String namespaceName, OpenItemDTO itemDTO) { - if (Strings.isNullOrEmpty(clusterName)) { - clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT; - } - if (Strings.isNullOrEmpty(namespaceName)) { - namespaceName = ConfigConsts.NAMESPACE_APPLICATION; - } - - checkNotEmpty(appId, "App id"); - checkNotEmpty(env, "Env"); - checkNotEmpty(itemDTO.getKey(), "Item key"); - checkNotEmpty(itemDTO.getDataChangeLastModifiedBy(), "Item modified by"); - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .itemsPathVal(itemDTO.getKey()); - - try (CloseableHttpResponse ignored = put(pathBuilder, itemDTO)) { - } catch (Throwable ex) { - throw new RuntimeException(String - .format("Update item: %s for appId: %s, cluster: %s, namespace: %s in env: %s failed", itemDTO.getKey(), - appId, clusterName, namespaceName, env), ex); - } - } - - @Override - public void createOrUpdateItem(String appId, String env, String clusterName, String namespaceName, OpenItemDTO itemDTO) { - if (Strings.isNullOrEmpty(clusterName)) { - clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT; - } - if (Strings.isNullOrEmpty(namespaceName)) { - namespaceName = ConfigConsts.NAMESPACE_APPLICATION; - } - - checkNotEmpty(appId, "App id"); - checkNotEmpty(env, "Env"); - checkNotEmpty(itemDTO.getKey(), "Item key"); - checkNotEmpty(itemDTO.getDataChangeCreatedBy(), "Item created by"); - - if (Strings.isNullOrEmpty(itemDTO.getDataChangeLastModifiedBy())) { - itemDTO.setDataChangeLastModifiedBy(itemDTO.getDataChangeCreatedBy()); - } - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .itemsPathVal(itemDTO.getKey()) - .addParam("createIfNotExists", "true"); - - try (CloseableHttpResponse ignored = put(pathBuilder, itemDTO)) { - } catch (Throwable ex) { - throw new RuntimeException(String - .format("CreateOrUpdate item: %s for appId: %s, cluster: %s, namespace: %s in env: %s failed", itemDTO.getKey(), - appId, clusterName, namespaceName, env), ex); - } - } - - @Override - public void removeItem(String appId, String env, String clusterName, String namespaceName, String key, String operator) { - if (Strings.isNullOrEmpty(clusterName)) { - clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT; - } - if (Strings.isNullOrEmpty(namespaceName)) { - namespaceName = ConfigConsts.NAMESPACE_APPLICATION; - } - - checkNotEmpty(appId, "App id"); - checkNotEmpty(env, "Env"); - checkNotEmpty(key, "Item key"); - checkNotEmpty(operator, "Operator"); - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .itemsPathVal(key) - .addParam("operator", operator); - - try (CloseableHttpResponse ignored = delete(pathBuilder)) { - } catch (Throwable ex) { - throw new RuntimeException(String - .format("Remove item: %s for appId: %s, cluster: %s, namespace: %s in env: %s failed", key, appId, - clusterName, namespaceName, env), ex); - } - - } - - @Override - public OpenPageDTO findItemsByNamespace(String appId, String env, String clusterName, - String namespaceName, int page, int size) { - if (Strings.isNullOrEmpty(clusterName)) { - clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT; - } - if (Strings.isNullOrEmpty(namespaceName)) { - namespaceName = ConfigConsts.NAMESPACE_APPLICATION; - } - - checkNotEmpty(appId, "App id"); - checkNotEmpty(env, "Env"); - checkPage(page); - checkSize(size); - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .itemsPathVal("") - .addParam("page", page) - .addParam("size", size); - - try (CloseableHttpResponse response = get(pathBuilder)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OPEN_PAGE_DTO_OPEN_ITEM_DTO_TYPE_REFERENCE); - } catch (Throwable ex) { - throw new RuntimeException(String.format("Paging get items: appId: %s, cluster: %s, namespace: %s in env: %s failed", - appId, clusterName, namespaceName, env), ex); - } - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/NamespaceOpenApiService.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/NamespaceOpenApiService.java deleted file mode 100644 index b1a0a530671..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/NamespaceOpenApiService.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright 2022 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.service; - -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.core.enums.ConfigFileFormat; -import com.ctrip.framework.apollo.openapi.client.url.OpenApiPathBuilder; -import com.ctrip.framework.apollo.openapi.dto.OpenAppNamespaceDTO; -import com.ctrip.framework.apollo.openapi.dto.OpenNamespaceDTO; -import com.ctrip.framework.apollo.openapi.dto.OpenNamespaceLockDTO; -import com.google.common.base.Strings; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import java.lang.reflect.Type; -import java.util.List; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.util.EntityUtils; - -public class NamespaceOpenApiService extends AbstractOpenApiService implements - com.ctrip.framework.apollo.openapi.api.NamespaceOpenApiService { - private static final Type OPEN_NAMESPACE_DTO_LIST_TYPE = new TypeToken>() { - }.getType(); - - public NamespaceOpenApiService(CloseableHttpClient client, String baseUrl, Gson gson) { - super(client, baseUrl, gson); - } - - @Override - public OpenNamespaceDTO getNamespace(String appId, String env, String clusterName, String namespaceName) { - if (Strings.isNullOrEmpty(clusterName)) { - clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT; - } - if (Strings.isNullOrEmpty(namespaceName)) { - namespaceName = ConfigConsts.NAMESPACE_APPLICATION; - } - - checkNotEmpty(appId, "App id"); - checkNotEmpty(env, "Env"); - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName); - - try (CloseableHttpResponse response = get(pathBuilder)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenNamespaceDTO.class); - } catch (Throwable ex) { - throw new RuntimeException(String - .format("Get namespace for appId: %s, cluster: %s, namespace: %s in env: %s failed", appId, clusterName, - namespaceName, env), ex); - } - } - - @Override - public List getNamespaces(String appId, String env, String clusterName) { - if (Strings.isNullOrEmpty(clusterName)) { - clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT; - } - - checkNotEmpty(appId, "App id"); - checkNotEmpty(env, "Env"); - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .customResource("namespaces"); - - try (CloseableHttpResponse response = get(pathBuilder)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OPEN_NAMESPACE_DTO_LIST_TYPE); - } catch (Throwable ex) { - throw new RuntimeException(String - .format("Get namespaces for appId: %s, cluster: %s in env: %s failed", appId, clusterName, env), ex); - } - } - - @Override - public OpenAppNamespaceDTO createAppNamespace(OpenAppNamespaceDTO appNamespaceDTO) { - checkNotEmpty(appNamespaceDTO.getAppId(), "App id"); - checkNotEmpty(appNamespaceDTO.getName(), "Name"); - checkNotEmpty(appNamespaceDTO.getDataChangeCreatedBy(), "Created by"); - - if (Strings.isNullOrEmpty(appNamespaceDTO.getFormat())) { - appNamespaceDTO.setFormat(ConfigFileFormat.Properties.getValue()); - } - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .appsPathVal(appNamespaceDTO.getAppId()) - .customResource("appnamespaces"); - - try (CloseableHttpResponse response = post(pathBuilder, appNamespaceDTO)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenAppNamespaceDTO.class); - } catch (Throwable ex) { - throw new RuntimeException(String - .format("Create app namespace: %s for appId: %s, format: %s failed", appNamespaceDTO.getName(), - appNamespaceDTO.getAppId(), appNamespaceDTO.getFormat()), ex); - } - } - - @Override - public OpenNamespaceLockDTO getNamespaceLock(String appId, String env, String clusterName, String namespaceName) { - if (Strings.isNullOrEmpty(clusterName)) { - clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT; - } - if (Strings.isNullOrEmpty(namespaceName)) { - namespaceName = ConfigConsts.NAMESPACE_APPLICATION; - } - - checkNotEmpty(appId, "App id"); - checkNotEmpty(env, "Env"); - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .customResource("lock"); - - try (CloseableHttpResponse response = get(pathBuilder)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenNamespaceLockDTO.class); - } catch (Throwable ex) { - throw new RuntimeException(String - .format("Get namespace lock for appId: %s, cluster: %s, namespace: %s in env: %s failed", appId, clusterName, - namespaceName, env), ex); - } - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/ReleaseOpenApiService.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/ReleaseOpenApiService.java deleted file mode 100644 index 4fa787a44ca..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/service/ReleaseOpenApiService.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright 2022 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.service; - -import com.ctrip.framework.apollo.core.ConfigConsts; -import com.ctrip.framework.apollo.openapi.client.url.OpenApiPathBuilder; -import com.ctrip.framework.apollo.openapi.dto.NamespaceReleaseDTO; -import com.ctrip.framework.apollo.openapi.dto.OpenReleaseDTO; -import com.google.common.base.Strings; -import com.google.gson.Gson; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.util.EntityUtils; - -public class ReleaseOpenApiService extends AbstractOpenApiService implements - com.ctrip.framework.apollo.openapi.api.ReleaseOpenApiService { - - public ReleaseOpenApiService(CloseableHttpClient client, String baseUrl, Gson gson) { - super(client, baseUrl, gson); - } - - @Override - public OpenReleaseDTO publishNamespace(String appId, String env, String clusterName, String namespaceName, - NamespaceReleaseDTO releaseDTO) { - if (Strings.isNullOrEmpty(clusterName)) { - clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT; - } - if (Strings.isNullOrEmpty(namespaceName)) { - namespaceName = ConfigConsts.NAMESPACE_APPLICATION; - } - - checkNotEmpty(appId, "App id"); - checkNotEmpty(env, "Env"); - checkNotEmpty(releaseDTO.getReleaseTitle(), "Release title"); - checkNotEmpty(releaseDTO.getReleasedBy(), "Released by"); - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .customResource("releases"); - - try (CloseableHttpResponse response = post(pathBuilder, releaseDTO)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenReleaseDTO.class); - } catch (Throwable ex) { - throw new RuntimeException(String - .format("Release namespace: %s for appId: %s, cluster: %s in env: %s failed", namespaceName, appId, - clusterName, env), ex); - } - } - - @Override - public OpenReleaseDTO getLatestActiveRelease(String appId, String env, String clusterName, String namespaceName) { - if (Strings.isNullOrEmpty(clusterName)) { - clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT; - } - if (Strings.isNullOrEmpty(namespaceName)) { - namespaceName = ConfigConsts.NAMESPACE_APPLICATION; - } - - checkNotEmpty(appId, "App id"); - checkNotEmpty(env, "Env"); - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .releasesPathVal("latest"); - - try (CloseableHttpResponse response = get(pathBuilder)) { - return gson.fromJson(EntityUtils.toString(response.getEntity()), OpenReleaseDTO.class); - } catch (Throwable ex) { - throw new RuntimeException(String - .format("Get latest active release for appId: %s, cluster: %s, namespace: %s in env: %s failed", appId, - clusterName, namespaceName, env), ex); - } - } - - @Override - public void rollbackRelease(String env, long releaseId, String operator) { - checkNotEmpty(env, "Env"); - checkNotEmpty(operator, "Operator"); - - OpenApiPathBuilder pathBuilder = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .releasesPathVal(String.valueOf(releaseId)) - .customResource("rollback") - .addParam("operator", operator); - - try (CloseableHttpResponse ignored = put(pathBuilder, null)) { - } catch (Throwable ex) { - throw new RuntimeException(String.format("Rollback release: %s in env: %s failed", releaseId, env), ex); - } - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/url/OpenApiPathBuilder.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/url/OpenApiPathBuilder.java deleted file mode 100644 index 72c94b07116..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/client/url/OpenApiPathBuilder.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright 2022 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.url; - - -import com.ctrip.framework.apollo.openapi.utils.UrlUtils; -import com.google.common.base.Joiner; -import com.google.common.base.Strings; -import com.google.common.escape.Escaper; -import com.google.common.net.UrlEscapers; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class OpenApiPathBuilder { - - private static final String ENV_PATH = "env"; - private static final String ENVS_PATH = "envs"; - private static final String APPS_PATH = "apps"; - private static final String CLUSTERS_PATH = "clusters"; - private static final String NAMESPACES_PATH = "namespaces"; - private static final String ITEMS_PATH = "items"; - private static final String ENCODED_ITEMS_PATH = "encodedItems"; - private static final String RELEASE_PATH = "releases"; - - private final static List SORTED_PATH_KEYS = Arrays.asList(ENVS_PATH, ENV_PATH, APPS_PATH, - CLUSTERS_PATH, - NAMESPACES_PATH, ITEMS_PATH, ENCODED_ITEMS_PATH, RELEASE_PATH); - - private static final Escaper PATH_ESCAPER = UrlEscapers.urlPathSegmentEscaper(); - private static final Escaper QUERY_PARAM_ESCAPER = UrlEscapers.urlFormParameterEscaper(); - private static final Joiner PATH_JOIN = Joiner.on("/"); - - private final Map pathVariable; - private final Map params; - - private String customResource; - - public static OpenApiPathBuilder newBuilder() { - return new OpenApiPathBuilder(); - } - - private OpenApiPathBuilder() { - this.pathVariable = new HashMap<>(); - this.params = new HashMap<>(); - } - - public OpenApiPathBuilder envPathVal(String env) { - pathVariable.put(ENV_PATH, escapePath(env)); - return this; - } - - public OpenApiPathBuilder envsPathVal(String envs) { - pathVariable.put(ENVS_PATH, escapePath(envs)); - return this; - } - - public OpenApiPathBuilder appsPathVal(String apps) { - pathVariable.put(APPS_PATH, escapePath(apps)); - return this; - } - - public OpenApiPathBuilder clustersPathVal(String clusters) { - pathVariable.put(CLUSTERS_PATH, escapePath(clusters)); - return this; - } - - public OpenApiPathBuilder namespacesPathVal(String namespaces) { - pathVariable.put(NAMESPACES_PATH, escapePath(namespaces)); - return this; - } - - public OpenApiPathBuilder itemsPathVal(String items) { - if (UrlUtils.hasIllegalChar(items)) { - items = new String(Base64.getEncoder().encode(items.getBytes(StandardCharsets.UTF_8))); - pathVariable.put(ENCODED_ITEMS_PATH, escapePath(items)); - } else { - pathVariable.put(ITEMS_PATH, escapePath(items)); - } - return this; - } - - public OpenApiPathBuilder releasesPathVal(String releases) { - pathVariable.put(RELEASE_PATH, escapePath(releases)); - return this; - } - - public OpenApiPathBuilder customResource(String customResource) { - this.customResource = customResource; - return this; - } - - public OpenApiPathBuilder addParam(String key, Object value) { - if (Strings.isNullOrEmpty(key)) { - throw new IllegalArgumentException("Param key should not be null or empty"); - } - this.params.put(key, escapeParam(String.valueOf(value))); - return this; - } - - public String buildPath(String baseUrl) { - if (Strings.isNullOrEmpty(baseUrl)) { - throw new IllegalArgumentException("Base url should not be null or empty"); - } - List parts = new ArrayList<>(); - parts.add(baseUrl); - - for (String k : SORTED_PATH_KEYS) { - if (pathVariable.containsKey(k)) { - parts.add(k); - String v = pathVariable.get(k); - if (!Strings.isNullOrEmpty(v)) { - parts.add(v); - } - } - } - - if (!Strings.isNullOrEmpty(this.customResource)) { - parts.add(this.customResource); - } - - String path = PATH_JOIN.join(parts); - - if (!params.isEmpty()) { - StringBuilder sb = new StringBuilder(); - for (Map.Entry kv : params.entrySet()) { - if (sb.length() > 0) { - sb.append("&"); - } - sb.append(kv.getKey()).append("=").append(kv.getValue()); - } - path += "?" + sb; - } - return path; - } - - protected String escapePath(String path) { - return PATH_ESCAPER.escape(path); - } - - protected String escapeParam(String param) { - return QUERY_PARAM_ESCAPER.escape(param); - } - -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/BaseDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/BaseDTO.java deleted file mode 100644 index a4aa46685d3..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/BaseDTO.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2022 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; - -import java.util.Date; - -public class BaseDTO { - - protected String dataChangeCreatedBy; - - protected String dataChangeLastModifiedBy; - - protected Date dataChangeCreatedTime; - - protected Date dataChangeLastModifiedTime; - - public String getDataChangeCreatedBy() { - return dataChangeCreatedBy; - } - - public void setDataChangeCreatedBy(String dataChangeCreatedBy) { - this.dataChangeCreatedBy = dataChangeCreatedBy; - } - - public String getDataChangeLastModifiedBy() { - return dataChangeLastModifiedBy; - } - - public void setDataChangeLastModifiedBy(String dataChangeLastModifiedBy) { - this.dataChangeLastModifiedBy = dataChangeLastModifiedBy; - } - - public Date getDataChangeCreatedTime() { - return dataChangeCreatedTime; - } - - public void setDataChangeCreatedTime(Date dataChangeCreatedTime) { - this.dataChangeCreatedTime = dataChangeCreatedTime; - } - - public Date getDataChangeLastModifiedTime() { - return dataChangeLastModifiedTime; - } - - public void setDataChangeLastModifiedTime(Date dataChangeLastModifiedTime) { - this.dataChangeLastModifiedTime = dataChangeLastModifiedTime; - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/NamespaceGrayDelReleaseDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/NamespaceGrayDelReleaseDTO.java deleted file mode 100644 index e96ec35fe4e..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/NamespaceGrayDelReleaseDTO.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2022 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; - -import java.util.Set; - -public class NamespaceGrayDelReleaseDTO extends NamespaceReleaseDTO { - private Set grayDelKeys; - - public Set getGrayDelKeys() { - return grayDelKeys; - } - - public void setGrayDelKeys(Set grayDelKeys) { - this.grayDelKeys = grayDelKeys; - } - -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/NamespaceReleaseDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/NamespaceReleaseDTO.java deleted file mode 100644 index c87156c01de..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/NamespaceReleaseDTO.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2022 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 NamespaceReleaseDTO { - - private String releaseTitle; - private String releaseComment; - private String releasedBy; - private boolean isEmergencyPublish; - - public String getReleaseTitle() { - return releaseTitle; - } - - public void setReleaseTitle(String releaseTitle) { - this.releaseTitle = releaseTitle; - } - - public String getReleaseComment() { - return releaseComment; - } - - public void setReleaseComment(String releaseComment) { - this.releaseComment = releaseComment; - } - - public String getReleasedBy() { - return releasedBy; - } - - public void setReleasedBy(String releasedBy) { - this.releasedBy = releasedBy; - } - - public boolean isEmergencyPublish() { - return isEmergencyPublish; - } - - public void setEmergencyPublish(boolean emergencyPublish) { - isEmergencyPublish = emergencyPublish; - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenAppDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenAppDTO.java deleted file mode 100644 index 45c98ab038a..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenAppDTO.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright 2022 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 OpenAppDTO extends BaseDTO { - - private String name; - - private String appId; - - private String orgId; - - private String orgName; - - private String ownerName; - - private String ownerEmail; - - public String getAppId() { - return appId; - } - - public String getName() { - return name; - } - - public String getOrgId() { - return orgId; - } - - public String getOrgName() { - return orgName; - } - - public String getOwnerEmail() { - return ownerEmail; - } - - public String getOwnerName() { - return ownerName; - } - - public void setAppId(String appId) { - this.appId = appId; - } - - public void setName(String name) { - this.name = name; - } - - public void setOrgId(String orgId) { - this.orgId = orgId; - } - - public void setOrgName(String orgName) { - this.orgName = orgName; - } - - public void setOwnerEmail(String ownerEmail) { - this.ownerEmail = ownerEmail; - } - - public void setOwnerName(String ownerName) { - this.ownerName = ownerName; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("OpenAppDTO{"); - sb.append("name='").append(name).append('\''); - sb.append(", appId='").append(appId).append('\''); - sb.append(", orgId='").append(orgId).append('\''); - sb.append(", orgName='").append(orgName).append('\''); - sb.append(", ownerName='").append(ownerName).append('\''); - sb.append(", ownerEmail='").append(ownerEmail).append('\''); - sb.append(", dataChangeCreatedBy='").append(dataChangeCreatedBy).append('\''); - sb.append(", dataChangeLastModifiedBy='").append(dataChangeLastModifiedBy).append('\''); - sb.append(", dataChangeCreatedTime=").append(dataChangeCreatedTime); - sb.append(", dataChangeLastModifiedTime=").append(dataChangeLastModifiedTime); - sb.append('}'); - return sb.toString(); - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenAppNamespaceDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenAppNamespaceDTO.java deleted file mode 100644 index fd4431cb1ca..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenAppNamespaceDTO.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2022 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 OpenAppNamespaceDTO extends BaseDTO { - private String name; - - private String appId; - - private String format; - - private boolean isPublic; - - // whether to append namespace prefix for public namespace name - private boolean appendNamespacePrefix = true; - - private String comment; - - 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; - } - - public String getFormat() { - return format; - } - - public void setFormat(String format) { - this.format = format; - } - - public boolean isPublic() { - return isPublic; - } - - public void setPublic(boolean aPublic) { - isPublic = aPublic; - } - - public boolean isAppendNamespacePrefix() { - return appendNamespacePrefix; - } - - public void setAppendNamespacePrefix(boolean appendNamespacePrefix) { - this.appendNamespacePrefix = appendNamespacePrefix; - } - - public String getComment() { - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } - - @Override - public String toString() { - return "OpenAppNamespaceDTO{" + - "name='" + name + '\'' + - ", appId='" + appId + '\'' + - ", format='" + format + '\'' + - ", isPublic=" + isPublic + - ", appendNamespacePrefix=" + appendNamespacePrefix + - ", comment='" + comment + '\'' + - ", dataChangeCreatedBy='" + dataChangeCreatedBy + '\'' + - ", dataChangeLastModifiedBy='" + dataChangeLastModifiedBy + '\'' + - ", dataChangeCreatedTime=" + dataChangeCreatedTime + - ", dataChangeLastModifiedTime=" + dataChangeLastModifiedTime + - '}'; - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenClusterDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenClusterDTO.java deleted file mode 100644 index 3f531a9d105..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenClusterDTO.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2022 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 + - '}'; - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenEnvClusterDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenEnvClusterDTO.java deleted file mode 100644 index 602e6691038..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenEnvClusterDTO.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2022 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; - -import java.util.Set; - -public class OpenEnvClusterDTO { - - private String env; - private Set clusters; - - public String getEnv() { - return env; - } - - public void setEnv(String env) { - this.env = env; - } - - public Set getClusters() { - return clusters; - } - - public void setClusters(Set clusters) { - this.clusters = clusters; - } - - @Override - public String toString() { - return "OpenEnvClusterDTO{" + - "env='" + env + '\'' + - ", clusters=" + clusters + - '}'; - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenGrayReleaseRuleDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenGrayReleaseRuleDTO.java deleted file mode 100644 index 7404e33afd2..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenGrayReleaseRuleDTO.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright 2022 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; - -import java.util.Set; - -public class OpenGrayReleaseRuleDTO extends BaseDTO{ - private String appId; - - private String clusterName; - - private String namespaceName; - - private String branchName; - - private Set ruleItems; - - public String getAppId() { - return appId; - } - - public void setAppId(String appId) { - this.appId = appId; - } - - public String getClusterName() { - return clusterName; - } - - public void setClusterName(String clusterName) { - this.clusterName = clusterName; - } - - public String getNamespaceName() { - return namespaceName; - } - - public void setNamespaceName(String namespaceName) { - this.namespaceName = namespaceName; - } - - public String getBranchName() { - return branchName; - } - - public void setBranchName(String branchName) { - this.branchName = branchName; - } - - public Set getRuleItems() { - return ruleItems; - } - - public void setRuleItems(Set ruleItems) { - this.ruleItems = ruleItems; - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenGrayReleaseRuleItemDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenGrayReleaseRuleItemDTO.java deleted file mode 100644 index 135e018e619..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenGrayReleaseRuleItemDTO.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2022 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; - -import java.util.Set; - -public class OpenGrayReleaseRuleItemDTO { - private String clientAppId; - private Set clientIpList; - private Set clientLabelList; - - public String getClientAppId() { - return clientAppId; - } - - public void setClientAppId(String clientAppId) { - this.clientAppId = clientAppId; - } - - public Set getClientIpList() { - return clientIpList; - } - - public void setClientIpList(Set clientIpList) { - this.clientIpList = clientIpList; - } - - public Set getClientLabelList() { - return clientLabelList; - } - - public void setClientLabelList(Set clientLabelList) { - this.clientLabelList = clientLabelList; - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenItemDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenItemDTO.java deleted file mode 100644 index df7f1462c11..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenItemDTO.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright 2022 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 OpenItemDTO extends BaseDTO { - - private String key; - - private int type; - - private String value; - - private String comment; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public int getType() { - return type; - } - - public void setType(int type) { - this.type = type; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public String getComment() { - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } - - @Override - public String toString() { - return "OpenItemDTO{" + - "key='" + key + '\'' + - ", type='" + type + '\'' + - ", value='" + value + '\'' + - ", comment='" + comment + '\'' + - ", dataChangeCreatedBy='" + dataChangeCreatedBy + '\'' + - ", dataChangeLastModifiedBy='" + dataChangeLastModifiedBy + '\'' + - ", dataChangeCreatedTime=" + dataChangeCreatedTime + - ", dataChangeLastModifiedTime=" + dataChangeLastModifiedTime + - '}'; - } - -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenNamespaceDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenNamespaceDTO.java deleted file mode 100644 index 50d27b77f0e..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenNamespaceDTO.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2022 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; - -import java.util.List; - -public class OpenNamespaceDTO extends BaseDTO { - - private String appId; - - private String clusterName; - - private String namespaceName; - - private String comment; - - private String format; - - private boolean isPublic; - - private List items; - - public String getAppId() { - return appId; - } - - public void setAppId(String appId) { - this.appId = appId; - } - - public String getClusterName() { - return clusterName; - } - - public void setClusterName(String clusterName) { - this.clusterName = clusterName; - } - - public String getNamespaceName() { - return namespaceName; - } - - public void setNamespaceName(String namespaceName) { - this.namespaceName = namespaceName; - } - - public String getComment() { - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } - - public String getFormat() { - return format; - } - - public void setFormat(String format) { - this.format = format; - } - - public boolean isPublic() { - return isPublic; - } - - public void setPublic(boolean aPublic) { - isPublic = aPublic; - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } - - @Override - public String toString() { - return "OpenNamespaceDTO{" + - "appId='" + appId + '\'' + - ", clusterName='" + clusterName + '\'' + - ", namespaceName='" + namespaceName + '\'' + - ", comment='" + comment + '\'' + - ", format='" + format + '\'' + - ", isPublic=" + isPublic + - ", items=" + items + - ", dataChangeCreatedBy='" + dataChangeCreatedBy + '\'' + - ", dataChangeLastModifiedBy='" + dataChangeLastModifiedBy + '\'' + - ", dataChangeCreatedTime=" + dataChangeCreatedTime + - ", dataChangeLastModifiedTime=" + dataChangeLastModifiedTime + - '}'; - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenNamespaceLockDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenNamespaceLockDTO.java deleted file mode 100644 index 2f051b03681..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenNamespaceLockDTO.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2022 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 OpenNamespaceLockDTO { - - private String namespaceName; - private boolean isLocked; - private String lockedBy; - - public String getNamespaceName() { - return namespaceName; - } - - public void setNamespaceName(String namespaceName) { - this.namespaceName = namespaceName; - } - - public boolean isLocked() { - return isLocked; - } - - public void setLocked(boolean locked) { - isLocked = locked; - } - - public String getLockedBy() { - return lockedBy; - } - - public void setLockedBy(String lockedBy) { - this.lockedBy = lockedBy; - } - - @Override - public String toString() { - return "OpenNamespaceLockDTO{" + - "namespaceName='" + namespaceName + '\'' + - ", isLocked=" + isLocked + - ", lockedBy='" + lockedBy + '\'' + - '}'; - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenPageDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenPageDTO.java deleted file mode 100644 index 4b4678cbfaf..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenPageDTO.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2022 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; - -import java.util.Collections; -import java.util.List; - -/** - * @author mghio (mghio.dev@gmail.com) - */ -public class OpenPageDTO { - - private final int page; - private final int size; - private final long total; - private final List content; - - public OpenPageDTO(int page, int size, long total, List content) { - this.page = page; - this.size = size; - this.total = total; - this.content = Collections.unmodifiableList(content); - } - - public int getPage() { - return page; - } - - public int getSize() { - return size; - } - - public long getTotal() { - return total; - } - - public List getContent() { - return content; - } - - public boolean hasContent() { - return content != null && content.size() > 0; - } - -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenReleaseDTO.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenReleaseDTO.java deleted file mode 100644 index c424d1a646f..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/dto/OpenReleaseDTO.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2022 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; - -import java.util.Map; - -public class OpenReleaseDTO extends BaseDTO { - - private long id; - - private String appId; - - private String clusterName; - - private String namespaceName; - - private String name; - - private Map configurations; - - private String comment; - - public long getId() { - return id; - } - - public void setId(long id) { - this.id = id; - } - - 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; - } - - public String getClusterName() { - return clusterName; - } - - public void setClusterName(String clusterName) { - this.clusterName = clusterName; - } - - public String getNamespaceName() { - return namespaceName; - } - - public void setNamespaceName(String namespaceName) { - this.namespaceName = namespaceName; - } - - public Map getConfigurations() { - return configurations; - } - - public void setConfigurations(Map configurations) { - this.configurations = configurations; - } - - public String getComment() { - return comment; - } - - public void setComment(String comment) { - this.comment = comment; - } - - @Override - public String toString() { - return "OpenReleaseDTO{" + - "id=" + id + - ", appId='" + appId + '\'' + - ", clusterName='" + clusterName + '\'' + - ", namespaceName='" + namespaceName + '\'' + - ", name='" + name + '\'' + - ", configurations=" + configurations + - ", comment='" + comment + '\'' + - ", dataChangeCreatedBy='" + dataChangeCreatedBy + '\'' + - ", dataChangeLastModifiedBy='" + dataChangeLastModifiedBy + '\'' + - ", dataChangeCreatedTime=" + dataChangeCreatedTime + - ", dataChangeLastModifiedTime=" + dataChangeLastModifiedTime + - '}'; - } -} diff --git a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/utils/UrlUtils.java b/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/utils/UrlUtils.java deleted file mode 100644 index ab93b6d42da..00000000000 --- a/apollo-openapi/src/main/java/com/ctrip/framework/apollo/openapi/utils/UrlUtils.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import com.google.common.base.Strings; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * @author Abner - * @since 8/31/22 - */ -public final class UrlUtils { - - private static final String ILLEGAL_KEY_REGEX = "[/\\\\]+"; - private static final Pattern ILLEGAL_KEY_PATTERN = Pattern.compile(ILLEGAL_KEY_REGEX, - Pattern.MULTILINE); - - private UrlUtils() { - } - - public static boolean hasIllegalChar(String key) { - if (Strings.isNullOrEmpty(key)) { - return false; - } - Matcher matcher = ILLEGAL_KEY_PATTERN.matcher(key); - return matcher.find(); - } -} diff --git a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/ApolloOpenApiClientTest.java b/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/ApolloOpenApiClientTest.java deleted file mode 100644 index 607735404a4..00000000000 --- a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/ApolloOpenApiClientTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright 2022 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; - -import static org.junit.Assert.assertEquals; -import org.junit.Test; - -public class ApolloOpenApiClientTest { - - @Test - public void testCreate() { - String someUrl = "http://someUrl"; - String someToken = "someToken"; - - ApolloOpenApiClient client = ApolloOpenApiClient.newBuilder().withPortalUrl(someUrl).withToken(someToken).build(); - - assertEquals(someUrl, client.getPortalUrl()); - assertEquals(someToken, client.getToken()); - } - - @Test(expected = IllegalArgumentException.class) - public void testCreateWithInvalidUrl() { - String someInvalidUrl = "someInvalidUrl"; - String someToken = "someToken"; - - ApolloOpenApiClient.newBuilder().withPortalUrl(someInvalidUrl).withToken(someToken).build(); - } -} diff --git a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/AbstractOpenApiServiceTest.java b/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/AbstractOpenApiServiceTest.java deleted file mode 100644 index 545dd18aa64..00000000000 --- a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/AbstractOpenApiServiceTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2022 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.service; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.openapi.client.constant.ApolloOpenApiConstants; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.impl.client.CloseableHttpClient; -import org.junit.Before; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; - -@RunWith(MockitoJUnitRunner.class) -abstract class AbstractOpenApiServiceTest { - @Mock - protected CloseableHttpClient httpClient; - @Mock - protected CloseableHttpResponse someHttpResponse; - @Mock - protected StatusLine statusLine; - - protected Gson gson; - - protected String someBaseUrl; - - @Before - public void setUp() throws Exception { - gson = new GsonBuilder().setDateFormat(ApolloOpenApiConstants.JSON_DATE_FORMAT).create(); - someBaseUrl = "http://someBaseUrl"; - - when(someHttpResponse.getStatusLine()).thenReturn(statusLine); - when(statusLine.getStatusCode()).thenReturn(200); - - when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(someHttpResponse); - } - -} diff --git a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/AppOpenApiServiceTest.java b/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/AppOpenApiServiceTest.java deleted file mode 100644 index ef3e9b7e19d..00000000000 --- a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/AppOpenApiServiceTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2022 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.service; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import org.apache.http.client.methods.HttpGet; -import org.apache.http.entity.StringEntity; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -public class AppOpenApiServiceTest extends AbstractOpenApiServiceTest { - - private AppOpenApiService appOpenApiService; - - private String someAppId; - - @Override - @Before - public void setUp() throws Exception { - super.setUp(); - someAppId = "someAppId"; - - StringEntity responseEntity = new StringEntity("[]"); - when(someHttpResponse.getEntity()).thenReturn(responseEntity); - - appOpenApiService = new AppOpenApiService(httpClient, someBaseUrl, gson); - } - - @Test - public void testGetEnvClusterInfo() throws Exception { - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpGet.class); - - appOpenApiService.getEnvClusterInfo(someAppId); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpGet get = request.getValue(); - - assertEquals(String - .format("%s/apps/%s/envclusters", someBaseUrl, someAppId), get.getURI().toString()); - } - - @Test(expected = RuntimeException.class) - public void testGetEnvClusterInfoWithError() throws Exception { - when(statusLine.getStatusCode()).thenReturn(500); - - appOpenApiService.getEnvClusterInfo(someAppId); - } -} diff --git a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/ClusterOpenApiServiceTest.java b/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/ClusterOpenApiServiceTest.java deleted file mode 100644 index ec8fa9923b6..00000000000 --- a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/ClusterOpenApiServiceTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright 2022 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.service; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.openapi.dto.OpenClusterDTO; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.util.EntityUtils; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -public class ClusterOpenApiServiceTest extends AbstractOpenApiServiceTest { - - private ClusterOpenApiService clusterOpenApiService; - - private String someAppId; - private String someEnv; - - @Before - public void setUp() throws Exception { - super.setUp(); - someAppId = "someAppId"; - someEnv = "someEnv"; - - StringEntity responseEntity = new StringEntity("{}"); - when(someHttpResponse.getEntity()).thenReturn(responseEntity); - - clusterOpenApiService = new ClusterOpenApiService(httpClient, someBaseUrl, gson); - } - - @Test - public void testGetCluster() throws Exception { - String someCluster = "someCluster"; - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpGet.class); - - clusterOpenApiService.getCluster(someAppId, someEnv, someCluster); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpGet get = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters/%s", someBaseUrl, someEnv, someAppId, someCluster), - get.getURI().toString()); - } - - @Test(expected = RuntimeException.class) - public void testGetClusterWithError() throws Exception { - String someCluster = "someCluster"; - - when(statusLine.getStatusCode()).thenReturn(404); - - clusterOpenApiService.getCluster(someAppId, someEnv, someCluster); - } - - @Test - public void testCreateCluster() throws Exception { - String someCluster = "someCluster"; - String someCreatedBy = "someCreatedBy"; - - OpenClusterDTO clusterDTO = new OpenClusterDTO(); - clusterDTO.setAppId(someAppId); - clusterDTO.setName(someCluster); - clusterDTO.setDataChangeCreatedBy(someCreatedBy); - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpPost.class); - - clusterOpenApiService.createCluster(someEnv, clusterDTO); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpPost post = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters", someBaseUrl, someEnv, someAppId), post.getURI().toString()); - - StringEntity entity = (StringEntity) post.getEntity(); - - assertEquals(ContentType.APPLICATION_JSON.toString(), entity.getContentType().getValue()); - assertEquals(gson.toJson(clusterDTO), EntityUtils.toString(entity)); - } - - @Test(expected = RuntimeException.class) - public void testCreateClusterWithError() throws Exception { - String someCluster = "someCluster"; - String someCreatedBy = "someCreatedBy"; - - OpenClusterDTO clusterDTO = new OpenClusterDTO(); - clusterDTO.setAppId(someAppId); - clusterDTO.setName(someCluster); - clusterDTO.setDataChangeCreatedBy(someCreatedBy); - - when(statusLine.getStatusCode()).thenReturn(400); - - clusterOpenApiService.createCluster(someEnv, clusterDTO); - } -} diff --git a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/ItemOpenApiServiceTest.java b/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/ItemOpenApiServiceTest.java deleted file mode 100644 index 81a24bc3456..00000000000 --- a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/ItemOpenApiServiceTest.java +++ /dev/null @@ -1,359 +0,0 @@ -/* - * Copyright 2022 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.service; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; -import com.ctrip.framework.apollo.openapi.dto.OpenItemDTO; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import org.apache.http.client.methods.HttpDelete; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.entity.ContentType; -import org.apache.http.entity.StringEntity; -import org.apache.http.util.EntityUtils; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -public class ItemOpenApiServiceTest extends AbstractOpenApiServiceTest { - - private ItemOpenApiService itemOpenApiService; - - private String someAppId; - private String someEnv; - private String someCluster; - private String someNamespace; - - @Override - @Before - public void setUp() throws Exception { - super.setUp(); - someAppId = "someAppId"; - someEnv = "someEnv"; - someCluster = "someCluster"; - someNamespace = "someNamespace"; - - StringEntity responseEntity = new StringEntity("{}"); - when(someHttpResponse.getEntity()).thenReturn(responseEntity); - - itemOpenApiService = new ItemOpenApiService(httpClient, someBaseUrl, gson); - } - - @Test - public void testGetItem() throws Exception { - String someKey = "someKey"; - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpGet.class); - - itemOpenApiService.getItem(someAppId, someEnv, someCluster, someNamespace, someKey); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpGet get = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s/items/%s", someBaseUrl, someEnv, - someAppId, someCluster, someNamespace, someKey), get.getURI().toString()); - } - - @Test - public void testGetItemByIllegalKey() throws Exception { - String someKey = "protocol//:host:port"; - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpGet.class); - - itemOpenApiService.getItem(someAppId, someEnv, someCluster, someNamespace, someKey); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpGet get = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s/encodedItems/%s", someBaseUrl, - someEnv, - someAppId, someCluster, someNamespace, - new String(Base64.getEncoder().encode(someKey.getBytes(StandardCharsets.UTF_8)))), - get.getURI().toString()); - } - - @Test - public void testGetNotExistedItem() throws Exception { - String someKey = "someKey"; - - when(statusLine.getStatusCode()).thenReturn(404); - - assertNull(itemOpenApiService.getItem(someAppId, someEnv, someCluster, someNamespace, someKey)); - } - - @Test - public void testCreateItem() throws Exception { - String someKey = "someKey"; - String someValue = "someValue"; - String someCreatedBy = "someCreatedBy"; - - OpenItemDTO itemDTO = new OpenItemDTO(); - itemDTO.setKey(someKey); - itemDTO.setValue(someValue); - itemDTO.setDataChangeCreatedBy(someCreatedBy); - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpPost.class); - - itemOpenApiService.createItem(someAppId, someEnv, someCluster, someNamespace, itemDTO); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpPost post = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s/items", someBaseUrl, someEnv, someAppId, someCluster, - someNamespace), post.getURI().toString()); - - StringEntity entity = (StringEntity) post.getEntity(); - - assertEquals(ContentType.APPLICATION_JSON.toString(), entity.getContentType().getValue()); - assertEquals(gson.toJson(itemDTO), EntityUtils.toString(entity)); - } - - @Test(expected = RuntimeException.class) - public void testCreateItemWithError() throws Exception { - String someKey = "someKey"; - String someValue = "someValue"; - String someCreatedBy = "someCreatedBy"; - - OpenItemDTO itemDTO = new OpenItemDTO(); - itemDTO.setKey(someKey); - itemDTO.setValue(someValue); - itemDTO.setDataChangeCreatedBy(someCreatedBy); - - when(statusLine.getStatusCode()).thenReturn(400); - - itemOpenApiService.createItem(someAppId, someEnv, someCluster, someNamespace, itemDTO); - } - - @Test - public void testUpdateItem() throws Exception { - String someKey = "someKey"; - String someValue = "someValue"; - String someModifiedBy = "someModifiedBy"; - - OpenItemDTO itemDTO = new OpenItemDTO(); - itemDTO.setKey(someKey); - itemDTO.setValue(someValue); - itemDTO.setDataChangeLastModifiedBy(someModifiedBy); - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpPut.class); - - itemOpenApiService.updateItem(someAppId, someEnv, someCluster, someNamespace, itemDTO); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpPut put = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s/items/%s", someBaseUrl, someEnv, someAppId, someCluster, - someNamespace, someKey), put.getURI().toString()); - } - - @Test - public void testUpdateItemByIllegalKey() throws Exception { - String someKey = "hello\\world"; - String someValue = "someValue"; - String someModifiedBy = "someModifiedBy"; - - OpenItemDTO itemDTO = new OpenItemDTO(); - itemDTO.setKey(someKey); - itemDTO.setValue(someValue); - itemDTO.setDataChangeLastModifiedBy(someModifiedBy); - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpPut.class); - - itemOpenApiService.updateItem(someAppId, someEnv, someCluster, someNamespace, itemDTO); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpPut put = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s/encodedItems/%s", someBaseUrl, - someEnv, someAppId, someCluster, - someNamespace, - new String(Base64.getEncoder().encode(someKey.getBytes(StandardCharsets.UTF_8)))), - put.getURI().toString()); - } - - @Test(expected = RuntimeException.class) - public void testUpdateItemWithError() throws Exception { - String someKey = "someKey"; - String someValue = "someValue"; - String someModifiedBy = "someModifiedBy"; - - OpenItemDTO itemDTO = new OpenItemDTO(); - itemDTO.setKey(someKey); - itemDTO.setValue(someValue); - itemDTO.setDataChangeLastModifiedBy(someModifiedBy); - - when(statusLine.getStatusCode()).thenReturn(400); - - itemOpenApiService.updateItem(someAppId, someEnv, someCluster, someNamespace, itemDTO); - } - - @Test - public void testCreateOrUpdateItem() throws Exception { - String someKey = "someKey"; - String someValue = "someValue"; - String someCreatedBy = "someCreatedBy"; - - OpenItemDTO itemDTO = new OpenItemDTO(); - itemDTO.setKey(someKey); - itemDTO.setValue(someValue); - itemDTO.setDataChangeCreatedBy(someCreatedBy); - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpPut.class); - - itemOpenApiService.createOrUpdateItem(someAppId, someEnv, someCluster, someNamespace, itemDTO); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpPut put = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s/items/%s?createIfNotExists=true", someBaseUrl, someEnv, - someAppId, someCluster, someNamespace, someKey), put.getURI().toString()); - } - - @Test(expected = RuntimeException.class) - public void testCreateOrUpdateItemWithError() throws Exception { - String someKey = "someKey"; - String someValue = "someValue"; - String someCreatedBy = "someCreatedBy"; - - OpenItemDTO itemDTO = new OpenItemDTO(); - itemDTO.setKey(someKey); - itemDTO.setValue(someValue); - itemDTO.setDataChangeCreatedBy(someCreatedBy); - - when(statusLine.getStatusCode()).thenReturn(400); - - itemOpenApiService.createOrUpdateItem(someAppId, someEnv, someCluster, someNamespace, itemDTO); - } - - @Test - public void testRemoveItem() throws Exception { - String someKey = "someKey"; - String someOperator = "someOperator"; - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpDelete.class); - - itemOpenApiService.removeItem(someAppId, someEnv, someCluster, someNamespace, someKey, someOperator); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpDelete delete = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s/items/%s?operator=%s", someBaseUrl, someEnv, - someAppId, someCluster, someNamespace, someKey, someOperator), delete.getURI().toString()); - } - - @Test - public void testRemoveItemByIllegalKey() throws Exception { - String someKey = "protocol//:host:port"; - String someOperator = "someOperator"; - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpDelete.class); - - itemOpenApiService.removeItem(someAppId, someEnv, someCluster, someNamespace, someKey, - someOperator); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpDelete delete = request.getValue(); - - assertEquals( - String.format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s/encodedItems/%s?operator=%s", - someBaseUrl, someEnv, someAppId, someCluster, someNamespace, - new String(Base64.getEncoder().encode(someKey.getBytes(StandardCharsets.UTF_8))), - someOperator), delete.getURI().toString()); - } - - @Test(expected = RuntimeException.class) - public void testRemoveItemWithError() throws Exception { - String someKey = "someKey"; - String someOperator = "someOperator"; - - when(statusLine.getStatusCode()).thenReturn(404); - - itemOpenApiService.removeItem(someAppId, someEnv, someCluster, someNamespace, someKey, someOperator); - } - - @Test - public void testFindItemsByNamespace() throws Exception { - final int page = 0; - final int size = 50; - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpGet.class); - - itemOpenApiService.findItemsByNamespace(someAppId, someEnv, someCluster, someNamespace, page, size); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpGet get = request.getValue(); - - assertEquals(String.format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s/items?size=%s&page=%s", - someBaseUrl, someEnv, someAppId, someCluster, someNamespace, size, page), get.getURI().toString()); - } - - @Test(expected = RuntimeException.class) - public void testFindItemsByNamespaceWithError() { - final int page = 0; - final int size = 50; - - when(statusLine.getStatusCode()).thenReturn(400); - - itemOpenApiService.findItemsByNamespace(someAppId, someEnv, someCluster, someNamespace, page, size); - } - - @Test(expected = IllegalArgumentException.class) - public void testFindItemsByNamespaceWithPageNegativeError() { - final int page = -1; - final int size = 50; - - itemOpenApiService.findItemsByNamespace(someAppId, someEnv, someCluster, someNamespace, page, size); - } - - @Test(expected = IllegalArgumentException.class) - public void testFindItemsByNamespaceWithSizeNegativeError() { - final int page = 0; - final int size = -50; - - itemOpenApiService.findItemsByNamespace(someAppId, someEnv, someCluster, someNamespace, page, size); - } - - @Test(expected = IllegalArgumentException.class) - public void testFindItemsByNamespaceWithPageAndSizeAllNegativeError() { - final int page = -1; - final int size = -50; - - itemOpenApiService.findItemsByNamespace(someAppId, someEnv, someCluster, someNamespace, page, size); - } - -} diff --git a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/NamespaceOpenApiServiceTest.java b/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/NamespaceOpenApiServiceTest.java deleted file mode 100644 index 31c656a268a..00000000000 --- a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/NamespaceOpenApiServiceTest.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2022 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.service; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.openapi.dto.OpenAppNamespaceDTO; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -public class NamespaceOpenApiServiceTest extends AbstractOpenApiServiceTest { - - private NamespaceOpenApiService namespaceOpenApiService; - - private String someAppId; - private String someEnv; - private String someCluster; - private String someNamespace; - - @Override - @Before - public void setUp() throws Exception { - super.setUp(); - - someAppId = "someAppId"; - someEnv = "someEnv"; - someCluster = "someCluster"; - someNamespace = "someNamespace"; - - StringEntity responseEntity = new StringEntity("{}"); - when(someHttpResponse.getEntity()).thenReturn(responseEntity); - - namespaceOpenApiService = new NamespaceOpenApiService(httpClient, someBaseUrl, gson); - } - - @Test - public void testGetNamespace() throws Exception { - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpGet.class); - - namespaceOpenApiService.getNamespace(someAppId, someEnv, someCluster, someNamespace); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpGet get = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s", someBaseUrl, someEnv, someAppId, someCluster, - someNamespace), get.getURI().toString()); - } - - @Test(expected = RuntimeException.class) - public void testGetNamespaceWithError() throws Exception { - when(statusLine.getStatusCode()).thenReturn(404); - - namespaceOpenApiService.getNamespace(someAppId, someEnv, someCluster, someNamespace); - } - - @Test - public void testGetNamespaces() throws Exception { - StringEntity responseEntity = new StringEntity("[]"); - when(someHttpResponse.getEntity()).thenReturn(responseEntity); - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpGet.class); - - namespaceOpenApiService.getNamespaces(someAppId, someEnv, someCluster); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpGet get = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters/%s/namespaces", someBaseUrl, someEnv, someAppId, someCluster), - get.getURI().toString()); - } - - @Test(expected = RuntimeException.class) - public void testGetNamespacesWithError() throws Exception { - when(statusLine.getStatusCode()).thenReturn(404); - - namespaceOpenApiService.getNamespaces(someAppId, someEnv, someCluster); - } - - @Test - public void testCreateAppNamespace() throws Exception { - String someName = "someName"; - String someCreatedBy = "someCreatedBy"; - - OpenAppNamespaceDTO appNamespaceDTO = new OpenAppNamespaceDTO(); - appNamespaceDTO.setAppId(someAppId); - appNamespaceDTO.setName(someName); - appNamespaceDTO.setDataChangeCreatedBy(someCreatedBy); - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpPost.class); - - namespaceOpenApiService.createAppNamespace(appNamespaceDTO); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpPost post = request.getValue(); - - assertEquals(String.format("%s/apps/%s/appnamespaces", someBaseUrl, someAppId), post.getURI().toString()); - } - - @Test(expected = RuntimeException.class) - public void testCreateAppNamespaceWithError() throws Exception { - String someName = "someName"; - String someCreatedBy = "someCreatedBy"; - - OpenAppNamespaceDTO appNamespaceDTO = new OpenAppNamespaceDTO(); - appNamespaceDTO.setAppId(someAppId); - appNamespaceDTO.setName(someName); - appNamespaceDTO.setDataChangeCreatedBy(someCreatedBy); - - when(statusLine.getStatusCode()).thenReturn(400); - - namespaceOpenApiService.createAppNamespace(appNamespaceDTO); - } - - @Test - public void testGetNamespaceLock() throws Exception { - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpGet.class); - - namespaceOpenApiService.getNamespaceLock(someAppId, someEnv, someCluster, someNamespace); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpGet post = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s/lock", someBaseUrl, someEnv, someAppId, someCluster, - someNamespace), post.getURI().toString()); - } - - @Test(expected = RuntimeException.class) - public void testGetNamespaceLockWithError() throws Exception { - when(statusLine.getStatusCode()).thenReturn(404); - - namespaceOpenApiService.getNamespaceLock(someAppId, someEnv, someCluster, someNamespace); - } -} diff --git a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/ReleaseOpenApiServiceTest.java b/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/ReleaseOpenApiServiceTest.java deleted file mode 100644 index 445245dd4dc..00000000000 --- a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/service/ReleaseOpenApiServiceTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright 2022 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.service; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import com.ctrip.framework.apollo.openapi.dto.NamespaceReleaseDTO; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.entity.StringEntity; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -public class ReleaseOpenApiServiceTest extends AbstractOpenApiServiceTest { - - private ReleaseOpenApiService releaseOpenApiService; - - private String someAppId; - private String someEnv; - private String someCluster; - private String someNamespace; - - @Override - @Before - public void setUp() throws Exception { - super.setUp(); - - someAppId = "someAppId"; - someEnv = "someEnv"; - someCluster = "someCluster"; - someNamespace = "someNamespace"; - - StringEntity responseEntity = new StringEntity("{}"); - when(someHttpResponse.getEntity()).thenReturn(responseEntity); - - releaseOpenApiService = new ReleaseOpenApiService(httpClient, someBaseUrl, gson); - } - - @Test - public void testPublishNamespace() throws Exception { - String someReleaseTitle = "someReleaseTitle"; - String someReleasedBy = "someReleasedBy"; - - NamespaceReleaseDTO namespaceReleaseDTO = new NamespaceReleaseDTO(); - namespaceReleaseDTO.setReleaseTitle(someReleaseTitle); - namespaceReleaseDTO.setReleasedBy(someReleasedBy); - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpPost.class); - - releaseOpenApiService.publishNamespace(someAppId, someEnv, someCluster, someNamespace, namespaceReleaseDTO); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpPost post = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s/releases", someBaseUrl, someEnv, someAppId, someCluster, - someNamespace), post.getURI().toString()); - } - - @Test(expected = RuntimeException.class) - public void testPublishNamespaceWithError() throws Exception { - String someReleaseTitle = "someReleaseTitle"; - String someReleasedBy = "someReleasedBy"; - - NamespaceReleaseDTO namespaceReleaseDTO = new NamespaceReleaseDTO(); - namespaceReleaseDTO.setReleaseTitle(someReleaseTitle); - namespaceReleaseDTO.setReleasedBy(someReleasedBy); - - when(statusLine.getStatusCode()).thenReturn(400); - - releaseOpenApiService.publishNamespace(someAppId, someEnv, someCluster, someNamespace, namespaceReleaseDTO); - } - - @Test - public void testGetLatestActiveRelease() throws Exception { - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpGet.class); - - releaseOpenApiService.getLatestActiveRelease(someAppId, someEnv, someCluster, someNamespace); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpGet get = request.getValue(); - - assertEquals(String - .format("%s/envs/%s/apps/%s/clusters/%s/namespaces/%s/releases/latest", someBaseUrl, someEnv, someAppId, someCluster, - someNamespace), get.getURI().toString()); - } - - @Test(expected = RuntimeException.class) - public void testGetLatestActiveReleaseWithError() throws Exception { - when(statusLine.getStatusCode()).thenReturn(400); - - releaseOpenApiService.getLatestActiveRelease(someAppId, someEnv, someCluster, someNamespace); - } - - @Test - public void testRollbackRelease() throws Exception { - long someReleaseId = 1L; - String someOperator = "someOperator"; - - final ArgumentCaptor request = ArgumentCaptor.forClass(HttpPut.class); - - releaseOpenApiService.rollbackRelease(someEnv, someReleaseId, someOperator); - - verify(httpClient, times(1)).execute(request.capture()); - - HttpPut put = request.getValue(); - - assertEquals( - String.format("%s/envs/%s/releases/%s/rollback?operator=%s", someBaseUrl, someEnv, someReleaseId, someOperator), - put.getURI().toString()); - } - - @Test(expected = RuntimeException.class) - public void testRollbackReleaseWithError() throws Exception { - long someReleaseId = 1L; - String someOperator = "someOperator"; - - when(statusLine.getStatusCode()).thenReturn(400); - - releaseOpenApiService.rollbackRelease(someEnv, someReleaseId, someOperator); - } -} diff --git a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/url/OpenApiPathBuilderTest.java b/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/url/OpenApiPathBuilderTest.java deleted file mode 100644 index 6050cde93d3..00000000000 --- a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/url/OpenApiPathBuilderTest.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright 2022 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.url; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -public class OpenApiPathBuilderTest { - - @Test - public void testBuildPath() { - String baseURL = "http://localhost"; - OpenApiPathBuilder tools = OpenApiPathBuilder.newBuilder(); - String path, expected, actual; - String env = "test"; - String appId = "appid-1001"; - String clusterName = "cluster-1001"; - String namespaceName = "application.yml"; - String key = "spring.profile"; - String operator = "junit"; - long releaseId = 1L; - - // AppOpenApiService path check - - path = String.format("apps/%s/envclusters", tools.escapePath(appId)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .appsPathVal(appId) - .customResource("envclusters") - .buildPath(baseURL); - assertEquals(expected, actual); - - String param = "1,2,3"; - path = String.format("apps?appIds=%s", tools.escapeParam(param)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .customResource("apps") - .addParam("appIds", param) - .buildPath(baseURL); - assertEquals(expected, actual); - - path = "apps/authorized"; - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .customResource("apps/authorized") - .buildPath(baseURL); - assertEquals(expected, actual); - - // ClusterOpenApiService path check - - path = String.format("envs/%s/apps/%s/clusters/%s", tools.escapePath(env), - tools.escapePath(appId), - tools.escapePath(clusterName)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .buildPath(baseURL); - assertEquals(expected, actual); - - path = String.format("envs/%s/apps/%s/clusters", tools.escapePath(env), - tools.escapePath(appId)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .customResource("clusters") - .buildPath(baseURL); - assertEquals(expected, actual); - - // ItemOpenApiService path check - - path = String.format("envs/%s/apps/%s/clusters/%s/namespaces/%s/items/%s", - tools.escapePath(env), tools.escapePath(appId), tools.escapePath(clusterName), - tools.escapePath(namespaceName), tools.escapePath(key)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .itemsPathVal(key) - .buildPath(baseURL); - assertEquals(expected, actual); - - path = String.format("envs/%s/apps/%s/clusters/%s/namespaces/%s/items", - tools.escapePath(env), tools.escapePath(appId), tools.escapePath(clusterName), - tools.escapePath(namespaceName)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .customResource("items") - .buildPath(baseURL); - assertEquals(expected, actual); - - path = String.format( - "envs/%s/apps/%s/clusters/%s/namespaces/%s/items/%s?createIfNotExists=true", - tools.escapePath(env), tools.escapePath(appId), tools.escapePath(clusterName), - tools.escapePath(namespaceName), tools.escapePath(key)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .itemsPathVal(key) - .addParam("createIfNotExists", "true") - .buildPath(baseURL); - assertEquals(expected, actual); - - path = String.format("envs/%s/apps/%s/clusters/%s/namespaces/%s/items/%s?operator=%s", - tools.escapePath(env), tools.escapePath(appId), tools.escapePath(clusterName), - tools.escapePath(namespaceName), tools.escapePath(key), tools.escapeParam(operator)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .itemsPathVal(key) - .addParam("operator", operator) - .buildPath(baseURL); - assertEquals(expected, actual); - - // NamespaceOpenApiService path check - - path = String.format("envs/%s/apps/%s/clusters/%s/namespaces/%s", tools.escapePath(env), - tools.escapePath(appId), tools.escapePath(clusterName), tools.escapePath(namespaceName)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .buildPath(baseURL); - assertEquals(expected, actual); - - path = String.format("envs/%s/apps/%s/clusters/%s/namespaces", tools.escapePath(env), - tools.escapePath(appId), tools.escapePath(clusterName)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .customResource("namespaces") - .buildPath(baseURL); - assertEquals(expected, actual); - - path = String.format("apps/%s/appnamespaces", tools.escapePath(appId)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .appsPathVal(appId) - .customResource("appnamespaces") - .buildPath(baseURL); - assertEquals(expected, actual); - - path = String.format("envs/%s/apps/%s/clusters/%s/namespaces/%s/lock", tools.escapePath(env), - tools.escapePath(appId), tools.escapePath(clusterName), tools.escapePath(namespaceName)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .customResource("lock") - .buildPath(baseURL); - assertEquals(expected, actual); - - // ReleaseOpenApiService path check - - path = String.format("envs/%s/apps/%s/clusters/%s/namespaces/%s/releases", - tools.escapePath(env), tools.escapePath(appId), tools.escapePath(clusterName), - tools.escapePath(namespaceName)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .customResource("releases") - .buildPath(baseURL); - assertEquals(expected, actual); - - path = String.format("envs/%s/apps/%s/clusters/%s/namespaces/%s/releases/latest", - tools.escapePath(env), tools.escapePath(appId), tools.escapePath(clusterName), - tools.escapePath(namespaceName)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .appsPathVal(appId) - .clustersPathVal(clusterName) - .namespacesPathVal(namespaceName) - .releasesPathVal("latest") - .buildPath(baseURL); - assertEquals(expected, actual); - - path = String.format("envs/%s/releases/%s/rollback?operator=%s", tools.escapePath(env), - releaseId, - tools.escapeParam(operator)); - expected = String.format("%s/%s", baseURL, path); - actual = OpenApiPathBuilder.newBuilder() - .envsPathVal(env) - .releasesPathVal(String.valueOf(releaseId)) - .customResource("rollback") - .addParam("operator", operator) - .buildPath(baseURL); - assertEquals(expected, actual); - } - - @Test(expected = IllegalArgumentException.class) - public void testAddParamKeyEmpty() { - OpenApiPathBuilder.newBuilder().addParam("", ""); - } - - @Test(expected = IllegalArgumentException.class) - public void testBuildPathURLEmpty() { - OpenApiPathBuilder.newBuilder().buildPath(""); - } -} \ No newline at end of file diff --git a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/utils/UrlUtilsTest.java b/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/utils/UrlUtilsTest.java deleted file mode 100644 index 80dc0690db4..00000000000 --- a/apollo-openapi/src/test/java/com/ctrip/framework/apollo/openapi/client/utils/UrlUtilsTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2022 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.utils; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import com.ctrip.framework.apollo.openapi.utils.UrlUtils; -import org.junit.Test; - -/** - * @author huanghousheng - * @since 9/7/22 - */ -public class UrlUtilsTest { - - @Test - public void testSlash() { - String someKey = "protocol//:host:port"; - assertTrue(UrlUtils.hasIllegalChar(someKey)); - } - - @Test - public void testBackslash() { - String someKey = "a\\c"; - assertTrue(UrlUtils.hasIllegalChar(someKey)); - } - - @Test - public void testNormalKey() { - String someKey = "someKey"; - assertFalse(UrlUtils.hasIllegalChar(someKey)); - } - - @Test - public void testDot() { - String someKey = "a.b"; - assertFalse(UrlUtils.hasIllegalChar(someKey)); - } - -} diff --git a/apollo-openapi/src/test/resources/log4j2.xml b/apollo-openapi/src/test/resources/log4j2.xml deleted file mode 100644 index 4dc6d6e29c4..00000000000 --- a/apollo-openapi/src/test/resources/log4j2.xml +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/apollo-client/doc/pic/app-id-location.png b/doc/images/app-id-location.png similarity index 100% rename from apollo-client/doc/pic/app-id-location.png rename to doc/images/app-id-location.png diff --git a/apollo-client/doc/pic/client-local-cache.png b/doc/images/client-local-cache.png similarity index 100% rename from apollo-client/doc/pic/client-local-cache.png rename to doc/images/client-local-cache.png diff --git a/docs/en/design/apollo-design.md b/docs/en/design/apollo-design.md index 87a7de602bf..d4596fd1959 100644 --- a/docs/en/design/apollo-design.md +++ b/docs/en/design/apollo-design.md @@ -248,7 +248,7 @@ The previous section briefly described how NotificationControllerV2 learns that The implementation is as follows. -1. the client initiates an Http request to the `notifications/v2` interface of the Config Service, which is [NotificationControllerV2](https://github.com/apolloconfig/apollo/blob/master/apollo-configservice/src/main/java/com/ctrip/framework/apollo/configservice/controller/NotificationControllerV2.java), see [ RemoteConfigLongPollService](https://github.com/apolloconfig/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java) +1. the client initiates an Http request to the `notifications/v2` interface of the Config Service, which is [NotificationControllerV2](https://github.com/apolloconfig/apollo/blob/master/apollo-configservice/src/main/java/com/ctrip/framework/apollo/configservice/controller/NotificationControllerV2.java), see [ RemoteConfigLongPollService](https://github.com/apolloconfig/apollo-java/blob/main/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java) 2. NotificationControllerV2 does not return the result immediately, but via [Spring DeferredResult](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/context/request/async/DeferredResult.html) to put the request on hold 3. if no configuration of interest to the client is published within 60 seconds, then the Http status code 304 is returned to the client 4. If there is a configuration published that the client cares about, NotificationControllerV2 will call [setResult](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/context/request/async/DeferredResult.html#setResult-T-) method of DeferredResult, passing in the namespace information with configuration changes, while the request is returned immediately. After the client gets the namespace with configuration changes from the returned result, it will immediately request the Config Service to get the latest configuration of the namespace. @@ -297,7 +297,7 @@ With the above principles understood, the means of integrating Apollo with Sprin ![Overview](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/doc/images/environment-remote-source.png) -The related code can be found in [PropertySourcesProcessor](https://github.com/apolloconfig/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/PropertySourcesProcessor.java) +The related code can be found in [PropertySourcesProcessor](https://github.com/apolloconfig/apollo-java/blob/main/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/PropertySourcesProcessor.java) # IV. Usability considerations diff --git a/docs/en/usage/java-sdk-user-guide.md b/docs/en/usage/java-sdk-user-guide.md index 940f68bf5ba..4cdc953d707 100644 --- a/docs/en/usage/java-sdk-user-guide.md +++ b/docs/en/usage/java-sdk-user-guide.md @@ -57,7 +57,7 @@ Make sure that the classpath:/META-INF/app.properties file exists and that its c The file location reference is as follows. -![app-id-location](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/apollo-client/doc/pic/app-id-location.png) +![app-id-location](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/doc/images/app-id-location.png) > Note: app.id is a unique id used to identify the application identity in the format string. @@ -119,7 +119,7 @@ One thing to note is that apollo will iterate through all MetaServerProviders in **If your company has many applications that need to access Apollo, it is recommended to package a jar package and then provide a custom Apollo Meta Server positioning logic so that the applications that access Apollo can be used with zero configuration. For example, write your own `xx-company-apollo-client`, the jar package depends on `apollo-client`, define a custom MetaServerProvider implementation in the jar package by spi, and then the application directly depends on `xx-company-apollo-client`.** -The implementation of MetaServerProvider can be found in [LegacyMetaServerProvider](https://github.com/apolloconfig/apollo/blob/master/apollo-core/src/main/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProvider.java) and [DefaultMetaServerProvider](https://github.com/apolloconfig/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProvider.java). +The implementation of MetaServerProvider can be found in [LegacyMetaServerProvider](https://github.com/apolloconfig/apollo/blob/master/apollo-core/src/main/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProvider.java) and [DefaultMetaServerProvider](https://github.com/apolloconfig/apollo-java/blob/main/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProvider.java). #### 1.2.2.2 Skip Apollo Meta Server service discovery @@ -163,7 +163,7 @@ The local configuration file will be placed under the local cache path in the fo * AppId is the application's own appId, e.g. 100004458 * Cluster is the cluster used by the application, generally in local mode without configuration, it is default * Namespace is the configuration `namespace` used by the application, usually `application` - ![client-local-cache](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/apollo-client/doc/pic/client-local-cache.png) + ![client-local-cache](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/doc/images/client-local-cache.png) The content of the file is stored in properties format, for example, if there are two keys, one is request.timeout, and the other is batch, then the content of the file is in the following format. @@ -392,7 +392,7 @@ Make sure that the `classpath:/META-INF/app.properties` file exists and that its The file location reference is as follows. -![app-id-location](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/apollo-client/doc/pic/app-id-location.png) +![app-id-location](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/doc/images/app-id-location.png) > Note: apollo.label is a label used to identify the application identity in the format string. @@ -1181,7 +1181,7 @@ Local configuration files need to be placed in the local configuration directory * AppId is the application's own appId, such as 100004458 * Cluster is the cluster used by the application, generally in local mode without configuration, it is default * Namespace is the configuration `namespace` used by the `application`, usually `application` - ![client-local-cache](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/apollo-client/doc/pic/client-local-cache.png) + ![client-local-cache](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/doc/images/client-local-cache.png) The content of the file is stored in properties format, for example, if there are two keys, one is request.timeout and the other is batch, then the content of the file is in the following format. diff --git a/docs/en/usage/other-language-client-user-guide.md b/docs/en/usage/other-language-client-user-guide.md index 7ad4578356e..782bf0811d1 100644 --- a/docs/en/usage/other-language-client-user-guide.md +++ b/docs/en/usage/other-language-client-user-guide.md @@ -107,7 +107,7 @@ If you need to be aware of configuration updates in real time (1 second), you ca ### 1.4.1 Configuration update push idea -Here we suggest you to refer to Apollo's Java implementation: [RemoteConfigLongPollService.java](https://github.com/apolloconfig/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java), which has more than 200 lines of code and is relatively simple in general. +Here we suggest you to refer to Apollo's Java implementation: [RemoteConfigLongPollService.java](https://github.com/apolloconfig/apollo-java/blob/main/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java), which has more than 200 lines of code and is relatively simple in general. #### 1.4.1.1 Initialization diff --git a/docs/zh/design/apollo-design.md b/docs/zh/design/apollo-design.md index 6adec45586d..4d8607ed0b3 100644 --- a/docs/zh/design/apollo-design.md +++ b/docs/zh/design/apollo-design.md @@ -250,7 +250,7 @@ Admin Service在配置发布后,需要通知所有的Config Service有配置 实现方式如下: -1. 客户端会发起一个Http请求到Config Service的`notifications/v2`接口,也就是[NotificationControllerV2](https://github.com/apolloconfig/apollo/blob/master/apollo-configservice/src/main/java/com/ctrip/framework/apollo/configservice/controller/NotificationControllerV2.java),参见[RemoteConfigLongPollService](https://github.com/apolloconfig/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java) +1. 客户端会发起一个Http请求到Config Service的`notifications/v2`接口,也就是[NotificationControllerV2](https://github.com/apolloconfig/apollo/blob/master/apollo-configservice/src/main/java/com/ctrip/framework/apollo/configservice/controller/NotificationControllerV2.java),参见[RemoteConfigLongPollService](https://github.com/apolloconfig/apollo-java/blob/main/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java) 2. NotificationControllerV2不会立即返回结果,而是通过[Spring DeferredResult](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/context/request/async/DeferredResult.html)把请求挂起 3. 如果在60秒内没有该客户端关心的配置发布,那么会返回Http状态码304给客户端 4. 如果有该客户端关心的配置发布,NotificationControllerV2会调用DeferredResult的[setResult](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/context/request/async/DeferredResult.html#setResult-T-)方法,传入有配置变化的namespace信息,同时该请求会立即返回。客户端从返回的结果中获取到配置变化的namespace后,会立即请求Config Service获取该namespace的最新配置。 @@ -298,7 +298,7 @@ Spring从3.1版本开始增加了`ConfigurableEnvironment`和`PropertySource`: ![Overview](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/doc/images/environment-remote-source.png) -相关代码可以参考[PropertySourcesProcessor](https://github.com/apolloconfig/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/PropertySourcesProcessor.java) +相关代码可以参考[PropertySourcesProcessor](https://github.com/apolloconfig/apollo-java/blob/main/apollo-client/src/main/java/com/ctrip/framework/apollo/spring/config/PropertySourcesProcessor.java) # 四、可用性考虑 diff --git a/docs/zh/development/apollo-release-guide.md b/docs/zh/development/apollo-release-guide.md index deb27380567..a243a005b24 100644 --- a/docs/zh/development/apollo-release-guide.md +++ b/docs/zh/development/apollo-release-guide.md @@ -86,7 +86,7 @@ github 创建 pre-release 通过 github workflow 来发布。 -[https://github.com/apolloconfig/apollo/actions/workflows/release.yml](https://github.com/apolloconfig/apollo/actions/workflows/release.yml) +[https://github.com/apolloconfig/apollo-java/actions/workflows/release.yml](https://github.com/apolloconfig/apollo-java/actions/workflows/release.yml) ![image.png](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/doc/images/local-development/publish-sdk.png) diff --git a/docs/zh/usage/java-sdk-user-guide.md b/docs/zh/usage/java-sdk-user-guide.md index f230196bc1a..4b79b1495d5 100644 --- a/docs/zh/usage/java-sdk-user-guide.md +++ b/docs/zh/usage/java-sdk-user-guide.md @@ -53,7 +53,7 @@ app.id=YOUR-APP-ID 文件位置参考如下: -![app-id-location](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/apollo-client/doc/pic/app-id-location.png) +![app-id-location](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/doc/images/app-id-location.png) > 注:app.id是用来标识应用身份的唯一id,格式为string。 @@ -113,7 +113,7 @@ pro.meta=http://apollo.xxx.com **如果你的公司有很多应用需要接入Apollo,建议封装一个jar包,然后提供自定义的Apollo Meta Server定位逻辑,从而可以让接入Apollo的应用零配置使用。比如自己写一个`xx-company-apollo-client`,该jar包依赖`apollo-client`,在该jar包中通过spi方式定义自定义的MetaServerProvider实现,然后应用直接依赖`xx-company-apollo-client`即可。** -MetaServerProvider的实现可以参考[LegacyMetaServerProvider](https://github.com/apolloconfig/apollo/blob/master/apollo-core/src/main/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProvider.java)和[DefaultMetaServerProvider](https://github.com/apolloconfig/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProvider.java)。 +MetaServerProvider的实现可以参考[LegacyMetaServerProvider](https://github.com/apolloconfig/apollo/blob/master/apollo-core/src/main/java/com/ctrip/framework/apollo/core/internals/LegacyMetaServerProvider.java)和[DefaultMetaServerProvider](https://github.com/apolloconfig/apollo-java/blob/main/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/DefaultMetaServerProvider.java)。 #### 1.2.2.2 跳过Apollo Meta Server服务发现 @@ -155,7 +155,7 @@ Apollo客户端会把从服务端获取到的配置在本地文件系统缓存 * appId就是应用自己的appId,如100004458 * cluster就是应用使用的集群,一般在本地模式下没有做过配置的话,就是default * namespace就是应用使用的配置namespace,一般是application -![client-local-cache](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/apollo-client/doc/pic/client-local-cache.png) +![client-local-cache](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/doc/images/client-local-cache.png) 文件内容以properties格式存储,比如如果有两个key,一个是request.timeout,另一个是batch,那么文件内容就是如下格式: ```properties @@ -377,7 +377,7 @@ apollo.label=YOUR-APOLLO-LABEL 文件位置参考如下: -![app-id-location](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/apollo-client/doc/pic/app-id-location.png) +![app-id-location](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/doc/images/app-id-location.png) > 注:apollo.label是用来标识应用身份的标签,格式为string。 @@ -1120,7 +1120,7 @@ appId就是应用的appId,如100004458。 * appId就是应用自己的appId,如100004458 * cluster就是应用使用的集群,一般在本地模式下没有做过配置的话,就是default * namespace就是应用使用的配置namespace,一般是application -![client-local-cache](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/apollo-client/doc/pic/client-local-cache.png) +![client-local-cache](https://cdn.jsdelivr.net/gh/apolloconfig/apollo@master/doc/images/client-local-cache.png) 文件内容以properties格式存储,比如如果有两个key,一个是request.timeout,另一个是batch,那么文件内容就是如下格式: ```properties diff --git a/docs/zh/usage/other-language-client-user-guide.md b/docs/zh/usage/other-language-client-user-guide.md index e0f5fd6e856..36a04291380 100644 --- a/docs/zh/usage/other-language-client-user-guide.md +++ b/docs/zh/usage/other-language-client-user-guide.md @@ -97,7 +97,7 @@ Apollo提供了基于Http long polling的配置更新推送通知,第三方客 ### 1.4.1 配置更新推送实现思路 -这里建议大家可以参考Apollo的Java实现:[RemoteConfigLongPollService.java](https://github.com/apolloconfig/apollo/blob/master/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java),代码量200多行,总体上还是比较简单的。 +这里建议大家可以参考Apollo的Java实现:[RemoteConfigLongPollService.java](https://github.com/apolloconfig/apollo-java/blob/main/apollo-client/src/main/java/com/ctrip/framework/apollo/internals/RemoteConfigLongPollService.java),代码量200多行,总体上还是比较简单的。 #### 1.4.1.1 初始化 首先需要确定哪些namespace需要配置更新推送,Apollo的实现方式是程序第一次获取某个namespace的配置时就会来注册一下,我们就知道有哪些namespace需要配置更新推送了。 diff --git a/pom.xml b/pom.xml index 46b7d0cd2cb..5045806806c 100644 --- a/pom.xml +++ b/pom.xml @@ -63,6 +63,7 @@ 2.1.0-SNAPSHOT 1.8 UTF-8 + 2.1.0-SNAPSHOT 2.6.8 2021.0.2 5.7.3 @@ -89,17 +90,12 @@ apollo-buildtools - apollo-core - apollo-client - apollo-client-config-data apollo-common apollo-biz apollo-configservice apollo-adminservice apollo-portal apollo-assembly - apollo-mockserver - apollo-openapi @@ -107,12 +103,12 @@ com.ctrip.framework.apollo apollo-core - ${project.version} + ${apollo-java.version} com.ctrip.framework.apollo apollo-client - ${project.version} + ${apollo-java.version} com.ctrip.framework.apollo @@ -147,7 +143,7 @@ com.ctrip.framework.apollo apollo-openapi - ${project.version} + ${apollo-java.version} @@ -683,84 +679,19 @@ - - release - - - - org.apache.maven.plugins - maven-javadoc-plugin - - - org.apache.maven.plugins - maven-gpg-plugin - - - - - - - - org.apache.maven.plugins - maven-project-info-reports-plugin - 2.9 - - - - index - summary - dependency-info - project-team - scm - issue-tracking - mailing-list - - - - cim - plugin-management - plugins - distribution-management - license - modules - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - 2.17 - - google_checks.xml - LICENSE-2.0.txt - - - - org.apache.maven.plugins - maven-pmd-plugin - 3.6 - - true - - - - org.codehaus.mojo - findbugs-maven-plugin - 3.0.3 - - - - + + - releases - ${releases.repo} + sonatype-nexus-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + true + - - snapshots - ${snapshots.repo} - - + \ No newline at end of file