diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFileLocator.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFileLocator.java index 53a3c7fd1..f201101a5 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFileLocator.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFileLocator.java @@ -66,7 +66,7 @@ public class PolarisConfigFileLocator implements PropertySourceLocator { // load spring boot default config files String[] activeProfiles = environment.getActiveProfiles(); String serviceName = environment.getProperty("spring.application.name"); - polarisConfigFilePuller.initInternalConfigFiles(compositePropertySource,activeProfiles,serviceName); + polarisConfigFilePuller.initInternalConfigFiles(compositePropertySource, activeProfiles, serviceName); // load custom config files List configFileGroups = polarisConfigProperties.getGroups(); diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFilePuller.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFilePuller.java index bff11cc85..2899d913b 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFilePuller.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFilePuller.java @@ -1 +1 @@ -/* * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.tencent.cloud.polaris.config.adapter; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import com.google.common.collect.Lists; import com.tencent.cloud.polaris.config.config.ConfigFileGroup; import com.tencent.cloud.polaris.config.configdata.PolarisConfigDataLoader; import com.tencent.cloud.polaris.config.enums.ConfigFileFormat; import com.tencent.cloud.polaris.context.config.PolarisContextProperties; import com.tencent.polaris.configuration.api.core.ConfigFileMetadata; import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.api.core.ConfigKVFile; import com.tencent.polaris.configuration.client.internal.DefaultConfigFileMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.config.Profiles; import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.Environment; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; /** * PolarisConfigFilePuller pull configFile from Polaris. * * @author wlx */ public final class PolarisConfigFilePuller { private static final Logger LOGGER = LoggerFactory.getLogger(PolarisConfigFileLocator.class); private PolarisContextProperties polarisContextProperties; private ConfigFileService configFileService; private PolarisPropertySourceManager polarisPropertySourceManager; private PolarisConfigFilePuller() { } /** * InitInternalConfigFiles for {@link PolarisConfigDataLoader}. * * @param compositePropertySource compositePropertySource * @param activeProfiles activeProfiles * @param serviceName serviceName */ public void initInternalConfigFiles(CompositePropertySource compositePropertySource, String[] activeProfiles, String serviceName) { List internalConfigFiles = getInternalConfigFiles(activeProfiles, serviceName); for (ConfigFileMetadata configFile : internalConfigFiles) { PolarisPropertySource polarisPropertySource = loadPolarisPropertySource( configFile.getNamespace(), configFile.getFileGroup(), configFile.getFileName()); compositePropertySource.addPropertySource(polarisPropertySource); polarisPropertySourceManager.addPropertySource(polarisPropertySource); LOGGER.info("[SCT Config] Load and inject polaris config file. file = {}", configFile); } } /** * Init multiple CustomPolarisConfigFile. * * @param compositePropertySource compositePropertySource * @param configFileGroups configFileGroups */ public void initCustomPolarisConfigFiles(CompositePropertySource compositePropertySource, List configFileGroups) { configFileGroups.forEach( configFileGroup -> initCustomPolarisConfigFile(compositePropertySource, configFileGroup) ); } /** * Init single CustomPolarisConfigFile. * * @param compositePropertySource compositePropertySource * @param configFileGroup configFileGroup */ public void initCustomPolarisConfigFile(CompositePropertySource compositePropertySource, ConfigFileGroup configFileGroup) { String namespace = polarisContextProperties.getNamespace(); String group = configFileGroup.getName(); if (!StringUtils.hasText(group)) { throw new IllegalArgumentException("polaris config group name cannot be empty."); } List files = configFileGroup.getFiles(); if (CollectionUtils.isEmpty(files)) { return; } for (String fileName : files) { PolarisPropertySource polarisPropertySource = loadPolarisPropertySource(namespace, group, fileName); compositePropertySource.addPropertySource(polarisPropertySource); polarisPropertySourceManager.addPropertySource(polarisPropertySource); LOGGER.info( "[SCT Config] Load and inject polaris config file success. namespace = {}, group = {}, fileName = {}", namespace, group, fileName); } } private PolarisPropertySource loadPolarisPropertySource(String namespace, String group, String fileName) { ConfigKVFile configKVFile; // unknown extension is resolved as properties file if (ConfigFileFormat.isPropertyFile(fileName) || ConfigFileFormat.isUnknownFile(fileName)) { configKVFile = configFileService.getConfigPropertiesFile(namespace, group, fileName); } else if (ConfigFileFormat.isYamlFile(fileName)) { configKVFile = configFileService.getConfigYamlFile(namespace, group, fileName); } else { LOGGER.warn("[SCT Config] Unsupported config file. namespace = {}, group = {}, fileName = {}", namespace, group, fileName); throw new IllegalStateException("Only configuration files in the format of properties / yaml / yaml" + " can be injected into the spring context"); } Map map = new ConcurrentHashMap<>(); for (String key : configKVFile.getPropertyNames()) { map.put(key, configKVFile.getProperty(key, null)); } return new PolarisPropertySource(namespace, group, fileName, configKVFile, map); } private List getInternalConfigFiles(String[] activeProfiles, String serviceName) { String namespace = polarisContextProperties.getNamespace(); if (StringUtils.hasText(polarisContextProperties.getService())) { serviceName = polarisContextProperties.getService(); } // priority: application-${profile} > application > boostrap-${profile} > boostrap return getInternalConfigFiles(activeProfiles, namespace, serviceName); } private List getInternalConfigFiles(String[] activeProfiles, String namespace, String serviceName) { List internalConfigFiles = new LinkedList<>(); for (String activeProfile : activeProfiles) { if (!StringUtils.hasText(activeProfile)) { continue; } internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application-" + activeProfile + ".properties")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application-" + activeProfile + ".yml")); } internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application.properties")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application.yml")); for (String activeProfile : activeProfiles) { if (!StringUtils.hasText(activeProfile)) { continue; } internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap-" + activeProfile + ".properties")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap-" + activeProfile + ".yml")); } internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap.properties")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap.yml")); return internalConfigFiles; } /** * Factory method to create PolarisConfigFilePuller for * {@link PolarisConfigDataLoader},{@link PolarisConfigFileLocator}. * * @param polarisContextProperties polarisContextProperties * @param configFileService configFileService * @param polarisPropertySourceManager polarisPropertySourceManager * @return PolarisConfigFilePuller instance */ public static PolarisConfigFilePuller get(PolarisContextProperties polarisContextProperties, ConfigFileService configFileService, PolarisPropertySourceManager polarisPropertySourceManager) { PolarisConfigFilePuller puller = new PolarisConfigFilePuller(); puller.polarisContextProperties = polarisContextProperties; puller.configFileService = configFileService; puller.polarisPropertySourceManager = polarisPropertySourceManager; return puller; } } \ No newline at end of file +/* * Tencent is pleased to support the open source community by making Spring Cloud Tencent available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software distributed * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package com.tencent.cloud.polaris.config.adapter; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.tencent.cloud.polaris.config.config.ConfigFileGroup; import com.tencent.cloud.polaris.config.configdata.PolarisConfigDataLoader; import com.tencent.cloud.polaris.config.enums.ConfigFileFormat; import com.tencent.cloud.polaris.context.config.PolarisContextProperties; import com.tencent.polaris.configuration.api.core.ConfigFileMetadata; import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.api.core.ConfigKVFile; import com.tencent.polaris.configuration.client.internal.DefaultConfigFileMetadata; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.CompositePropertySource; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; /** * PolarisConfigFilePuller pull configFile from Polaris. * * @author wlx */ public final class PolarisConfigFilePuller { private static final Logger LOGGER = LoggerFactory.getLogger(PolarisConfigFileLocator.class); private PolarisContextProperties polarisContextProperties; private ConfigFileService configFileService; private PolarisPropertySourceManager polarisPropertySourceManager; private PolarisConfigFilePuller() { } /** * InitInternalConfigFiles for {@link PolarisConfigDataLoader}. * * @param compositePropertySource compositePropertySource * @param activeProfiles activeProfiles * @param serviceName serviceName */ public void initInternalConfigFiles(CompositePropertySource compositePropertySource, String[] activeProfiles, String serviceName) { List internalConfigFiles = getInternalConfigFiles(activeProfiles, serviceName); for (ConfigFileMetadata configFile : internalConfigFiles) { PolarisPropertySource polarisPropertySource = loadPolarisPropertySource( configFile.getNamespace(), configFile.getFileGroup(), configFile.getFileName()); compositePropertySource.addPropertySource(polarisPropertySource); polarisPropertySourceManager.addPropertySource(polarisPropertySource); LOGGER.info("[SCT Config] Load and inject polaris config file. file = {}", configFile); } } /** * Init multiple CustomPolarisConfigFile. * * @param compositePropertySource compositePropertySource * @param configFileGroups configFileGroups */ public void initCustomPolarisConfigFiles(CompositePropertySource compositePropertySource, List configFileGroups) { configFileGroups.forEach( configFileGroup -> initCustomPolarisConfigFile(compositePropertySource, configFileGroup) ); } /** * Init single CustomPolarisConfigFile. * * @param compositePropertySource compositePropertySource * @param configFileGroup configFileGroup */ public void initCustomPolarisConfigFile(CompositePropertySource compositePropertySource, ConfigFileGroup configFileGroup) { String namespace = polarisContextProperties.getNamespace(); String group = configFileGroup.getName(); if (!StringUtils.hasText(group)) { throw new IllegalArgumentException("polaris config group name cannot be empty."); } List files = configFileGroup.getFiles(); if (CollectionUtils.isEmpty(files)) { return; } for (String fileName : files) { PolarisPropertySource polarisPropertySource = loadPolarisPropertySource(namespace, group, fileName); compositePropertySource.addPropertySource(polarisPropertySource); polarisPropertySourceManager.addPropertySource(polarisPropertySource); LOGGER.info( "[SCT Config] Load and inject polaris config file success. namespace = {}, group = {}, fileName = {}", namespace, group, fileName); } } private PolarisPropertySource loadPolarisPropertySource(String namespace, String group, String fileName) { ConfigKVFile configKVFile; // unknown extension is resolved as properties file if (ConfigFileFormat.isPropertyFile(fileName) || ConfigFileFormat.isUnknownFile(fileName)) { configKVFile = configFileService.getConfigPropertiesFile(namespace, group, fileName); } else if (ConfigFileFormat.isYamlFile(fileName)) { configKVFile = configFileService.getConfigYamlFile(namespace, group, fileName); } else { LOGGER.warn("[SCT Config] Unsupported config file. namespace = {}, group = {}, fileName = {}", namespace, group, fileName); throw new IllegalStateException("Only configuration files in the format of properties / yaml / yaml" + " can be injected into the spring context"); } Map map = new ConcurrentHashMap<>(); for (String key : configKVFile.getPropertyNames()) { map.put(key, configKVFile.getProperty(key, null)); } return new PolarisPropertySource(namespace, group, fileName, configKVFile, map); } private List getInternalConfigFiles(String[] activeProfiles, String serviceName) { String namespace = polarisContextProperties.getNamespace(); if (StringUtils.hasText(polarisContextProperties.getService())) { serviceName = polarisContextProperties.getService(); } // priority: application-${profile} > application > boostrap-${profile} > boostrap return getInternalConfigFiles(activeProfiles, namespace, serviceName); } private List getInternalConfigFiles(String[] activeProfiles, String namespace, String serviceName) { List internalConfigFiles = new LinkedList<>(); for (String activeProfile : activeProfiles) { if (!StringUtils.hasText(activeProfile)) { continue; } internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application-" + activeProfile + ".properties")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application-" + activeProfile + ".yml")); } internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application.properties")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "application.yml")); for (String activeProfile : activeProfiles) { if (!StringUtils.hasText(activeProfile)) { continue; } internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap-" + activeProfile + ".properties")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap-" + activeProfile + ".yml")); } internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap.properties")); internalConfigFiles.add(new DefaultConfigFileMetadata(namespace, serviceName, "bootstrap.yml")); return internalConfigFiles; } /** * Factory method to create PolarisConfigFilePuller for * {@link PolarisConfigDataLoader},{@link PolarisConfigFileLocator}. * * @param polarisContextProperties polarisContextProperties * @param configFileService configFileService * @param polarisPropertySourceManager polarisPropertySourceManager * @return PolarisConfigFilePuller instance */ public static PolarisConfigFilePuller get(PolarisContextProperties polarisContextProperties, ConfigFileService configFileService, PolarisPropertySourceManager polarisPropertySourceManager) { PolarisConfigFilePuller puller = new PolarisConfigFilePuller(); puller.polarisContextProperties = polarisContextProperties; puller.configFileService = configFileService; puller.polarisPropertySourceManager = polarisPropertySourceManager; return puller; } } \ No newline at end of file diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/configdata/PolarisConfigDataLoader.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/configdata/PolarisConfigDataLoader.java index 7dc4f9e9f..14fc9ddbc 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/configdata/PolarisConfigDataLoader.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/configdata/PolarisConfigDataLoader.java @@ -38,7 +38,6 @@ import org.springframework.boot.context.config.ConfigDataResourceNotFoundExcepti import org.springframework.boot.context.config.Profiles; import org.springframework.boot.logging.DeferredLogFactory; import org.springframework.core.env.CompositePropertySource; -import org.springframework.core.env.PropertySource; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; @@ -65,9 +64,9 @@ public class PolarisConfigDataLoader implements ConfigDataLoader typeClass) { + return typeClass.isPrimitive() || + Number.class.isAssignableFrom(typeClass) || + String.class.isAssignableFrom(typeClass) || + Character.class.isAssignableFrom(typeClass) || + Boolean.class.isAssignableFrom(typeClass); + } } diff --git a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/configdata/PolarisImportExceptionFailureAnalyzer.java b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/configdata/PolarisImportExceptionFailureAnalyzer.java index c62bf5a28..fd626b6d1 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/configdata/PolarisImportExceptionFailureAnalyzer.java +++ b/spring-cloud-starter-tencent-polaris-config/src/main/java/com/tencent/cloud/polaris/config/configdata/PolarisImportExceptionFailureAnalyzer.java @@ -7,6 +7,9 @@ import org.springframework.cloud.commons.ConfigDataMissingEnvironmentPostProcess /** * Class for most {@code FailureAnalyzer} implementations, to analyze ImportException when * miss Polaris configData config. + *

Refer to the Nacos project implementation: + * + * ImportExceptionFailureAnalyzer * * @author wlx * @see AbstractFailureAnalyzer diff --git a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFilePullerTest.java b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFilePullerTest.java index 06f9367aa..e5ef4a18a 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFilePullerTest.java +++ b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/adapter/PolarisConfigFilePullerTest.java @@ -8,7 +8,6 @@ import java.util.Map; import com.google.common.collect.Lists; import com.tencent.cloud.polaris.config.config.ConfigFileGroup; -import com.tencent.cloud.polaris.config.config.PolarisConfigProperties; import com.tencent.cloud.polaris.context.config.PolarisContextProperties; import com.tencent.polaris.configuration.api.core.ConfigFileService; import com.tencent.polaris.configuration.api.core.ConfigKVFile; @@ -18,7 +17,6 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.boot.context.config.Profiles; import org.springframework.core.env.CompositePropertySource; import static org.mockito.Mockito.when; diff --git a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/configdata/PolarisConfigDataLoaderTest.java b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/configdata/PolarisConfigDataLoaderTest.java index 0897f0600..e4967b599 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/configdata/PolarisConfigDataLoaderTest.java +++ b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/configdata/PolarisConfigDataLoaderTest.java @@ -4,7 +4,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Optional; import com.google.common.collect.Lists; import com.tencent.cloud.polaris.config.adapter.MockedConfigKVFile; @@ -19,7 +18,6 @@ import org.junit.Assert; import org.junit.Test; import org.junit.jupiter.api.AfterAll; import org.junit.runner.RunWith; -import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.MockitoJUnitRunner; @@ -31,7 +29,10 @@ import org.springframework.boot.logging.DeferredLogs; import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.PropertySource; +import static com.tencent.cloud.polaris.config.configdata.PolarisConfigDataLoader.CUSTOM_POLARIS_CONFIG_FILE_LOADED; +import static com.tencent.cloud.polaris.config.configdata.PolarisConfigDataLoader.INTERNAL_CONFIG_FILES_LOADED; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; import static org.mockito.Mockito.when; @@ -44,29 +45,22 @@ import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class PolarisConfigDataLoaderTest { - @Mock - private ConfigDataLoaderContext context; - @Mock - private PolarisConfigDataResource polarisConfigDataResource; - @Mock - private ConfigurableBootstrapContext bootstrapContext; - @Mock - private PolarisConfigProperties polarisConfigProperties; - @Mock - private PolarisContextProperties polarisContextProperties; - @Mock - private ConfigFileService configFileService; - @Mock - private Profiles profiles; - - private static SDKContext sdkContext; + private static final SDKContext sdkContext = SDKContext.initContext(); private final String testNamespace = "testNamespace"; private final String testServiceName = "testServiceName"; + private final String polarisConfigPropertySourceName = "polaris-config"; @Test public void loadConfigDataInternalConfigFilesTest() { try (MockedStatic mockedStatic = mockStatic(ConfigFileServiceFactory.class)) { + ConfigDataLoaderContext context = mock(ConfigDataLoaderContext.class); + PolarisConfigDataResource polarisConfigDataResource = mock(PolarisConfigDataResource.class); + ConfigurableBootstrapContext bootstrapContext = mock(ConfigurableBootstrapContext.class); + PolarisConfigProperties polarisConfigProperties = mock(PolarisConfigProperties.class); + PolarisContextProperties polarisContextProperties = mock(PolarisContextProperties.class); + ConfigFileService configFileService = mock(ConfigFileService.class); + Profiles profiles = mock(Profiles.class); Map emptyMap = new HashMap<>(); ConfigKVFile emptyConfigFile = new MockedConfigKVFile(emptyMap); when(configFileService.getConfigYamlFile(testNamespace, testServiceName, "application.yml")).thenReturn(emptyConfigFile); @@ -79,13 +73,9 @@ public class PolarisConfigDataLoaderTest { ConfigKVFile propertiesFile = new MockedConfigKVFile(applicationProperties); when(configFileService.getConfigPropertiesFile(testNamespace, testServiceName, "application.properties")) .thenReturn(propertiesFile); - - mockSDKContext(); when(context.getBootstrapContext()).thenReturn(bootstrapContext); - when(bootstrapContext.isRegistered(eq(SDKContext.class))).thenReturn(false); when(bootstrapContext.get(eq(SDKContext.class))).thenReturn(sdkContext); - when(bootstrapContext.isRegistered(eq(PolarisPropertySourceManager.class))).thenReturn(false); when(bootstrapContext.get(eq(PolarisPropertySourceManager.class))).thenReturn(new PolarisPropertySourceManager()); when(polarisContextProperties.getNamespace()).thenReturn(testNamespace); @@ -95,6 +85,12 @@ public class PolarisConfigDataLoaderTest { when(profiles.getActive()).thenReturn(Lists.newArrayList()); PolarisConfigDataLoader polarisConfigDataLoader = new PolarisConfigDataLoader(new DeferredLogs()); + if (INTERNAL_CONFIG_FILES_LOADED.get()) { + INTERNAL_CONFIG_FILES_LOADED.compareAndSet(true, false); + } + if (CUSTOM_POLARIS_CONFIG_FILE_LOADED.get()) { + CUSTOM_POLARIS_CONFIG_FILE_LOADED.compareAndSet(true, false); + } when(polarisConfigDataResource.getPolarisConfigProperties()).thenReturn(polarisConfigProperties); when(polarisConfigDataResource.getPolarisContextProperties()).thenReturn(polarisContextProperties); when(polarisConfigDataResource.getServiceName()).thenReturn(testServiceName); @@ -102,25 +98,28 @@ public class PolarisConfigDataLoaderTest { mockedStatic.when(() -> { ConfigFileServiceFactory.createConfigFileService(sdkContext); - }).thenReturn(this.configFileService); + }).thenReturn(configFileService); ConfigData configData = polarisConfigDataLoader.load(context, polarisConfigDataResource); List> propertySources = configData.getPropertySources(); - Optional> propertySource = propertySources.stream().findFirst(); - if (propertySource.isPresent()) { - PropertySource source = propertySource.get(); - Assert.assertTrue(source instanceof CompositePropertySource); - CompositePropertySource compositePropertySource = (CompositePropertySource) source; - Assert.assertEquals("v1", compositePropertySource.getProperty("k1")); - Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); - Assert.assertEquals("v3", compositePropertySource.getProperty("k3")); - } + CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName); + propertySources.forEach(compositePropertySource::addPropertySource); + Assert.assertEquals("v1", compositePropertySource.getProperty("k1")); + Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); + Assert.assertEquals("v3", compositePropertySource.getProperty("k3")); } } @Test public void loadConfigDataInternalConfigFilesTestWithProfile() { try (MockedStatic mockedStatic = mockStatic(ConfigFileServiceFactory.class)) { + ConfigDataLoaderContext context = mock(ConfigDataLoaderContext.class); + PolarisConfigDataResource polarisConfigDataResource = mock(PolarisConfigDataResource.class); + ConfigurableBootstrapContext bootstrapContext = mock(ConfigurableBootstrapContext.class); + PolarisConfigProperties polarisConfigProperties = mock(PolarisConfigProperties.class); + PolarisContextProperties polarisContextProperties = mock(PolarisContextProperties.class); + ConfigFileService configFileService = mock(ConfigFileService.class); + Profiles profiles = mock(Profiles.class); Map applicationProperties = new HashMap<>(); applicationProperties.put("k1", "v1"); applicationProperties.put("k2", "v2"); @@ -151,12 +150,8 @@ public class PolarisConfigDataLoaderTest { active.add("dev"); when(profiles.getActive()).thenReturn(active); - mockSDKContext(); when(context.getBootstrapContext()).thenReturn(bootstrapContext); - when(bootstrapContext.isRegistered(eq(SDKContext.class))).thenReturn(false); when(bootstrapContext.get(eq(SDKContext.class))).thenReturn(sdkContext); - - when(bootstrapContext.isRegistered(eq(PolarisPropertySourceManager.class))).thenReturn(false); when(bootstrapContext.get(eq(PolarisPropertySourceManager.class))).thenReturn(new PolarisPropertySourceManager()); when(polarisContextProperties.getNamespace()).thenReturn(testNamespace); @@ -165,33 +160,44 @@ public class PolarisConfigDataLoaderTest { when(polarisConfigProperties.getGroups()).thenReturn(null); PolarisConfigDataLoader polarisConfigDataLoader = new PolarisConfigDataLoader(new DeferredLogs()); + if (INTERNAL_CONFIG_FILES_LOADED.get()) { + INTERNAL_CONFIG_FILES_LOADED.compareAndSet(true, false); + } + if (CUSTOM_POLARIS_CONFIG_FILE_LOADED.get()) { + CUSTOM_POLARIS_CONFIG_FILE_LOADED.compareAndSet(true, false); + } when(polarisConfigDataResource.getPolarisConfigProperties()).thenReturn(polarisConfigProperties); when(polarisConfigDataResource.getPolarisContextProperties()).thenReturn(polarisContextProperties); when(polarisConfigDataResource.getServiceName()).thenReturn(testServiceName); when(polarisConfigDataResource.getProfiles()).thenReturn(profiles); - mockedStatic.when(() -> { ConfigFileServiceFactory.createConfigFileService(sdkContext); - }).thenReturn(this.configFileService); + }).thenReturn(configFileService); ConfigData configData = polarisConfigDataLoader.load(context, polarisConfigDataResource); List> propertySources = configData.getPropertySources(); - Optional> propertySource = propertySources.stream().findFirst(); - if (propertySource.isPresent()) { - PropertySource source = propertySource.get(); - Assert.assertTrue(source instanceof CompositePropertySource); - CompositePropertySource compositePropertySource = (CompositePropertySource) source; - Assert.assertEquals("v11", compositePropertySource.getProperty("k1")); - Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); - Assert.assertEquals("v3", compositePropertySource.getProperty("k3")); - } + + CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName); + propertySources.forEach(compositePropertySource::addPropertySource); + + Assert.assertEquals("v11", compositePropertySource.getProperty("k1")); + Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); + Assert.assertEquals("v3", compositePropertySource.getProperty("k3")); + } } @Test public void loadConfigDataCustomConfigFilesTestWithProfile() { try (MockedStatic mockedStatic = mockStatic(ConfigFileServiceFactory.class)) { + ConfigDataLoaderContext context = mock(ConfigDataLoaderContext.class); + PolarisConfigDataResource polarisConfigDataResource = mock(PolarisConfigDataResource.class); + ConfigurableBootstrapContext bootstrapContext = mock(ConfigurableBootstrapContext.class); + PolarisConfigProperties polarisConfigProperties = mock(PolarisConfigProperties.class); + PolarisContextProperties polarisContextProperties = mock(PolarisContextProperties.class); + ConfigFileService configFileService = mock(ConfigFileService.class); + Profiles profiles = mock(Profiles.class); Map emptyMap = new HashMap<>(); ConfigKVFile emptyConfigFile = new MockedConfigKVFile(emptyMap); @@ -216,13 +222,9 @@ public class PolarisConfigDataLoaderTest { ConfigKVFile file1 = new MockedConfigKVFile(file1Map); when(configFileService.getConfigPropertiesFile(testNamespace, customGroup, customFile1)).thenReturn(file1); - - mockSDKContext(); when(context.getBootstrapContext()).thenReturn(bootstrapContext); - when(bootstrapContext.isRegistered(eq(SDKContext.class))).thenReturn(false); when(bootstrapContext.get(eq(SDKContext.class))).thenReturn(sdkContext); - when(bootstrapContext.isRegistered(eq(PolarisPropertySourceManager.class))).thenReturn(false); when(bootstrapContext.get(eq(PolarisPropertySourceManager.class))).thenReturn(new PolarisPropertySourceManager()); when(polarisContextProperties.getNamespace()).thenReturn(testNamespace); @@ -232,6 +234,13 @@ public class PolarisConfigDataLoaderTest { when(profiles.getActive()).thenReturn(Lists.newArrayList()); PolarisConfigDataLoader polarisConfigDataLoader = new PolarisConfigDataLoader(new DeferredLogs()); + + if (INTERNAL_CONFIG_FILES_LOADED.get()) { + INTERNAL_CONFIG_FILES_LOADED.compareAndSet(true, false); + } + if (CUSTOM_POLARIS_CONFIG_FILE_LOADED.get()) { + CUSTOM_POLARIS_CONFIG_FILE_LOADED.compareAndSet(true, false); + } when(polarisConfigDataResource.getPolarisConfigProperties()).thenReturn(polarisConfigProperties); when(polarisConfigDataResource.getPolarisContextProperties()).thenReturn(polarisContextProperties); when(polarisConfigDataResource.getServiceName()).thenReturn(testServiceName); @@ -239,19 +248,17 @@ public class PolarisConfigDataLoaderTest { mockedStatic.when(() -> { ConfigFileServiceFactory.createConfigFileService(sdkContext); - }).thenReturn(this.configFileService); + }).thenReturn(configFileService); ConfigData configData = polarisConfigDataLoader.load(context, polarisConfigDataResource); List> propertySources = configData.getPropertySources(); - Optional> propertySource = propertySources.stream().findFirst(); - if (propertySource.isPresent()) { - PropertySource source = propertySource.get(); - Assert.assertTrue(source instanceof CompositePropertySource); - CompositePropertySource compositePropertySource = (CompositePropertySource) source; - Assert.assertEquals("v1", compositePropertySource.getProperty("k1")); - Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); - Assert.assertEquals("v3", compositePropertySource.getProperty("k3")); - } + CompositePropertySource compositePropertySource = new CompositePropertySource(polarisConfigPropertySourceName); + propertySources.forEach(compositePropertySource::addPropertySource); + + Assert.assertEquals("v1", compositePropertySource.getProperty("k1")); + Assert.assertEquals("v2", compositePropertySource.getProperty("k2")); + Assert.assertEquals("v3", compositePropertySource.getProperty("k3")); + } } @@ -261,10 +268,4 @@ public class PolarisConfigDataLoaderTest { sdkContext.destroy(); } } - - private void mockSDKContext() { - if (sdkContext == null) { - sdkContext = SDKContext.initContext(); - } - } } diff --git a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/configdata/PolarisConfigDataLocationResolverTest.java b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/configdata/PolarisConfigDataLocationResolverTest.java index 4a21afd2e..eb672644f 100644 --- a/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/configdata/PolarisConfigDataLocationResolverTest.java +++ b/spring-cloud-starter-tencent-polaris-config/src/test/java/com/tencent/cloud/polaris/config/configdata/PolarisConfigDataLocationResolverTest.java @@ -1,10 +1,63 @@ package com.tencent.cloud.polaris.config.configdata; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import org.springframework.boot.ConfigurableBootstrapContext; +import org.springframework.boot.context.config.ConfigDataLocation; +import org.springframework.boot.context.config.ConfigDataLocationResolverContext; +import org.springframework.boot.context.properties.bind.Binder; +import org.springframework.boot.logging.DeferredLogs; +import org.springframework.mock.env.MockEnvironment; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + /** * Test for {@link PolarisConfigDataLocationResolver}. * * @author wlx * @date 2022/7/16 4:10 下午 */ +@RunWith(MockitoJUnitRunner.class) public class PolarisConfigDataLocationResolverTest { + + private final PolarisConfigDataLocationResolver resolver = new PolarisConfigDataLocationResolver(new DeferredLogs()); + + @Mock + private ConfigDataLocationResolverContext context; + + private final MockEnvironment environment = new MockEnvironment(); + + private final Binder environmentBinder = Binder.get(this.environment); + + @Mock + private ConfigurableBootstrapContext bootstrapContext; + + @Test + public void testIsResolvable() { + when(context.getBinder()).thenReturn(environmentBinder); + when(context.getBootstrapContext()).thenReturn(bootstrapContext); + assertThat( + this.resolver.isResolvable(this.context, ConfigDataLocation.of("configserver:"))) + .isFalse(); + assertThat( + this.resolver.isResolvable(this.context, ConfigDataLocation.of("polaris:"))) + .isTrue(); + assertThat( + this.resolver.isResolvable(this.context, ConfigDataLocation.of("polaris"))) + .isTrue(); + } + + @Test + public void unEnabledPolarisConfigData() { + environment.setProperty("spring.cloud.polaris.config.enabled", "false"); + when(context.getBinder()).thenReturn(environmentBinder); + when(context.getBootstrapContext()).thenReturn(bootstrapContext); + assertThat( + this.resolver.isResolvable(this.context, ConfigDataLocation.of("polaris:"))) + .isFalse(); + } } diff --git a/spring-cloud-tencent-examples/polaris-config-data-example/src/main/resources/application.yml b/spring-cloud-tencent-examples/polaris-config-data-example/src/main/resources/application.yml index 18b5e1146..cf786f713 100644 --- a/spring-cloud-tencent-examples/polaris-config-data-example/src/main/resources/application.yml +++ b/spring-cloud-tencent-examples/polaris-config-data-example/src/main/resources/application.yml @@ -15,6 +15,9 @@ spring: config: import: - optional:polaris + - optional:polaris:test.yml + - optional:polaris:configdataexample:test.yml + - optional:polaris:config/bootstrap.yml management: endpoints: web: