Commit 7c7f7b2a authored by Jason Song's avatar Jason Song

format according google code style

parent d25e0cbf
...@@ -2,7 +2,6 @@ package com.ctrip.apollo; ...@@ -2,7 +2,6 @@ package com.ctrip.apollo;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication @SpringBootApplication
......
...@@ -2,6 +2,7 @@ package com.ctrip.apollo.adminservice.controller; ...@@ -2,6 +2,7 @@ package com.ctrip.apollo.adminservice.controller;
import com.ctrip.apollo.biz.service.AdminConfigService; import com.ctrip.apollo.biz.service.AdminConfigService;
import com.ctrip.apollo.core.dto.ClusterDTO; import com.ctrip.apollo.core.dto.ClusterDTO;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
...@@ -17,7 +18,7 @@ public class ClusterController { ...@@ -17,7 +18,7 @@ public class ClusterController {
private AdminConfigService adminConfigService; private AdminConfigService adminConfigService;
@RequestMapping("/app/{appId}") @RequestMapping("/app/{appId}")
public List<ClusterDTO> findClustersByApp(@PathVariable long appId){ public List<ClusterDTO> findClustersByApp(@PathVariable long appId) {
return adminConfigService.findClustersByApp(appId); return adminConfigService.findClustersByApp(appId);
} }
} }
...@@ -3,14 +3,16 @@ package com.ctrip.apollo.adminservice.controller; ...@@ -3,14 +3,16 @@ package com.ctrip.apollo.adminservice.controller;
import com.ctrip.apollo.biz.service.AdminConfigService; import com.ctrip.apollo.biz.service.AdminConfigService;
import com.ctrip.apollo.core.dto.ConfigItemDTO; import com.ctrip.apollo.core.dto.ConfigItemDTO;
import com.ctrip.apollo.core.dto.ReleaseSnapshotDTO; import com.ctrip.apollo.core.dto.ReleaseSnapshotDTO;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List; import java.util.List;
import javax.annotation.Resource;
@RestController @RestController
@RequestMapping("/configs") @RequestMapping("/configs")
public class ConfigController { public class ConfigController {
...@@ -20,12 +22,13 @@ public class ConfigController { ...@@ -20,12 +22,13 @@ public class ConfigController {
@RequestMapping("/release/{releaseId}") @RequestMapping("/release/{releaseId}")
public List<ReleaseSnapshotDTO> getRelaseSnapshot(@PathVariable long releaseId){ public List<ReleaseSnapshotDTO> getRelaseSnapshot(@PathVariable long releaseId) {
return adminConfigService.findReleaseSnapshotByReleaseId(releaseId); return adminConfigService.findReleaseSnapshotByReleaseId(releaseId);
} }
@RequestMapping("/latest") @RequestMapping("/latest")
public List<ConfigItemDTO> findConfigItemsByClusters(@RequestParam(value = "clusterIds") List<Long> clusterIds){ public List<ConfigItemDTO> findConfigItemsByClusters(
@RequestParam(value = "clusterIds") List<Long> clusterIds) {
return adminConfigService.findConfigItemsByClusters(clusterIds); return adminConfigService.findConfigItemsByClusters(clusterIds);
} }
......
...@@ -2,6 +2,7 @@ package com.ctrip.apollo.adminservice.controller; ...@@ -2,6 +2,7 @@ package com.ctrip.apollo.adminservice.controller;
import com.ctrip.apollo.biz.service.AdminConfigService; import com.ctrip.apollo.biz.service.AdminConfigService;
import com.ctrip.apollo.core.dto.VersionDTO; import com.ctrip.apollo.core.dto.VersionDTO;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
...@@ -17,17 +18,15 @@ public class VersionController { ...@@ -17,17 +18,15 @@ public class VersionController {
private AdminConfigService adminConfigService; private AdminConfigService adminConfigService;
@RequestMapping("/app/{appId}") @RequestMapping("/app/{appId}")
public List<VersionDTO> versions(@PathVariable long appId){ public List<VersionDTO> versions(@PathVariable long appId) {
return adminConfigService.findVersionsByApp(appId); return adminConfigService.findVersionsByApp(appId);
} }
@RequestMapping("/{versionId}") @RequestMapping("/{versionId}")
public VersionDTO version(@PathVariable long versionId){ public VersionDTO version(@PathVariable long versionId) {
return adminConfigService.loadVersionById(versionId); return adminConfigService.loadVersionById(versionId);
} }
} }
package com.ctrip.apollo.biz.entity; package com.ctrip.apollo.biz.entity;
import com.ctrip.apollo.core.dto.ClusterDTO; import com.ctrip.apollo.core.dto.ClusterDTO;
import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where; import org.hibernate.annotations.Where;
...@@ -63,7 +64,7 @@ public class Cluster { ...@@ -63,7 +64,7 @@ public class Cluster {
isDeleted = deleted; isDeleted = deleted;
} }
public ClusterDTO toDTO(){ public ClusterDTO toDTO() {
ClusterDTO dto = new ClusterDTO(); ClusterDTO dto = new ClusterDTO();
dto.setAppId(appId); dto.setAppId(appId);
dto.setId(id); dto.setId(id);
......
package com.ctrip.apollo.biz.entity; package com.ctrip.apollo.biz.entity;
import com.ctrip.apollo.core.dto.ConfigItemDTO; import com.ctrip.apollo.core.dto.ConfigItemDTO;
import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where; import org.hibernate.annotations.Where;
import java.util.Date;
import javax.persistence.Column; import javax.persistence.Column;
import javax.persistence.Entity; import javax.persistence.Entity;
import javax.persistence.GeneratedValue; import javax.persistence.GeneratedValue;
import javax.persistence.Id; import javax.persistence.Id;
import java.util.Date;
@Entity @Entity
@Where(clause = "isDeleted = 0") @Where(clause = "isDeleted = 0")
...@@ -148,7 +150,7 @@ public class ConfigItem { ...@@ -148,7 +150,7 @@ public class ConfigItem {
this.dataChangeLastModifiedTime = dataChangeLastModifiedTime; this.dataChangeLastModifiedTime = dataChangeLastModifiedTime;
} }
public ConfigItemDTO toDTO(){ public ConfigItemDTO toDTO() {
ConfigItemDTO dto = new ConfigItemDTO(); ConfigItemDTO dto = new ConfigItemDTO();
dto.setAppId(appId); dto.setAppId(appId);
dto.setId(id); dto.setId(id);
......
package com.ctrip.apollo.biz.entity; package com.ctrip.apollo.biz.entity;
import com.ctrip.apollo.core.dto.ReleaseSnapshotDTO; import com.ctrip.apollo.core.dto.ReleaseSnapshotDTO;
import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where; import org.hibernate.annotations.Where;
...@@ -74,7 +75,7 @@ public class ReleaseSnapShot { ...@@ -74,7 +75,7 @@ public class ReleaseSnapShot {
isDeleted = deleted; isDeleted = deleted;
} }
public ReleaseSnapshotDTO toDTO(){ public ReleaseSnapshotDTO toDTO() {
ReleaseSnapshotDTO dto = new ReleaseSnapshotDTO(); ReleaseSnapshotDTO dto = new ReleaseSnapshotDTO();
dto.setId(id); dto.setId(id);
dto.setClusterName(clusterName); dto.setClusterName(clusterName);
......
package com.ctrip.apollo.biz.entity; package com.ctrip.apollo.biz.entity;
import com.ctrip.apollo.core.dto.VersionDTO; import com.ctrip.apollo.core.dto.VersionDTO;
import org.hibernate.annotations.SQLDelete; import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where; import org.hibernate.annotations.Where;
......
...@@ -2,6 +2,7 @@ package com.ctrip.apollo.biz.repository; ...@@ -2,6 +2,7 @@ package com.ctrip.apollo.biz.repository;
import com.ctrip.apollo.biz.entity.Cluster; import com.ctrip.apollo.biz.entity.Cluster;
import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List; import java.util.List;
......
package com.ctrip.apollo.biz.repository; package com.ctrip.apollo.biz.repository;
import com.ctrip.apollo.biz.entity.ConfigItem; import com.ctrip.apollo.biz.entity.ConfigItem;
import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List; import java.util.List;
......
package com.ctrip.apollo.biz.repository; package com.ctrip.apollo.biz.repository;
import com.ctrip.apollo.biz.entity.ReleaseSnapShot; import com.ctrip.apollo.biz.entity.ReleaseSnapShot;
import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List; import java.util.List;
...@@ -8,7 +9,8 @@ import java.util.List; ...@@ -8,7 +9,8 @@ import java.util.List;
/** /**
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public interface ReleaseSnapShotRepository extends PagingAndSortingRepository<ReleaseSnapShot, Long> { public interface ReleaseSnapShotRepository
extends PagingAndSortingRepository<ReleaseSnapShot, Long> {
ReleaseSnapShot findByReleaseIdAndClusterName(long releaseId, String clusterName); ReleaseSnapShot findByReleaseIdAndClusterName(long releaseId, String clusterName);
List<ReleaseSnapShot> findByReleaseId(long releaseId); List<ReleaseSnapShot> findByReleaseId(long releaseId);
......
package com.ctrip.apollo.biz.repository; package com.ctrip.apollo.biz.repository;
import com.ctrip.apollo.biz.entity.Version; import com.ctrip.apollo.biz.entity.Version;
import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.PagingAndSortingRepository;
import java.util.List; import java.util.List;
......
package com.ctrip.apollo.biz.service; package com.ctrip.apollo.biz.service;
import com.ctrip.apollo.core.dto.*; import com.ctrip.apollo.core.dto.ClusterDTO;
import com.ctrip.apollo.core.dto.ConfigItemDTO;
import com.ctrip.apollo.core.dto.ReleaseSnapshotDTO;
import com.ctrip.apollo.core.dto.VersionDTO;
import java.util.List; import java.util.List;
......
...@@ -5,31 +5,22 @@ import com.ctrip.apollo.core.dto.ApolloConfig; ...@@ -5,31 +5,22 @@ import com.ctrip.apollo.core.dto.ApolloConfig;
/** /**
* Config Service * Config Service
*
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public interface ConfigService { public interface ConfigService {
/** /**
* Load configuration from database * Load configuration from database
* @param appId
* @param clusterName
* @param versionName
* @return
*/ */
ApolloConfig loadConfig(long appId, String clusterName, String versionName); ApolloConfig loadConfig(long appId, String clusterName, String versionName);
/** /**
* Load Version by appId and versionName from database * Load Version by appId and versionName from database
* @param appId
* @param versionName
* @return
*/ */
Version loadVersionByAppIdAndVersionName(long appId, String versionName); Version loadVersionByAppIdAndVersionName(long appId, String versionName);
/** /**
* Load Config by version and clusterName from database * Load Config by version and clusterName from database
* @param version
* @param clusterName
* @return
*/ */
ApolloConfig loadConfigByVersionAndClusterName(Version version, String clusterName); ApolloConfig loadConfigByVersionAndClusterName(Version version, String clusterName);
} }
...@@ -9,11 +9,17 @@ import com.ctrip.apollo.biz.repository.ConfigItemRepository; ...@@ -9,11 +9,17 @@ import com.ctrip.apollo.biz.repository.ConfigItemRepository;
import com.ctrip.apollo.biz.repository.ReleaseSnapShotRepository; import com.ctrip.apollo.biz.repository.ReleaseSnapShotRepository;
import com.ctrip.apollo.biz.repository.VersionRepository; import com.ctrip.apollo.biz.repository.VersionRepository;
import com.ctrip.apollo.biz.service.AdminConfigService; import com.ctrip.apollo.biz.service.AdminConfigService;
import com.ctrip.apollo.core.dto.*; import com.ctrip.apollo.core.dto.ClusterDTO;
import com.ctrip.apollo.core.dto.ConfigItemDTO;
import com.ctrip.apollo.core.dto.ReleaseSnapshotDTO;
import com.ctrip.apollo.core.dto.VersionDTO;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.*; import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@Service("adminConfigService") @Service("adminConfigService")
public class AdminConfigServiceImpl implements AdminConfigService { public class AdminConfigServiceImpl implements AdminConfigService {
...@@ -29,18 +35,18 @@ public class AdminConfigServiceImpl implements AdminConfigService { ...@@ -29,18 +35,18 @@ public class AdminConfigServiceImpl implements AdminConfigService {
@Override @Override
public List<ReleaseSnapshotDTO> findReleaseSnapshotByReleaseId(long releaseId) { public List<ReleaseSnapshotDTO> findReleaseSnapshotByReleaseId(long releaseId) {
if (releaseId <= 0){ if (releaseId <= 0) {
return Collections.EMPTY_LIST; return Collections.EMPTY_LIST;
} }
List<ReleaseSnapShot> releaseSnapShots = releaseSnapShotRepository.findByReleaseId(releaseId); List<ReleaseSnapShot> releaseSnapShots = releaseSnapShotRepository.findByReleaseId(releaseId);
if (releaseSnapShots == null || releaseSnapShots.size() == 0){ if (releaseSnapShots == null || releaseSnapShots.size() == 0) {
return Collections.EMPTY_LIST; return Collections.EMPTY_LIST;
} }
List<ReleaseSnapshotDTO> result = new ArrayList<>(releaseSnapShots.size()); List<ReleaseSnapshotDTO> result = new ArrayList<>(releaseSnapShots.size());
for (ReleaseSnapShot releaseSnapShot: releaseSnapShots){ for (ReleaseSnapShot releaseSnapShot : releaseSnapShots) {
result.add(releaseSnapShot.toDTO()); result.add(releaseSnapShot.toDTO());
} }
return result; return result;
...@@ -67,7 +73,7 @@ public class AdminConfigServiceImpl implements AdminConfigService { ...@@ -67,7 +73,7 @@ public class AdminConfigServiceImpl implements AdminConfigService {
@Override @Override
public VersionDTO loadVersionById(long versionId) { public VersionDTO loadVersionById(long versionId) {
if (versionId <= 0){ if (versionId <= 0) {
return null; return null;
} }
Version version = versionRepository.findById(versionId); Version version = versionRepository.findById(versionId);
...@@ -76,16 +82,16 @@ public class AdminConfigServiceImpl implements AdminConfigService { ...@@ -76,16 +82,16 @@ public class AdminConfigServiceImpl implements AdminConfigService {
@Override @Override
public List<ClusterDTO> findClustersByApp(long appId) { public List<ClusterDTO> findClustersByApp(long appId) {
if (appId <= 0){ if (appId <= 0) {
return Collections.EMPTY_LIST; return Collections.EMPTY_LIST;
} }
List<Cluster> clusters = clusterRepository.findByAppId(appId); List<Cluster> clusters = clusterRepository.findByAppId(appId);
if (clusters == null || clusters.size() == 0){ if (clusters == null || clusters.size() == 0) {
return Collections.EMPTY_LIST; return Collections.EMPTY_LIST;
} }
List<ClusterDTO> result = new ArrayList<>(clusters.size()); List<ClusterDTO> result = new ArrayList<>(clusters.size());
for (Cluster cluster: clusters){ for (Cluster cluster : clusters) {
result.add(cluster.toDTO()); result.add(cluster.toDTO());
} }
return result; return result;
...@@ -93,16 +99,16 @@ public class AdminConfigServiceImpl implements AdminConfigService { ...@@ -93,16 +99,16 @@ public class AdminConfigServiceImpl implements AdminConfigService {
@Override @Override
public List<ConfigItemDTO> findConfigItemsByClusters(List<Long> clusterIds) { public List<ConfigItemDTO> findConfigItemsByClusters(List<Long> clusterIds) {
if (clusterIds == null || clusterIds.size() == 0){ if (clusterIds == null || clusterIds.size() == 0) {
return Collections.EMPTY_LIST; return Collections.EMPTY_LIST;
} }
List<ConfigItem> configItems = configItemRepository.findByClusterIdIsIn(clusterIds); List<ConfigItem> configItems = configItemRepository.findByClusterIdIsIn(clusterIds);
if (configItems == null || configItems.size() == 0){ if (configItems == null || configItems.size() == 0) {
return Collections.EMPTY_LIST; return Collections.EMPTY_LIST;
} }
List<ConfigItemDTO> result = new ArrayList<>(configItems.size()); List<ConfigItemDTO> result = new ArrayList<>(configItems.size());
for (ConfigItem configItem: configItems){ for (ConfigItem configItem : configItems) {
result.add(configItem.toDTO()); result.add(configItem.toDTO());
} }
return result; return result;
......
package com.ctrip.apollo.biz.service.impl; package com.ctrip.apollo.biz.service.impl;
import com.google.common.collect.Maps;
import com.ctrip.apollo.biz.entity.ReleaseSnapShot; import com.ctrip.apollo.biz.entity.ReleaseSnapShot;
import com.ctrip.apollo.biz.entity.Version; import com.ctrip.apollo.biz.entity.Version;
import com.ctrip.apollo.biz.repository.ReleaseSnapShotRepository; import com.ctrip.apollo.biz.repository.ReleaseSnapShotRepository;
...@@ -8,7 +10,7 @@ import com.ctrip.apollo.biz.service.ConfigService; ...@@ -8,7 +10,7 @@ import com.ctrip.apollo.biz.service.ConfigService;
import com.ctrip.apollo.core.dto.ApolloConfig; import com.ctrip.apollo.core.dto.ApolloConfig;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
...@@ -48,7 +50,8 @@ public class ConfigServiceImpl implements ConfigService { ...@@ -48,7 +50,8 @@ public class ConfigServiceImpl implements ConfigService {
@Override @Override
public ApolloConfig loadConfigByVersionAndClusterName(Version version, String clusterName) { public ApolloConfig loadConfigByVersionAndClusterName(Version version, String clusterName) {
ReleaseSnapShot releaseSnapShot = ReleaseSnapShot releaseSnapShot =
releaseSnapShotRepository.findByReleaseIdAndClusterName(version.getReleaseId(), clusterName); releaseSnapShotRepository
.findByReleaseIdAndClusterName(version.getReleaseId(), clusterName);
if (releaseSnapShot == null) { if (releaseSnapShot == null) {
return null; return null;
} }
...@@ -58,7 +61,8 @@ public class ConfigServiceImpl implements ConfigService { ...@@ -58,7 +61,8 @@ public class ConfigServiceImpl implements ConfigService {
private ApolloConfig assembleConfig(Version version, ReleaseSnapShot releaseSnapShot) { private ApolloConfig assembleConfig(Version version, ReleaseSnapShot releaseSnapShot) {
ApolloConfig config = ApolloConfig config =
new ApolloConfig(version.getAppId(), releaseSnapShot.getClusterName(), version.getName(), version.getReleaseId()); new ApolloConfig(version.getAppId(), releaseSnapShot.getClusterName(), version.getName(),
version.getReleaseId());
config.setConfigurations(transformConfigurationToMap(releaseSnapShot.getConfigurations())); config.setConfigurations(transformConfigurationToMap(releaseSnapShot.getConfigurations()));
return config; return config;
......
package com.ctrip.apollo.biz; package com.ctrip.apollo.biz;
import com.ctrip.apollo.biz.service.impl.ConfigServiceImplTest; import com.ctrip.apollo.biz.service.impl.ConfigServiceImplTest;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.Suite; import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses; import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class) @RunWith(Suite.class)
@SuiteClasses({ @SuiteClasses({
ConfigServiceImplTest.class}) ConfigServiceImplTest.class})
public class AllTests { public class AllTests {
} }
package com.ctrip.apollo.biz.service.impl; package com.ctrip.apollo.biz.service.impl;
import com.google.common.collect.Maps;
import com.ctrip.apollo.biz.entity.ReleaseSnapShot; import com.ctrip.apollo.biz.entity.ReleaseSnapShot;
import com.ctrip.apollo.biz.entity.Version; import com.ctrip.apollo.biz.entity.Version;
import com.ctrip.apollo.biz.repository.ReleaseSnapShotRepository; import com.ctrip.apollo.biz.repository.ReleaseSnapShotRepository;
...@@ -7,7 +9,7 @@ import com.ctrip.apollo.biz.repository.VersionRepository; ...@@ -7,7 +9,7 @@ import com.ctrip.apollo.biz.repository.VersionRepository;
import com.ctrip.apollo.core.dto.ApolloConfig; import com.ctrip.apollo.core.dto.ApolloConfig;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
...@@ -21,7 +23,11 @@ import java.util.Map; ...@@ -21,7 +23,11 @@ import java.util.Map;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*; 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) * @author Jason Song(song_s@ctrip.com)
...@@ -40,7 +46,8 @@ public class ConfigServiceImplTest { ...@@ -40,7 +46,8 @@ public class ConfigServiceImplTest {
public void setUp() throws Exception { public void setUp() throws Exception {
configService = new ConfigServiceImpl(); configService = new ConfigServiceImpl();
ReflectionTestUtils.setField(configService, "versionRepository", versionRepository); ReflectionTestUtils.setField(configService, "versionRepository", versionRepository);
ReflectionTestUtils.setField(configService, "releaseSnapShotRepository", releaseSnapShotRepository); ReflectionTestUtils
.setField(configService, "releaseSnapShotRepository", releaseSnapShotRepository);
ReflectionTestUtils.setField(configService, "objectMapper", objectMapper); ReflectionTestUtils.setField(configService, "objectMapper", objectMapper);
} }
...@@ -53,12 +60,16 @@ public class ConfigServiceImplTest { ...@@ -53,12 +60,16 @@ public class ConfigServiceImplTest {
String someValidConfiguration = "{\"apollo.bar\": \"foo\"}"; String someValidConfiguration = "{\"apollo.bar\": \"foo\"}";
Version someVersion = assembleVersion(someAppId, someVersionName, someReleaseId); Version someVersion = assembleVersion(someAppId, someVersionName, someReleaseId);
ReleaseSnapShot someReleaseSnapShot = assembleReleaseSnapShot(someReleaseId, someClusterName, someValidConfiguration); ReleaseSnapShot
someReleaseSnapShot =
assembleReleaseSnapShot(someReleaseId, someClusterName, someValidConfiguration);
Map<String, Object> someMap = Maps.newHashMap(); Map<String, Object> someMap = Maps.newHashMap();
when(versionRepository.findByAppIdAndName(someAppId, someVersionName)).thenReturn(someVersion); when(versionRepository.findByAppIdAndName(someAppId, someVersionName)).thenReturn(someVersion);
when(releaseSnapShotRepository.findByReleaseIdAndClusterName(someReleaseId, someClusterName)).thenReturn(someReleaseSnapShot); when(releaseSnapShotRepository.findByReleaseIdAndClusterName(someReleaseId, someClusterName))
when(objectMapper.readValue(eq(someValidConfiguration), (TypeReference) anyObject())).thenReturn(someMap); .thenReturn(someReleaseSnapShot);
when(objectMapper.readValue(eq(someValidConfiguration), (TypeReference) anyObject()))
.thenReturn(someMap);
ApolloConfig result = configService.loadConfig(someAppId, someClusterName, someVersionName); ApolloConfig result = configService.loadConfig(someAppId, someClusterName, someVersionName);
...@@ -92,13 +103,15 @@ public class ConfigServiceImplTest { ...@@ -92,13 +103,15 @@ public class ConfigServiceImplTest {
Version someVersion = assembleVersion(someAppId, someVersionName, someReleaseId); Version someVersion = assembleVersion(someAppId, someVersionName, someReleaseId);
when(versionRepository.findByAppIdAndName(someAppId, someVersionName)).thenReturn(someVersion); when(versionRepository.findByAppIdAndName(someAppId, someVersionName)).thenReturn(someVersion);
when(releaseSnapShotRepository.findByReleaseIdAndClusterName(someReleaseId, someClusterName)).thenReturn(null); when(releaseSnapShotRepository.findByReleaseIdAndClusterName(someReleaseId, someClusterName))
.thenReturn(null);
ApolloConfig result = configService.loadConfig(someAppId, someClusterName, someVersionName); ApolloConfig result = configService.loadConfig(someAppId, someClusterName, someVersionName);
assertNull(result); assertNull(result);
verify(versionRepository, times(1)).findByAppIdAndName(someAppId, someVersionName); verify(versionRepository, times(1)).findByAppIdAndName(someAppId, someVersionName);
verify(releaseSnapShotRepository, times(1)).findByReleaseIdAndClusterName(someReleaseId, someClusterName); verify(releaseSnapShotRepository, times(1))
.findByReleaseIdAndClusterName(someReleaseId, someClusterName);
} }
private Version assembleVersion(long appId, String versionName, long releaseId) { private Version assembleVersion(long appId, String versionName, long releaseId) {
...@@ -109,7 +122,8 @@ public class ConfigServiceImplTest { ...@@ -109,7 +122,8 @@ public class ConfigServiceImplTest {
return version; return version;
} }
private ReleaseSnapShot assembleReleaseSnapShot(long releaseId, String clusterName, String configurations) { private ReleaseSnapShot assembleReleaseSnapShot(long releaseId, String clusterName,
String configurations) {
ReleaseSnapShot releaseSnapShot = new ReleaseSnapShot(); ReleaseSnapShot releaseSnapShot = new ReleaseSnapShot();
releaseSnapShot.setReleaseId(releaseId); releaseSnapShot.setReleaseId(releaseId);
releaseSnapShot.setClusterName(clusterName); releaseSnapShot.setClusterName(clusterName);
...@@ -122,20 +136,25 @@ public class ConfigServiceImplTest { ...@@ -122,20 +136,25 @@ public class ConfigServiceImplTest {
public void testTransformConfigurationToMapSuccessful() throws Exception { public void testTransformConfigurationToMapSuccessful() throws Exception {
String someValidConfiguration = "{\"apollo.bar\": \"foo\"}"; String someValidConfiguration = "{\"apollo.bar\": \"foo\"}";
Map<String, String> someMap = Maps.newHashMap(); Map<String, String> someMap = Maps.newHashMap();
when(objectMapper.readValue(eq(someValidConfiguration), (TypeReference) anyObject())).thenReturn(someMap); when(objectMapper.readValue(eq(someValidConfiguration), (TypeReference) anyObject()))
.thenReturn(someMap);
Map<String, Object> result = configService.transformConfigurationToMap(someValidConfiguration); Map<String, Object> result = configService.transformConfigurationToMap(someValidConfiguration);
assertEquals(someMap, result); assertEquals(someMap, result);
verify(objectMapper, times(1)).readValue(eq(someValidConfiguration), (TypeReference) anyObject()); verify(objectMapper, times(1))
.readValue(eq(someValidConfiguration), (TypeReference) anyObject());
} }
@Test @Test
public void testTransformConfigurationToMapFailed() throws Exception { public void testTransformConfigurationToMapFailed() throws Exception {
String someInvalidConfiguration = "xxx"; String someInvalidConfiguration = "xxx";
when(objectMapper.readValue(eq(someInvalidConfiguration), (TypeReference) anyObject())).thenThrow(IOException.class); when(objectMapper.readValue(eq(someInvalidConfiguration), (TypeReference) anyObject()))
.thenThrow(IOException.class);
Map<String, Object> result = configService.transformConfigurationToMap(someInvalidConfiguration); Map<String, Object>
result =
configService.transformConfigurationToMap(someInvalidConfiguration);
assertTrue(result.isEmpty()); assertTrue(result.isEmpty());
......
...@@ -5,6 +5,7 @@ import com.ctrip.apollo.client.loader.ConfigLoaderManager; ...@@ -5,6 +5,7 @@ import com.ctrip.apollo.client.loader.ConfigLoaderManager;
import com.ctrip.apollo.client.model.PropertyChange; import com.ctrip.apollo.client.model.PropertyChange;
import com.ctrip.apollo.client.model.PropertySourceReloadResult; import com.ctrip.apollo.client.model.PropertySourceReloadResult;
import com.ctrip.apollo.client.util.ConfigUtil; import com.ctrip.apollo.client.util.ConfigUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
...@@ -35,9 +36,12 @@ import java.util.concurrent.atomic.AtomicReference; ...@@ -35,9 +36,12 @@ import java.util.concurrent.atomic.AtomicReference;
* *
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor, PriorityOrdered, ApplicationContextAware { public class ApolloConfigManager
implements BeanDefinitionRegistryPostProcessor, PriorityOrdered, ApplicationContextAware {
private static final Logger logger = LoggerFactory.getLogger(ApolloConfigManager.class); private static final Logger logger = LoggerFactory.getLogger(ApolloConfigManager.class);
private static AtomicReference<ApolloConfigManager> singletonProtector = new AtomicReference<ApolloConfigManager>(); private static AtomicReference<ApolloConfigManager>
singletonProtector =
new AtomicReference<ApolloConfigManager>();
private ConfigLoaderManager configLoaderManager; private ConfigLoaderManager configLoaderManager;
private ConfigurableApplicationContext applicationContext; private ConfigurableApplicationContext applicationContext;
...@@ -47,7 +51,7 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor, ...@@ -47,7 +51,7 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor,
private RefreshScope scope; private RefreshScope scope;
public ApolloConfigManager() { public ApolloConfigManager() {
if(!singletonProtector.compareAndSet(null, this)) { if (!singletonProtector.compareAndSet(null, this)) {
throw new IllegalStateException("There should be only one ApolloConfigManager instance!"); throw new IllegalStateException("There should be only one ApolloConfigManager instance!");
} }
this.configLoaderManager = ConfigLoaderFactory.getInstance().getConfigLoaderManager(); this.configLoaderManager = ConfigLoaderFactory.getInstance().getConfigLoaderManager();
...@@ -55,8 +59,8 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor, ...@@ -55,8 +59,8 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor,
this.counter = new AtomicLong(); this.counter = new AtomicLong();
executorService = Executors.newScheduledThreadPool(1, new ThreadFactory() { executorService = Executors.newScheduledThreadPool(1, new ThreadFactory() {
@Override @Override
public Thread newThread(Runnable r) { public Thread newThread(Runnable runnable) {
Thread thread = new Thread(r, "ApolloConfigManager-" + counter.incrementAndGet()); Thread thread = new Thread(runnable, "ApolloConfigManager-" + counter.incrementAndGet());
return thread; return thread;
} }
}); });
...@@ -66,7 +70,9 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor, ...@@ -66,7 +70,9 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor,
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (!(applicationContext instanceof ConfigurableApplicationContext)) { if (!(applicationContext instanceof ConfigurableApplicationContext)) {
throw new RuntimeException( throw new RuntimeException(
String.format("ApplicationContext must implement ConfigurableApplicationContext, but found: %s", applicationContext.getClass().getName())); String.format(
"ApplicationContext must implement ConfigurableApplicationContext, but found: %s",
applicationContext.getClass().getName()));
} }
this.applicationContext = (ConfigurableApplicationContext) applicationContext; this.applicationContext = (ConfigurableApplicationContext) applicationContext;
this.configUtil.setApplicationContext(applicationContext); this.configUtil.setApplicationContext(applicationContext);
...@@ -78,7 +84,8 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor, ...@@ -78,7 +84,8 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor,
* so that configurations could be injected correctly * so that configurations could be injected correctly
*/ */
@Override @Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
throws BeansException {
registerDependentBeans(registry); registerDependentBeans(registry);
initializePropertySource(); initializePropertySource();
schedulePeriodicRefresh(); schedulePeriodicRefresh();
...@@ -92,25 +99,30 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor, ...@@ -92,25 +99,30 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor,
* <li> * <li>
* - PropertySourcesPlaceholderConfigurer: used to support placeholder configuration injection * - PropertySourcesPlaceholderConfigurer: used to support placeholder configuration injection
* </li> * </li>
* @param registry
*/ */
private void registerDependentBeans(BeanDefinitionRegistry registry) { private void registerDependentBeans(BeanDefinitionRegistry registry) {
BeanDefinition refreshScope = BeanDefinitionBuilder.genericBeanDefinition(RefreshScope.class).getBeanDefinition(); BeanDefinition
refreshScope =
BeanDefinitionBuilder.genericBeanDefinition(RefreshScope.class).getBeanDefinition();
registry.registerBeanDefinition("refreshScope", refreshScope); registry.registerBeanDefinition("refreshScope", refreshScope);
BeanDefinition propertySourcesPlaceholderConfigurer = BeanDefinitionBuilder.genericBeanDefinition(PropertySourcesPlaceholderConfigurer.class).getBeanDefinition(); BeanDefinition
registry.registerBeanDefinition("propertySourcesPlaceholderConfigurer", propertySourcesPlaceholderConfigurer); propertySourcesPlaceholderConfigurer =
BeanDefinitionBuilder.genericBeanDefinition(PropertySourcesPlaceholderConfigurer.class)
.getBeanDefinition();
registry.registerBeanDefinition("propertySourcesPlaceholderConfigurer",
propertySourcesPlaceholderConfigurer);
} }
/** /**
* This is executed after postProcessBeanDefinitionRegistry * This is executed after postProcessBeanDefinitionRegistry
*/ */
@Override @Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
throws BeansException {
} }
/** /**
* Make sure this bean is called before other beans * Make sure this bean is called before other beans
* @return
*/ */
@Override @Override
public int getOrder() { public int getOrder() {
...@@ -128,7 +140,9 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor, ...@@ -128,7 +140,9 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor,
} }
private void updateEnvironmentPropertySource(CompositePropertySource currentPropertySource) { private void updateEnvironmentPropertySource(CompositePropertySource currentPropertySource) {
MutablePropertySources currentPropertySources = applicationContext.getEnvironment().getPropertySources(); MutablePropertySources
currentPropertySources =
applicationContext.getEnvironment().getPropertySources();
if (currentPropertySources.contains(currentPropertySource.getName())) { if (currentPropertySources.contains(currentPropertySource.getName())) {
currentPropertySources.replace(currentPropertySource.getName(), currentPropertySource); currentPropertySources.replace(currentPropertySource.getName(), currentPropertySource);
return; return;
...@@ -137,16 +151,18 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor, ...@@ -137,16 +151,18 @@ public class ApolloConfigManager implements BeanDefinitionRegistryPostProcessor,
} }
void schedulePeriodicRefresh() { void schedulePeriodicRefresh() {
executorService.scheduleAtFixedRate(new Runnable() { executorService.scheduleAtFixedRate(
new Runnable() {
@Override @Override
public void run() { public void run() {
try { try {
updatePropertySource(); updatePropertySource();
} catch (Throwable e) { } catch (Throwable ex) {
logger.error("Refreshing config failed", e); logger.error("Refreshing config failed", ex);
} }
} }
}, configUtil.getRefreshInterval(), configUtil.getRefreshInterval(), configUtil.getRefreshTimeUnit()); }, configUtil.getRefreshInterval(), configUtil.getRefreshInterval(),
configUtil.getRefreshTimeUnit());
} }
public List<PropertyChange> updatePropertySource() { public List<PropertyChange> updatePropertySource() {
......
package com.ctrip.apollo.client.env; package com.ctrip.apollo.client.env;
import com.ctrip.apollo.Apollo;
import com.ctrip.apollo.Apollo.Env;
import com.ctrip.apollo.client.constants.Constants;
import com.ctrip.apollo.core.MetaDomainConsts;
import com.ctrip.apollo.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
...@@ -10,20 +19,11 @@ import java.util.Enumeration; ...@@ -10,20 +19,11 @@ import java.util.Enumeration;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctrip.apollo.Apollo;
import com.ctrip.apollo.Apollo.Env;
import com.ctrip.apollo.client.constants.Constants;
import com.ctrip.apollo.core.MetaDomainConsts;
import com.ctrip.apollo.core.utils.StringUtils;
public class ClientEnvironment { public class ClientEnvironment {
private static final Logger logger = LoggerFactory.getLogger(ClientEnvironment.class); private static final Logger logger = LoggerFactory.getLogger(ClientEnvironment.class);
private final static String DEFAULT_FILE = "/apollo.properties"; private static final String DEFAULT_FILE = "/apollo.properties";
private AtomicReference<Env> env = new AtomicReference<Env>(); private AtomicReference<Env> env = new AtomicReference<Env>();
...@@ -84,20 +84,20 @@ public class ClientEnvironment { ...@@ -84,20 +84,20 @@ public class ClientEnvironment {
props.load(in); props.load(in);
in.close(); in.close();
} }
} catch (Exception e) { } catch (Exception ex) {
logger.warn("Reading config failed: {}", e.getMessage()); logger.warn("Reading config failed: {}", ex.getMessage());
} finally { } finally {
if (in != null) { if (in != null) {
try { try {
in.close(); in.close();
} catch (IOException e) { } catch (IOException ex) {
logger.warn("Close config failed: {}", e.getMessage()); logger.warn("Close config failed: {}", ex.getMessage());
} }
} }
} }
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (Enumeration<String> e = (Enumeration<String>) props.propertyNames(); e for (Enumeration<String> e = (Enumeration<String>) props.propertyNames(); e
.hasMoreElements();) { .hasMoreElements(); ) {
String key = e.nextElement(); String key = e.nextElement();
String val = (String) props.getProperty(key); String val = (String) props.getProperty(key);
sb.append(key).append('=').append(val).append('\n'); sb.append(key).append('=').append(val).append('\n');
......
package com.ctrip.apollo.client.loader; package com.ctrip.apollo.client.loader;
import com.ctrip.apollo.client.loader.impl.InMemoryConfigLoader;
import com.ctrip.apollo.client.loader.impl.LocalFileConfigLoader;
import com.ctrip.apollo.Apollo.Env; import com.ctrip.apollo.Apollo.Env;
import com.ctrip.apollo.client.env.ClientEnvironment; import com.ctrip.apollo.client.env.ClientEnvironment;
import com.ctrip.apollo.client.loader.impl.InMemoryConfigLoader;
import com.ctrip.apollo.client.loader.impl.LocalFileConfigLoader;
import com.ctrip.apollo.client.loader.impl.RemoteConfigLoader; import com.ctrip.apollo.client.loader.impl.RemoteConfigLoader;
import com.ctrip.apollo.client.util.ConfigUtil; import com.ctrip.apollo.client.util.ConfigUtil;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
/** /**
...@@ -14,7 +15,8 @@ import org.springframework.web.client.RestTemplate; ...@@ -14,7 +15,8 @@ import org.springframework.web.client.RestTemplate;
public class ConfigLoaderFactory { public class ConfigLoaderFactory {
private static ConfigLoaderFactory configLoaderFactory = new ConfigLoaderFactory(); private static ConfigLoaderFactory configLoaderFactory = new ConfigLoaderFactory();
private ConfigLoaderFactory() {} private ConfigLoaderFactory() {
}
public static ConfigLoaderFactory getInstance() { public static ConfigLoaderFactory getInstance() {
return configLoaderFactory; return configLoaderFactory;
...@@ -32,7 +34,10 @@ public class ConfigLoaderFactory { ...@@ -32,7 +34,10 @@ public class ConfigLoaderFactory {
} }
public ConfigLoader getRemoteConfigLoader() { public ConfigLoader getRemoteConfigLoader() {
ConfigLoader remoteConfigLoader = new RemoteConfigLoader(new RestTemplate(), ConfigUtil.getInstance(), new ConfigServiceLocator()); ConfigLoader
remoteConfigLoader =
new RemoteConfigLoader(new RestTemplate(), ConfigUtil.getInstance(),
new ConfigServiceLocator());
// remoteConfigLoader.setFallBackLoader(getInMemoryConfigLoader()); // remoteConfigLoader.setFallBackLoader(getInMemoryConfigLoader());
return remoteConfigLoader; return remoteConfigLoader;
} }
......
package com.ctrip.apollo.client.loader; package com.ctrip.apollo.client.loader;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.ctrip.apollo.client.enums.PropertyChangeType; import com.ctrip.apollo.client.enums.PropertyChangeType;
import com.ctrip.apollo.client.model.ApolloRegistry; import com.ctrip.apollo.client.model.ApolloRegistry;
import com.ctrip.apollo.client.model.PropertyChange; import com.ctrip.apollo.client.model.PropertyChange;
import com.ctrip.apollo.client.model.PropertySourceReloadResult; import com.ctrip.apollo.client.model.PropertySourceReloadResult;
import com.ctrip.apollo.client.util.ConfigUtil; import com.ctrip.apollo.client.util.ConfigUtil;
import com.ctrip.apollo.core.dto.ApolloConfig; import com.ctrip.apollo.core.dto.ApolloConfig;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.CompositePropertySource;
...@@ -19,7 +21,12 @@ import java.util.Collections; ...@@ -19,7 +21,12 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.*; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
/** /**
...@@ -42,8 +49,8 @@ public class ConfigLoaderManager { ...@@ -42,8 +49,8 @@ public class ConfigLoaderManager {
this.counter = new AtomicLong(); this.counter = new AtomicLong();
this.executorService = Executors.newFixedThreadPool(5, new ThreadFactory() { this.executorService = Executors.newFixedThreadPool(5, new ThreadFactory() {
@Override @Override
public Thread newThread(Runnable r) { public Thread newThread(Runnable runnable) {
Thread thread = new Thread(r, "ConfigLoaderManager-" + counter.incrementAndGet()); Thread thread = new Thread(runnable, "ConfigLoaderManager-" + counter.incrementAndGet());
return thread; return thread;
} }
}); });
...@@ -53,8 +60,8 @@ public class ConfigLoaderManager { ...@@ -53,8 +60,8 @@ public class ConfigLoaderManager {
public CompositePropertySource loadPropertySource() { public CompositePropertySource loadPropertySource() {
try { try {
apolloRegistries = configUtil.loadApolloRegistries(); apolloRegistries = configUtil.loadApolloRegistries();
} catch (IOException e) { } catch (IOException ex) {
throw new RuntimeException("Load apollo config registry failed", e); throw new RuntimeException("Load apollo config registry failed", ex);
} }
return loadPropertySourceWithApolloRegistries(apolloRegistries); return loadPropertySourceWithApolloRegistries(apolloRegistries);
...@@ -62,7 +69,9 @@ public class ConfigLoaderManager { ...@@ -62,7 +69,9 @@ public class ConfigLoaderManager {
public PropertySourceReloadResult reloadPropertySource() { public PropertySourceReloadResult reloadPropertySource() {
CompositePropertySource composite = loadPropertySourceWithApolloRegistries(apolloRegistries); CompositePropertySource composite = loadPropertySourceWithApolloRegistries(apolloRegistries);
List<ApolloConfig> previous = Lists.newArrayList(this.previousApolloRegistryConfigCache.values()); List<ApolloConfig>
previous =
Lists.newArrayList(this.previousApolloRegistryConfigCache.values());
List<ApolloConfig> current = Lists.newArrayList(this.currentApolloRegistryConfigCache.values()); List<ApolloConfig> current = Lists.newArrayList(this.currentApolloRegistryConfigCache.values());
return new PropertySourceReloadResult(composite, calcPropertyChanges(previous, current)); return new PropertySourceReloadResult(composite, calcPropertyChanges(previous, current));
} }
...@@ -71,10 +80,9 @@ public class ConfigLoaderManager { ...@@ -71,10 +80,9 @@ public class ConfigLoaderManager {
* Load property source with apollo registries provided * Load property source with apollo registries provided
* Should not be invoked in parallel since there are some operations like create/destroy cache, * Should not be invoked in parallel since there are some operations like create/destroy cache,
* writing to files etc. * writing to files etc.
* @param apolloRegistries
* @return
*/ */
private synchronized CompositePropertySource loadPropertySourceWithApolloRegistries(List<ApolloRegistry> apolloRegistries) { private synchronized CompositePropertySource loadPropertySourceWithApolloRegistries(
List<ApolloRegistry> apolloRegistries) {
resetApolloRegistryConfigCache(); resetApolloRegistryConfigCache();
CompositePropertySource composite = new CompositePropertySource(APOLLO_PROPERTY_SOURCE_NAME); CompositePropertySource composite = new CompositePropertySource(APOLLO_PROPERTY_SOURCE_NAME);
if (apolloRegistries == null || apolloRegistries.isEmpty()) { if (apolloRegistries == null || apolloRegistries.isEmpty()) {
...@@ -86,7 +94,8 @@ public class ConfigLoaderManager { ...@@ -86,7 +94,8 @@ public class ConfigLoaderManager {
Collections.sort(apolloConfigList); Collections.sort(apolloConfigList);
for (ApolloConfig apolloConfig : apolloConfigList) { for (ApolloConfig apolloConfig : apolloConfigList) {
composite.addPropertySource(new MapPropertySource(assemblePropertySourceName(apolloConfig), apolloConfig.getConfigurations())); composite.addPropertySource(new MapPropertySource(assemblePropertySourceName(apolloConfig),
apolloConfig.getConfigurations()));
} }
return composite; return composite;
} catch (Throwable throwable) { } catch (Throwable throwable) {
...@@ -94,7 +103,8 @@ public class ConfigLoaderManager { ...@@ -94,7 +103,8 @@ public class ConfigLoaderManager {
} }
} }
List<PropertyChange> calcPropertyChanges(List<ApolloConfig> previous, List<ApolloConfig> current) { List<PropertyChange> calcPropertyChanges(List<ApolloConfig> previous,
List<ApolloConfig> current) {
Map<String, Object> previousMap = collectConfigurations(previous); Map<String, Object> previousMap = collectConfigurations(previous);
Map<String, Object> currentMap = collectConfigurations(current); Map<String, Object> currentMap = collectConfigurations(current);
...@@ -112,14 +122,17 @@ public class ConfigLoaderManager { ...@@ -112,14 +122,17 @@ public class ConfigLoaderManager {
} }
for (String removedKey : removedKeys) { for (String removedKey : removedKeys) {
changes.add(new PropertyChange(removedKey, previousMap.get(removedKey), null, PropertyChangeType.DELETED)); changes.add(new PropertyChange(removedKey, previousMap.get(removedKey), null,
PropertyChangeType.DELETED));
} }
for (String commonKey : commonKeys) { for (String commonKey : commonKeys) {
if (previousMap.get(commonKey).equals(currentMap.get(commonKey))) { if (previousMap.get(commonKey).equals(currentMap.get(commonKey))) {
continue; continue;
} }
changes.add(new PropertyChange(commonKey, previousMap.get(commonKey), currentMap.get(commonKey), PropertyChangeType.MODIFIED)); changes.add(
new PropertyChange(commonKey, previousMap.get(commonKey), currentMap.get(commonKey),
PropertyChangeType.MODIFIED));
} }
return changes; return changes;
...@@ -152,15 +165,17 @@ public class ConfigLoaderManager { ...@@ -152,15 +165,17 @@ public class ConfigLoaderManager {
continue; continue;
} }
apolloConfigList.add(result); apolloConfigList.add(result);
} catch (ExecutionException e) { } catch (ExecutionException ex) {
throw e.getCause(); throw ex.getCause();
} }
} }
return apolloConfigList; return apolloConfigList;
} }
ApolloConfig loadSingleApolloConfig(ApolloRegistry apolloRegistry) { ApolloConfig loadSingleApolloConfig(ApolloRegistry apolloRegistry) {
ApolloConfig result = configLoader.loadApolloConfig(apolloRegistry, getPreviousApolloConfig(apolloRegistry)); ApolloConfig
result =
configLoader.loadApolloConfig(apolloRegistry, getPreviousApolloConfig(apolloRegistry));
if (result == null) { if (result == null) {
logger.error("Loaded config null..."); logger.error("Loaded config null...");
return null; return null;
...@@ -185,6 +200,7 @@ public class ConfigLoaderManager { ...@@ -185,6 +200,7 @@ public class ConfigLoaderManager {
} }
private String assemblePropertySourceName(ApolloConfig apolloConfig) { private String assemblePropertySourceName(ApolloConfig apolloConfig) {
return String.format("%d-%s-%s-%d", apolloConfig.getAppId(), apolloConfig.getCluster(), apolloConfig.getVersion(), apolloConfig.getReleaseId()); return String.format("%d-%s-%s-%d", apolloConfig.getAppId(), apolloConfig.getCluster(),
apolloConfig.getVersion(), apolloConfig.getReleaseId());
} }
} }
package com.ctrip.apollo.client.loader; package com.ctrip.apollo.client.loader;
import java.net.URI; import com.ctrip.apollo.client.env.ClientEnvironment;
import java.util.ArrayList; import com.ctrip.apollo.core.serivce.ApolloService;
import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import com.ctrip.apollo.client.env.ClientEnvironment; import java.net.URI;
import com.ctrip.apollo.core.serivce.ApolloService; import java.util.ArrayList;
import java.util.List;
public class ConfigServiceLocator { public class ConfigServiceLocator {
...@@ -31,8 +31,8 @@ public class ConfigServiceLocator { ...@@ -31,8 +31,8 @@ public class ConfigServiceLocator {
serviceCaches.add(service); serviceCaches.add(service);
} }
} }
} catch (Exception e) { } catch (Exception ex) {
logger.warn(e.getMessage()); logger.warn(ex.getMessage());
} }
return serviceCaches; return serviceCaches;
} }
......
...@@ -3,6 +3,7 @@ package com.ctrip.apollo.client.loader.impl; ...@@ -3,6 +3,7 @@ package com.ctrip.apollo.client.loader.impl;
import com.ctrip.apollo.client.loader.ConfigLoader; import com.ctrip.apollo.client.loader.ConfigLoader;
import com.ctrip.apollo.client.model.ApolloRegistry; import com.ctrip.apollo.client.model.ApolloRegistry;
import com.ctrip.apollo.core.dto.ApolloConfig; import com.ctrip.apollo.core.dto.ApolloConfig;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
...@@ -17,16 +18,19 @@ public abstract class AbstractConfigLoader implements ConfigLoader { ...@@ -17,16 +18,19 @@ public abstract class AbstractConfigLoader implements ConfigLoader {
public ApolloConfig loadApolloConfig(ApolloRegistry apolloRegistry, ApolloConfig previous) { public ApolloConfig loadApolloConfig(ApolloRegistry apolloRegistry, ApolloConfig previous) {
try { try {
return doLoadApolloConfig(apolloRegistry, previous); return doLoadApolloConfig(apolloRegistry, previous);
} catch (Throwable e) { } catch (Throwable ex) {
if (this.fallback == null) { if (this.fallback == null) {
throw new RuntimeException(String.format("Load Apollo Config failed - %s", apolloRegistry.toString()), e); throw new RuntimeException(
String.format("Load Apollo Config failed - %s", apolloRegistry.toString()), ex);
} }
logger.error("Load Config via {} failed, try to use its fallback {} to load", getClass().getSimpleName(), fallback.getClass().getSimpleName(), e); logger.error("Load Config via {} failed, try to use its fallback {} to load",
getClass().getSimpleName(), fallback.getClass().getSimpleName(), ex);
return this.fallback.loadApolloConfig(apolloRegistry, previous); return this.fallback.loadApolloConfig(apolloRegistry, previous);
} }
} }
protected abstract ApolloConfig doLoadApolloConfig(ApolloRegistry apolloRegistry, ApolloConfig previous); protected abstract ApolloConfig doLoadApolloConfig(ApolloRegistry apolloRegistry,
ApolloConfig previous);
@Override @Override
public void setFallBackLoader(ConfigLoader configLoader) { public void setFallBackLoader(ConfigLoader configLoader) {
......
...@@ -6,7 +6,7 @@ import com.ctrip.apollo.core.dto.ApolloConfig; ...@@ -6,7 +6,7 @@ import com.ctrip.apollo.core.dto.ApolloConfig;
/** /**
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public class InMemoryConfigLoader extends AbstractConfigLoader{ public class InMemoryConfigLoader extends AbstractConfigLoader {
@Override @Override
protected ApolloConfig doLoadApolloConfig(ApolloRegistry apolloRegistry, ApolloConfig previous) { protected ApolloConfig doLoadApolloConfig(ApolloRegistry apolloRegistry, ApolloConfig previous) {
......
...@@ -5,9 +5,10 @@ import com.ctrip.apollo.core.dto.ApolloConfig; ...@@ -5,9 +5,10 @@ import com.ctrip.apollo.core.dto.ApolloConfig;
/** /**
* Load config from local backup file * Load config from local backup file
*
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public class LocalFileConfigLoader extends AbstractConfigLoader{ public class LocalFileConfigLoader extends AbstractConfigLoader {
@Override @Override
public ApolloConfig doLoadApolloConfig(ApolloRegistry apolloRegistry, ApolloConfig previous) { public ApolloConfig doLoadApolloConfig(ApolloRegistry apolloRegistry, ApolloConfig previous) {
return null; return null;
......
package com.ctrip.apollo.client.loader.impl; package com.ctrip.apollo.client.loader.impl;
import com.google.common.collect.Maps;
import com.ctrip.apollo.client.loader.ConfigServiceLocator; import com.ctrip.apollo.client.loader.ConfigServiceLocator;
import com.ctrip.apollo.client.model.ApolloRegistry; import com.ctrip.apollo.client.model.ApolloRegistry;
import com.ctrip.apollo.client.util.ConfigUtil; import com.ctrip.apollo.client.util.ConfigUtil;
import com.ctrip.apollo.core.dto.ApolloConfig; import com.ctrip.apollo.core.dto.ApolloConfig;
import com.ctrip.apollo.core.serivce.ApolloService; import com.ctrip.apollo.core.serivce.ApolloService;
import com.google.common.collect.Maps;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity; import org.springframework.http.HttpEntity;
...@@ -29,17 +31,20 @@ public class RemoteConfigLoader extends AbstractConfigLoader { ...@@ -29,17 +31,20 @@ public class RemoteConfigLoader extends AbstractConfigLoader {
private final ConfigUtil configUtil; private final ConfigUtil configUtil;
private final ConfigServiceLocator serviceLocator; private final ConfigServiceLocator serviceLocator;
public RemoteConfigLoader(RestTemplate restTemplate, ConfigUtil configUtil, ConfigServiceLocator locator) { public RemoteConfigLoader(RestTemplate restTemplate, ConfigUtil configUtil,
ConfigServiceLocator locator) {
this.restTemplate = restTemplate; this.restTemplate = restTemplate;
this.configUtil = configUtil; this.configUtil = configUtil;
this.serviceLocator = locator; this.serviceLocator = locator;
} }
ApolloConfig getRemoteConfig(RestTemplate restTemplate, String uri, String cluster, ApolloRegistry apolloRegistry, ApolloConfig previousConfig) { ApolloConfig getRemoteConfig(RestTemplate restTemplate, String uri, String cluster,
ApolloRegistry apolloRegistry, ApolloConfig previousConfig) {
long appId = apolloRegistry.getAppId(); long appId = apolloRegistry.getAppId();
String version = apolloRegistry.getVersion(); String version = apolloRegistry.getVersion();
logger.info("Loading config from {}, appId={}, cluster={}, version={}", uri, appId, cluster, version); logger.info("Loading config from {}, appId={}, cluster={}, version={}", uri, appId, cluster,
version);
String path = "/config/{appId}/{cluster}"; String path = "/config/{appId}/{cluster}";
Map<String, Object> paramMap = Maps.newHashMap(); Map<String, Object> paramMap = Maps.newHashMap();
paramMap.put("appId", appId); paramMap.put("appId", appId);
...@@ -60,8 +65,8 @@ public class RemoteConfigLoader extends AbstractConfigLoader { ...@@ -60,8 +65,8 @@ public class RemoteConfigLoader extends AbstractConfigLoader {
// TODO retry // TODO retry
response = restTemplate.exchange(uri response = restTemplate.exchange(uri
+ path, HttpMethod.GET, new HttpEntity<Void>((Void) null), ApolloConfig.class, paramMap); + path, HttpMethod.GET, new HttpEntity<Void>((Void) null), ApolloConfig.class, paramMap);
} catch (Throwable e) { } catch (Throwable ex) {
throw e; throw ex;
} }
if (response == null) { if (response == null) {
...@@ -73,7 +78,8 @@ public class RemoteConfigLoader extends AbstractConfigLoader { ...@@ -73,7 +78,8 @@ public class RemoteConfigLoader extends AbstractConfigLoader {
} }
if (response.getStatusCode() != HttpStatus.OK) { if (response.getStatusCode() != HttpStatus.OK) {
throw new RuntimeException(String.format("Load apollo config failed, response status %s", response.getStatusCode())); throw new RuntimeException(
String.format("Load apollo config failed, response status %s", response.getStatusCode()));
} }
ApolloConfig result = response.getBody(); ApolloConfig result = response.getBody();
...@@ -91,7 +97,7 @@ public class RemoteConfigLoader extends AbstractConfigLoader { ...@@ -91,7 +97,7 @@ public class RemoteConfigLoader extends AbstractConfigLoader {
private String getConfigServiceUrl() { private String getConfigServiceUrl() {
List<ApolloService> services = serviceLocator.getConfigServices(); List<ApolloService> services = serviceLocator.getConfigServices();
if(services.size()==0){ if (services.size() == 0) {
throw new RuntimeException("No available config service"); throw new RuntimeException("No available config service");
} }
return services.get(0).getHomepageUrl(); return services.get(0).getHomepageUrl();
......
...@@ -11,7 +11,8 @@ public class PropertyChange { ...@@ -11,7 +11,8 @@ public class PropertyChange {
private Object newValue; private Object newValue;
private PropertyChangeType changeType; private PropertyChangeType changeType;
public PropertyChange(String propertyName, Object oldValue, Object newValue, PropertyChangeType changeType) { public PropertyChange(String propertyName, Object oldValue, Object newValue,
PropertyChangeType changeType) {
this.propertyName = propertyName; this.propertyName = propertyName;
this.oldValue = oldValue; this.oldValue = oldValue;
this.newValue = newValue; this.newValue = newValue;
......
package com.ctrip.apollo.client.model; package com.ctrip.apollo.client.model;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.CompositePropertySource;
import java.util.List; import java.util.List;
...@@ -17,7 +18,8 @@ public class PropertySourceReloadResult { ...@@ -17,7 +18,8 @@ public class PropertySourceReloadResult {
changes = Lists.newArrayList(); changes = Lists.newArrayList();
} }
public PropertySourceReloadResult(CompositePropertySource propertySource, List<PropertyChange> changes) { public PropertySourceReloadResult(CompositePropertySource propertySource,
List<PropertyChange> changes) {
this.propertySource = propertySource; this.propertySource = propertySource;
this.changes = changes; this.changes = changes;
} }
......
package com.ctrip.apollo.client.util; package com.ctrip.apollo.client.util;
import com.ctrip.apollo.client.constants.Constants;
import com.ctrip.apollo.client.model.ApolloRegistry;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.common.base.Predicates; import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable; import com.google.common.collect.FluentIterable;
import com.ctrip.apollo.client.constants.Constants;
import com.ctrip.apollo.client.model.ApolloRegistry;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource; import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.EncodedResource;
...@@ -66,7 +68,8 @@ public class ConfigUtil { ...@@ -66,7 +68,8 @@ public class ConfigUtil {
} }
ApolloRegistry registry = new ApolloRegistry(); ApolloRegistry registry = new ApolloRegistry();
registry.setAppId(Long.parseLong(properties.getProperty(Constants.APP_ID))); registry.setAppId(Long.parseLong(properties.getProperty(Constants.APP_ID)));
registry.setVersion(properties.getProperty(Constants.VERSION, Constants.DEFAULT_VERSION_NAME)); registry.setVersion(
properties.getProperty(Constants.VERSION, Constants.DEFAULT_VERSION_NAME));
return registry; return registry;
} }
}).filter(Predicates.notNull()).toList(); }).filter(Predicates.notNull()).toList();
...@@ -80,8 +83,8 @@ public class ConfigUtil { ...@@ -80,8 +83,8 @@ public class ConfigUtil {
} }
try { try {
return PropertiesLoaderUtils.loadProperties(new EncodedResource(resource, "UTF-8")); return PropertiesLoaderUtils.loadProperties(new EncodedResource(resource, "UTF-8"));
} catch (IOException e) { } catch (IOException ex) {
e.printStackTrace(); ex.printStackTrace();
} }
return null; return null;
} }
......
...@@ -3,14 +3,15 @@ package com.ctrip.apollo.client; ...@@ -3,14 +3,15 @@ package com.ctrip.apollo.client;
import com.ctrip.apollo.client.loader.ConfigLoaderManagerTest; import com.ctrip.apollo.client.loader.ConfigLoaderManagerTest;
import com.ctrip.apollo.client.loader.impl.RemoteConfigLoaderTest; import com.ctrip.apollo.client.loader.impl.RemoteConfigLoaderTest;
import com.ctrip.apollo.client.util.ConfigUtilTest; import com.ctrip.apollo.client.util.ConfigUtilTest;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.Suite; import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses; import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class) @RunWith(Suite.class)
@SuiteClasses({ @SuiteClasses({
ApolloConfigManagerTest.class, ConfigLoaderManagerTest.class, RemoteConfigLoaderTest.class, ApolloConfigManagerTest.class, ConfigLoaderManagerTest.class, RemoteConfigLoaderTest.class,
ConfigUtilTest.class ConfigUtilTest.class
}) })
public class AllTests { public class AllTests {
......
...@@ -3,6 +3,7 @@ package com.ctrip.apollo.client; ...@@ -3,6 +3,7 @@ package com.ctrip.apollo.client;
import com.ctrip.apollo.client.loader.ConfigLoaderManager; import com.ctrip.apollo.client.loader.ConfigLoaderManager;
import com.ctrip.apollo.client.model.PropertyChange; import com.ctrip.apollo.client.model.PropertyChange;
import com.ctrip.apollo.client.model.PropertySourceReloadResult; import com.ctrip.apollo.client.model.PropertySourceReloadResult;
import org.junit.After; import org.junit.After;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
...@@ -25,7 +26,15 @@ import java.util.List; ...@@ -25,7 +26,15 @@ import java.util.List;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doNothing;
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;
/** /**
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
...@@ -61,7 +70,8 @@ public class ApolloConfigManagerTest { ...@@ -61,7 +70,8 @@ public class ApolloConfigManagerTest {
@After @After
public void tearDown() throws Exception { public void tearDown() throws Exception {
AtomicReference<ApolloConfigManager> singletonProtector = AtomicReference<ApolloConfigManager> singletonProtector =
(AtomicReference<ApolloConfigManager>)ReflectionTestUtils.getField(ApolloConfigManager.class, "singletonProtector"); (AtomicReference<ApolloConfigManager>) ReflectionTestUtils
.getField(ApolloConfigManager.class, "singletonProtector");
singletonProtector.set(null); singletonProtector.set(null);
} }
...@@ -74,7 +84,9 @@ public class ApolloConfigManagerTest { ...@@ -74,7 +84,9 @@ public class ApolloConfigManagerTest {
@Test @Test
public void testInitializePropertySourceSuccessfully() { public void testInitializePropertySourceSuccessfully() {
CompositePropertySource somePropertySource = mock(CompositePropertySource.class); CompositePropertySource somePropertySource = mock(CompositePropertySource.class);
final ArgumentCaptor<CompositePropertySource> captor = ArgumentCaptor.forClass(CompositePropertySource.class); final ArgumentCaptor<CompositePropertySource>
captor =
ArgumentCaptor.forClass(CompositePropertySource.class);
when(configLoaderManager.loadPropertySource()).thenReturn(somePropertySource); when(configLoaderManager.loadPropertySource()).thenReturn(somePropertySource);
...@@ -94,12 +106,15 @@ public class ApolloConfigManagerTest { ...@@ -94,12 +106,15 @@ public class ApolloConfigManagerTest {
apolloConfigManager.postProcessBeanDefinitionRegistry(beanDefinitionRegistry); apolloConfigManager.postProcessBeanDefinitionRegistry(beanDefinitionRegistry);
verify(beanDefinitionRegistry, times(2)).registerBeanDefinition(anyString(), any(BeanDefinition.class)); verify(beanDefinitionRegistry, times(2))
.registerBeanDefinition(anyString(), any(BeanDefinition.class));
} }
@Test @Test
public void testUpdatePropertySourceWithChanges() throws Exception { public void testUpdatePropertySourceWithChanges() throws Exception {
PropertySourceReloadResult somePropertySourceReloadResult = mock(PropertySourceReloadResult.class); PropertySourceReloadResult
somePropertySourceReloadResult =
mock(PropertySourceReloadResult.class);
CompositePropertySource somePropertySource = mock(CompositePropertySource.class); CompositePropertySource somePropertySource = mock(CompositePropertySource.class);
List<PropertyChange> someChanges = mock(List.class); List<PropertyChange> someChanges = mock(List.class);
...@@ -116,7 +131,9 @@ public class ApolloConfigManagerTest { ...@@ -116,7 +131,9 @@ public class ApolloConfigManagerTest {
@Test @Test
public void testUpdatePropertySourceWithNoChange() throws Exception { public void testUpdatePropertySourceWithNoChange() throws Exception {
PropertySourceReloadResult somePropertySourceReloadResult = mock(PropertySourceReloadResult.class); PropertySourceReloadResult
somePropertySourceReloadResult =
mock(PropertySourceReloadResult.class);
CompositePropertySource somePropertySource = mock(CompositePropertySource.class); CompositePropertySource somePropertySource = mock(CompositePropertySource.class);
List<PropertyChange> emptyChanges = Collections.emptyList(); List<PropertyChange> emptyChanges = Collections.emptyList();
......
package com.ctrip.apollo.client.loader; package com.ctrip.apollo.client.loader;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ctrip.apollo.client.enums.PropertyChangeType; import com.ctrip.apollo.client.enums.PropertyChangeType;
import com.ctrip.apollo.client.model.ApolloRegistry; import com.ctrip.apollo.client.model.ApolloRegistry;
import com.ctrip.apollo.client.model.PropertyChange; import com.ctrip.apollo.client.model.PropertyChange;
import com.ctrip.apollo.client.model.PropertySourceReloadResult; import com.ctrip.apollo.client.model.PropertySourceReloadResult;
import com.ctrip.apollo.client.util.ConfigUtil; import com.ctrip.apollo.client.util.ConfigUtil;
import com.ctrip.apollo.core.dto.ApolloConfig; import com.ctrip.apollo.core.dto.ApolloConfig;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.ObjectArrays;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner; import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySource;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
...@@ -26,7 +26,12 @@ import java.util.Map; ...@@ -26,7 +26,12 @@ import java.util.Map;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.anyList;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/** /**
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
...@@ -49,7 +54,9 @@ public class ConfigLoaderManagerTest { ...@@ -49,7 +54,9 @@ public class ConfigLoaderManagerTest {
long someAppId = 100; long someAppId = 100;
long anotherAppId = 101; long anotherAppId = 101;
ApolloRegistry someApolloRegistry = assembleSomeApolloRegistry(someAppId, "someVersion"); ApolloRegistry someApolloRegistry = assembleSomeApolloRegistry(someAppId, "someVersion");
ApolloRegistry anotherApolloRegistry = assembleSomeApolloRegistry(anotherAppId, "anotherVersion"); ApolloRegistry
anotherApolloRegistry =
assembleSomeApolloRegistry(anotherAppId, "anotherVersion");
ApolloConfig someApolloConfig = mock(ApolloConfig.class); ApolloConfig someApolloConfig = mock(ApolloConfig.class);
ApolloConfig anotherApolloConfig = mock(ApolloConfig.class); ApolloConfig anotherApolloConfig = mock(ApolloConfig.class);
Map<String, Object> someMap = mock(Map.class); Map<String, Object> someMap = mock(Map.class);
...@@ -57,9 +64,11 @@ public class ConfigLoaderManagerTest { ...@@ -57,9 +64,11 @@ public class ConfigLoaderManagerTest {
when(someApolloConfig.getAppId()).thenReturn(someAppId); when(someApolloConfig.getAppId()).thenReturn(someAppId);
when(someApolloConfig.getAppId()).thenReturn(anotherAppId); when(someApolloConfig.getAppId()).thenReturn(anotherAppId);
when(configUtil.loadApolloRegistries()).thenReturn(Lists.newArrayList(someApolloRegistry, anotherApolloRegistry)); when(configUtil.loadApolloRegistries())
.thenReturn(Lists.newArrayList(someApolloRegistry, anotherApolloRegistry));
doReturn(someApolloConfig).when(configLoaderManager).loadSingleApolloConfig(someApolloRegistry); doReturn(someApolloConfig).when(configLoaderManager).loadSingleApolloConfig(someApolloRegistry);
doReturn(anotherApolloConfig).when(configLoaderManager).loadSingleApolloConfig(anotherApolloRegistry); doReturn(anotherApolloConfig).when(configLoaderManager)
.loadSingleApolloConfig(anotherApolloRegistry);
when(someApolloConfig.getConfigurations()).thenReturn(someMap); when(someApolloConfig.getConfigurations()).thenReturn(someMap);
when(anotherApolloConfig.getConfigurations()).thenReturn(anotherMap); when(anotherApolloConfig.getConfigurations()).thenReturn(anotherMap);
...@@ -67,10 +76,13 @@ public class ConfigLoaderManagerTest { ...@@ -67,10 +76,13 @@ public class ConfigLoaderManagerTest {
assertEquals(2, result.getPropertySources().size()); assertEquals(2, result.getPropertySources().size());
List<Map<String, Object>> resultMaps = FluentIterable.from(result.getPropertySources()).transform(new Function<PropertySource<?>, Map<String, Object>>() { List<Map<String, Object>>
resultMaps =
FluentIterable.from(result.getPropertySources())
.transform(new Function<PropertySource<?>, Map<String, Object>>() {
@Override @Override
public Map<String, Object> apply(PropertySource<?> input) { public Map<String, Object> apply(PropertySource<?> input) {
return (Map<String, Object>)input.getSource(); return (Map<String, Object>) input.getSource();
} }
}).toList(); }).toList();
...@@ -108,7 +120,8 @@ public class ConfigLoaderManagerTest { ...@@ -108,7 +120,8 @@ public class ConfigLoaderManagerTest {
doReturn(null).when(configLoaderManager).getPreviousApolloConfig(someApolloRegistry); doReturn(null).when(configLoaderManager).getPreviousApolloConfig(someApolloRegistry);
when(someApolloConfig.getConfigurations()).thenReturn(someMap); when(someApolloConfig.getConfigurations()).thenReturn(someMap);
when(configLoader.loadApolloConfig(someApolloRegistry, previousConfig)).thenReturn(someApolloConfig); when(configLoader.loadApolloConfig(someApolloRegistry, previousConfig))
.thenReturn(someApolloConfig);
ApolloConfig result = configLoaderManager.loadSingleApolloConfig(someApolloRegistry); ApolloConfig result = configLoaderManager.loadSingleApolloConfig(someApolloRegistry);
...@@ -122,7 +135,8 @@ public class ConfigLoaderManagerTest { ...@@ -122,7 +135,8 @@ public class ConfigLoaderManagerTest {
ApolloConfig someApolloConfig = mock(ApolloConfig.class); ApolloConfig someApolloConfig = mock(ApolloConfig.class);
Map<String, Object> someMap = mock(Map.class); Map<String, Object> someMap = mock(Map.class);
List<PropertyChange> someChanges = mock(List.class); List<PropertyChange> someChanges = mock(List.class);
ReflectionTestUtils.setField(configLoaderManager, "apolloRegistries", Lists.newArrayList(someApolloRegistry)); ReflectionTestUtils
.setField(configLoaderManager, "apolloRegistries", Lists.newArrayList(someApolloRegistry));
doReturn(someApolloConfig).when(configLoaderManager).loadSingleApolloConfig(someApolloRegistry); doReturn(someApolloConfig).when(configLoaderManager).loadSingleApolloConfig(someApolloRegistry);
when(someApolloConfig.getAppId()).thenReturn(someAppId); when(someApolloConfig.getAppId()).thenReturn(someAppId);
...@@ -133,10 +147,13 @@ public class ConfigLoaderManagerTest { ...@@ -133,10 +147,13 @@ public class ConfigLoaderManagerTest {
assertEquals(1, result.getPropertySource().getPropertySources().size()); assertEquals(1, result.getPropertySource().getPropertySources().size());
assertEquals(someChanges, result.getChanges()); assertEquals(someChanges, result.getChanges());
List<Map<String, Object>> resultMaps = FluentIterable.from(result.getPropertySource().getPropertySources()).transform(new Function<PropertySource<?>, Map<String, Object>>() { List<Map<String, Object>>
resultMaps =
FluentIterable.from(result.getPropertySource().getPropertySources())
.transform(new Function<PropertySource<?>, Map<String, Object>>() {
@Override @Override
public Map<String, Object> apply(PropertySource<?> input) { public Map<String, Object> apply(PropertySource<?> input) {
return (Map<String, Object>)input.getSource(); return (Map<String, Object>) input.getSource();
} }
}).toList(); }).toList();
...@@ -161,7 +178,9 @@ public class ConfigLoaderManagerTest { ...@@ -161,7 +178,9 @@ public class ConfigLoaderManagerTest {
assertEquals(3, changes.size()); assertEquals(3, changes.size());
List<String> changeResult = FluentIterable.from(changes).transform(new Function<PropertyChange, String>() { List<String>
changeResult =
FluentIterable.from(changes).transform(new Function<PropertyChange, String>() {
@Override @Override
public String apply(PropertyChange input) { public String apply(PropertyChange input) {
return String.format("%s-%s", input.getPropertyName(), input.getChangeType()); return String.format("%s-%s", input.getPropertyName(), input.getChangeType());
......
package com.ctrip.apollo.client.loader.impl; package com.ctrip.apollo.client.loader.impl;
import static org.junit.Assert.assertEquals; import com.ctrip.apollo.client.loader.ConfigServiceLocator;
import static org.junit.Assert.assertNull; import com.ctrip.apollo.client.model.ApolloRegistry;
import static org.mockito.Matchers.any; import com.ctrip.apollo.client.util.ConfigUtil;
import static org.mockito.Matchers.anyMap; import com.ctrip.apollo.core.dto.ApolloConfig;
import static org.mockito.Matchers.anyString; import com.ctrip.apollo.core.serivce.ApolloService;
import static org.mockito.Matchers.eq;
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 java.util.ArrayList;
import java.util.List;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
...@@ -25,11 +17,19 @@ import org.springframework.http.HttpStatus; ...@@ -25,11 +17,19 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate; import org.springframework.web.client.RestTemplate;
import com.ctrip.apollo.client.loader.ConfigServiceLocator; import java.util.ArrayList;
import com.ctrip.apollo.client.model.ApolloRegistry; import java.util.List;
import com.ctrip.apollo.client.util.ConfigUtil;
import com.ctrip.apollo.core.dto.ApolloConfig; import static org.junit.Assert.assertEquals;
import com.ctrip.apollo.core.serivce.ApolloService; import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyMap;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/** /**
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
...@@ -60,7 +60,6 @@ public class RemoteConfigLoaderTest { ...@@ -60,7 +60,6 @@ public class RemoteConfigLoaderTest {
ApolloRegistry apolloRegistry = assembleSomeApolloRegistry(someAppId, "someVersion"); ApolloRegistry apolloRegistry = assembleSomeApolloRegistry(someAppId, "someVersion");
ApolloConfig previousConfig = null; ApolloConfig previousConfig = null;
ApolloService someService = new ApolloService(); ApolloService someService = new ApolloService();
someService.setHomepageUrl(someServerUrl); someService.setHomepageUrl(someServerUrl);
List<ApolloService> someServices = new ArrayList<>(); List<ApolloService> someServices = new ArrayList<>();
...@@ -90,7 +89,11 @@ public class RemoteConfigLoaderTest { ...@@ -90,7 +89,11 @@ public class RemoteConfigLoaderTest {
when(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), when(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class),
eq(ApolloConfig.class), anyMap())).thenReturn(someResponse); eq(ApolloConfig.class), anyMap())).thenReturn(someResponse);
ApolloConfig result = remoteConfigLoader.getRemoteConfig(restTemplate, someServerUrl, someClusterName, apolloRegistry, previousConfig); ApolloConfig
result =
remoteConfigLoader
.getRemoteConfig(restTemplate, someServerUrl, someClusterName, apolloRegistry,
previousConfig);
assertEquals(someApolloConfig, result); assertEquals(someApolloConfig, result);
} }
...@@ -109,7 +112,8 @@ public class RemoteConfigLoaderTest { ...@@ -109,7 +112,8 @@ public class RemoteConfigLoaderTest {
when(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), when(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class),
eq(ApolloConfig.class), anyMap())).thenReturn(someResponse); eq(ApolloConfig.class), anyMap())).thenReturn(someResponse);
remoteConfigLoader.getRemoteConfig(restTemplate, someServerUrl, someClusterName, apolloRegistry, previousConfig); remoteConfigLoader.getRemoteConfig(restTemplate, someServerUrl, someClusterName, apolloRegistry,
previousConfig);
} }
@Test @Test
...@@ -125,7 +129,11 @@ public class RemoteConfigLoaderTest { ...@@ -125,7 +129,11 @@ public class RemoteConfigLoaderTest {
when(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class), when(restTemplate.exchange(anyString(), eq(HttpMethod.GET), any(HttpEntity.class),
eq(ApolloConfig.class), anyMap())).thenReturn(someResponse); eq(ApolloConfig.class), anyMap())).thenReturn(someResponse);
ApolloConfig result = remoteConfigLoader.getRemoteConfig(restTemplate, someServerUrl, someClusterName, apolloRegistry, previousConfig); ApolloConfig
result =
remoteConfigLoader
.getRemoteConfig(restTemplate, someServerUrl, someClusterName, apolloRegistry,
previousConfig);
assertNull(result); assertNull(result);
} }
......
package com.ctrip.apollo.client.util; package com.ctrip.apollo.client.util;
import com.google.common.collect.Lists;
import com.ctrip.apollo.client.constants.Constants; import com.ctrip.apollo.client.constants.Constants;
import com.ctrip.apollo.client.model.ApolloRegistry; import com.ctrip.apollo.client.model.ApolloRegistry;
import com.google.common.collect.Lists;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
...@@ -19,7 +21,12 @@ import java.util.Properties; ...@@ -19,7 +21,12 @@ import java.util.Properties;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
/** /**
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
<PatternLayout pattern="[apollo-client][%t]%d %-5p [%c] %m%n"/> <PatternLayout pattern="[apollo-client][%t]%d %-5p [%c] %m%n"/>
</Console> </Console>
<Async name="Async" includeLocation="true"> <Async name="Async" includeLocation="true">
<AppenderRef ref="Console" /> <AppenderRef ref="Console"/>
</Async> </Async>
</appenders> </appenders>
<loggers> <loggers>
......
...@@ -5,6 +5,7 @@ import org.springframework.boot.context.web.SpringBootServletInitializer; ...@@ -5,6 +5,7 @@ import org.springframework.boot.context.web.SpringBootServletInitializer;
/** /**
* Entry point for traditional web app * Entry point for traditional web app
*
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public class ServletInitializer extends SpringBootServletInitializer { public class ServletInitializer extends SpringBootServletInitializer {
......
...@@ -3,11 +3,17 @@ package com.ctrip.apollo.configservice.controller; ...@@ -3,11 +3,17 @@ package com.ctrip.apollo.configservice.controller;
import com.ctrip.apollo.biz.entity.Version; import com.ctrip.apollo.biz.entity.Version;
import com.ctrip.apollo.biz.service.ConfigService; import com.ctrip.apollo.biz.service.ConfigService;
import com.ctrip.apollo.core.dto.ApolloConfig; import com.ctrip.apollo.core.dto.ApolloConfig;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/** /**
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
...@@ -27,7 +33,8 @@ public class ConfigController { ...@@ -27,7 +33,8 @@ public class ConfigController {
Version version = configService.loadVersionByAppIdAndVersionName(appId, versionName); Version version = configService.loadVersionByAppIdAndVersionName(appId, versionName);
if (version == null) { if (version == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, response.sendError(HttpServletResponse.SC_NOT_FOUND,
String.format("Could not load version with appId: %d, versionName: %s", appId, versionName)); String.format("Could not load version with appId: %d, versionName: %s", appId,
versionName));
return null; return null;
} }
if (version.getReleaseId() == clientSideReleaseId) { if (version.getReleaseId() == clientSideReleaseId) {
...@@ -41,7 +48,8 @@ public class ConfigController { ...@@ -41,7 +48,8 @@ public class ConfigController {
if (apolloConfig == null) { if (apolloConfig == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, response.sendError(HttpServletResponse.SC_NOT_FOUND,
String.format("Could not load config with releaseId: %d, clusterName: %s", version.getReleaseId(), clusterName)); String.format("Could not load config with releaseId: %d, clusterName: %s",
version.getReleaseId(), clusterName));
return null; return null;
} }
......
package com.ctrip.apollo.metaservice.controller; package com.ctrip.apollo.metaservice.controller;
import java.util.ArrayList; import com.ctrip.apollo.core.serivce.ApolloService;
import java.util.List; import com.ctrip.apollo.metaservice.service.DiscoveryService;
import com.netflix.appinfo.InstanceInfo;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.ctrip.apollo.core.serivce.ApolloService; import java.util.ArrayList;
import com.ctrip.apollo.metaservice.service.DiscoveryService; import java.util.List;
import com.netflix.appinfo.InstanceInfo;
@RestController @RestController
@RequestMapping("/services") @RequestMapping("/services")
......
package com.ctrip.apollo.metaservice.service; package com.ctrip.apollo.metaservice.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ctrip.apollo.core.ServiceNameConsts; import com.ctrip.apollo.core.ServiceNameConsts;
import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Application;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service @Service
public class DiscoveryService { public class DiscoveryService {
...@@ -27,7 +27,7 @@ public class DiscoveryService { ...@@ -27,7 +27,7 @@ public class DiscoveryService {
return application != null ? application.getInstances() : new ArrayList<>(); return application != null ? application.getInstances() : new ArrayList<>();
} }
public List<InstanceInfo> getAdminServiceInstances(){ public List<InstanceInfo> getAdminServiceInstances() {
Application application = eurekaClient.getApplication(ServiceNameConsts.APOLLO_ADMINSERVICE); Application application = eurekaClient.getApplication(ServiceNameConsts.APOLLO_ADMINSERVICE);
return application != null ? application.getInstances() : new ArrayList<>(); return application != null ? application.getInstances() : new ArrayList<>();
} }
......
package com.ctrip.apollo.configservice; package com.ctrip.apollo.configservice;
import com.ctrip.apollo.ServerApplication; import com.ctrip.apollo.ServerApplication;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
......
package com.ctrip.apollo.configservice; package com.ctrip.apollo.configservice;
import com.ctrip.apollo.configservice.controller.ConfigControllerTest;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.Suite; import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses; import org.junit.runners.Suite.SuiteClasses;
import com.ctrip.apollo.configservice.controller.ConfigControllerTest;
@RunWith(Suite.class) @RunWith(Suite.class)
@SuiteClasses({ @SuiteClasses({
ConfigControllerTest.class ConfigControllerTest.class
}) })
public class AllTests { public class AllTests {
......
...@@ -2,8 +2,8 @@ package com.ctrip.apollo.configservice.controller; ...@@ -2,8 +2,8 @@ package com.ctrip.apollo.configservice.controller;
import com.ctrip.apollo.biz.entity.Version; import com.ctrip.apollo.biz.entity.Version;
import com.ctrip.apollo.biz.service.ConfigService; import com.ctrip.apollo.biz.service.ConfigService;
import com.ctrip.apollo.configservice.controller.ConfigController;
import com.ctrip.apollo.core.dto.ApolloConfig; import com.ctrip.apollo.core.dto.ApolloConfig;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
...@@ -15,7 +15,14 @@ import javax.servlet.http.HttpServletResponse; ...@@ -15,7 +15,14 @@ import javax.servlet.http.HttpServletResponse;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.mockito.Mockito.*; import static org.mockito.Mockito.any;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.eq;
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;
/** /**
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
...@@ -43,11 +50,17 @@ public class ConfigControllerTest { ...@@ -43,11 +50,17 @@ public class ConfigControllerTest {
HttpServletResponse someResponse = mock(HttpServletResponse.class); HttpServletResponse someResponse = mock(HttpServletResponse.class);
Version someVersion = mock(Version.class); Version someVersion = mock(Version.class);
when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName)).thenReturn(someVersion); when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName))
.thenReturn(someVersion);
when(someVersion.getReleaseId()).thenReturn(someServerSideNewReleaseId); when(someVersion.getReleaseId()).thenReturn(someServerSideNewReleaseId);
when(configService.loadConfigByVersionAndClusterName(someVersion, someClusterName)).thenReturn(someApolloConfig); when(configService.loadConfigByVersionAndClusterName(someVersion, someClusterName))
.thenReturn(someApolloConfig);
ApolloConfig result = configController.queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId, someResponse); ApolloConfig
result =
configController
.queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId,
someResponse);
assertEquals(someApolloConfig, result); assertEquals(someApolloConfig, result);
verify(configService, times(1)).loadVersionByAppIdAndVersionName(someAppId, someVersionName); verify(configService, times(1)).loadVersionByAppIdAndVersionName(someAppId, someVersionName);
...@@ -62,9 +75,14 @@ public class ConfigControllerTest { ...@@ -62,9 +75,14 @@ public class ConfigControllerTest {
long someClientSideReleaseId = 1; long someClientSideReleaseId = 1;
HttpServletResponse someResponse = mock(HttpServletResponse.class); HttpServletResponse someResponse = mock(HttpServletResponse.class);
when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName)).thenReturn(null); when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName))
.thenReturn(null);
ApolloConfig result = configController.queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId, someResponse); ApolloConfig
result =
configController
.queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId,
someResponse);
assertNull(result); assertNull(result);
verify(someResponse, times(1)).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString()); verify(someResponse, times(1)).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
...@@ -80,11 +98,17 @@ public class ConfigControllerTest { ...@@ -80,11 +98,17 @@ public class ConfigControllerTest {
HttpServletResponse someResponse = mock(HttpServletResponse.class); HttpServletResponse someResponse = mock(HttpServletResponse.class);
Version someVersion = mock(Version.class); Version someVersion = mock(Version.class);
when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName)).thenReturn(someVersion); when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName))
.thenReturn(someVersion);
when(someVersion.getReleaseId()).thenReturn(someServerSideNewReleaseId); when(someVersion.getReleaseId()).thenReturn(someServerSideNewReleaseId);
when(configService.loadConfigByVersionAndClusterName(someVersion, someClusterName)).thenReturn(null); when(configService.loadConfigByVersionAndClusterName(someVersion, someClusterName))
.thenReturn(null);
ApolloConfig result = configController.queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId, someResponse); ApolloConfig
result =
configController
.queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId,
someResponse);
assertNull(result); assertNull(result);
verify(someResponse, times(1)).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString()); verify(someResponse, times(1)).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
...@@ -100,13 +124,19 @@ public class ConfigControllerTest { ...@@ -100,13 +124,19 @@ public class ConfigControllerTest {
HttpServletResponse someResponse = mock(HttpServletResponse.class); HttpServletResponse someResponse = mock(HttpServletResponse.class);
Version someVersion = mock(Version.class); Version someVersion = mock(Version.class);
when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName)).thenReturn(someVersion); when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName))
.thenReturn(someVersion);
when(someVersion.getReleaseId()).thenReturn(someServerSideReleaseId); when(someVersion.getReleaseId()).thenReturn(someServerSideReleaseId);
ApolloConfig result = configController.queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId, someResponse); ApolloConfig
result =
configController
.queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId,
someResponse);
assertNull(result); assertNull(result);
verify(someResponse, times(1)).setStatus(HttpServletResponse.SC_NOT_MODIFIED); verify(someResponse, times(1)).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
verify(configService, never()).loadConfigByVersionAndClusterName(any(Version.class), anyString()); verify(configService, never())
.loadConfigByVersionAndClusterName(any(Version.class), anyString());
} }
} }
...@@ -2,7 +2,7 @@ package com.ctrip.apollo; ...@@ -2,7 +2,7 @@ package com.ctrip.apollo;
public class Apollo { public class Apollo {
public final static String VERSION = "java-0.0.1-SNAPSHOT"; public static final String VERSION = "java-0.0.1-SNAPSHOT";
private static Env m_env; private static Env m_env;
......
package com.ctrip.apollo.core; package com.ctrip.apollo.core;
import com.ctrip.apollo.Apollo.Env;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import com.ctrip.apollo.Apollo.Env;
public class MetaDomainConsts { public class MetaDomainConsts {
public static final String DEFAULT_PORT = "8080"; public static final String DEFAULT_PORT = "8080";
......
package com.ctrip.apollo.core.dto; package com.ctrip.apollo.core.dto;
import com.google.common.base.MoreObjects;
import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import java.util.Comparator;
import java.util.Map; import java.util.Map;
/** /**
...@@ -81,11 +81,11 @@ public class ApolloConfig implements Comparable<ApolloConfig> { ...@@ -81,11 +81,11 @@ public class ApolloConfig implements Comparable<ApolloConfig> {
} }
@Override @Override
public int compareTo(ApolloConfig o) { public int compareTo(ApolloConfig toCompare) {
if (o == null || this.getOrder() > o.getOrder()) { if (toCompare == null || this.getOrder() > toCompare.getOrder()) {
return 1; return 1;
} }
if (o.getOrder() > this.getOrder()) { if (toCompare.getOrder() > this.getOrder()) {
return -1; return -1;
} }
return 0; return 0;
......
...@@ -22,15 +22,15 @@ public class ConfigItemDTO { ...@@ -22,15 +22,15 @@ public class ConfigItemDTO {
private Date dataChangeCreatedTime; private Date dataChangeCreatedTime;
private String DataChangeLastModifiedBy; private String dataChangeLastModifiedBy;
private Date dataChangeLastModifiedTime; private Date dataChangeLastModifiedTime;
public ConfigItemDTO(){ public ConfigItemDTO() {
} }
public ConfigItemDTO(String key, String value){ public ConfigItemDTO(String key, String value) {
this.key = key; this.key = key;
this.value = value; this.value = value;
} }
...@@ -100,11 +100,11 @@ public class ConfigItemDTO { ...@@ -100,11 +100,11 @@ public class ConfigItemDTO {
} }
public String getDataChangeLastModifiedBy() { public String getDataChangeLastModifiedBy() {
return DataChangeLastModifiedBy; return dataChangeLastModifiedBy;
} }
public void setDataChangeLastModifiedBy(String dataChangeLastModifiedBy) { public void setDataChangeLastModifiedBy(String dataChangeLastModifiedBy) {
DataChangeLastModifiedBy = dataChangeLastModifiedBy; this.dataChangeLastModifiedBy = dataChangeLastModifiedBy;
} }
public Date getDataChangeLastModifiedTime() { public Date getDataChangeLastModifiedTime() {
......
...@@ -12,7 +12,7 @@ public class VersionDTO { ...@@ -12,7 +12,7 @@ public class VersionDTO {
private Long parentVersion; private Long parentVersion;
public VersionDTO(){ public VersionDTO() {
} }
......
package com.ctrip.apollo.core.utils; package com.ctrip.apollo.core.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays; import java.util.Arrays;
import java.util.HashSet; import java.util.HashSet;
import java.util.Set; import java.util.Set;
...@@ -7,22 +10,19 @@ import java.util.concurrent.ThreadFactory; ...@@ -7,22 +10,19 @@ import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ApolloThreadFactory implements ThreadFactory { public class ApolloThreadFactory implements ThreadFactory {
private static Logger log = LoggerFactory.getLogger(ApolloThreadFactory.class); private static Logger log = LoggerFactory.getLogger(ApolloThreadFactory.class);
private final AtomicLong m_threadNumber = new AtomicLong(1); private final AtomicLong threadNumber = new AtomicLong(1);
private final String m_namePrefix; private final String namePrefix;
private final boolean m_daemon; private final boolean daemon;
private final static ThreadGroup m_threadGroup = new ThreadGroup("Apollo"); private static final ThreadGroup threadGroup = new ThreadGroup("Apollo");
public static ThreadGroup getThreadGroup() { public static ThreadGroup getThreadGroup() {
return m_threadGroup; return threadGroup;
} }
public static ThreadFactory create(String namePrefix, boolean daemon) { public static ThreadFactory create(String namePrefix, boolean daemon) {
...@@ -40,15 +40,15 @@ public class ApolloThreadFactory implements ThreadFactory { ...@@ -40,15 +40,15 @@ public class ApolloThreadFactory implements ThreadFactory {
while (System.currentTimeMillis() < expire) { while (System.currentTimeMillis() < expire) {
classify(alives, dies, new ClassifyStandard<Thread>() { classify(alives, dies, new ClassifyStandard<Thread>() {
@Override @Override
public boolean satisfy(Thread t) { public boolean satisfy(Thread thread) {
return !t.isAlive() || t.isInterrupted() || t.isDaemon(); return !thread.isAlive() || thread.isInterrupted() || thread.isDaemon();
} }
}); });
if (alives.size() > 0) { if (alives.size() > 0) {
log.info("Alive apollo threads: {}", alives); log.info("Alive apollo threads: {}", alives);
try { try {
TimeUnit.SECONDS.sleep(2); TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) { } catch (InterruptedException ex) {
// ignore // ignore
} }
} else { } else {
...@@ -56,36 +56,38 @@ public class ApolloThreadFactory implements ThreadFactory { ...@@ -56,36 +56,38 @@ public class ApolloThreadFactory implements ThreadFactory {
return true; return true;
} }
} }
log.warn("Some apollo threads are still alive but expire time has reached, alive threads: {}", alives); log.warn("Some apollo threads are still alive but expire time has reached, alive threads: {}",
alives);
return false; return false;
} }
private static interface ClassifyStandard<T> { private static interface ClassifyStandard<T> {
boolean satisfy(T t); boolean satisfy(T thread);
} }
private static <T> void classify(Set<T> src, Set<T> des, ClassifyStandard<T> standard) { private static <T> void classify(Set<T> src, Set<T> des, ClassifyStandard<T> standard) {
Set<T> s = new HashSet<>(); Set<T> set = new HashSet<>();
for (T t : src) { for (T t : src) {
if (standard.satisfy(t)) { if (standard.satisfy(t)) {
s.add(t); set.add(t);
} }
} }
src.removeAll(s); src.removeAll(set);
des.addAll(s); des.addAll(set);
} }
private ApolloThreadFactory(String namePrefix, boolean daemon) { private ApolloThreadFactory(String namePrefix, boolean daemon) {
m_namePrefix = namePrefix; this.namePrefix = namePrefix;
m_daemon = daemon; this.daemon = daemon;
} }
public Thread newThread(Runnable r) { public Thread newThread(Runnable runnable) {
Thread t = new Thread(m_threadGroup, r,// Thread thread = new Thread(threadGroup, runnable,//
m_threadGroup.getName() + "-" + m_namePrefix + "-" + m_threadNumber.getAndIncrement()); threadGroup.getName() + "-" + namePrefix + "-" + threadNumber.getAndIncrement());
t.setDaemon(m_daemon); thread.setDaemon(daemon);
if (t.getPriority() != Thread.NORM_PRIORITY) if (thread.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY); thread.setPriority(Thread.NORM_PRIORITY);
return t; }
return thread;
} }
} }
...@@ -24,8 +24,7 @@ public class StringUtils { ...@@ -24,8 +24,7 @@ public class StringUtils {
* NOTE: This method changed in Lang version 2.0. It no longer trims the String. That functionality is available in isBlank(). * NOTE: This method changed in Lang version 2.0. It no longer trims the String. That functionality is available in isBlank().
* </p> * </p>
* *
* @param str * @param str the String to check, may be null
* the String to check, may be null
* @return <code>true</code> if the String is empty or null * @return <code>true</code> if the String is empty or null
*/ */
public static boolean isEmpty(String str) { public static boolean isEmpty(String str) {
...@@ -45,8 +44,7 @@ public class StringUtils { ...@@ -45,8 +44,7 @@ public class StringUtils {
* StringUtils.isBlank(" bob ") = false * StringUtils.isBlank(" bob ") = false
* </pre> * </pre>
* *
* @param str * @param str the String to check, may be null
* the String to check, may be null
* @return <code>true</code> if the String is null, empty or whitespace * @return <code>true</code> if the String is null, empty or whitespace
*/ */
public static boolean isBlank(String str) { public static boolean isBlank(String str) {
...@@ -80,8 +78,7 @@ public class StringUtils { ...@@ -80,8 +78,7 @@ public class StringUtils {
* StringUtils.trimToNull(" abc ") = "abc" * StringUtils.trimToNull(" abc ") = "abc"
* </pre> * </pre>
* *
* @param str * @param str the String to be trimmed, may be null
* the String to be trimmed, may be null
* @return the trimmed String, <code>null</code> if only chars &lt;= 32, empty or null String input * @return the trimmed String, <code>null</code> if only chars &lt;= 32, empty or null String input
* @since 2.0 * @since 2.0
*/ */
...@@ -108,8 +105,7 @@ public class StringUtils { ...@@ -108,8 +105,7 @@ public class StringUtils {
* StringUtils.trimToEmpty(" abc ") = "abc" * StringUtils.trimToEmpty(" abc ") = "abc"
* </pre> * </pre>
* *
* @param str * @param str the String to be trimmed, may be null
* the String to be trimmed, may be null
* @return the trimmed String, or an empty String if <code>null</code> input * @return the trimmed String, or an empty String if <code>null</code> input
* @since 2.0 * @since 2.0
*/ */
...@@ -140,8 +136,7 @@ public class StringUtils { ...@@ -140,8 +136,7 @@ public class StringUtils {
* StringUtils.trim(" abc ") = "abc" * StringUtils.trim(" abc ") = "abc"
* </pre> * </pre>
* *
* @param str * @param str the String to be trimmed, may be null
* the String to be trimmed, may be null
* @return the trimmed string, <code>null</code> if null String input * @return the trimmed string, <code>null</code> if null String input
*/ */
public static String trim(String str) { public static String trim(String str) {
...@@ -166,12 +161,10 @@ public class StringUtils { ...@@ -166,12 +161,10 @@ public class StringUtils {
* StringUtils.equals("abc", "ABC") = false * StringUtils.equals("abc", "ABC") = false
* </pre> * </pre>
* *
* @see java.lang.String#equals(Object) * @param str1 the first String, may be null
* @param str1 * @param str2 the second String, may be null
* the first String, may be null
* @param str2
* the second String, may be null
* @return <code>true</code> if the Strings are equal, case sensitive, or both <code>null</code> * @return <code>true</code> if the Strings are equal, case sensitive, or both <code>null</code>
* @see java.lang.String#equals(Object)
*/ */
public static boolean equals(String str1, String str2) { public static boolean equals(String str1, String str2) {
return str1 == null ? str2 == null : str1.equals(str2); return str1 == null ? str2 == null : str1.equals(str2);
...@@ -195,12 +188,10 @@ public class StringUtils { ...@@ -195,12 +188,10 @@ public class StringUtils {
* StringUtils.equalsIgnoreCase("abc", "ABC") = true * StringUtils.equalsIgnoreCase("abc", "ABC") = true
* </pre> * </pre>
* *
* @see java.lang.String#equalsIgnoreCase(String) * @param str1 the first String, may be null
* @param str1 * @param str2 the second String, may be null
* the first String, may be null
* @param str2
* the second String, may be null
* @return <code>true</code> if the Strings are equal, case insensitive, or both <code>null</code> * @return <code>true</code> if the Strings are equal, case insensitive, or both <code>null</code>
* @see java.lang.String#equalsIgnoreCase(String)
*/ */
public static boolean equalsIgnoreCase(String str1, String str2) { public static boolean equalsIgnoreCase(String str1, String str2) {
return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2); return str1 == null ? str2 == null : str1.equalsIgnoreCase(str2);
...@@ -224,18 +215,37 @@ public class StringUtils { ...@@ -224,18 +215,37 @@ public class StringUtils {
* StringUtils.startsWith("ABCDEF", "abc") = false * StringUtils.startsWith("ABCDEF", "abc") = false
* </pre> * </pre>
* *
* @see java.lang.String#startsWith(String) * @param str the String to check, may be null
* @param str * @param prefix the prefix to find, may be null
* the String to check, may be null
* @param prefix
* the prefix to find, may be null
* @return <code>true</code> if the String starts with the prefix, case sensitive, or both <code>null</code> * @return <code>true</code> if the String starts with the prefix, case sensitive, or both <code>null</code>
* @see java.lang.String#startsWith(String)
* @since 2.4 * @since 2.4
*/ */
public static boolean startsWith(String str, String prefix) { public static boolean startsWith(String str, String prefix) {
return startsWith(str, prefix, false); return startsWith(str, prefix, false);
} }
/**
* <p>
* Check if a String starts with a specified prefix (optionally case insensitive).
* </p>
*
* @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 <code>true</code> if the String starts with the prefix or both <code>null</code>
* @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());
}
/** /**
* <p> * <p>
* Case insensitive check if a String starts with a specified prefix. * Case insensitive check if a String starts with a specified prefix.
...@@ -254,12 +264,10 @@ public class StringUtils { ...@@ -254,12 +264,10 @@ public class StringUtils {
* StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true * StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
* </pre> * </pre>
* *
* @see java.lang.String#startsWith(String) * @param str the String to check, may be null
* @param str * @param prefix the prefix to find, may be null
* the String to check, may be null
* @param prefix
* the prefix to find, may be null
* @return <code>true</code> if the String starts with the prefix, case insensitive, or both <code>null</code> * @return <code>true</code> if the String starts with the prefix, case insensitive, or both <code>null</code>
* @see java.lang.String#startsWith(String)
* @since 2.4 * @since 2.4
*/ */
public static boolean startsWithIgnoreCase(String str, String prefix) { public static boolean startsWithIgnoreCase(String str, String prefix) {
...@@ -286,8 +294,7 @@ public class StringUtils { ...@@ -286,8 +294,7 @@ public class StringUtils {
* StringUtils.isNumeric("12.3") = false * StringUtils.isNumeric("12.3") = false
* </pre> * </pre>
* *
* @param str * @param str the String to check, may be null
* the String to check, may be null
* @return <code>true</code> if only contains digits, and is non-null * @return <code>true</code> if only contains digits, and is non-null
*/ */
public static boolean isNumeric(String str) { public static boolean isNumeric(String str) {
...@@ -303,30 +310,6 @@ public class StringUtils { ...@@ -303,30 +310,6 @@ public class StringUtils {
return true; return true;
} }
/**
* <p>
* Check if a String starts with a specified prefix (optionally case insensitive).
* </p>
*
* @see java.lang.String#startsWith(String)
* @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 <code>true</code> if the String starts with the prefix or both <code>null</code>
*/
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());
}
public static interface StringFormatter<T> { public static interface StringFormatter<T> {
public String format(T obj); public String format(T obj);
} }
...@@ -340,7 +323,8 @@ public class StringUtils { ...@@ -340,7 +323,8 @@ public class StringUtils {
}); });
} }
public static <T> String join(Collection<T> collection, String separator, StringFormatter<T> formatter) { public static <T> String join(Collection<T> collection, String separator,
StringFormatter<T> formatter) {
Iterator<T> iterator = collection.iterator(); Iterator<T> iterator = collection.iterator();
// handle null, zero and one elements before building a buffer // handle null, zero and one elements before building a buffer
if (iterator == null) { if (iterator == null) {
......
package com.ctrip.apollo.demo; package com.ctrip.apollo.demo;
import com.ctrip.apollo.client.ApolloConfigManager; import com.ctrip.apollo.client.ApolloConfigManager;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
......
...@@ -6,8 +6,8 @@ import com.ctrip.apollo.client.model.PropertyChange; ...@@ -6,8 +6,8 @@ import com.ctrip.apollo.client.model.PropertyChange;
import com.ctrip.apollo.client.util.ConfigUtil; import com.ctrip.apollo.client.util.ConfigUtil;
import com.ctrip.apollo.demo.model.Config; import com.ctrip.apollo.demo.model.Config;
import com.ctrip.apollo.demo.service.DemoService; import com.ctrip.apollo.demo.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.annotation.PropertySource; import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
......
...@@ -2,6 +2,7 @@ package com.ctrip.apollo.demo.exception; ...@@ -2,6 +2,7 @@ package com.ctrip.apollo.demo.exception;
import com.ctrip.apollo.demo.model.ErrorResult; import com.ctrip.apollo.demo.model.ErrorResult;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
...@@ -17,7 +18,8 @@ public class RestExceptionHandler { ...@@ -17,7 +18,8 @@ public class RestExceptionHandler {
@ExceptionHandler(Exception.class) @ExceptionHandler(Exception.class)
ResponseEntity<ErrorResult> handleWebExceptions(Exception ex, ResponseEntity<ErrorResult> handleWebExceptions(Exception ex,
WebRequest request) throws JsonProcessingException { WebRequest request)
throws JsonProcessingException {
ErrorResult error = new ErrorResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage()); ErrorResult error = new ErrorResult(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage());
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(error); return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(error);
......
...@@ -5,7 +5,7 @@ ...@@ -5,7 +5,7 @@
<PatternLayout pattern="[apollo-demo][%t]%d %-5p [%c] %m%n"/> <PatternLayout pattern="[apollo-demo][%t]%d %-5p [%c] %m%n"/>
</Console> </Console>
<Async name="Async" includeLocation="true"> <Async name="Async" includeLocation="true">
<AppenderRef ref="Console" /> <AppenderRef ref="Console"/>
</Async> </Async>
</appenders> </appenders>
<loggers> <loggers>
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
<title>Apollo Config Client</title> <title>Apollo Config Client</title>
<link rel="stylesheet" type="text/css" href="http://apps.bdimg.com/libs/bootstrap/3.3.0/css/bootstrap.min.css"/> <link rel="stylesheet" type="text/css" href="http://apps.bdimg.com/libs/bootstrap/3.3.0/css/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="/styles/angular-toastr-1.4.1.min.css"/> <link rel="stylesheet" type="text/css" href="/styles/angular-toastr-1.4.1.min.css"/>
<link rel='stylesheet' href='/styles/loading-bar.min.css' type='text/css' media='all' /> <link rel='stylesheet' href='/styles/loading-bar.min.css' type='text/css' media='all'/>
<link rel="stylesheet" type="text/css" href="/styles/app.css"/> <link rel="stylesheet" type="text/css" href="/styles/app.css"/>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="http://apps.bdimg.com/libs/angular.js/1.3.9/angular.min.js"></script> <script type="text/javascript" src="http://apps.bdimg.com/libs/angular.js/1.3.9/angular.min.js"></script>
......
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
var self = this; var self = this;
this.loadRegistries = function() { this.loadRegistries = function () {
$http.get("demo/client/registries") $http.get("demo/client/registries")
.success(function (data) { .success(function (data) {
self.registries = data; self.registries = data;
...@@ -26,43 +26,43 @@ ...@@ -26,43 +26,43 @@
}); });
}; };
this.queryConfig = function() { this.queryConfig = function () {
$http.get("demo/config/" + encodeURIComponent(this.configQuery.configName)) $http.get("demo/config/" + encodeURIComponent(this.configQuery.configName))
.success(function(data) { .success(function (data) {
self.configQuery.configValue = data.value; self.configQuery.configValue = data.value;
}) })
.error(function(data, status) { .error(function (data, status) {
toastr.error((data && data.msg) || 'Load config failed'); toastr.error((data && data.msg) || 'Load config failed');
}); });
}; };
this.queryInjectedConfig = function () { this.queryInjectedConfig = function () {
$http.get("demo/injected/config") $http.get("demo/injected/config")
.success(function(data) { .success(function (data) {
self.injectedConfigValue = data.value; self.injectedConfigValue = data.value;
}) })
.error(function(data, status) { .error(function (data, status) {
toastr.error((data && data.msg) || 'Load injected config failed'); toastr.error((data && data.msg) || 'Load injected config failed');
}); });
}; };
this.refreshConfig = function() { this.refreshConfig = function () {
$http.post("demo/refresh") $http.post("demo/refresh")
.success(function(data) { .success(function (data) {
self.assembleRefreshResult(data); self.assembleRefreshResult(data);
}) })
.error(function(data, status) { .error(function (data, status) {
toastr.error((data && data.msg) || 'Refresh config failed'); toastr.error((data && data.msg) || 'Refresh config failed');
}); });
}; };
this.assembleRefreshResult = function(changedPropertyArray) { this.assembleRefreshResult = function (changedPropertyArray) {
if(!changedPropertyArray || !changedPropertyArray.length) { if (!changedPropertyArray || !changedPropertyArray.length) {
this.refreshResult = NONE; this.refreshResult = NONE;
return; return;
} }
this.refreshResult = _.map(changedPropertyArray, function(propertyChange) { this.refreshResult = _.map(changedPropertyArray, function (propertyChange) {
return propertyChange.propertyName + '(' + propertyChange.changeType + ')'; return propertyChange.propertyName + '(' + propertyChange.changeType + ')';
}); });
}; };
......
...@@ -4,4 +4,95 @@ ...@@ -4,4 +4,95 @@
* Copyright (c) 2015 Wes Cruver * Copyright (c) 2015 Wes Cruver
* License: MIT * License: MIT
*/ */
!function(){"use strict";angular.module("angular-loading-bar",["cfp.loadingBarInterceptor"]),angular.module("chieffancypants.loadingBar",["cfp.loadingBarInterceptor"]),angular.module("cfp.loadingBarInterceptor",["cfp.loadingBar"]).config(["$httpProvider",function(a){var b=["$q","$cacheFactory","$timeout","$rootScope","$log","cfpLoadingBar",function(b,c,d,e,f,g){function h(){d.cancel(j),g.complete(),l=0,k=0}function i(b){var d,e=c.get("$http"),f=a.defaults;!b.cache&&!f.cache||b.cache===!1||"GET"!==b.method&&"JSONP"!==b.method||(d=angular.isObject(b.cache)?b.cache:angular.isObject(f.cache)?f.cache:e);var g=void 0!==d?void 0!==d.get(b.url):!1;return void 0!==b.cached&&g!==b.cached?b.cached:(b.cached=g,g)}var j,k=0,l=0,m=g.latencyThreshold;return{request:function(a){return a.ignoreLoadingBar||i(a)||(e.$broadcast("cfpLoadingBar:loading",{url:a.url}),0===k&&(j=d(function(){g.start()},m)),k++,g.set(l/k)),a},response:function(a){return a&&a.config?(a.config.ignoreLoadingBar||i(a.config)||(l++,e.$broadcast("cfpLoadingBar:loaded",{url:a.config.url,result:a}),l>=k?h():g.set(l/k)),a):(f.error("Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50"),a)},responseError:function(a){return a&&a.config?(a.config.ignoreLoadingBar||i(a.config)||(l++,e.$broadcast("cfpLoadingBar:loaded",{url:a.config.url,result:a}),l>=k?h():g.set(l/k)),b.reject(a)):(f.error("Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50"),b.reject(a))}}}];a.interceptors.push(b)}]),angular.module("cfp.loadingBar",[]).provider("cfpLoadingBar",function(){this.autoIncrement=!0,this.includeSpinner=!0,this.includeBar=!0,this.latencyThreshold=100,this.startSize=.02,this.parentSelector="body",this.spinnerTemplate='<div id="loading-bar-spinner"><div class="spinner-icon"></div></div>',this.loadingBarTemplate='<div id="loading-bar"><div class="bar"><div class="peg"></div></div></div>',this.$get=["$injector","$document","$timeout","$rootScope",function(a,b,c,d){function e(){k||(k=a.get("$animate"));var e=b.find(n).eq(0);c.cancel(m),r||(d.$broadcast("cfpLoadingBar:started"),r=!0,v&&k.enter(o,e,angular.element(e[0].lastChild)),u&&k.enter(q,e,angular.element(e[0].lastChild)),f(w))}function f(a){if(r){var b=100*a+"%";p.css("width",b),s=a,t&&(c.cancel(l),l=c(function(){g()},250))}}function g(){if(!(h()>=1)){var a=0,b=h();a=b>=0&&.25>b?(3*Math.random()+3)/100:b>=.25&&.65>b?3*Math.random()/100:b>=.65&&.9>b?2*Math.random()/100:b>=.9&&.99>b?.005:0;var c=h()+a;f(c)}}function h(){return s}function i(){s=0,r=!1}function j(){k||(k=a.get("$animate")),d.$broadcast("cfpLoadingBar:completed"),f(1),c.cancel(m),m=c(function(){var a=k.leave(o,i);a&&a.then&&a.then(i),k.leave(q)},500)}var k,l,m,n=this.parentSelector,o=angular.element(this.loadingBarTemplate),p=o.find("div").eq(0),q=angular.element(this.spinnerTemplate),r=!1,s=0,t=this.autoIncrement,u=this.includeSpinner,v=this.includeBar,w=this.startSize;return{start:e,set:f,status:h,inc:g,complete:j,autoIncrement:this.autoIncrement,includeSpinner:this.includeSpinner,latencyThreshold:this.latencyThreshold,parentSelector:this.parentSelector,startSize:this.startSize}}]})}(); !function () {
\ No newline at end of file "use strict";
angular.module("angular-loading-bar", ["cfp.loadingBarInterceptor"]), angular.module("chieffancypants.loadingBar", ["cfp.loadingBarInterceptor"]), angular.module("cfp.loadingBarInterceptor", ["cfp.loadingBar"]).config(["$httpProvider", function (a) {
var b = ["$q", "$cacheFactory", "$timeout", "$rootScope", "$log", "cfpLoadingBar", function (b, c, d, e, f, g) {
function h() {
d.cancel(j), g.complete(), l = 0, k = 0
}
function i(b) {
var d, e = c.get("$http"), f = a.defaults;
!b.cache && !f.cache || b.cache === !1 || "GET" !== b.method && "JSONP" !== b.method || (d = angular.isObject(b.cache) ? b.cache : angular.isObject(f.cache) ? f.cache : e);
var g = void 0 !== d ? void 0 !== d.get(b.url) : !1;
return void 0 !== b.cached && g !== b.cached ? b.cached : (b.cached = g, g)
}
var j, k = 0, l = 0, m = g.latencyThreshold;
return {
request: function (a) {
return a.ignoreLoadingBar || i(a) || (e.$broadcast("cfpLoadingBar:loading", {url: a.url}), 0 === k && (j = d(function () {
g.start()
}, m)), k++, g.set(l / k)), a
}, response: function (a) {
return a && a.config ? (a.config.ignoreLoadingBar || i(a.config) || (l++, e.$broadcast("cfpLoadingBar:loaded", {
url: a.config.url,
result: a
}), l >= k ? h() : g.set(l / k)), a) : (f.error("Broken interceptor detected: Config object not supplied in response:\n https://github.com/chieffancypants/angular-loading-bar/pull/50"), a)
}, responseError: function (a) {
return a && a.config ? (a.config.ignoreLoadingBar || i(a.config) || (l++, e.$broadcast("cfpLoadingBar:loaded", {
url: a.config.url,
result: a
}), l >= k ? h() : g.set(l / k)), b.reject(a)) : (f.error("Broken interceptor detected: Config object not supplied in rejection:\n https://github.com/chieffancypants/angular-loading-bar/pull/50"), b.reject(a))
}
}
}];
a.interceptors.push(b)
}]), angular.module("cfp.loadingBar", []).provider("cfpLoadingBar", function () {
this.autoIncrement = !0, this.includeSpinner = !0, this.includeBar = !0, this.latencyThreshold = 100, this.startSize = .02, this.parentSelector = "body", this.spinnerTemplate = '<div id="loading-bar-spinner"><div class="spinner-icon"></div></div>', this.loadingBarTemplate = '<div id="loading-bar"><div class="bar"><div class="peg"></div></div></div>', this.$get = ["$injector", "$document", "$timeout", "$rootScope", function (a, b, c, d) {
function e() {
k || (k = a.get("$animate"));
var e = b.find(n).eq(0);
c.cancel(m), r || (d.$broadcast("cfpLoadingBar:started"), r = !0, v && k.enter(o, e, angular.element(e[0].lastChild)), u && k.enter(q, e, angular.element(e[0].lastChild)), f(w))
}
function f(a) {
if (r) {
var b = 100 * a + "%";
p.css("width", b), s = a, t && (c.cancel(l), l = c(function () {
g()
}, 250))
}
}
function g() {
if (!(h() >= 1)) {
var a = 0, b = h();
a = b >= 0 && .25 > b ? (3 * Math.random() + 3) / 100 : b >= .25 && .65 > b ? 3 * Math.random() / 100 : b >= .65 && .9 > b ? 2 * Math.random() / 100 : b >= .9 && .99 > b ? .005 : 0;
var c = h() + a;
f(c)
}
}
function h() {
return s
}
function i() {
s = 0, r = !1
}
function j() {
k || (k = a.get("$animate")), d.$broadcast("cfpLoadingBar:completed"), f(1), c.cancel(m), m = c(function () {
var a = k.leave(o, i);
a && a.then && a.then(i), k.leave(q)
}, 500)
}
var k, l, m, n = this.parentSelector, o = angular.element(this.loadingBarTemplate), p = o.find("div").eq(0), q = angular.element(this.spinnerTemplate), r = !1, s = 0, t = this.autoIncrement, u = this.includeSpinner, v = this.includeBar, w = this.startSize;
return {
start: e,
set: f,
status: h,
inc: g,
complete: j,
autoIncrement: this.autoIncrement,
includeSpinner: this.includeSpinner,
latencyThreshold: this.latencyThreshold,
parentSelector: this.parentSelector,
startSize: this.startSize
}
}]
})
}();
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
#loading-bar,#loading-bar-spinner{pointer-events:none;-webkit-pointer-events:none;-webkit-transition:350ms linear all;-moz-transition:350ms linear all;-o-transition:350ms linear all;transition:350ms linear all}#loading-bar-spinner.ng-enter,#loading-bar-spinner.ng-leave.ng-leave-active,#loading-bar.ng-enter,#loading-bar.ng-leave.ng-leave-active{opacity:0}#loading-bar-spinner.ng-enter.ng-enter-active,#loading-bar-spinner.ng-leave,#loading-bar.ng-enter.ng-enter-active,#loading-bar.ng-leave{opacity:1}#loading-bar .bar{-webkit-transition:width 350ms;-moz-transition:width 350ms;-o-transition:width 350ms;transition:width 350ms;background:#29d;position:fixed;z-index:10002;top:0;left:0;width:100%;height:2px;border-bottom-right-radius:1px;border-top-right-radius:1px}#loading-bar .peg{position:absolute;width:70px;right:0;top:0;height:2px;opacity:.45;-moz-box-shadow:#29d 1px 0 6px 1px;-ms-box-shadow:#29d 1px 0 6px 1px;-webkit-box-shadow:#29d 1px 0 6px 1px;box-shadow:#29d 1px 0 6px 1px;-moz-border-radius:100%;-webkit-border-radius:100%;border-radius:100%}#loading-bar-spinner{display:block;position:fixed;z-index:10002;top:10px;left:10px}#loading-bar-spinner .spinner-icon{width:14px;height:14px;border:2px solid transparent;border-top-color:#29d;border-left-color:#29d;border-radius:50%;-webkit-animation:loading-bar-spinner 400ms linear infinite;-moz-animation:loading-bar-spinner 400ms linear infinite;-ms-animation:loading-bar-spinner 400ms linear infinite;-o-animation:loading-bar-spinner 400ms linear infinite;animation:loading-bar-spinner 400ms linear infinite}@-webkit-keyframes loading-bar-spinner{0%{-webkit-transform:rotate(0);transform:rotate(0)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@-moz-keyframes loading-bar-spinner{0%{-moz-transform:rotate(0);transform:rotate(0)}100%{-moz-transform:rotate(360deg);transform:rotate(360deg)}}@-o-keyframes loading-bar-spinner{0%{-o-transform:rotate(0);transform:rotate(0)}100%{-o-transform:rotate(360deg);transform:rotate(360deg)}}@-ms-keyframes loading-bar-spinner{0%{-ms-transform:rotate(0);transform:rotate(0)}100%{-ms-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes loading-bar-spinner{0%{transform:rotate(0)}100%{transform:rotate(360deg)}} #loading-bar, #loading-bar-spinner {
\ No newline at end of file pointer-events: none;
-webkit-pointer-events: none;
-webkit-transition: 350ms linear all;
-moz-transition: 350ms linear all;
-o-transition: 350ms linear all;
transition: 350ms linear all
}
#loading-bar-spinner.ng-enter, #loading-bar-spinner.ng-leave.ng-leave-active, #loading-bar.ng-enter, #loading-bar.ng-leave.ng-leave-active {
opacity: 0
}
#loading-bar-spinner.ng-enter.ng-enter-active, #loading-bar-spinner.ng-leave, #loading-bar.ng-enter.ng-enter-active, #loading-bar.ng-leave {
opacity: 1
}
#loading-bar .bar {
-webkit-transition: width 350ms;
-moz-transition: width 350ms;
-o-transition: width 350ms;
transition: width 350ms;
background: #29d;
position: fixed;
z-index: 10002;
top: 0;
left: 0;
width: 100%;
height: 2px;
border-bottom-right-radius: 1px;
border-top-right-radius: 1px
}
#loading-bar .peg {
position: absolute;
width: 70px;
right: 0;
top: 0;
height: 2px;
opacity: .45;
-moz-box-shadow: #29d 1px 0 6px 1px;
-ms-box-shadow: #29d 1px 0 6px 1px;
-webkit-box-shadow: #29d 1px 0 6px 1px;
box-shadow: #29d 1px 0 6px 1px;
-moz-border-radius: 100%;
-webkit-border-radius: 100%;
border-radius: 100%
}
#loading-bar-spinner {
display: block;
position: fixed;
z-index: 10002;
top: 10px;
left: 10px
}
#loading-bar-spinner .spinner-icon {
width: 14px;
height: 14px;
border: 2px solid transparent;
border-top-color: #29d;
border-left-color: #29d;
border-radius: 50%;
-webkit-animation: loading-bar-spinner 400ms linear infinite;
-moz-animation: loading-bar-spinner 400ms linear infinite;
-ms-animation: loading-bar-spinner 400ms linear infinite;
-o-animation: loading-bar-spinner 400ms linear infinite;
animation: loading-bar-spinner 400ms linear infinite
}
@-webkit-keyframes loading-bar-spinner {
0% {
-webkit-transform: rotate(0);
transform: rotate(0)
}
100% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg)
}
}
@-moz-keyframes loading-bar-spinner {
0% {
-moz-transform: rotate(0);
transform: rotate(0)
}
100% {
-moz-transform: rotate(360deg);
transform: rotate(360deg)
}
}
@-o-keyframes loading-bar-spinner {
0% {
-o-transform: rotate(0);
transform: rotate(0)
}
100% {
-o-transform: rotate(360deg);
transform: rotate(360deg)
}
}
@-ms-keyframes loading-bar-spinner {
0% {
-ms-transform: rotate(0);
transform: rotate(0)
}
100% {
-ms-transform: rotate(360deg);
transform: rotate(360deg)
}
}
@keyframes loading-bar-spinner {
0% {
transform: rotate(0)
}
100% {
transform: rotate(360deg)
}
}
...@@ -44,7 +44,8 @@ ...@@ -44,7 +44,8 @@
<div id="config-value-wrapper" class="clearfix"> <div id="config-value-wrapper" class="clearfix">
<label class="col-sm-2 control-label">Config Value</label> <label class="col-sm-2 control-label">Config Value</label>
<div class="col-sm-3"> <div class="col-sm-3">
<textarea rows="2" cols="38" readonly class="form-control">{{demoCtrl.configQuery.configValue}}</textarea> <textarea rows="2" cols="38" readonly
class="form-control">{{demoCtrl.configQuery.configValue}}</textarea>
</div> </div>
</div> </div>
</div> </div>
......
package com.ctrip.apollo.portal.controller; package com.ctrip.apollo.portal.controller;
import java.util.List; import com.ctrip.apollo.portal.entity.App;
import com.ctrip.apollo.portal.exception.NotFoundException;
import com.ctrip.apollo.portal.service.AppService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
...@@ -11,9 +13,7 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -11,9 +13,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.ctrip.apollo.portal.entity.App; import java.util.List;
import com.ctrip.apollo.portal.exception.NotFoundException;
import com.ctrip.apollo.portal.service.AppService;
@RestController @RestController
@RequestMapping("/apps") @RequestMapping("/apps")
......
...@@ -4,6 +4,7 @@ import com.ctrip.apollo.portal.constants.PortalConstants; ...@@ -4,6 +4,7 @@ import com.ctrip.apollo.portal.constants.PortalConstants;
import com.ctrip.apollo.portal.entity.AppConfigVO; import com.ctrip.apollo.portal.entity.AppConfigVO;
import com.ctrip.apollo.portal.exception.NotFoundException; import com.ctrip.apollo.portal.exception.NotFoundException;
import com.ctrip.apollo.portal.service.ConfigService; import com.ctrip.apollo.portal.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
...@@ -17,7 +18,8 @@ public class ConfigController { ...@@ -17,7 +18,8 @@ public class ConfigController {
private ConfigService configService; private ConfigService configService;
@RequestMapping("/{appId}/{env}/{versionId}") @RequestMapping("/{appId}/{env}/{versionId}")
public AppConfigVO detail(@PathVariable long appId, @PathVariable String env, @PathVariable long versionId) { public AppConfigVO detail(@PathVariable long appId, @PathVariable String env,
@PathVariable long versionId) {
if (appId <= 0) { if (appId <= 0) {
throw new NotFoundException(); throw new NotFoundException();
......
package com.ctrip.apollo.portal.controller; package com.ctrip.apollo.portal.controller;
import static org.springframework.http.HttpStatus.BAD_REQUEST; import com.ctrip.apollo.portal.exception.NotFoundException;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import static org.springframework.http.MediaType.APPLICATION_JSON;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
...@@ -19,7 +11,18 @@ import org.springframework.web.bind.annotation.ControllerAdvice; ...@@ -19,7 +11,18 @@ import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.ResponseStatus;
import com.ctrip.apollo.portal.exception.NotFoundException; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR;
import static org.springframework.http.HttpStatus.NOT_FOUND;
import static org.springframework.http.MediaType.APPLICATION_JSON;
@ControllerAdvice @ControllerAdvice
public class GlobalDefaultExceptionHandler { public class GlobalDefaultExceptionHandler {
...@@ -34,7 +37,8 @@ public class GlobalDefaultExceptionHandler { ...@@ -34,7 +37,8 @@ public class GlobalDefaultExceptionHandler {
} }
private ResponseEntity<Map<String, Object>> handleError(HttpServletRequest request, private ResponseEntity<Map<String, Object>> handleError(HttpServletRequest request,
HttpStatus status, Throwable ex, String message) { HttpStatus status, Throwable ex,
String message) {
ex = resolveError(ex); ex = resolveError(ex);
Map<String, Object> errorAttributes = new LinkedHashMap<>(); Map<String, Object> errorAttributes = new LinkedHashMap<>();
errorAttributes.put("status", status.value()); errorAttributes.put("status", status.value());
...@@ -55,7 +59,8 @@ public class GlobalDefaultExceptionHandler { ...@@ -55,7 +59,8 @@ public class GlobalDefaultExceptionHandler {
@ExceptionHandler(NotFoundException.class) @ExceptionHandler(NotFoundException.class)
@ResponseStatus(value = NOT_FOUND) @ResponseStatus(value = NOT_FOUND)
public void notFound(HttpServletRequest req, NotFoundException ex) {} public void notFound(HttpServletRequest req, NotFoundException ex) {
}
private Throwable resolveError(Throwable ex) { private Throwable resolveError(Throwable ex) {
while (ex instanceof ServletException && ex.getCause() != null) { while (ex instanceof ServletException && ex.getCause() != null) {
......
...@@ -2,6 +2,7 @@ package com.ctrip.apollo.portal.controller; ...@@ -2,6 +2,7 @@ package com.ctrip.apollo.portal.controller;
import com.ctrip.apollo.core.dto.VersionDTO; import com.ctrip.apollo.core.dto.VersionDTO;
import com.ctrip.apollo.portal.service.VersionService; import com.ctrip.apollo.portal.service.VersionService;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
...@@ -17,7 +18,7 @@ public class VersionController { ...@@ -17,7 +18,7 @@ public class VersionController {
private VersionService versionService; private VersionService versionService;
@RequestMapping("/{appId}/{env}") @RequestMapping("/{appId}/{env}")
public List<VersionDTO> versions(@PathVariable long appId, @PathVariable String env){ public List<VersionDTO> versions(@PathVariable long appId, @PathVariable String env) {
return versionService.findVersionsByApp(appId, env); return versionService.findVersionsByApp(appId, env);
} }
} }
...@@ -39,16 +39,14 @@ public class AppConfigVO { ...@@ -39,16 +39,14 @@ public class AppConfigVO {
* {b -> D} * {b -> D}
* *
* if client read cluster1 configs will return {a -> A, b -> D, c -> C} * if client read cluster1 configs will return {a -> A, b -> D, c -> C}
*
*
*/ */
private List<OverrideClusterConfig> overrideClusterConfigs; private List<OverrideClusterConfig> overrideClusterConfigs;
public AppConfigVO(){ public AppConfigVO() {
} }
public static AppConfigVO newInstance(long appId, long versionId){ public static AppConfigVO newInstance(long appId, long versionId) {
AppConfigVO instance = new AppConfigVO(); AppConfigVO instance = new AppConfigVO();
instance.setAppId(appId); instance.setAppId(appId);
instance.setVersionId(versionId); instance.setVersionId(versionId);
...@@ -67,7 +65,7 @@ public class AppConfigVO { ...@@ -67,7 +65,7 @@ public class AppConfigVO {
private long appId; private long appId;
private List<ConfigItemDTO> configs; private List<ConfigItemDTO> configs;
public OverrideAppConfig(){ public OverrideAppConfig() {
} }
...@@ -87,8 +85,8 @@ public class AppConfigVO { ...@@ -87,8 +85,8 @@ public class AppConfigVO {
this.configs = configs; this.configs = configs;
} }
public void addConfig(ConfigItemDTO config){ public void addConfig(ConfigItemDTO config) {
if (configs == null){ if (configs == null) {
configs = new LinkedList<>(); configs = new LinkedList<>();
} }
configs.add(config); configs.add(config);
...@@ -101,7 +99,8 @@ public class AppConfigVO { ...@@ -101,7 +99,8 @@ public class AppConfigVO {
private String clusterName; private String clusterName;
private List<ConfigItemDTO> configs; private List<ConfigItemDTO> configs;
public OverrideClusterConfig(){} public OverrideClusterConfig() {
}
public String getClusterName() { public String getClusterName() {
return clusterName; return clusterName;
...@@ -121,8 +120,6 @@ public class AppConfigVO { ...@@ -121,8 +120,6 @@ public class AppConfigVO {
} }
public long getAppId() { public long getAppId() {
return appId; return appId;
} }
......
...@@ -2,7 +2,8 @@ package com.ctrip.apollo.portal.enums; ...@@ -2,7 +2,8 @@ package com.ctrip.apollo.portal.enums;
public enum Env { public enum Env {
DEV("dev"), FWS("fws"), FAT("fat"), UAT("uat"), LPT("lpt"), PROD("prod"), TOOLS("tools"), UN_KNOW(""); DEV("dev"), FWS("fws"), FAT("fat"), UAT("uat"), LPT("lpt"), PROD("prod"), TOOLS("tools"), UN_KNOW(
"");
private String value; private String value;
...@@ -25,7 +26,7 @@ public enum Env { ...@@ -25,7 +26,7 @@ public enum Env {
return PROD; return PROD;
} else if ("tools".equals(env)) { } else if ("tools".equals(env)) {
return TOOLS; return TOOLS;
} else{ } else {
return UN_KNOW; return UN_KNOW;
} }
} }
......
package com.ctrip.apollo.portal.repository; package com.ctrip.apollo.portal.repository;
import com.ctrip.apollo.portal.entity.App;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.PagingAndSortingRepository;
import com.ctrip.apollo.portal.entity.App;
public interface AppRepository extends PagingAndSortingRepository<App, String> { public interface AppRepository extends PagingAndSortingRepository<App, String> {
Page<App> findAll(Pageable pageable); Page<App> findAll(Pageable pageable);
......
package com.ctrip.apollo.portal.repository; package com.ctrip.apollo.portal.repository;
import java.util.List; import com.ctrip.apollo.portal.entity.Privilege;
import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.PagingAndSortingRepository;
import com.ctrip.apollo.portal.entity.Privilege; import java.util.List;
public interface PrivilegeRepository extends PagingAndSortingRepository<Privilege, Long> { public interface PrivilegeRepository extends PagingAndSortingRepository<Privilege, Long> {
......
package com.ctrip.apollo.portal.service; package com.ctrip.apollo.portal.service;
import java.util.Date; import com.ctrip.apollo.portal.entity.App;
import com.ctrip.apollo.portal.repository.AppRepository;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.ctrip.apollo.portal.entity.App; import java.util.Date;
import com.ctrip.apollo.portal.repository.AppRepository;
@Service @Service
public class AppService { public class AppService {
......
...@@ -6,9 +6,6 @@ public interface ConfigService { ...@@ -6,9 +6,6 @@ public interface ConfigService {
/** /**
* load config info by appId and versionId * load config info by appId and versionId
* @param appId
* @param versionId
* @return
*/ */
AppConfigVO loadReleaseConfig(long appId, long versionId); AppConfigVO loadReleaseConfig(long appId, long versionId);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment