Skip to content

Commit

Permalink
Use HttpURLConnection and gson to remove Spring and Jackson dependencies
Browse files Browse the repository at this point in the history
  • Loading branch information
nobodyiam committed Apr 11, 2016
1 parent 76528a1 commit f5d513f
Show file tree
Hide file tree
Showing 20 changed files with 413 additions and 237 deletions.
@@ -1,17 +1,18 @@
package com.ctrip.apollo.biz.service;

import java.io.IOException;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.ctrip.apollo.biz.entity.Release;
import com.ctrip.apollo.biz.repository.ReleaseRepository;
import com.ctrip.apollo.core.dto.ApolloConfig;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.Map;

/**
* Config Service
Expand All @@ -24,10 +25,9 @@ public class ConfigService {
@Autowired
private ReleaseRepository releaseRepository;

private ObjectMapper objectMapper = new ObjectMapper();
private Gson gson = new Gson();

private TypeReference<Map<String, String>> configurationTypeReference =
new TypeReference<Map<String, String>>() {};
private Type configurationTypeReference = new TypeToken<Map<String, String>>(){}.getType();

public Release findRelease(String appId, String clusterName, String namespaceName) {
Release release = releaseRepository.findLatest(appId, clusterName, namespaceName);
Expand All @@ -49,8 +49,8 @@ public ApolloConfig loadConfig(Release release, String namespaceName) {

Map<String, String> transformConfigurationToMap(String configurations) {
try {
return objectMapper.readValue(configurations, configurationTypeReference);
} catch (IOException e) {
return gson.fromJson(configurations, configurationTypeReference);
} catch (Throwable e) {
e.printStackTrace();
return Maps.newHashMap();
}
Expand Down
@@ -1,11 +1,9 @@
package com.ctrip.apollo.biz.service;

import com.google.common.collect.Maps;

import com.ctrip.apollo.biz.entity.Release;
import com.ctrip.apollo.biz.repository.ReleaseRepository;
import com.ctrip.apollo.biz.service.ConfigService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.junit.Before;
import org.junit.Test;
Expand All @@ -14,16 +12,10 @@
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;

import java.io.IOException;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.anyObject;
import static org.mockito.Mockito.eq;
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)
Expand All @@ -32,16 +24,13 @@
public class ConfigServiceTest {
@Mock
private ReleaseRepository releaseRepository;
@Mock
private ObjectMapper objectMapper;
private ConfigService configService;

@Before
public void setUp() throws Exception {
configService = new ConfigService();
ReflectionTestUtils
.setField(configService, "releaseRepository", releaseRepository);
ReflectionTestUtils.setField(configService, "objectMapper", objectMapper);
}

// @Test
Expand Down Expand Up @@ -131,21 +120,16 @@ private Release assembleRelease(long releaseId, String clusterName, String group
public void testTransformConfigurationToMapSuccessful() throws Exception {
String someValidConfiguration = "{\"apollo.bar\": \"foo\"}";
Map<String, String> someMap = Maps.newHashMap();
when(objectMapper.readValue(eq(someValidConfiguration), (TypeReference) anyObject()))
.thenReturn(someMap);
someMap.put("apollo.bar", "foo");

Map<String, String> result = configService.transformConfigurationToMap(someValidConfiguration);

assertEquals(someMap, result);
verify(objectMapper, times(1))
.readValue(eq(someValidConfiguration), (TypeReference) anyObject());
}

@Test
public void testTransformConfigurationToMapFailed() throws Exception {
String someInvalidConfiguration = "xxx";
when(objectMapper.readValue(eq(someInvalidConfiguration), (TypeReference) anyObject()))
.thenThrow(IOException.class);

Map<String, String>
result =
Expand Down
41 changes: 16 additions & 25 deletions apollo-client/pom.xml
Expand Up @@ -24,38 +24,29 @@
<groupId>com.dianping.cat</groupId>
<artifactId>cat-client</artifactId>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</dependency>
<!-- end of spring -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<!-- end of util -->
<!-- test -->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<scope>test</scope>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<scope>test</scope>
<artifactId>log4j-slf4j-impl</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
</exclusions>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<scope>test</scope>
<artifactId>log4j-core</artifactId>
<scope>provided</scope>
</dependency>
<!-- end of test -->
</dependencies>
</project>
@@ -1,9 +1,12 @@
package com.ctrip.apollo.build;

import com.ctrip.apollo.internals.ConfigServiceLocator;
import com.ctrip.apollo.internals.DefaultConfigManager;
import com.ctrip.apollo.spi.DefaultConfigFactory;
import com.ctrip.apollo.spi.DefaultConfigFactoryManager;
import com.ctrip.apollo.spi.DefaultConfigRegistry;
import com.ctrip.apollo.util.ConfigUtil;
import com.ctrip.apollo.util.http.HttpUtil;

import org.unidal.lookup.configuration.AbstractResourceConfigurator;
import org.unidal.lookup.configuration.Component;
Expand All @@ -27,6 +30,9 @@ public List<Component> defineComponents() {
all.add(A(DefaultConfigFactory.class));
all.add(A(DefaultConfigRegistry.class));
all.add(A(DefaultConfigFactoryManager.class));
all.add(A(ConfigUtil.class));
all.add(A(ConfigServiceLocator.class));
all.add(A(HttpUtil.class));

return all;
}
Expand Down
Expand Up @@ -2,38 +2,46 @@

import com.ctrip.apollo.core.dto.ServiceDTO;
import com.ctrip.apollo.env.ClientEnvironment;
import com.ctrip.apollo.util.http.HttpRequest;
import com.ctrip.apollo.util.http.HttpResponse;
import com.ctrip.apollo.util.http.HttpUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
import org.unidal.lookup.annotation.Inject;
import org.unidal.lookup.annotation.Named;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Named(type = ConfigServiceLocator.class)
public class ConfigServiceLocator {

private static final Logger logger = LoggerFactory.getLogger(ConfigServiceLocator.class);

private RestTemplate restTemplate = new RestTemplate();

@Inject
private HttpUtil m_httpUtil;
private List<ServiceDTO> serviceCaches = new ArrayList<>();

public List<ServiceDTO> getConfigServices() {
ClientEnvironment env = ClientEnvironment.getInstance();
String domainName = env.getMetaServerDomainName();
String url = domainName + "/services/config";

HttpRequest request = new HttpRequest(url);

try {
ServiceDTO[] services = restTemplate.getForObject(new URI(url), ServiceDTO[].class);
HttpResponse<ServiceDTO[]> response = m_httpUtil.doGet(request, ServiceDTO[].class);
ServiceDTO[] services = response.getBody();
if (services != null && services.length > 0) {
serviceCaches.clear();
for (ServiceDTO service : services) {
serviceCaches.add(service);
}
}
} catch (Exception ex) {
logger.warn(ex.getMessage());
} catch (Throwable t) {
logger.error("Get config services failed", t);
throw new RuntimeException("Get config services failed", t);
}

return serviceCaches;
}
}
Expand Up @@ -4,6 +4,9 @@
import com.ctrip.apollo.core.utils.ClassLoaderUtil;
import com.dianping.cat.Cat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
Expand All @@ -12,6 +15,7 @@
* @author Jason Song(song_s@ctrip.com)
*/
public class DefaultConfig implements Config {
private static final Logger logger = LoggerFactory.getLogger(DefaultConfig.class);
private final String m_namespace;
private Properties m_resourceProperties;
private Properties m_configProperties;
Expand All @@ -28,9 +32,10 @@ private void initialize() {
try {
m_configProperties = m_configRepository.loadConfig();
} catch (Throwable ex) {
throw new RuntimeException(
String.format("Init Apollo Local Config failed - namespace: %s",
m_namespace), ex);
String message = String.format("Init Apollo Local Config failed - namespace: %s",
m_namespace);
logger.error(message, ex);
throw new RuntimeException(message, ex);
}
}

Expand Down Expand Up @@ -74,6 +79,7 @@ private Properties loadFromResource(String namespace) {
try {
properties.load(in);
} catch (IOException e) {
logger.error("Load resource config for namespace {} failed", namespace, e);
Cat.logError(e);
} finally {
try {
Expand Down
Expand Up @@ -5,9 +5,14 @@
import com.ctrip.apollo.util.ConfigUtil;
import com.dianping.cat.Cat;

import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unidal.lookup.ContainerLoader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
Expand All @@ -18,16 +23,23 @@
* @author Jason Song(song_s@ctrip.com)
*/
public class LocalFileConfigRepository implements ConfigRepository {
private static final Logger logger = LoggerFactory.getLogger(LocalFileConfigRepository.class);
private PlexusContainer m_container;
private final String m_namespace;
private final File m_baseDir;
private final ConfigUtil m_configUtil;
private Properties m_fileProperties;
private ConfigRepository m_fallback;

public LocalFileConfigRepository(File baseDir, String namespace, ConfigUtil configUtil) {
public LocalFileConfigRepository(File baseDir, String namespace) {
m_baseDir = baseDir;
m_namespace = namespace;
m_configUtil = configUtil;
m_container = ContainerLoader.getDefaultContainer();
try {
m_configUtil = m_container.lookup(ConfigUtil.class);
} catch (ComponentLookupException e) {
throw new IllegalStateException("Unable to load component!", e);
}
}

@Override
Expand All @@ -53,6 +65,7 @@ void initLocalConfig() {
persistLocalCacheFile(m_baseDir, m_namespace);
return;
} catch (Throwable ex) {
logger.error("Load config from fallback loader failed", ex);
Cat.logError(ex);
}
}
Expand All @@ -79,6 +92,7 @@ private Properties loadFromLocalCacheFile(File baseDir, String namespace) throws
properties = new Properties();
properties.load(in);
} catch (IOException e) {
logger.error("Loading config from local cache file {} failed", file.getAbsolutePath(), e);
Cat.logError(e);
throw e;
} finally {
Expand All @@ -91,7 +105,10 @@ private Properties loadFromLocalCacheFile(File baseDir, String namespace) throws
}
}
} else {
//TODO error handling
String message =
String.format("Cannot read from local cache file %s", file.getAbsolutePath());
logger.error(message);
throw new RuntimeException(message);
}

return properties;
Expand All @@ -108,9 +125,8 @@ void persistLocalCacheFile(File baseDir, String namespace) {
try {
out = new FileOutputStream(file);
m_fileProperties.store(out, "Persisted by DefaultConfig");
} catch (FileNotFoundException ex) {
Cat.logError(ex);
} catch (IOException ex) {
logger.error("Persist local cache file {} failed", file.getAbsolutePath(), ex);
Cat.logError(ex);
} finally {
if (out != null) {
Expand Down

0 comments on commit f5d513f

Please sign in to comment.