Skip to content

Commit

Permalink
enhance to load mocked properties from apollo.cache-dir (#58)
Browse files Browse the repository at this point in the history
* enhance to load mocked properties from apollo.cache-dir

* enhance to load mocked properties from apollo.cache-dir

* enhance to load mocked properties from apollo.cache-dir add UT

* enhance to load mocked properties from apollo.cache-dir del test files

* enhance to load mocked properties from apollo.cache-dir revert ApolloMockServerApiTest

* enhance to load mocked properties from apollo.cache-dir align with review

* enhance to load mocked properties from apollo.cache-dir using getDefaultLocalCacheDir instead

* enhance to load mocked properties from apollo.cache-dir using getDefaultLocalCacheDir instead

* enhance to load mocked properties from apollo.cache-dir optimize

* use localFileConfigRepository.getConfig() instead of reflect

* update CHANGES.md

* update CHANGES.md

* update CHANGES.md

* little optimized
  • Loading branch information
cheese8 authored Apr 25, 2024
1 parent 1a16249 commit bcc4053
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Apollo Java 2.3.0
------------------
* [add an initialize method to avoid DefaultProviderManager's logic being triggered when using custom ProviderManager.](https://github.com/apolloconfig/apollo-java/pull/50)
* [Implement parsing time based on pattern for @ApolloJsonValue](https://github.com/apolloconfig/apollo-java/pull/53)
* [Enhance to load mocked properties from apollo.cache-dir](https://github.com/apolloconfig/apollo-java/pull/58)

------------------
All issues and pull requests are [here](https://github.com/apolloconfig/apollo-java/milestone/3?closed=1)
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
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.ctrip.framework.apollo.internals.LocalFileConfigRepository;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
Expand All @@ -34,13 +36,15 @@
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
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 java.util.Objects;

public class ApolloTestingServer implements AutoCloseable {

Expand All @@ -51,6 +55,11 @@ public class ApolloTestingServer implements AutoCloseable {
private static Method CONFIG_SERVICE_LOCATOR_CLEAR;
private static ConfigServiceLocator CONFIG_SERVICE_LOCATOR;

private static ConfigUtil CONFIG_UTIL;

private static Method RESOURCES_UTILS_CLEAR;
private static ResourceUtils RESOURCES_UTILS;

private static final Gson GSON = new Gson();
private final Map<String, Map<String, String>> addedOrModifiedPropertiesOfNamespace = Maps.newConcurrentMap();
private final Map<String, Set<String>> deletedKeysOfNamespace = Maps.newConcurrentMap();
Expand All @@ -67,6 +76,13 @@ public class ApolloTestingServer implements AutoCloseable {
CONFIG_SERVICE_LOCATOR = ApolloInjector.getInstance(ConfigServiceLocator.class);
CONFIG_SERVICE_LOCATOR_CLEAR = ConfigServiceLocator.class.getDeclaredMethod("initConfigServices");
CONFIG_SERVICE_LOCATOR_CLEAR.setAccessible(true);

CONFIG_UTIL = ApolloInjector.getInstance(ConfigUtil.class);

RESOURCES_UTILS = ApolloInjector.getInstance(ResourceUtils.class);
RESOURCES_UTILS_CLEAR = ResourceUtils.class.getDeclaredMethod("loadConfigFileFromDefaultSearchLocations",
new Class[] {String.class});
RESOURCES_UTILS_CLEAR.setAccessible(true);
} catch (NoSuchMethodException e) {
logger.error(e.getMessage(), e);
}
Expand Down Expand Up @@ -135,8 +151,7 @@ private void mockConfigServiceUrl(String url) {
}

private String loadConfigFor(String namespace) {
String filename = String.format("mockdata-%s.properties", namespace);
final Properties prop = ResourceUtils.readConfigFile(filename, new Properties());
final Properties prop = loadPropertiesOfNamespace(namespace);
Map<String, String> configurations = Maps.newHashMap();
for (String propertyName : prop.stringPropertyNames()) {
configurations.put(propertyName, prop.getProperty(propertyName));
Expand All @@ -148,6 +163,21 @@ private String loadConfigFor(String namespace) {
return GSON.toJson(apolloConfig);
}

private Properties loadPropertiesOfNamespace(String namespace) {
String filename = String.format("mockdata-%s.properties", namespace);
Object mockdataPropertiesExits = null;
try {
mockdataPropertiesExits = RESOURCES_UTILS_CLEAR.invoke(RESOURCES_UTILS, filename);
} catch (IllegalAccessException | InvocationTargetException e) {
logger.error("invoke resources util locator clear failed.", e);
}
if (!Objects.isNull(mockdataPropertiesExits)) {
logger.debug("load {} from {}", namespace, filename);
return ResourceUtils.readConfigFile(filename, new Properties());
}
return new LocalFileConfigRepository(namespace).getConfig();
}

private String mockLongPollBody(String notificationsStr) {
List<ApolloConfigNotification> oldNotifications = GSON.fromJson(notificationsStr, notificationType);
List<ApolloConfigNotification> newNotifications = new ArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
* Copyright 2022 Apollo Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Config;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.core.ApolloClientSystemConsts;
import com.ctrip.framework.apollo.core.ConfigConsts;
import com.ctrip.framework.apollo.internals.LocalFileConfigRepository;
import com.ctrip.framework.apollo.util.ConfigUtil;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import org.junit.ClassRule;
import org.junit.Test;
import org.springframework.test.util.ReflectionTestUtils;

import java.io.BufferedWriter;
import java.io.File;
import java.lang.reflect.Field;
import java.nio.file.Files;

import static org.junit.Assert.*;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;

public class ApolloMockServerApiWhileCacheDirSpecifiedTest {

@ClassRule
public static EmbeddedApollo embeddedApollo = new EmbeddedApollo();

@Test
public void testLoadDefaultLocalCacheDir() throws Exception {
String someCacheDir = "src/test/resources/config-cache";
String someAppId = "someAppId";
String someNamespace = "someNamespace";
String someKey = "someKey";
String someValue = "someValue";
System.setProperty(ApolloClientSystemConsts.APOLLO_CACHE_DIR, someCacheDir);

ConfigUtil configUtil = spy(new ConfigUtil());
doReturn(someAppId).when(configUtil).getAppId();
String defaultLocalCacheDir = ReflectionTestUtils.invokeMethod(configUtil, "getDefaultLocalCacheDir", new Object[]{});
assertEquals(someCacheDir + "/" + someAppId, defaultLocalCacheDir);

// LocalFileConfigRepository.CONFIG_DIR
LocalFileConfigRepository localFileConfigRepository = new LocalFileConfigRepository(someNamespace);
Field FIELD_CONFIG_DIR = localFileConfigRepository.getClass().getDeclaredField("CONFIG_DIR");
FIELD_CONFIG_DIR.setAccessible(true);
String configDir = (String) FIELD_CONFIG_DIR.get(localFileConfigRepository);

File someBaseDir = new File(defaultLocalCacheDir, configDir);
someBaseDir.mkdirs();
File file = new File(someBaseDir, String.format("%s.properties", Joiner.on(ConfigConsts.CLUSTER_NAMESPACE_SEPARATOR).join(
someAppId, "default", someNamespace)));
try (BufferedWriter writer = Files.newBufferedWriter(file.toPath(), Charsets.UTF_8)) {
writer.write(someKey + "=" + someValue);
}
Config config = ConfigService.getConfig(someNamespace);
assertEquals(someValue, config.getProperty(someKey, null));
file.deleteOnExit();
someBaseDir.deleteOnExit();
}
}

0 comments on commit bcc4053

Please sign in to comment.