下面列出了org.springframework.test.context.jdbc.Sql#com.ctrip.framework.apollo.core.ConfigConsts 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-gray-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryGrayConfigWithDefaultClusterAndDefaultNamespaceAndIncorrectCase() throws Exception {
AtomicBoolean stop = new AtomicBoolean();
periodicSendMessage(executorService, assembleKey(someAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, ConfigConsts.NAMESPACE_APPLICATION),
stop);
TimeUnit.MILLISECONDS.sleep(500);
stop.set(true);
ResponseEntity<ApolloConfig> response = restTemplate
.getForEntity("http://{baseurl}/configs/{appId}/{clusterName}/{namespace}?ip={clientIp}", ApolloConfig.class,
getHostUrl(), someAppId, ConfigConsts.CLUSTER_NAME_DEFAULT,
ConfigConsts.NAMESPACE_APPLICATION.toUpperCase(), someClientIp);
ApolloConfig result = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals("TEST-GRAY-RELEASE-KEY1", result.getReleaseKey());
assertEquals("v1-gray", result.getConfigurations().get("k1"));
}
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");
String path = String.format("envs/%s/apps/%s/clusters/%s/namespaces/%s/releases",
escapePath(env), escapePath(appId), escapePath(clusterName), escapePath(namespaceName));
try (CloseableHttpResponse response = post(path, 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);
}
}
@Test
public void testApplicationPropertySourceWithValueInjectedAsParameter() throws Exception {
int someTimeout = 1000;
int someBatch = 2000;
Config config = mock(Config.class);
when(config.getProperty(eq(TIMEOUT_PROPERTY), anyString())).thenReturn(String.valueOf(someTimeout));
when(config.getProperty(eq(BATCH_PROPERTY), anyString())).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
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPrivateConfigFileWithPublicNamespaceExists() throws Exception {
String namespaceName = "anotherNamespace";
ResponseEntity<ApolloConfig> response = restTemplate
.getForEntity("http://{baseurl}/configs/{appId}/{clusterName}/{namespace}",
ApolloConfig.class,
getHostUrl(), someAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, namespaceName);
ApolloConfig result = response.getBody();
assertEquals("TEST-RELEASE-KEY6", result.getReleaseKey());
assertEquals(someAppId, result.getAppId());
assertEquals(ConfigConsts.CLUSTER_NAME_DEFAULT, result.getCluster());
assertEquals(namespaceName, result.getNamespaceName());
assertEquals("v1-file", result.getConfigurations().get("k1"));
assertEquals(null, result.getConfigurations().get("k2"));
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-dc-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigWithDataCenterFoundAndOverride() throws Exception {
ResponseEntity<ApolloConfig> response = restTemplate
.getForEntity("http://{baseurl}/configs/{appId}/{clusterName}/{namespace}?dataCenter={dateCenter}",
ApolloConfig.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace, someDC);
ApolloConfig result = response.getBody();
assertEquals(
"TEST-RELEASE-KEY6" + ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR + "TEST-RELEASE-KEY4",
result.getReleaseKey());
assertEquals(someAppId, result.getAppId());
assertEquals(someDC, result.getCluster());
assertEquals(somePublicNamespace, result.getNamespaceName());
assertEquals("override-someDC-v1", result.getConfigurations().get("k1"));
assertEquals("someDC-v2", result.getConfigurations().get("k2"));
}
@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), anyString())).thenReturn(String.valueOf(someTimeout));
when(fxApollo.getProperty(eq(BATCH_PROPERTY), anyString())).thenReturn(String.valueOf(someBatch));
mockConfig(FX_APOLLO_NAMESPACE, fxApollo);
Config application = mock(Config.class);
when(application.getProperty(eq(TIMEOUT_PROPERTY), anyString())).thenReturn(String.valueOf(anotherTimeout));
mockConfig(ConfigConsts.NAMESPACE_APPLICATION, application);
check(someTimeout, someBatch, AppConfig6.class);
}
public List<OpenNamespaceDTO> getNamespaces(String appId, String env, String clusterName) {
if (Strings.isNullOrEmpty(clusterName)) {
clusterName = ConfigConsts.CLUSTER_NAME_DEFAULT;
}
checkNotEmpty(appId, "App id");
checkNotEmpty(env, "Env");
String path = String.format("envs/%s/apps/%s/clusters/%s/namespaces", escapePath(env), escapePath(appId),
escapePath(clusterName));
try (CloseableHttpResponse response = get(path)) {
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);
}
}
@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());
}
/**
* 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
return;
}
String namespaces = environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, ConfigConsts.NAMESPACE_APPLICATION);
logger.debug("Apollo bootstrap namespaces: {}", namespaces);
List<String> namespaceList = NAMESPACE_SPLITTER.splitToList(namespaces);
CompositePropertySource composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME);
for (String namespace : namespaceList) {
Config config = ConfigService.getConfig(namespace);
composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config));
}
environment.getPropertySources().addFirst(composite);
}
@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());
}
@Test(timeout = 5000L)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testPollNotificationWithDefaultNamespace() throws Exception {
AtomicBoolean stop = new AtomicBoolean();
String key = assembleKey(someAppId, someCluster, defaultNamespace);
periodicSendMessage(executorService, key, stop);
ResponseEntity<List<ApolloConfigNotification>> result = restTemplate.exchange(
"http://{baseurl}/notifications/v2?appId={appId}&cluster={clusterName}¬ifications={notifications}",
HttpMethod.GET, null, typeReference,
getHostUrl(), someAppId, someCluster,
transformApolloConfigNotificationsToString(defaultNamespace, ConfigConsts.NOTIFICATION_ID_PLACEHOLDER));
stop.set(true);
List<ApolloConfigNotification> notifications = result.getBody();
assertEquals(HttpStatus.OK, result.getStatusCode());
assertEquals(1, notifications.size());
assertEquals(defaultNamespace, notifications.get(0).getNamespaceName());
assertNotEquals(0, notifications.get(0).getNotificationId());
ApolloNotificationMessages messages = result.getBody().get(0).getMessages();
assertEquals(1, messages.getDetails().size());
assertTrue(messages.has(key));
assertNotEquals(ConfigConsts.NOTIFICATION_ID_PLACEHOLDER, messages.get(key).longValue());
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-release-public-default-override.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-gray-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicGrayConfigWithIncorrectCaseAndOverride() throws Exception {
AtomicBoolean stop = new AtomicBoolean();
periodicSendMessage(executorService, assembleKey(somePublicAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, somePublicNamespace),
stop);
TimeUnit.MILLISECONDS.sleep(500);
stop.set(true);
ResponseEntity<ApolloConfig> response = restTemplate
.getForEntity("http://{baseurl}/configs/{appId}/{clusterName}/{namespace}?ip={clientIp}", ApolloConfig.class,
getHostUrl(), someAppId, someDefaultCluster, somePublicNamespace.toUpperCase(), someClientIp);
ApolloConfig result = response.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertEquals(
"TEST-RELEASE-KEY5" + ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR + "TEST-GRAY-RELEASE-KEY2",
result.getReleaseKey());
assertEquals("override-v1", result.getConfigurations().get("k1"));
assertEquals("gray-v2", result.getConfigurations().get("k2"));
}
@Override
public Release loadConfig(String clientAppId, String clientIp, String configAppId, String configClusterName,
String configNamespace, String dataCenter, ApolloNotificationMessages clientMessages) {
// load from specified cluster fist
if (!Objects.equals(ConfigConsts.CLUSTER_NAME_DEFAULT, configClusterName)) {
Release clusterRelease = findRelease(clientAppId, clientIp, configAppId, configClusterName, configNamespace,
clientMessages);
if (!Objects.isNull(clusterRelease)) {
return clusterRelease;
}
}
// try to load via data center
if (!Strings.isNullOrEmpty(dataCenter) && !Objects.equals(dataCenter, configClusterName)) {
Release dataCenterRelease = findRelease(clientAppId, clientIp, configAppId, dataCenter, configNamespace,
clientMessages);
if (!Objects.isNull(dataCenterRelease)) {
return dataCenterRelease;
}
}
// fallback to default release
return findRelease(clientAppId, clientIp, configAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, configNamespace,
clientMessages);
}
@Test(timeout = 5000L)
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testPollNotificationWithPrivateNamespaceAsFile() throws Exception {
String namespace = "someNamespace.xml";
AtomicBoolean stop = new AtomicBoolean();
periodicSendMessage(executorService, assembleKey(someAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, namespace), stop);
ResponseEntity<ApolloConfigNotification> result = restTemplate
.getForEntity(
"http://{baseurl}/notifications?appId={appId}&cluster={clusterName}&namespace={namespace}",
ApolloConfigNotification.class,
getHostUrl(), someAppId, someCluster, namespace);
stop.set(true);
ApolloConfigNotification notification = result.getBody();
assertEquals(HttpStatus.OK, result.getStatusCode());
assertEquals(namespace, notification.getNamespaceName());
assertNotEquals(0, notification.getNotificationId());
}
@Before
public void setUp() throws Exception {
controller = new NotificationController(watchKeysUtil, releaseMessageService, entityManagerUtil, namespaceUtil);
someAppId = "someAppId";
someCluster = "someCluster";
defaultNamespace = ConfigConsts.NAMESPACE_APPLICATION;
someDataCenter = "someDC";
someNotificationId = 1;
someClientIp = "someClientIp";
when(namespaceUtil.filterNamespaceName(defaultNamespace)).thenReturn(defaultNamespace);
deferredResults =
(Multimap<String, DeferredResult<ResponseEntity<ApolloConfigNotification>>>) ReflectionTestUtils
.getField(controller, "deferredResults");
}
@Test
public void testMultiplePropertySourcesWithSameProperties() throws Exception {
int someTimeout = 1000;
int anotherTimeout = someTimeout + 1;
int someBatch = 2000;
Config application = mock(Config.class);
when(application.getProperty(eq(TIMEOUT_PROPERTY), anyString())).thenReturn(String.valueOf(someTimeout));
when(application.getProperty(eq(BATCH_PROPERTY), anyString())).thenReturn(String.valueOf(someBatch));
mockConfig(ConfigConsts.NAMESPACE_APPLICATION, application);
Config fxApollo = mock(Config.class);
when(fxApollo.getProperty(eq(TIMEOUT_PROPERTY), anyString())).thenReturn(String.valueOf(anotherTimeout));
mockConfig(FX_APOLLO_NAMESPACE, fxApollo);
check("spring/XmlConfigPlaceholderTest3.xml", someTimeout, someBatch);
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryPublicConfigForNoAppIdPlaceHolder() throws Exception {
ResponseEntity<ApolloConfig> response = restTemplate
.getForEntity("http://{baseurl}/configs/{appId}/{clusterName}/{namespace}?dataCenter={dateCenter}",
ApolloConfig.class,
getHostUrl(), ConfigConsts.NO_APPID_PLACEHOLDER, someCluster, somePublicNamespace, someDC);
ApolloConfig result = response.getBody();
assertEquals("TEST-RELEASE-KEY4", result.getReleaseKey());
assertEquals(ConfigConsts.NO_APPID_PLACEHOLDER, result.getAppId());
assertEquals(someCluster, result.getCluster());
assertEquals(somePublicNamespace, result.getNamespaceName());
assertEquals("someDC-v1", result.getConfigurations().get("k1"));
assertEquals("someDC-v2", result.getConfigurations().get("k2"));
}
@Test
public void testQueryConfigForNoAppIdPlaceHolder() throws Exception {
String someClientSideReleaseKey = "1";
HttpServletResponse someResponse = mock(HttpServletResponse.class);
String appId = ConfigConsts.NO_APPID_PLACEHOLDER;
ApolloConfig result = configController.queryConfig(appId, someClusterName,
defaultNamespaceName, someDataCenter, someClientSideReleaseKey,
someClientIp, someMessagesAsString, someRequest, someResponse);
verify(configService, never()).loadConfig(appId, someClientIp, someAppId, someClusterName, defaultNamespaceName,
someDataCenter, someNotificationMessages);
verify(appNamespaceService, never()).findPublicNamespaceByName(defaultNamespaceName);
assertNull(result);
verify(someResponse, times(1)).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
}
@Test
public void testNamespaceEverPublishedAndModifiedAfter() {
Cluster cluster = createCluster(ConfigConsts.CLUSTER_NAME_DEFAULT);
Namespace namespace = createNamespace(ConfigConsts.CLUSTER_NAME_DEFAULT, ConfigConsts.NAMESPACE_APPLICATION);
Item item = createItem(namespace.getId(), "a", "b");
Release release = createRelease("{\"a\":\"c\"}");
when(clusterService.findParentClusters(testApp)).thenReturn(Collections.singletonList(cluster));
when(namespaceRepository.findByAppIdAndClusterNameOrderByIdAsc(testApp, ConfigConsts.CLUSTER_NAME_DEFAULT))
.thenReturn(Collections.singletonList(namespace));
when(releaseService.findLatestActiveRelease(namespace)).thenReturn(release);
when(itemService.findItemsModifiedAfterDate(anyLong(), any())).thenReturn(Collections.singletonList(item));
Map<String, Boolean> result = namespaceService.namespacePublishInfo(testApp);
Assert.assertEquals(1, result.size());
Assert.assertTrue(result.get(ConfigConsts.CLUSTER_NAME_DEFAULT));
}
@Transactional
public void createDefaultAppNamespace(String appId, String createBy) {
if (!isAppNamespaceNameUnique(appId, ConfigConsts.NAMESPACE_APPLICATION)) {
throw new ServiceException("appnamespace not unique");
}
AppNamespace appNs = new AppNamespace();
appNs.setAppId(appId);
appNs.setName(ConfigConsts.NAMESPACE_APPLICATION);
appNs.setComment("default app namespace");
appNs.setFormat(ConfigFileFormat.Properties.getValue());
appNs.setDataChangeCreatedBy(createBy);
appNs.setDataChangeLastModifiedBy(createBy);
appNamespaceRepository.save(appNs);
auditService.audit(AppNamespace.class.getSimpleName(), appNs.getId(), Audit.OP.INSERT,
createBy);
}
@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<Set> applicationConfigInterestedKeys = ArgumentCaptor.forClass(Set.class);
final ArgumentCaptor<Set> fxApolloConfigInterestedKeys = ArgumentCaptor.forClass(Set.class);
verify(applicationConfig, times(2))
.addChangeListener(any(ConfigChangeListener.class), applicationConfigInterestedKeys.capture(), anySetOf(String.class));
verify(fxApolloConfig, times(1))
.addChangeListener(any(ConfigChangeListener.class), fxApolloConfigInterestedKeys.capture(), anySetOf(String.class));
assertEquals(2, applicationConfigInterestedKeys.getAllValues().size());
Set<String> result = Sets.newHashSet();
for (Set interestedKeys : applicationConfigInterestedKeys.getAllValues()) {
result.addAll(interestedKeys);
}
assertEquals(Sets.newHashSet("someKey", "anotherKey"), result);
assertEquals(1, fxApolloConfigInterestedKeys.getAllValues().size());
assertEquals(asList(Sets.newHashSet("anotherKey")), fxApolloConfigInterestedKeys.getAllValues());
}
private boolean namespaceBelongsToAppId(String appId, String namespaceName) {
//Every app has an 'application' namespace
if (Objects.equals(ConfigConsts.NAMESPACE_APPLICATION, namespaceName)) {
return true;
}
//if no appId is present, then no other namespace belongs to it
if (ConfigConsts.NO_APPID_PLACEHOLDER.equalsIgnoreCase(appId)) {
return false;
}
AppNamespace appNamespace = appNamespaceService.findByAppIdAndNamespace(appId, namespaceName);
return appNamespace != null;
}
@Test
@Sql(scripts = "/integration-test/test-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/test-gray-release.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/integration-test/cleanup.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void testQueryConfigAsPropertiesWithGrayRelease() throws Exception {
AtomicBoolean stop = new AtomicBoolean();
periodicSendMessage(executorService, assembleKey(someAppId, ConfigConsts.CLUSTER_NAME_DEFAULT, ConfigConsts.NAMESPACE_APPLICATION),
stop);
TimeUnit.MILLISECONDS.sleep(500);
stop.set(true);
ResponseEntity<String> response =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}?ip={clientIp}", String.class,
getHostUrl(), someAppId, someDefaultCluster, ConfigConsts.NAMESPACE_APPLICATION, grayClientIp);
ResponseEntity<String> anotherResponse =
restTemplate
.getForEntity("http://{baseurl}/configfiles/{appId}/{clusterName}/{namespace}?ip={clientIp}", String.class,
getHostUrl(), someAppId, someDefaultCluster, ConfigConsts.NAMESPACE_APPLICATION, nonGrayClientIp);
String result = response.getBody();
String anotherResult = anotherResponse.getBody();
assertEquals(HttpStatus.OK, response.getStatusCode());
assertTrue(result.contains("k1=v1-gray"));
assertEquals(HttpStatus.OK, anotherResponse.getStatusCode());
assertFalse(anotherResult.contains("k1=v1-gray"));
assertTrue(anotherResult.contains("k1=v1"));
}
@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 testFillFromEnvironmentWithSystemPropertyAlreadyFilled() throws Exception {
String someAppId = "someAppId";
String someCluster = "someCluster";
String someCacheDir = "someCacheDir";
String someApolloMeta = "someApolloMeta";
System.setProperty("app.id", someAppId);
System.setProperty(ConfigConsts.APOLLO_CLUSTER_KEY, someCluster);
System.setProperty("apollo.cacheDir", 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("app.id")).thenReturn(anotherAppId);
when(environment.getProperty(ConfigConsts.APOLLO_CLUSTER_KEY)).thenReturn(anotherCluster);
when(environment.getProperty("apollo.cacheDir")).thenReturn(anotherCacheDir);
when(environment.getProperty(ConfigConsts.APOLLO_META_KEY)).thenReturn(anotherApolloMeta);
apolloApplicationContextInitializer.initializeSystemProperty(environment);
assertEquals(someAppId, System.getProperty("app.id"));
assertEquals(someCluster, System.getProperty(ConfigConsts.APOLLO_CLUSTER_KEY));
assertEquals(someCacheDir, System.getProperty("apollo.cacheDir"));
assertEquals(someApolloMeta, System.getProperty(ConfigConsts.APOLLO_META_KEY));
}
@Override
public String getContent() {
if (!this.hasContent()) {
return null;
}
return m_configProperties.get().getProperty(ConfigConsts.CONFIG_FILE_CONTENT_KEY);
}
@ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, "TEST1.apollo", "application.yaml"},
interestedKeyPrefixes = {"redis.cache."})
public void onChange(ConfigChangeEvent changeEvent) {
logger.info("before refresh {}", sampleRedisConfig.toString());
refreshScope.refresh("sampleRedisConfig");
logger.info("after refresh {}", sampleRedisConfig.toString());
}
/**
* 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;
}
private List<ApolloConfigNotification> getApolloConfigNotifications(Set<String> namespaces,
Map<String, Long> clientSideNotifications,
Multimap<String, String> watchedKeysMap,
List<ReleaseMessage> latestReleaseMessages) {
List<ApolloConfigNotification> newNotifications = Lists.newArrayList();
if (!CollectionUtils.isEmpty(latestReleaseMessages)) {
Map<String, Long> latestNotifications = Maps.newHashMap();
for (ReleaseMessage releaseMessage : latestReleaseMessages) {
latestNotifications.put(releaseMessage.getMessage(), releaseMessage.getId());
}
for (String namespace : namespaces) {
long clientSideId = clientSideNotifications.get(namespace);
long latestId = ConfigConsts.NOTIFICATION_ID_PLACEHOLDER;
Collection<String> namespaceWatchedKeys = watchedKeysMap.get(namespace);
for (String namespaceWatchedKey : namespaceWatchedKeys) {
long namespaceNotificationId =
latestNotifications.getOrDefault(namespaceWatchedKey, ConfigConsts.NOTIFICATION_ID_PLACEHOLDER);
if (namespaceNotificationId > latestId) {
latestId = namespaceNotificationId;
}
}
if (latestId > clientSideId) {
ApolloConfigNotification notification = new ApolloConfigNotification(namespace, latestId);
namespaceWatchedKeys.stream().filter(latestNotifications::containsKey).forEach(namespaceWatchedKey ->
notification.addMessage(namespaceWatchedKey, latestNotifications.get(namespaceWatchedKey)));
newNotifications.add(notification);
}
}
}
return newNotifications;
}
@Test
public void testAssembleWatchKeysForNoAppIdPlaceHolder() throws Exception {
Multimap<String, String> watchKeysMap =
watchKeysUtil.assembleAllWatchKeys(ConfigConsts.NO_APPID_PLACEHOLDER, someCluster,
Sets.newHashSet(someNamespace, anotherNamespace), someDC);
assertTrue(watchKeysMap.isEmpty());
}