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

format according google code style

parent d25e0cbf
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent> <parent>
<groupId>com.ctrip.apollo</groupId> <groupId>com.ctrip.apollo</groupId>
<artifactId>apollo</artifactId> <artifactId>apollo</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>apollo-adminservice</artifactId> <artifactId>apollo-adminservice</artifactId>
<name>Apollo AdminService</name> <name>Apollo AdminService</name>
<dependencies> <dependencies>
<!-- apollo --> <!-- apollo -->
<dependency> <dependency>
<groupId>com.ctrip.apollo</groupId> <groupId>com.ctrip.apollo</groupId>
<artifactId>apollo-biz</artifactId> <artifactId>apollo-biz</artifactId>
</dependency> </dependency>
<!-- end of apollo --> <!-- end of apollo -->
<!-- redis --> <!-- redis -->
<dependency> <dependency>
<groupId>org.springframework.data</groupId> <groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId> <artifactId>spring-data-redis</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>redis.clients</groupId> <groupId>redis.clients</groupId>
<artifactId>jedis</artifactId> <artifactId>jedis</artifactId>
</dependency> </dependency>
<!-- end of redis --> <!-- end of redis -->
<!-- eureka --> <!-- eureka -->
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId> <artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency> </dependency>
<!-- end of eureka --> <!-- end of eureka -->
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
</project> </project>
...@@ -2,13 +2,12 @@ package com.ctrip.apollo; ...@@ -2,13 +2,12 @@ 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
//@EnableEurekaClient //@EnableEurekaClient
public class AdminServiceApplication { public class AdminServiceApplication {
public static void main(String[] args) { public static void main(String[] args) {
new SpringApplicationBuilder(AdminServiceApplication.class).web(true).run(args); new SpringApplicationBuilder(AdminServiceApplication.class).web(true).run(args);
} }
} }
...@@ -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;
...@@ -13,11 +14,11 @@ import java.util.List; ...@@ -13,11 +14,11 @@ import java.util.List;
@RequestMapping("/cluster") @RequestMapping("/cluster")
public class ClusterController { public class ClusterController {
@Autowired @Autowired
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,31 +3,34 @@ package com.ctrip.apollo.adminservice.controller; ...@@ -3,31 +3,34 @@ 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 {
@Resource(name = "adminConfigService") @Resource(name = "adminConfigService")
private AdminConfigService adminConfigService; private AdminConfigService adminConfigService;
@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(
return adminConfigService.findConfigItemsByClusters(clusterIds); @RequestParam(value = "clusterIds") List<Long> 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;
...@@ -13,21 +14,19 @@ import java.util.List; ...@@ -13,21 +14,19 @@ import java.util.List;
@RequestMapping("/version") @RequestMapping("/version")
public class VersionController { public class VersionController {
@Autowired @Autowired
private AdminConfigService adminConfigService; private AdminConfigService adminConfigService;
@RequestMapping("/app/{appId}")
public List<VersionDTO> versions(@PathVariable long appId){
return adminConfigService.findVersionsByApp(appId);
}
@RequestMapping("/{versionId}") @RequestMapping("/app/{appId}")
public VersionDTO version(@PathVariable long versionId){ public List<VersionDTO> versions(@PathVariable long appId) {
return adminConfigService.loadVersionById(versionId);
}
return adminConfigService.findVersionsByApp(appId);
}
@RequestMapping("/{versionId}")
public VersionDTO version(@PathVariable long 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;
...@@ -16,58 +17,58 @@ import javax.persistence.Id; ...@@ -16,58 +17,58 @@ import javax.persistence.Id;
@Where(clause = "isDeleted = 0") @Where(clause = "isDeleted = 0")
@SQLDelete(sql = "Update Cluster set isDeleted = 1 where id = ?") @SQLDelete(sql = "Update Cluster set isDeleted = 1 where id = ?")
public class Cluster { public class Cluster {
@Id @Id
@GeneratedValue @GeneratedValue
private long id; private long id;
@Column(nullable = false) @Column(nullable = false)
private String name; private String name;
@Column(nullable = false) @Column(nullable = false)
private long appId; private long appId;
private boolean isDeleted; private boolean isDeleted;
public Cluster() { public Cluster() {
} }
public long getId() { public long getId() {
return id; return id;
} }
public void setId(long id) { public void setId(long id) {
this.id = id; this.id = id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public long getAppId() { public long getAppId() {
return appId; return appId;
} }
public void setAppId(long appId) { public void setAppId(long appId) {
this.appId = appId; this.appId = appId;
} }
public boolean isDeleted() { public boolean isDeleted() {
return isDeleted; return isDeleted;
} }
public void setDeleted(boolean deleted) { public void setDeleted(boolean deleted) {
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);
dto.setName(name); dto.setName(name);
return dto; return dto;
} }
} }
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")
@SQLDelete(sql = "Update ConfigItem set isDeleted = 1 where id = ?") @SQLDelete(sql = "Update ConfigItem set isDeleted = 1 where id = ?")
public class ConfigItem { public class ConfigItem {
@Id @Id
@GeneratedValue @GeneratedValue
private long id; private long id;
@Column(nullable = false) @Column(nullable = false)
private long clusterId; private long clusterId;
@Column(nullable = false) @Column(nullable = false)
private String clusterName; private String clusterName;
@Column(nullable = false) @Column(nullable = false)
private long appId; private long appId;
@Column(nullable = false) @Column(nullable = false)
private String key; private String key;
@Column @Column
private String value; private String value;
@Column @Column
private String comment; private String comment;
@Column @Column
private String dataChangeCreatedBy; private String dataChangeCreatedBy;
@Column @Column
private Date dataChangeCreatedTime; private Date dataChangeCreatedTime;
@Column @Column
private String dataChangeLastModifiedBy; private String dataChangeLastModifiedBy;
@Column @Column
private Date dataChangeLastModifiedTime; private Date dataChangeLastModifiedTime;
@Column @Column
private boolean IsDeleted; private boolean IsDeleted;
public long getId() { public long getId() {
return id; return id;
} }
public void setId(long id) { public void setId(long id) {
this.id = id; this.id = id;
} }
public long getClusterId() { public long getClusterId() {
return clusterId; return clusterId;
} }
public void setClusterId(long clusterId) { public void setClusterId(long clusterId) {
this.clusterId = clusterId; this.clusterId = clusterId;
} }
public String getClusterName() { public String getClusterName() {
return clusterName; return clusterName;
} }
public void setClusterName(String clusterName) { public void setClusterName(String clusterName) {
this.clusterName = clusterName; this.clusterName = clusterName;
} }
public long getAppId() { public long getAppId() {
return appId; return appId;
} }
public void setAppId(long appId) { public void setAppId(long appId) {
this.appId = appId; this.appId = appId;
} }
public String getKey() { public String getKey() {
return key; return key;
} }
public void setKey(String key) { public void setKey(String key) {
this.key = key; this.key = key;
} }
public String getValue() { public String getValue() {
return value; return value;
} }
public void setValue(String value) { public void setValue(String value) {
this.value = value; this.value = value;
} }
public String getComment() { public String getComment() {
return comment; return comment;
} }
public void setComment(String comment) { public void setComment(String comment) {
this.comment = comment; this.comment = comment;
} }
public String getDataChangeCreatedBy() { public String getDataChangeCreatedBy() {
return dataChangeCreatedBy; return dataChangeCreatedBy;
} }
public void setDataChangeCreatedBy(String dataChangeCreatedBy) { public void setDataChangeCreatedBy(String dataChangeCreatedBy) {
this.dataChangeCreatedBy = dataChangeCreatedBy; this.dataChangeCreatedBy = dataChangeCreatedBy;
} }
public Date getDataChangeCreatedTime() { public Date getDataChangeCreatedTime() {
return dataChangeCreatedTime; return dataChangeCreatedTime;
} }
public void setDataChangeCreatedTime(Date dataChangeCreatedTime) { public void setDataChangeCreatedTime(Date dataChangeCreatedTime) {
this.dataChangeCreatedTime = dataChangeCreatedTime; this.dataChangeCreatedTime = dataChangeCreatedTime;
} }
public String getDataChangeLastModifiedBy() { public String getDataChangeLastModifiedBy() {
return dataChangeLastModifiedBy; return dataChangeLastModifiedBy;
} }
public void setDataChangeLastModifiedBy(String dataChangeLastModifiedBy) { public void setDataChangeLastModifiedBy(String dataChangeLastModifiedBy) {
this.dataChangeLastModifiedBy = dataChangeLastModifiedBy; this.dataChangeLastModifiedBy = dataChangeLastModifiedBy;
} }
public boolean isDeleted() { public boolean isDeleted() {
return IsDeleted; return IsDeleted;
} }
public void setDeleted(boolean isDeleted) { public void setDeleted(boolean isDeleted) {
IsDeleted = isDeleted; IsDeleted = isDeleted;
} }
public Date getDataChangeLastModifiedTime() { public Date getDataChangeLastModifiedTime() {
return dataChangeLastModifiedTime; return dataChangeLastModifiedTime;
} }
public void setDataChangeLastModifiedTime(Date dataChangeLastModifiedTime) { public void setDataChangeLastModifiedTime(Date dataChangeLastModifiedTime) {
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);
dto.setClusterId(clusterId); dto.setClusterId(clusterId);
dto.setClusterName(clusterName); dto.setClusterName(clusterName);
dto.setDataChangeCreatedBy(dataChangeCreatedBy); dto.setDataChangeCreatedBy(dataChangeCreatedBy);
dto.setDataChangeLastModifiedBy(dataChangeLastModifiedBy); dto.setDataChangeLastModifiedBy(dataChangeLastModifiedBy);
dto.setDataChangeCreatedTime(dataChangeCreatedTime); dto.setDataChangeCreatedTime(dataChangeCreatedTime);
dto.setDataChangeLastModifiedTime(dataChangeLastModifiedTime); dto.setDataChangeLastModifiedTime(dataChangeLastModifiedTime);
dto.setKey(key); dto.setKey(key);
dto.setValue(value); dto.setValue(value);
dto.setComment(comment); dto.setComment(comment);
return dto; return dto;
} }
} }
...@@ -14,55 +14,55 @@ import javax.persistence.Id; ...@@ -14,55 +14,55 @@ import javax.persistence.Id;
@Where(clause = "isDeleted = 0") @Where(clause = "isDeleted = 0")
@SQLDelete(sql = "Update Release set isDeleted = 1 where id = ?") @SQLDelete(sql = "Update Release set isDeleted = 1 where id = ?")
public class Release { public class Release {
@Id @Id
@GeneratedValue @GeneratedValue
private long id; private long id;
private String name; private String name;
private long appId; private long appId;
private String comment; private String comment;
private boolean isDeleted; private boolean isDeleted;
public Release() { public Release() {
} }
public long getId() { public long getId() {
return id; return id;
} }
public void setId(long id) { public void setId(long id) {
this.id = id; this.id = id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public long getAppId() { public long getAppId() {
return appId; return appId;
} }
public void setAppId(long appId) { public void setAppId(long appId) {
this.appId = appId; this.appId = appId;
} }
public String getComment() { public String getComment() {
return comment; return comment;
} }
public void setComment(String comment) { public void setComment(String comment) {
this.comment = comment; this.comment = comment;
} }
public boolean isDeleted() { public boolean isDeleted() {
return isDeleted; return isDeleted;
} }
public void setDeleted(boolean deleted) { public void setDeleted(boolean deleted) {
isDeleted = deleted; isDeleted = deleted;
} }
} }
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;
...@@ -16,70 +17,70 @@ import javax.persistence.Id; ...@@ -16,70 +17,70 @@ import javax.persistence.Id;
@Where(clause = "isDeleted = 0") @Where(clause = "isDeleted = 0")
@SQLDelete(sql = "Update ReleaseSnapShot set isDeleted = 1 where id = ?") @SQLDelete(sql = "Update ReleaseSnapShot set isDeleted = 1 where id = ?")
public class ReleaseSnapShot { public class ReleaseSnapShot {
@Id @Id
@GeneratedValue @GeneratedValue
private long id; private long id;
@Column(nullable = false) @Column(nullable = false)
private long releaseId; private long releaseId;
@Column(nullable = false) @Column(nullable = false)
private String clusterName; private String clusterName;
@Column(nullable = false) @Column(nullable = false)
private String configurations; private String configurations;
private boolean isDeleted; private boolean isDeleted;
public ReleaseSnapShot() { public ReleaseSnapShot() {
} }
public long getId() { public long getId() {
return id; return id;
} }
public void setId(long id) { public void setId(long id) {
this.id = id; this.id = id;
} }
public long getReleaseId() { public long getReleaseId() {
return releaseId; return releaseId;
} }
public void setReleaseId(long releaseId) { public void setReleaseId(long releaseId) {
this.releaseId = releaseId; this.releaseId = releaseId;
} }
public String getClusterName() { public String getClusterName() {
return clusterName; return clusterName;
} }
public void setClusterName(String clusterName) { public void setClusterName(String clusterName) {
this.clusterName = clusterName; this.clusterName = clusterName;
} }
public String getConfigurations() { public String getConfigurations() {
return configurations; return configurations;
} }
public void setConfigurations(String configurations) { public void setConfigurations(String configurations) {
this.configurations = configurations; this.configurations = configurations;
} }
public boolean isDeleted() { public boolean isDeleted() {
return isDeleted; return isDeleted;
} }
public void setDeleted(boolean deleted) { public void setDeleted(boolean deleted) {
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);
dto.setConfigurations(configurations); dto.setConfigurations(configurations);
dto.setReleaseId(releaseId); dto.setReleaseId(releaseId);
return dto; return dto;
} }
} }
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;
...@@ -16,80 +17,80 @@ import javax.persistence.Id; ...@@ -16,80 +17,80 @@ import javax.persistence.Id;
@Where(clause = "isDeleted = 0") @Where(clause = "isDeleted = 0")
@SQLDelete(sql = "Update Version set isDeleted = 1 where id = ?") @SQLDelete(sql = "Update Version set isDeleted = 1 where id = ?")
public class Version { public class Version {
@Id @Id
@GeneratedValue @GeneratedValue
private long id; private long id;
@Column(nullable = false) @Column(nullable = false)
private String name; private String name;
@Column(nullable = false) @Column(nullable = false)
private long appId; private long appId;
@Column(nullable = false) @Column(nullable = false)
private long releaseId; private long releaseId;
//parent version could be null //parent version could be null
private Long parentVersion; private Long parentVersion;
private boolean isDeleted; private boolean isDeleted;
public Version() { public Version() {
} }
public long getId() { public long getId() {
return id; return id;
} }
public void setId(long id) { public void setId(long id) {
this.id = id; this.id = id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public long getAppId() { public long getAppId() {
return appId; return appId;
} }
public void setAppId(long appId) { public void setAppId(long appId) {
this.appId = appId; this.appId = appId;
} }
public long getReleaseId() { public long getReleaseId() {
return releaseId; return releaseId;
} }
public void setReleaseId(long releaseId) { public void setReleaseId(long releaseId) {
this.releaseId = releaseId; this.releaseId = releaseId;
} }
public boolean isDeleted() { public boolean isDeleted() {
return isDeleted; return isDeleted;
} }
public void setDeleted(boolean deleted) { public void setDeleted(boolean deleted) {
isDeleted = deleted; isDeleted = deleted;
} }
public Long getParentVersion() { public Long getParentVersion() {
return parentVersion; return parentVersion;
} }
public void setParentVersion(Long parentVersion) { public void setParentVersion(Long parentVersion) {
this.parentVersion = parentVersion; this.parentVersion = parentVersion;
} }
public VersionDTO toDTO() { public VersionDTO toDTO() {
VersionDTO dto = new VersionDTO(); VersionDTO dto = new VersionDTO();
dto.setAppId(this.appId); dto.setAppId(this.appId);
dto.setId(this.id); dto.setId(this.id);
dto.setName(this.name); dto.setName(this.name);
dto.setParentVersion(this.parentVersion); dto.setParentVersion(this.parentVersion);
dto.setReleaseId(this.releaseId); dto.setReleaseId(this.releaseId);
return dto; return dto;
} }
} }
...@@ -2,12 +2,13 @@ package com.ctrip.apollo.biz.repository; ...@@ -2,12 +2,13 @@ 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;
public interface ClusterRepository extends PagingAndSortingRepository<Cluster, Long> { public interface ClusterRepository extends PagingAndSortingRepository<Cluster, Long> {
List<Cluster> findByAppId(long appId); List<Cluster> findByAppId(long appId);
} }
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;
public interface ConfigItemRepository extends PagingAndSortingRepository<ConfigItem, Long> { public interface ConfigItemRepository extends PagingAndSortingRepository<ConfigItem, Long> {
List<ConfigItem> findByClusterIdIsIn(List<Long> clusterIds); List<ConfigItem> findByClusterIdIsIn(List<Long> clusterIds);
} }
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,8 +9,9 @@ import java.util.List; ...@@ -8,8 +9,9 @@ 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
ReleaseSnapShot findByReleaseIdAndClusterName(long releaseId, String clusterName); extends PagingAndSortingRepository<ReleaseSnapShot, Long> {
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;
...@@ -9,9 +10,9 @@ import java.util.List; ...@@ -9,9 +10,9 @@ import java.util.List;
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public interface VersionRepository extends PagingAndSortingRepository<Version, Long> { public interface VersionRepository extends PagingAndSortingRepository<Version, Long> {
Version findByAppIdAndName(long appId, String name); Version findByAppIdAndName(long appId, String name);
Version findById(long id); Version findById(long id);
List<Version> findByAppId(long appId); List<Version> findByAppId(long appId);
} }
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;
...@@ -9,14 +12,14 @@ import java.util.List; ...@@ -9,14 +12,14 @@ import java.util.List;
*/ */
public interface AdminConfigService { public interface AdminConfigService {
List<ReleaseSnapshotDTO> findReleaseSnapshotByReleaseId(long releaseId); List<ReleaseSnapshotDTO> findReleaseSnapshotByReleaseId(long releaseId);
List<VersionDTO> findVersionsByApp(long appId); List<VersionDTO> findVersionsByApp(long appId);
VersionDTO loadVersionById(long versionId); VersionDTO loadVersionById(long versionId);
List<ClusterDTO> findClustersByApp(long appId); List<ClusterDTO> findClustersByApp(long appId);
List<ConfigItemDTO> findConfigItemsByClusters(List<Long> clusterIds); List<ConfigItemDTO> findConfigItemsByClusters(List<Long> clusterIds);
} }
...@@ -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 ApolloConfig loadConfig(long appId, String clusterName, String versionName);
* @param versionName
* @return
*/
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 Version loadVersionByAppIdAndVersionName(long appId, String versionName);
* @return
*/
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 ApolloConfig loadConfigByVersionAndClusterName(Version version, String clusterName);
* @return
*/
ApolloConfig loadConfigByVersionAndClusterName(Version version, String clusterName);
} }
...@@ -9,103 +9,109 @@ import com.ctrip.apollo.biz.repository.ConfigItemRepository; ...@@ -9,103 +9,109 @@ 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 {
@Autowired @Autowired
private VersionRepository versionRepository; private VersionRepository versionRepository;
@Autowired @Autowired
private ReleaseSnapShotRepository releaseSnapShotRepository; private ReleaseSnapShotRepository releaseSnapShotRepository;
@Autowired @Autowired
private ClusterRepository clusterRepository; private ClusterRepository clusterRepository;
@Autowired @Autowired
private ConfigItemRepository configItemRepository; private ConfigItemRepository configItemRepository;
@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);
if (releaseSnapShots == null || releaseSnapShots.size() == 0){
return Collections.EMPTY_LIST;
}
List<ReleaseSnapshotDTO> result = new ArrayList<>(releaseSnapShots.size());
for (ReleaseSnapShot releaseSnapShot: releaseSnapShots){
result.add(releaseSnapShot.toDTO());
}
return result;
} }
List<ReleaseSnapShot> releaseSnapShots = releaseSnapShotRepository.findByReleaseId(releaseId);
if (releaseSnapShots == null || releaseSnapShots.size() == 0) {
return Collections.EMPTY_LIST;
}
@Override List<ReleaseSnapshotDTO> result = new ArrayList<>(releaseSnapShots.size());
public List<VersionDTO> findVersionsByApp(long appId) { for (ReleaseSnapShot releaseSnapShot : releaseSnapShots) {
if (appId <= 0) { result.add(releaseSnapShot.toDTO());
return Collections.EMPTY_LIST; }
} return result;
}
List<Version> versions = versionRepository.findByAppId(appId);
if (versions == null || versions.size() == 0) {
return Collections.EMPTY_LIST;
}
List<VersionDTO> result = new ArrayList<>(versions.size()); @Override
for (Version version : versions) { public List<VersionDTO> findVersionsByApp(long appId) {
result.add(version.toDTO()); if (appId <= 0) {
} return Collections.EMPTY_LIST;
return result;
} }
@Override List<Version> versions = versionRepository.findByAppId(appId);
public VersionDTO loadVersionById(long versionId) { if (versions == null || versions.size() == 0) {
if (versionId <= 0){ return Collections.EMPTY_LIST;
return null;
}
Version version = versionRepository.findById(versionId);
return version.toDTO();
} }
@Override List<VersionDTO> result = new ArrayList<>(versions.size());
public List<ClusterDTO> findClustersByApp(long appId) { for (Version version : versions) {
if (appId <= 0){ result.add(version.toDTO());
return Collections.EMPTY_LIST; }
} return result;
List<Cluster> clusters = clusterRepository.findByAppId(appId); }
if (clusters == null || clusters.size() == 0){
return Collections.EMPTY_LIST; @Override
} public VersionDTO loadVersionById(long versionId) {
if (versionId <= 0) {
List<ClusterDTO> result = new ArrayList<>(clusters.size()); return null;
for (Cluster cluster: clusters){ }
result.add(cluster.toDTO()); Version version = versionRepository.findById(versionId);
} return version.toDTO();
return result; }
@Override
public List<ClusterDTO> findClustersByApp(long appId) {
if (appId <= 0) {
return Collections.EMPTY_LIST;
}
List<Cluster> clusters = clusterRepository.findByAppId(appId);
if (clusters == null || clusters.size() == 0) {
return Collections.EMPTY_LIST;
}
List<ClusterDTO> result = new ArrayList<>(clusters.size());
for (Cluster cluster : clusters) {
result.add(cluster.toDTO());
}
return result;
}
@Override
public List<ConfigItemDTO> findConfigItemsByClusters(List<Long> clusterIds) {
if (clusterIds == null || clusterIds.size() == 0) {
return Collections.EMPTY_LIST;
}
List<ConfigItem> configItems = configItemRepository.findByClusterIdIsIn(clusterIds);
if (configItems == null || configItems.size() == 0) {
return Collections.EMPTY_LIST;
} }
@Override List<ConfigItemDTO> result = new ArrayList<>(configItems.size());
public List<ConfigItemDTO> findConfigItemsByClusters(List<Long> clusterIds) { for (ConfigItem configItem : configItems) {
if (clusterIds == null || clusterIds.size() == 0){ result.add(configItem.toDTO());
return Collections.EMPTY_LIST;
}
List<ConfigItem> configItems = configItemRepository.findByClusterIdIsIn(clusterIds);
if (configItems == null || configItems.size() == 0){
return Collections.EMPTY_LIST;
}
List<ConfigItemDTO> result = new ArrayList<>(configItems.size());
for (ConfigItem configItem: configItems){
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;
...@@ -20,56 +22,58 @@ import java.util.Map; ...@@ -20,56 +22,58 @@ import java.util.Map;
*/ */
@Service("configService") @Service("configService")
public class ConfigServiceImpl implements ConfigService { public class ConfigServiceImpl implements ConfigService {
@Autowired @Autowired
private VersionRepository versionRepository; private VersionRepository versionRepository;
@Autowired @Autowired
private ReleaseSnapShotRepository releaseSnapShotRepository; private ReleaseSnapShotRepository releaseSnapShotRepository;
@Autowired @Autowired
private ObjectMapper objectMapper; private ObjectMapper objectMapper;
private TypeReference<Map<String, Object>> configurationTypeReference = private TypeReference<Map<String, Object>> configurationTypeReference =
new TypeReference<Map<String, Object>>() { new TypeReference<Map<String, Object>>() {
}; };
@Override @Override
public ApolloConfig loadConfig(long appId, String clusterName, String versionName) { public ApolloConfig loadConfig(long appId, String clusterName, String versionName) {
Version version = loadVersionByAppIdAndVersionName(appId, versionName); Version version = loadVersionByAppIdAndVersionName(appId, versionName);
if (version == null) { if (version == null) {
return null; return null;
}
return loadConfigByVersionAndClusterName(version, clusterName);
} }
@Override return loadConfigByVersionAndClusterName(version, clusterName);
public Version loadVersionByAppIdAndVersionName(long appId, String versionName) { }
return versionRepository.findByAppIdAndName(appId, versionName);
}
@Override @Override
public ApolloConfig loadConfigByVersionAndClusterName(Version version, String clusterName) { public Version loadVersionByAppIdAndVersionName(long appId, String versionName) {
ReleaseSnapShot releaseSnapShot = return versionRepository.findByAppIdAndName(appId, versionName);
releaseSnapShotRepository.findByReleaseIdAndClusterName(version.getReleaseId(), clusterName); }
if (releaseSnapShot == null) {
return null;
}
return assembleConfig(version, releaseSnapShot); @Override
public ApolloConfig loadConfigByVersionAndClusterName(Version version, String clusterName) {
ReleaseSnapShot releaseSnapShot =
releaseSnapShotRepository
.findByReleaseIdAndClusterName(version.getReleaseId(), clusterName);
if (releaseSnapShot == null) {
return null;
} }
private ApolloConfig assembleConfig(Version version, ReleaseSnapShot releaseSnapShot) { return assembleConfig(version, releaseSnapShot);
ApolloConfig config = }
new ApolloConfig(version.getAppId(), releaseSnapShot.getClusterName(), version.getName(), version.getReleaseId());
config.setConfigurations(transformConfigurationToMap(releaseSnapShot.getConfigurations()));
return config; private ApolloConfig assembleConfig(Version version, ReleaseSnapShot releaseSnapShot) {
} ApolloConfig config =
new ApolloConfig(version.getAppId(), releaseSnapShot.getClusterName(), version.getName(),
version.getReleaseId());
config.setConfigurations(transformConfigurationToMap(releaseSnapShot.getConfigurations()));
return config;
}
Map<String, Object> transformConfigurationToMap(String configurations) { Map<String, Object> transformConfigurationToMap(String configurations) {
try { try {
return objectMapper.readValue(configurations, configurationTypeReference); return objectMapper.readValue(configurations, configurationTypeReference);
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
return Maps.newHashMap(); return Maps.newHashMap();
}
} }
}
} }
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 {
} }
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent> <parent>
<groupId>com.ctrip.apollo</groupId> <groupId>com.ctrip.apollo</groupId>
<artifactId>apollo</artifactId> <artifactId>apollo</artifactId>
......
...@@ -4,8 +4,8 @@ package com.ctrip.apollo.client.constants; ...@@ -4,8 +4,8 @@ package com.ctrip.apollo.client.constants;
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public class Constants { public class Constants {
public static final String APP_ID = "app.id"; public static final String APP_ID = "app.id";
public static final String VERSION = "version"; public static final String VERSION = "version";
public static final String DEFAULT_VERSION_NAME = "latest-release"; public static final String DEFAULT_VERSION_NAME = "latest-release";
public static final String ENV = "env"; public static final String ENV = "env";
} }
...@@ -5,17 +5,17 @@ package com.ctrip.apollo.client.enums; ...@@ -5,17 +5,17 @@ package com.ctrip.apollo.client.enums;
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public enum PropertyChangeType { public enum PropertyChangeType {
NEW("New"), NEW("New"),
MODIFIED("Modified"), MODIFIED("Modified"),
DELETED("Deleted"); DELETED("Deleted");
private String type; private String type;
PropertyChangeType(String type) { PropertyChangeType(String type) {
this.type = type; this.type = type;
} }
public String getType() { public String getType() {
return type; return type;
} }
} }
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');
......
...@@ -7,7 +7,7 @@ import com.ctrip.apollo.core.dto.ApolloConfig; ...@@ -7,7 +7,7 @@ import com.ctrip.apollo.core.dto.ApolloConfig;
* @author Jason Song(songs_ctrip.com) * @author Jason Song(songs_ctrip.com)
*/ */
public interface ConfigLoader { public interface ConfigLoader {
ApolloConfig loadApolloConfig(ApolloRegistry apolloRegistry, ApolloConfig previous); ApolloConfig loadApolloConfig(ApolloRegistry apolloRegistry, ApolloConfig previous);
void setFallBackLoader(ConfigLoader configLoader); void setFallBackLoader(ConfigLoader configLoader);
} }
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,35 +15,39 @@ import org.springframework.web.client.RestTemplate; ...@@ -14,35 +15,39 @@ 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;
} }
public ConfigLoader getLocalFileConfigLoader() { public ConfigLoader getLocalFileConfigLoader() {
ConfigLoader configLoader = new LocalFileConfigLoader(); ConfigLoader configLoader = new LocalFileConfigLoader();
return configLoader; return configLoader;
} }
public ConfigLoader getInMemoryConfigLoader() { public ConfigLoader getInMemoryConfigLoader() {
ConfigLoader inMemoryConfigLoader = new InMemoryConfigLoader(); ConfigLoader inMemoryConfigLoader = new InMemoryConfigLoader();
inMemoryConfigLoader.setFallBackLoader(getLocalFileConfigLoader()); inMemoryConfigLoader.setFallBackLoader(getLocalFileConfigLoader());
return inMemoryConfigLoader; return inMemoryConfigLoader;
} }
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;
} }
public ConfigLoaderManager getConfigLoaderManager() { public ConfigLoaderManager getConfigLoaderManager() {
ClientEnvironment env = ClientEnvironment.getInstance(); ClientEnvironment env = ClientEnvironment.getInstance();
if (env.getEnv().equals(Env.LOCAL)) { if (env.getEnv().equals(Env.LOCAL)) {
return new ConfigLoaderManager(getLocalFileConfigLoader(), ConfigUtil.getInstance()); return new ConfigLoaderManager(getLocalFileConfigLoader(), ConfigUtil.getInstance());
} else { } else {
return new ConfigLoaderManager(getRemoteConfigLoader(), ConfigUtil.getInstance()); return new ConfigLoaderManager(getRemoteConfigLoader(), ConfigUtil.getInstance());
}
} }
}
} }
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;
...@@ -10,26 +11,29 @@ import org.slf4j.LoggerFactory; ...@@ -10,26 +11,29 @@ import org.slf4j.LoggerFactory;
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public abstract class AbstractConfigLoader implements ConfigLoader { public abstract class AbstractConfigLoader implements ConfigLoader {
private static final Logger logger = LoggerFactory.getLogger(AbstractConfigLoader.class); private static final Logger logger = LoggerFactory.getLogger(AbstractConfigLoader.class);
private ConfigLoader fallback; private ConfigLoader fallback;
@Override @Override
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); }
return this.fallback.loadApolloConfig(apolloRegistry, previous); 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);
} }
}
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) {
this.fallback = configLoader; this.fallback = configLoader;
} }
} }
...@@ -6,10 +6,10 @@ import com.ctrip.apollo.core.dto.ApolloConfig; ...@@ -6,10 +6,10 @@ 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) {
return null; return null;
} }
} }
...@@ -5,11 +5,12 @@ import com.ctrip.apollo.core.dto.ApolloConfig; ...@@ -5,11 +5,12 @@ 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;
...@@ -24,76 +26,80 @@ import java.util.Map; ...@@ -24,76 +26,80 @@ import java.util.Map;
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public class RemoteConfigLoader extends AbstractConfigLoader { public class RemoteConfigLoader extends AbstractConfigLoader {
private static final Logger logger = LoggerFactory.getLogger(RemoteConfigLoader.class); private static final Logger logger = LoggerFactory.getLogger(RemoteConfigLoader.class);
private final RestTemplate restTemplate; private final RestTemplate restTemplate;
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,
this.restTemplate = restTemplate; ConfigServiceLocator locator) {
this.configUtil = configUtil; this.restTemplate = restTemplate;
this.serviceLocator = locator; this.configUtil = configUtil;
this.serviceLocator = locator;
}
ApolloConfig getRemoteConfig(RestTemplate restTemplate, String uri, String cluster,
ApolloRegistry apolloRegistry, ApolloConfig previousConfig) {
long appId = apolloRegistry.getAppId();
String version = apolloRegistry.getVersion();
logger.info("Loading config from {}, appId={}, cluster={}, version={}", uri, appId, cluster,
version);
String path = "/config/{appId}/{cluster}";
Map<String, Object> paramMap = Maps.newHashMap();
paramMap.put("appId", appId);
paramMap.put("cluster", cluster);
if (StringUtils.hasText(version)) {
path = path + "/{version}";
paramMap.put("version", version);
}
if (previousConfig != null) {
path = path + "?releaseId={releaseId}";
paramMap.put("releaseId", previousConfig.getReleaseId());
} }
ApolloConfig getRemoteConfig(RestTemplate restTemplate, String uri, String cluster, ApolloRegistry apolloRegistry, ApolloConfig previousConfig) { ResponseEntity<ApolloConfig> response;
long appId = apolloRegistry.getAppId();
String version = apolloRegistry.getVersion(); try {
// TODO retry
logger.info("Loading config from {}, appId={}, cluster={}, version={}", uri, appId, cluster, version); response = restTemplate.exchange(uri
String path = "/config/{appId}/{cluster}"; + path, HttpMethod.GET, new HttpEntity<Void>((Void) null), ApolloConfig.class, paramMap);
Map<String, Object> paramMap = Maps.newHashMap(); } catch (Throwable ex) {
paramMap.put("appId", appId); throw ex;
paramMap.put("cluster", cluster); }
if (StringUtils.hasText(version)) { if (response == null) {
path = path + "/{version}"; throw new RuntimeException("Load apollo config failed, response is null");
paramMap.put("version", version); }
}
if (previousConfig != null) { if (response.getStatusCode() == HttpStatus.NOT_MODIFIED) {
path = path + "?releaseId={releaseId}"; return null;
paramMap.put("releaseId", previousConfig.getReleaseId());
}
ResponseEntity<ApolloConfig> response;
try {
// TODO retry
response = restTemplate.exchange(uri
+ path, HttpMethod.GET, new HttpEntity<Void>((Void) null), ApolloConfig.class, paramMap);
} catch (Throwable e) {
throw e;
}
if (response == null) {
throw new RuntimeException("Load apollo config failed, response is null");
}
if (response.getStatusCode() == HttpStatus.NOT_MODIFIED) {
return null;
}
if (response.getStatusCode() != HttpStatus.OK) {
throw new RuntimeException(String.format("Load apollo config failed, response status %s", response.getStatusCode()));
}
ApolloConfig result = response.getBody();
return result;
} }
@Override if (response.getStatusCode() != HttpStatus.OK) {
protected ApolloConfig doLoadApolloConfig(ApolloRegistry apolloRegistry, ApolloConfig previous) { throw new RuntimeException(
ApolloConfig result = this.getRemoteConfig(restTemplate, String.format("Load apollo config failed, response status %s", response.getStatusCode()));
getConfigServiceUrl(), configUtil.getCluster(), }
apolloRegistry, previous);
//When remote server return 304, we need to return the previous result ApolloConfig result = response.getBody();
return result == null ? previous : result; return result;
}
@Override
protected ApolloConfig doLoadApolloConfig(ApolloRegistry apolloRegistry, ApolloConfig previous) {
ApolloConfig result = this.getRemoteConfig(restTemplate,
getConfigServiceUrl(), configUtil.getCluster(),
apolloRegistry, previous);
//When remote server return 304, we need to return the previous result
return result == null ? previous : result;
}
private String getConfigServiceUrl() {
List<ApolloService> services = serviceLocator.getConfigServices();
if (services.size() == 0) {
throw new RuntimeException("No available config service");
} }
return services.get(0).getHomepageUrl();
private String getConfigServiceUrl() { }
List<ApolloService> services = serviceLocator.getConfigServices(); }
if(services.size()==0){
throw new RuntimeException("No available config service");
}
return services.get(0).getHomepageUrl();
}
}
\ No newline at end of file
...@@ -6,31 +6,31 @@ import com.google.common.base.MoreObjects; ...@@ -6,31 +6,31 @@ import com.google.common.base.MoreObjects;
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public class ApolloRegistry { public class ApolloRegistry {
private long appId; private long appId;
private String version; private String version;
public long getAppId() { public long getAppId() {
return appId; return appId;
} }
public void setAppId(long appId) { public void setAppId(long appId) {
this.appId = appId; this.appId = appId;
} }
public String getVersion() { public String getVersion() {
return version; return version;
} }
public void setVersion(String version) { public void setVersion(String version) {
this.version = version; this.version = version;
} }
@Override @Override
public String toString() { public String toString() {
return MoreObjects.toStringHelper(this) return MoreObjects.toStringHelper(this)
.omitNullValues() .omitNullValues()
.add("appId", appId) .add("appId", appId)
.add("version", version) .add("version", version)
.toString(); .toString();
} }
} }
...@@ -6,47 +6,48 @@ import com.ctrip.apollo.client.enums.PropertyChangeType; ...@@ -6,47 +6,48 @@ import com.ctrip.apollo.client.enums.PropertyChangeType;
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public class PropertyChange { public class PropertyChange {
private String propertyName; private String propertyName;
private Object oldValue; private Object oldValue;
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,
this.propertyName = propertyName; PropertyChangeType changeType) {
this.oldValue = oldValue; this.propertyName = propertyName;
this.newValue = newValue; this.oldValue = oldValue;
this.changeType = changeType; this.newValue = newValue;
} this.changeType = changeType;
}
public String getPropertyName() {
return propertyName; public String getPropertyName() {
} return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName; public void setPropertyName(String propertyName) {
} this.propertyName = propertyName;
}
public Object getOldValue() {
return oldValue; public Object getOldValue() {
} return oldValue;
}
public void setOldValue(Object oldValue) {
this.oldValue = oldValue; public void setOldValue(Object oldValue) {
} this.oldValue = oldValue;
}
public Object getNewValue() {
return newValue; public Object getNewValue() {
} return newValue;
}
public void setNewValue(Object newValue) {
this.newValue = newValue; public void setNewValue(Object newValue) {
} this.newValue = newValue;
}
public PropertyChangeType getChangeType() {
return changeType; public PropertyChangeType getChangeType() {
} return changeType;
}
public void setChangeType(PropertyChangeType changeType) {
this.changeType = changeType; public void setChangeType(PropertyChangeType changeType) {
} this.changeType = changeType;
}
} }
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;
...@@ -9,36 +10,37 @@ import java.util.List; ...@@ -9,36 +10,37 @@ import java.util.List;
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public class PropertySourceReloadResult { public class PropertySourceReloadResult {
private CompositePropertySource propertySource; private CompositePropertySource propertySource;
private List<PropertyChange> changes; private List<PropertyChange> changes;
public PropertySourceReloadResult(CompositePropertySource propertySource) { public PropertySourceReloadResult(CompositePropertySource propertySource) {
this.propertySource = propertySource; this.propertySource = propertySource;
changes = Lists.newArrayList(); changes = Lists.newArrayList();
} }
public PropertySourceReloadResult(CompositePropertySource propertySource, List<PropertyChange> changes) { public PropertySourceReloadResult(CompositePropertySource propertySource,
this.propertySource = propertySource; List<PropertyChange> changes) {
this.changes = changes; this.propertySource = propertySource;
} this.changes = changes;
}
public CompositePropertySource getPropertySource() {
return propertySource; public CompositePropertySource getPropertySource() {
} return propertySource;
}
public void setPropertySource(CompositePropertySource propertySource) {
this.propertySource = propertySource; public void setPropertySource(CompositePropertySource propertySource) {
} this.propertySource = propertySource;
}
public List<PropertyChange> getChanges() {
return changes; public List<PropertyChange> getChanges() {
} return changes;
}
public void setChanges(List<PropertyChange> changes) {
this.changes = changes; public void setChanges(List<PropertyChange> changes) {
} this.changes = changes;
}
public boolean hasChanges() {
return !changes.isEmpty(); public boolean hasChanges() {
} return !changes.isEmpty();
}
} }
...@@ -7,18 +7,18 @@ import org.slf4j.LoggerFactory; ...@@ -7,18 +7,18 @@ import org.slf4j.LoggerFactory;
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public class ClassLoaderUtil { public class ClassLoaderUtil {
private static final Logger logger = LoggerFactory.getLogger(ClassLoaderUtil.class); private static final Logger logger = LoggerFactory.getLogger(ClassLoaderUtil.class);
private static ClassLoader loader = Thread.currentThread().getContextClassLoader(); private static ClassLoader loader = Thread.currentThread().getContextClassLoader();
static { static {
if (loader == null) { if (loader == null) {
logger.info("Using system class loader"); logger.info("Using system class loader");
loader = ClassLoader.getSystemClassLoader(); loader = ClassLoader.getSystemClassLoader();
}
} }
}
public static ClassLoader getLoader() { public static ClassLoader getLoader() {
return loader; return loader;
} }
} }
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;
...@@ -21,68 +23,69 @@ import java.util.concurrent.TimeUnit; ...@@ -21,68 +23,69 @@ import java.util.concurrent.TimeUnit;
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
public class ConfigUtil { public class ConfigUtil {
public static final String APOLLO_PROPERTY = "apollo.properties"; public static final String APOLLO_PROPERTY = "apollo.properties";
//TODO read from config? //TODO read from config?
private static final int refreshInterval = 5; private static final int refreshInterval = 5;
private static final TimeUnit refreshIntervalTimeUnit = TimeUnit.MINUTES; private static final TimeUnit refreshIntervalTimeUnit = TimeUnit.MINUTES;
private static ConfigUtil configUtil = new ConfigUtil(); private static ConfigUtil configUtil = new ConfigUtil();
private ApplicationContext applicationContext; private ApplicationContext applicationContext;
private ConfigUtil() {
}
public static ConfigUtil getInstance() { private ConfigUtil() {
return configUtil; }
}
public String getCluster() { public static ConfigUtil getInstance() {
// TODO return the actual cluster return configUtil;
return "default"; }
}
public void setApplicationContext(ApplicationContext applicationContext) { public String getCluster() {
this.applicationContext = applicationContext; // TODO return the actual cluster
} return "default";
}
public int getRefreshInterval() { public void setApplicationContext(ApplicationContext applicationContext) {
return refreshInterval; this.applicationContext = applicationContext;
} }
public TimeUnit getRefreshTimeUnit() { public int getRefreshInterval() {
return refreshIntervalTimeUnit; return refreshInterval;
} }
public List<ApolloRegistry> loadApolloRegistries() throws IOException { public TimeUnit getRefreshTimeUnit() {
List<URL> resourceUrls = return refreshIntervalTimeUnit;
Collections.list(ClassLoaderUtil.getLoader().getResources(APOLLO_PROPERTY)); }
List<ApolloRegistry> registries =
FluentIterable.from(resourceUrls).transform(new Function<URL, ApolloRegistry>() { public List<ApolloRegistry> loadApolloRegistries() throws IOException {
@Override List<URL> resourceUrls =
public ApolloRegistry apply(URL input) { Collections.list(ClassLoaderUtil.getLoader().getResources(APOLLO_PROPERTY));
Properties properties = loadPropertiesFromResourceURL(input); List<ApolloRegistry> registries =
if (properties == null || !properties.containsKey(Constants.APP_ID)) { FluentIterable.from(resourceUrls).transform(new Function<URL, ApolloRegistry>() {
return null; @Override
} public ApolloRegistry apply(URL input) {
ApolloRegistry registry = new ApolloRegistry(); Properties properties = loadPropertiesFromResourceURL(input);
registry.setAppId(Long.parseLong(properties.getProperty(Constants.APP_ID))); if (properties == null || !properties.containsKey(Constants.APP_ID)) {
registry.setVersion(properties.getProperty(Constants.VERSION, Constants.DEFAULT_VERSION_NAME)); return null;
return registry; }
} ApolloRegistry registry = new ApolloRegistry();
}).filter(Predicates.notNull()).toList(); registry.setAppId(Long.parseLong(properties.getProperty(Constants.APP_ID)));
return registries; registry.setVersion(
} properties.getProperty(Constants.VERSION, Constants.DEFAULT_VERSION_NAME));
return registry;
}
}).filter(Predicates.notNull()).toList();
return registries;
}
Properties loadPropertiesFromResourceURL(URL resourceUrl) { Properties loadPropertiesFromResourceURL(URL resourceUrl) {
Resource resource = applicationContext.getResource(resourceUrl.toExternalForm()); Resource resource = applicationContext.getResource(resourceUrl.toExternalForm());
if (resource == null || !resource.exists()) { if (resource == null || !resource.exists()) {
return null; return null;
} }
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,110 +26,126 @@ import java.util.List; ...@@ -25,110 +26,126 @@ 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)
*/ */
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class ApolloConfigManagerTest { public class ApolloConfigManagerTest {
private ApolloConfigManager apolloConfigManager; private ApolloConfigManager apolloConfigManager;
@Mock @Mock
private ConfigLoaderManager configLoaderManager; private ConfigLoaderManager configLoaderManager;
@Mock @Mock
private ConfigurableApplicationContext applicationContext; private ConfigurableApplicationContext applicationContext;
@Mock @Mock
private ConfigurableEnvironment env; private ConfigurableEnvironment env;
@Mock @Mock
private MutablePropertySources mutablePropertySources; private MutablePropertySources mutablePropertySources;
@Mock @Mock
private BeanDefinitionRegistry beanDefinitionRegistry; private BeanDefinitionRegistry beanDefinitionRegistry;
@Mock @Mock
private RefreshScope scope; private RefreshScope scope;
@Before @Before
public void setUp() { public void setUp() {
apolloConfigManager = spy(new ApolloConfigManager()); apolloConfigManager = spy(new ApolloConfigManager());
when(applicationContext.getEnvironment()).thenReturn(env); when(applicationContext.getEnvironment()).thenReturn(env);
when(env.getPropertySources()).thenReturn(mutablePropertySources); when(env.getPropertySources()).thenReturn(mutablePropertySources);
apolloConfigManager.setApplicationContext(applicationContext); apolloConfigManager.setApplicationContext(applicationContext);
ReflectionTestUtils.setField(apolloConfigManager, "configLoaderManager", configLoaderManager); ReflectionTestUtils.setField(apolloConfigManager, "configLoaderManager", configLoaderManager);
ReflectionTestUtils.setField(apolloConfigManager, "scope", scope); ReflectionTestUtils.setField(apolloConfigManager, "scope", scope);
} }
@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
singletonProtector.set(null); .getField(ApolloConfigManager.class, "singletonProtector");
} singletonProtector.set(null);
}
@Test(expected = RuntimeException.class)
public void testInvalidApplicationContext() { @Test(expected = RuntimeException.class)
ApplicationContext someInvalidApplication = mock(ApplicationContext.class); public void testInvalidApplicationContext() {
apolloConfigManager.setApplicationContext(someInvalidApplication); ApplicationContext someInvalidApplication = mock(ApplicationContext.class);
} apolloConfigManager.setApplicationContext(someInvalidApplication);
}
@Test
public void testInitializePropertySourceSuccessfully() { @Test
CompositePropertySource somePropertySource = mock(CompositePropertySource.class); public void testInitializePropertySourceSuccessfully() {
final ArgumentCaptor<CompositePropertySource> captor = ArgumentCaptor.forClass(CompositePropertySource.class); CompositePropertySource somePropertySource = mock(CompositePropertySource.class);
final ArgumentCaptor<CompositePropertySource>
when(configLoaderManager.loadPropertySource()).thenReturn(somePropertySource); captor =
ArgumentCaptor.forClass(CompositePropertySource.class);
apolloConfigManager.initializePropertySource();
when(configLoaderManager.loadPropertySource()).thenReturn(somePropertySource);
verify(configLoaderManager, times(1)).loadPropertySource();
verify(mutablePropertySources, times(1)).addFirst(captor.capture()); apolloConfigManager.initializePropertySource();
final CompositePropertySource insertedPropertySource = captor.getValue(); verify(configLoaderManager, times(1)).loadPropertySource();
verify(mutablePropertySources, times(1)).addFirst(captor.capture());
assertEquals(insertedPropertySource, somePropertySource);
} final CompositePropertySource insertedPropertySource = captor.getValue();
@Test assertEquals(insertedPropertySource, somePropertySource);
public void testPostProcessBeanDefinitionRegistry() { }
doNothing().when(apolloConfigManager).initializePropertySource();
@Test
apolloConfigManager.postProcessBeanDefinitionRegistry(beanDefinitionRegistry); public void testPostProcessBeanDefinitionRegistry() {
doNothing().when(apolloConfigManager).initializePropertySource();
verify(beanDefinitionRegistry, times(2)).registerBeanDefinition(anyString(), any(BeanDefinition.class));
} apolloConfigManager.postProcessBeanDefinitionRegistry(beanDefinitionRegistry);
@Test verify(beanDefinitionRegistry, times(2))
public void testUpdatePropertySourceWithChanges() throws Exception { .registerBeanDefinition(anyString(), any(BeanDefinition.class));
PropertySourceReloadResult somePropertySourceReloadResult = mock(PropertySourceReloadResult.class); }
CompositePropertySource somePropertySource = mock(CompositePropertySource.class);
List<PropertyChange> someChanges = mock(List.class); @Test
public void testUpdatePropertySourceWithChanges() throws Exception {
when(somePropertySourceReloadResult.hasChanges()).thenReturn(true); PropertySourceReloadResult
when(somePropertySourceReloadResult.getPropertySource()).thenReturn(somePropertySource); somePropertySourceReloadResult =
when(somePropertySourceReloadResult.getChanges()).thenReturn(someChanges); mock(PropertySourceReloadResult.class);
when(configLoaderManager.reloadPropertySource()).thenReturn(somePropertySourceReloadResult); CompositePropertySource somePropertySource = mock(CompositePropertySource.class);
List<PropertyChange> someChanges = mock(List.class);
List<PropertyChange> result = apolloConfigManager.updatePropertySource();
when(somePropertySourceReloadResult.hasChanges()).thenReturn(true);
assertEquals(someChanges, result); when(somePropertySourceReloadResult.getPropertySource()).thenReturn(somePropertySource);
verify(scope, times(1)).refreshAll(); when(somePropertySourceReloadResult.getChanges()).thenReturn(someChanges);
} when(configLoaderManager.reloadPropertySource()).thenReturn(somePropertySourceReloadResult);
@Test List<PropertyChange> result = apolloConfigManager.updatePropertySource();
public void testUpdatePropertySourceWithNoChange() throws Exception {
PropertySourceReloadResult somePropertySourceReloadResult = mock(PropertySourceReloadResult.class); assertEquals(someChanges, result);
CompositePropertySource somePropertySource = mock(CompositePropertySource.class); verify(scope, times(1)).refreshAll();
List<PropertyChange> emptyChanges = Collections.emptyList(); }
when(somePropertySourceReloadResult.hasChanges()).thenReturn(false); @Test
when(somePropertySourceReloadResult.getPropertySource()).thenReturn(somePropertySource); public void testUpdatePropertySourceWithNoChange() throws Exception {
when(somePropertySourceReloadResult.getChanges()).thenReturn(emptyChanges); PropertySourceReloadResult
when(configLoaderManager.reloadPropertySource()).thenReturn(somePropertySourceReloadResult); somePropertySourceReloadResult =
mock(PropertySourceReloadResult.class);
List<PropertyChange> result = apolloConfigManager.updatePropertySource(); CompositePropertySource somePropertySource = mock(CompositePropertySource.class);
List<PropertyChange> emptyChanges = Collections.emptyList();
assertEquals(emptyChanges, result);
verify(scope, never()).refreshAll(); when(somePropertySourceReloadResult.hasChanges()).thenReturn(false);
when(somePropertySourceReloadResult.getPropertySource()).thenReturn(somePropertySource);
} when(somePropertySourceReloadResult.getChanges()).thenReturn(emptyChanges);
when(configLoaderManager.reloadPropertySource()).thenReturn(somePropertySourceReloadResult);
List<PropertyChange> result = apolloConfigManager.updatePropertySource();
assertEquals(emptyChanges, result);
verify(scope, never()).refreshAll();
}
} }
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,60 +21,65 @@ import java.util.Properties; ...@@ -19,60 +21,65 @@ 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)
*/ */
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class ConfigUtilTest { public class ConfigUtilTest {
private ConfigUtil configUtil; private ConfigUtil configUtil;
@Mock @Mock
private ConfigurableApplicationContext applicationContext; private ConfigurableApplicationContext applicationContext;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
configUtil = spy(ConfigUtil.getInstance()); configUtil = spy(ConfigUtil.getInstance());
configUtil.setApplicationContext(applicationContext); configUtil.setApplicationContext(applicationContext);
} }
@Test @Test
public void testLoadApolloRegistriesSuccessfully() throws Exception { public void testLoadApolloRegistriesSuccessfully() throws Exception {
Properties someProperties = mock(Properties.class); Properties someProperties = mock(Properties.class);
preparePropertiesFromLocalResource(someProperties); preparePropertiesFromLocalResource(someProperties);
String someAppId = "1"; String someAppId = "1";
String someVersionId = "someVersion"; String someVersionId = "someVersion";
when(someProperties.containsKey(Constants.APP_ID)).thenReturn(true); when(someProperties.containsKey(Constants.APP_ID)).thenReturn(true);
when(someProperties.getProperty(Constants.APP_ID)).thenReturn(someAppId); when(someProperties.getProperty(Constants.APP_ID)).thenReturn(someAppId);
when(someProperties.getProperty(eq(Constants.VERSION), anyString())).thenReturn(someVersionId); when(someProperties.getProperty(eq(Constants.VERSION), anyString())).thenReturn(someVersionId);
List<ApolloRegistry> apolloRegistries = configUtil.loadApolloRegistries(); List<ApolloRegistry> apolloRegistries = configUtil.loadApolloRegistries();
ApolloRegistry apolloRegistry = apolloRegistries.get(0); ApolloRegistry apolloRegistry = apolloRegistries.get(0);
assertEquals(1, apolloRegistries.size()); assertEquals(1, apolloRegistries.size());
assertEquals(Long.parseLong(someAppId), apolloRegistry.getAppId()); assertEquals(Long.parseLong(someAppId), apolloRegistry.getAppId());
assertEquals(someVersionId, apolloRegistry.getVersion()); assertEquals(someVersionId, apolloRegistry.getVersion());
} }
@Test @Test
public void testLoadApolloRegistriesError() throws Exception { public void testLoadApolloRegistriesError() throws Exception {
preparePropertiesFromLocalResource(null); preparePropertiesFromLocalResource(null);
List<ApolloRegistry> apolloRegistries = configUtil.loadApolloRegistries(); List<ApolloRegistry> apolloRegistries = configUtil.loadApolloRegistries();
assertTrue(apolloRegistries.isEmpty()); assertTrue(apolloRegistries.isEmpty());
} }
private void preparePropertiesFromLocalResource(Properties someProperties) throws IOException { private void preparePropertiesFromLocalResource(Properties someProperties) throws IOException {
ClassLoader someClassLoader = mock(ClassLoader.class); ClassLoader someClassLoader = mock(ClassLoader.class);
Thread.currentThread().setContextClassLoader(someClassLoader); Thread.currentThread().setContextClassLoader(someClassLoader);
URL someUrl = new URL("http", "somepath/", "someFile"); URL someUrl = new URL("http", "somepath/", "someFile");
Enumeration<URL> someResourceUrls = Collections.enumeration(Lists.newArrayList(someUrl)); Enumeration<URL> someResourceUrls = Collections.enumeration(Lists.newArrayList(someUrl));
when(someClassLoader.getResources(anyString())).thenReturn(someResourceUrls); when(someClassLoader.getResources(anyString())).thenReturn(someResourceUrls);
doReturn(someProperties).when(configUtil).loadPropertiesFromResourceURL(someUrl); doReturn(someProperties).when(configUtil).loadPropertiesFromResourceURL(someUrl);
} }
} }
...@@ -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>
......
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent> <parent>
<groupId>com.ctrip.apollo</groupId> <groupId>com.ctrip.apollo</groupId>
<artifactId>apollo</artifactId> <artifactId>apollo</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>apollo-configservice</artifactId> <artifactId>apollo-configservice</artifactId>
<name>Apollo ConfigService</name> <name>Apollo ConfigService</name>
<dependencies> <dependencies>
<!-- apollo --> <!-- apollo -->
<dependency> <dependency>
<groupId>com.ctrip.apollo</groupId> <groupId>com.ctrip.apollo</groupId>
<artifactId>apollo-biz</artifactId> <artifactId>apollo-biz</artifactId>
</dependency> </dependency>
<!-- end of apollo --> <!-- end of apollo -->
<!-- redis --> <!-- redis -->
<!-- <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <!-- <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId>
</dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId>
</dependency> --> </dependency> -->
<!-- end of redis --> <!-- end of redis -->
<!-- eureka --> <!-- eureka -->
<dependency> <dependency>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId> <artifactId>spring-cloud-starter-eureka-server</artifactId>
<exclusions> <exclusions>
<exclusion> <exclusion>
<artifactId> <artifactId>
spring-cloud-starter-archaius spring-cloud-starter-archaius
</artifactId> </artifactId>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>spring-cloud-starter-ribbon</artifactId> <artifactId>spring-cloud-starter-ribbon</artifactId>
<groupId>org.springframework.cloud</groupId> <groupId>org.springframework.cloud</groupId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>ribbon-eureka</artifactId> <artifactId>ribbon-eureka</artifactId>
<groupId>com.netflix.ribbon</groupId> <groupId>com.netflix.ribbon</groupId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>aws-java-sdk-core</artifactId> <artifactId>aws-java-sdk-core</artifactId>
<groupId>com.amazonaws</groupId> <groupId>com.amazonaws</groupId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>aws-java-sdk-ec2</artifactId> <artifactId>aws-java-sdk-ec2</artifactId>
<groupId>com.amazonaws</groupId> <groupId>com.amazonaws</groupId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>aws-java-sdk-autoscaling</artifactId> <artifactId>aws-java-sdk-autoscaling</artifactId>
<groupId>com.amazonaws</groupId> <groupId>com.amazonaws</groupId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>aws-java-sdk-sts</artifactId> <artifactId>aws-java-sdk-sts</artifactId>
<groupId>com.amazonaws</groupId> <groupId>com.amazonaws</groupId>
</exclusion> </exclusion>
<exclusion> <exclusion>
<artifactId>aws-java-sdk-route53</artifactId> <artifactId>aws-java-sdk-route53</artifactId>
<groupId>com.amazonaws</groupId> <groupId>com.amazonaws</groupId>
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<!-- end of eureka --> <!-- end of eureka -->
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<configuration> <configuration>
<executable>true</executable> <executable>true</executable>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
</project> </project>
...@@ -6,15 +6,15 @@ import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; ...@@ -6,15 +6,15 @@ import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
/** /**
* Spring boot application entry point * Spring boot application entry point
* *
* @author Jason Song(song_s@ctrip.com) * @author Jason Song(song_s@ctrip.com)
*/ */
@SpringBootApplication @SpringBootApplication
@EnableEurekaServer @EnableEurekaServer
public class ServerApplication { public class ServerApplication {
public static void main(String[] args) { public static void main(String[] args) {
new SpringApplicationBuilder(ServerApplication.class).web(true).run(args); new SpringApplicationBuilder(ServerApplication.class).web(true).run(args);
} }
} }
...@@ -5,13 +5,14 @@ import org.springframework.boot.context.web.SpringBootServletInitializer; ...@@ -5,13 +5,14 @@ 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 {
@Override @Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ServerApplication.class); return application.sources(ServerApplication.class);
} }
} }
...@@ -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)
...@@ -15,36 +21,38 @@ import java.io.IOException; ...@@ -15,36 +21,38 @@ import java.io.IOException;
@RestController @RestController
@RequestMapping("/config") @RequestMapping("/config")
public class ConfigController { public class ConfigController {
@Resource(name = "configService") @Resource(name = "configService")
private ConfigService configService; private ConfigService configService;
@RequestMapping(value = "/{appId}/{clusterName}/{versionName:.*}", method = RequestMethod.GET) @RequestMapping(value = "/{appId}/{clusterName}/{versionName:.*}", method = RequestMethod.GET)
public ApolloConfig queryConfig(@PathVariable long appId, public ApolloConfig queryConfig(@PathVariable long appId,
@PathVariable String clusterName, @PathVariable String clusterName,
@PathVariable String versionName, @PathVariable String versionName,
@RequestParam(value = "releaseId", defaultValue = "-1") long clientSideReleaseId, @RequestParam(value = "releaseId", defaultValue = "-1") long clientSideReleaseId,
HttpServletResponse response) throws IOException { HttpServletResponse response) throws IOException {
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,
return null; versionName));
} return null;
if (version.getReleaseId() == clientSideReleaseId) {
//Client side configuration is the same with server side, return 304
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return null;
}
ApolloConfig apolloConfig =
configService.loadConfigByVersionAndClusterName(version, clusterName);
if (apolloConfig == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND,
String.format("Could not load config with releaseId: %d, clusterName: %s", version.getReleaseId(), clusterName));
return null;
}
return apolloConfig;
} }
if (version.getReleaseId() == clientSideReleaseId) {
//Client side configuration is the same with server side, return 304
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return null;
}
ApolloConfig apolloConfig =
configService.loadConfigByVersionAndClusterName(version, clusterName);
if (apolloConfig == null) {
response.sendError(HttpServletResponse.SC_NOT_FOUND,
String.format("Could not load config with releaseId: %d, clusterName: %s",
version.getReleaseId(), clusterName));
return null;
}
return apolloConfig;
}
} }
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,98 +15,128 @@ import javax.servlet.http.HttpServletResponse; ...@@ -15,98 +15,128 @@ 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)
*/ */
@RunWith(MockitoJUnitRunner.class) @RunWith(MockitoJUnitRunner.class)
public class ConfigControllerTest { public class ConfigControllerTest {
private ConfigController configController; private ConfigController configController;
@Mock @Mock
private ConfigService configService; private ConfigService configService;
@Before @Before
public void setUp() throws Exception { public void setUp() throws Exception {
configController = new ConfigController(); configController = new ConfigController();
ReflectionTestUtils.setField(configController, "configService", configService); ReflectionTestUtils.setField(configController, "configService", configService);
} }
@Test @Test
public void testQueryConfig() throws Exception { public void testQueryConfig() throws Exception {
ApolloConfig someApolloConfig = mock(ApolloConfig.class); ApolloConfig someApolloConfig = mock(ApolloConfig.class);
long someAppId = 1; long someAppId = 1;
String someClusterName = "someClusterName"; String someClusterName = "someClusterName";
String someVersionName = "someVersion"; String someVersionName = "someVersion";
long someClientSideReleaseId = 1; long someClientSideReleaseId = 1;
long someServerSideNewReleaseId = 2; long someServerSideNewReleaseId = 2;
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))
when(someVersion.getReleaseId()).thenReturn(someServerSideNewReleaseId); .thenReturn(someVersion);
when(configService.loadConfigByVersionAndClusterName(someVersion, someClusterName)).thenReturn(someApolloConfig); when(someVersion.getReleaseId()).thenReturn(someServerSideNewReleaseId);
when(configService.loadConfigByVersionAndClusterName(someVersion, someClusterName))
ApolloConfig result = configController.queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId, someResponse); .thenReturn(someApolloConfig);
assertEquals(someApolloConfig, result); ApolloConfig
verify(configService, times(1)).loadVersionByAppIdAndVersionName(someAppId, someVersionName); result =
verify(configService, times(1)).loadConfigByVersionAndClusterName(someVersion, someClusterName); configController
} .queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId,
someResponse);
@Test
public void testQueryConfigWithVersionNotFound() throws Exception { assertEquals(someApolloConfig, result);
long someAppId = 1; verify(configService, times(1)).loadVersionByAppIdAndVersionName(someAppId, someVersionName);
String someClusterName = "someClusterName"; verify(configService, times(1)).loadConfigByVersionAndClusterName(someVersion, someClusterName);
String someVersionName = "someVersion"; }
long someClientSideReleaseId = 1;
HttpServletResponse someResponse = mock(HttpServletResponse.class); @Test
public void testQueryConfigWithVersionNotFound() throws Exception {
when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName)).thenReturn(null); long someAppId = 1;
String someClusterName = "someClusterName";
ApolloConfig result = configController.queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId, someResponse); String someVersionName = "someVersion";
long someClientSideReleaseId = 1;
assertNull(result); HttpServletResponse someResponse = mock(HttpServletResponse.class);
verify(someResponse, times(1)).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
} when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName))
.thenReturn(null);
@Test
public void testQueryConfigWithApolloConfigNotFound() throws Exception { ApolloConfig
long someAppId = 1; result =
String someClusterName = "someClusterName"; configController
String someVersionName = "someVersion"; .queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId,
long someClientSideReleaseId = 1; someResponse);
long someServerSideNewReleaseId = 2;
HttpServletResponse someResponse = mock(HttpServletResponse.class); assertNull(result);
Version someVersion = mock(Version.class); verify(someResponse, times(1)).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
}
when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName)).thenReturn(someVersion);
when(someVersion.getReleaseId()).thenReturn(someServerSideNewReleaseId); @Test
when(configService.loadConfigByVersionAndClusterName(someVersion, someClusterName)).thenReturn(null); public void testQueryConfigWithApolloConfigNotFound() throws Exception {
long someAppId = 1;
ApolloConfig result = configController.queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId, someResponse); String someClusterName = "someClusterName";
String someVersionName = "someVersion";
assertNull(result); long someClientSideReleaseId = 1;
verify(someResponse, times(1)).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString()); long someServerSideNewReleaseId = 2;
} HttpServletResponse someResponse = mock(HttpServletResponse.class);
Version someVersion = mock(Version.class);
@Test
public void testQueryConfigWithApolloConfigNotModified() throws Exception { when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName))
long someAppId = 1; .thenReturn(someVersion);
String someClusterName = "someClusterName"; when(someVersion.getReleaseId()).thenReturn(someServerSideNewReleaseId);
String someVersionName = "someVersion"; when(configService.loadConfigByVersionAndClusterName(someVersion, someClusterName))
long someClientSideReleaseId = 1; .thenReturn(null);
long someServerSideReleaseId = someClientSideReleaseId;
HttpServletResponse someResponse = mock(HttpServletResponse.class); ApolloConfig
Version someVersion = mock(Version.class); result =
configController
when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName)).thenReturn(someVersion); .queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId,
when(someVersion.getReleaseId()).thenReturn(someServerSideReleaseId); someResponse);
ApolloConfig result = configController.queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId, someResponse); assertNull(result);
verify(someResponse, times(1)).sendError(eq(HttpServletResponse.SC_NOT_FOUND), anyString());
assertNull(result); }
verify(someResponse, times(1)).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
verify(configService, never()).loadConfigByVersionAndClusterName(any(Version.class), anyString()); @Test
} public void testQueryConfigWithApolloConfigNotModified() throws Exception {
long someAppId = 1;
String someClusterName = "someClusterName";
String someVersionName = "someVersion";
long someClientSideReleaseId = 1;
long someServerSideReleaseId = someClientSideReleaseId;
HttpServletResponse someResponse = mock(HttpServletResponse.class);
Version someVersion = mock(Version.class);
when(configService.loadVersionByAppIdAndVersionName(someAppId, someVersionName))
.thenReturn(someVersion);
when(someVersion.getReleaseId()).thenReturn(someServerSideReleaseId);
ApolloConfig
result =
configController
.queryConfig(someAppId, someClusterName, someVersionName, someClientSideReleaseId,
someResponse);
assertNull(result);
verify(someResponse, times(1)).setStatus(HttpServletResponse.SC_NOT_MODIFIED);
verify(configService, never())
.loadConfigByVersionAndClusterName(any(Version.class), anyString());
}
} }
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent> <parent>
<groupId>com.ctrip.apollo</groupId> <groupId>com.ctrip.apollo</groupId>
<artifactId>apollo</artifactId> <artifactId>apollo</artifactId>
<version>0.0.1-SNAPSHOT</version> <version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>apollo-core</artifactId> <artifactId>apollo-core</artifactId>
<name>Apollo Core</name> <name>Apollo Core</name>
<packaging>jar</packaging> <packaging>jar</packaging>
<dependencies> <dependencies>
<!-- json --> <!-- json -->
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId> <artifactId>jackson-annotations</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId> <artifactId>jackson-databind</artifactId>
</dependency> </dependency>
<!-- end of json --> <!-- end of json -->
<!-- util --> <!-- util -->
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>com.google.guava</groupId>
<artifactId>guava</artifactId> <artifactId>guava</artifactId>
</dependency> </dependency>
<!-- end of util --> <!-- end of util -->
<!-- log --> <!-- log -->
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
</dependency> </dependency>
<!-- end of log --> <!-- end of log -->
</dependencies> </dependencies>
</project> </project>
package com.ctrip.apollo; 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;
public enum Env { public enum Env {
LOCAL, DEV, FWS, FAT, UAT, LPT, PRO, TOOLS LOCAL, DEV, FWS, FAT, UAT, LPT, PRO, TOOLS
} }
public static void initialize(Env env) { public static void initialize(Env env) {
m_env = env; m_env = env;
} }
public static Env getEnv() { public static Env getEnv() {
return m_env; return m_env;
} }
} }
...@@ -2,6 +2,6 @@ package com.ctrip.apollo.core; ...@@ -2,6 +2,6 @@ package com.ctrip.apollo.core;
public interface Constants { public interface Constants {
String DEFAULT_CLUSTER_NAME = "default-cluster-name"; String DEFAULT_CLUSTER_NAME = "default-cluster-name";
} }
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";
......
...@@ -7,6 +7,6 @@ public class ServiceNameConsts { ...@@ -7,6 +7,6 @@ public class ServiceNameConsts {
public static final String APOLLO_CONFIGSERVICE = "apollo-configservice"; public static final String APOLLO_CONFIGSERVICE = "apollo-configservice";
public static final String APOLLO_ADMINSERVICE = "apollo-adminservice"; public static final String APOLLO_ADMINSERVICE = "apollo-adminservice";
public static final String APOLLO_PORTAL = "apollo-portal"; public static final String APOLLO_PORTAL = "apollo-portal";
} }
...@@ -2,33 +2,33 @@ package com.ctrip.apollo.core.dto; ...@@ -2,33 +2,33 @@ package com.ctrip.apollo.core.dto;
public class ClusterDTO { public class ClusterDTO {
private long id; private long id;
private String name; private String name;
private long appId; private long appId;
public long getId() { public long getId() {
return id; return id;
} }
public void setId(long id) { public void setId(long id) {
this.id = id; this.id = id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public long getAppId() { public long getAppId() {
return appId; return appId;
} }
public void setAppId(long appId) { public void setAppId(long appId) {
this.appId = appId; this.appId = appId;
} }
} }
...@@ -7,17 +7,17 @@ import java.util.List; ...@@ -7,17 +7,17 @@ import java.util.List;
public class DNSUtil { public class DNSUtil {
public static List<String> resolve(String domainName) throws UnknownHostException { public static List<String> resolve(String domainName) throws UnknownHostException {
List<String> result = new ArrayList<String>(); List<String> result = new ArrayList<String>();
InetAddress[] addresses = InetAddress.getAllByName(domainName); InetAddress[] addresses = InetAddress.getAllByName(domainName);
if (addresses != null) { if (addresses != null) {
for (InetAddress addr : addresses) { for (InetAddress addr : addresses) {
result.add(addr.getHostAddress()); result.add(addr.getHostAddress());
} }
} }
return result; return result;
} }
} }
...@@ -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>
......
This diff is collapsed.
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