Apply formatting and code cleanup rules

This commit is contained in:
Phillip Webb
2015-01-14 11:42:42 -08:00
parent 8ac6edc577
commit 4d941e1c0a
20 changed files with 276 additions and 237 deletions

View File

@@ -1,5 +1,7 @@
package org.springframework.cloud.client;
import java.util.List;
import org.springframework.boot.actuate.health.HealthAggregator;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
@@ -13,8 +15,6 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import java.util.List;
/**
* @author Spencer Gibb
*/
@@ -28,12 +28,14 @@ public class CommonsClientAutoConfiguration {
@ConditionalOnExpression("${spring.cloud.discovery.enabled:true}")
protected static class HealthConfiguration {
@Bean
public DiscoveryClientHealthIndicator instancesHealthIndicator(DiscoveryClient discoveryClient) {
public DiscoveryClientHealthIndicator instancesHealthIndicator(
DiscoveryClient discoveryClient) {
return new DiscoveryClientHealthIndicator(discoveryClient);
}
@Bean
public DiscoveryCompositeHealthIndicator discoveryHealthIndicator(HealthAggregator aggregator, List<DiscoveryHealthIndicator> indicators) {
public DiscoveryCompositeHealthIndicator discoveryHealthIndicator(
HealthAggregator aggregator, List<DiscoveryHealthIndicator> indicators) {
return new DiscoveryCompositeHealthIndicator(aggregator, indicators);
}
}

View File

@@ -7,7 +7,7 @@ import lombok.Data;
*/
@Data
public class DefaultServiceInstance implements ServiceInstance {
private final String serviceId;
private final String host;
private final int port;
private final String serviceId;
private final String host;
private final int port;
}

View File

@@ -1,12 +1,12 @@
package org.springframework.cloud.client;
/**
* @author Spencer Gibb
* TODO: name? Server? HostAndPort? Instance?
* @author Spencer Gibb TODO: name? Server? HostAndPort? Instance?
*/
public interface ServiceInstance {
public String getServiceId();
public String getHost();
public int getPort();
public String getServiceId();
public String getHost();
public int getPort();
}

View File

@@ -33,7 +33,7 @@ public abstract class SingleImplementationImportSelector<T> implements
@SuppressWarnings("unchecked")
protected SingleImplementationImportSelector() {
annotationClass = (Class<T>) GenericTypeResolver.resolveTypeArgument(
this.annotationClass = (Class<T>) GenericTypeResolver.resolveTypeArgument(
this.getClass(), SingleImplementationImportSelector.class);
}
@@ -43,14 +43,14 @@ public abstract class SingleImplementationImportSelector<T> implements
return new String[0];
}
AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata
.getAnnotationAttributes(annotationClass.getName(), true));
.getAnnotationAttributes(this.annotationClass.getName(), true));
Assert.notNull(attributes, "No " + getSimpleName() + " attributes found. Is "
+ metadata.getClassName() + " annotated with @" + getSimpleName() + "?");
// Find all possible auto configuration classes, filtering duplicates
List<String> factories = new ArrayList<>(new LinkedHashSet<>(
SpringFactoriesLoader.loadFactoryNames(annotationClass,
SpringFactoriesLoader.loadFactoryNames(this.annotationClass,
this.beanClassLoader)));
if (factories.size() > 1) {
@@ -69,15 +69,15 @@ public abstract class SingleImplementationImportSelector<T> implements
protected abstract boolean isEnabled();
protected String getSimpleName() {
return annotationClass.getSimpleName();
return this.annotationClass.getSimpleName();
}
protected Class<T> getAnnotationClass() {
return annotationClass;
return this.annotationClass;
}
protected Environment getEnvironment() {
return environment;
return this.environment;
}
@Override

View File

@@ -1,8 +1,13 @@
package org.springframework.cloud.client.circuitbreaker;
import org.springframework.context.annotation.Import;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.*;
import org.springframework.context.annotation.Import;
/**
* @author Spencer Gibb

View File

@@ -9,10 +9,12 @@ import org.springframework.core.annotation.Order;
* @author Spencer Gibb
*/
@Order(Ordered.LOWEST_PRECEDENCE - 100)
public class EnableCircuitBreakerImportSelector extends SingleImplementationImportSelector<EnableCircuitBreaker> {
public class EnableCircuitBreakerImportSelector extends
SingleImplementationImportSelector<EnableCircuitBreaker> {
@Override
protected boolean isEnabled() {
return new RelaxedPropertyResolver(getEnvironment()).getProperty("spring.cloud.circuit.breaker.enabled", Boolean.class, Boolean.TRUE);
return new RelaxedPropertyResolver(getEnvironment()).getProperty(
"spring.cloud.circuit.breaker.enabled", Boolean.class, Boolean.TRUE);
}
}

View File

@@ -1,109 +1,117 @@
package org.springframework.cloud.client.discovery;
import javax.annotation.PreDestroy;
import org.springframework.beans.BeansException;
import org.springframework.boot.actuate.autoconfigure.ManagementServerProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import javax.annotation.PreDestroy;
/**
* @author Spencer Gibb
*/
public abstract class AbstractDiscoveryLifecycle implements DiscoveryLifecycle, ApplicationContextAware {
public abstract class AbstractDiscoveryLifecycle implements DiscoveryLifecycle,
ApplicationContextAware {
protected boolean autoStartup = true;
protected boolean running;
protected int order = 0;
protected ApplicationContext context;
protected Environment environment;
protected boolean autoStartup = true;
protected boolean running;
protected int order = 0;
protected ApplicationContext context;
protected Environment environment;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
environment = context.getEnvironment();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context = applicationContext;
this.environment = this.context.getEnvironment();
}
@Override
public boolean isAutoStartup() {
return autoStartup;
}
@Override
public boolean isAutoStartup() {
return this.autoStartup;
}
@Override
public void stop(Runnable callback) {
stop();
callback.run();
}
@Override
public void stop(Runnable callback) {
stop();
callback.run();
}
@Override
public void start() {
if (!isEnabled()) return;
@Override
public void start() {
if (!isEnabled()) {
return;
}
register();
if (ManagementServerPortUtils.isDifferent(context)) {
registerManagement();
}
context.publishEvent(new InstanceRegisteredEvent<>(this, getConfiguration()));
running = true;
}
register();
if (ManagementServerPortUtils.isDifferent(this.context)) {
registerManagement();
}
this.context
.publishEvent(new InstanceRegisteredEvent<>(this, getConfiguration()));
this.running = true;
}
protected abstract Object getConfiguration();
protected abstract Object getConfiguration();
protected abstract void register();
protected abstract void register();
protected void registerManagement() {}
protected void registerManagement() {
}
protected abstract void deregister();
protected abstract void deregister();
protected void deregisterManagement() {}
protected void deregisterManagement() {
}
protected abstract boolean isEnabled();
protected abstract boolean isEnabled();
protected String getManagementServiceId() {
return context.getId() + ":management"; //TODO: configurable management suffix
}
protected String getManagementServiceId() {
return this.context.getId() + ":management"; // TODO: configurable management
// suffix
}
protected String getManagementServiceName() {
return getAppName() + ":management"; //TODO: configurable management suffix
}
protected String getManagementServiceName() {
return getAppName() + ":management"; // TODO: configurable management suffix
}
protected Integer getManagementPort() {
return context.getBean(ManagementServerProperties.class).getPort();
}
protected Integer getManagementPort() {
return this.context.getBean(ManagementServerProperties.class).getPort();
}
protected String getAppName() {
return environment.getProperty("spring.application.name");
}
protected String getAppName() {
return this.environment.getProperty("spring.application.name");
}
@Override
public void stop() {
if (isEnabled()) {
deregister();
if (getManagementPort() != null) {
deregisterManagement();
}
}
running = false;
}
@Override
public void stop() {
if (isEnabled()) {
deregister();
if (getManagementPort() != null) {
deregisterManagement();
}
}
this.running = false;
}
@PreDestroy
public void destroy() {
stop();
}
@PreDestroy
public void destroy() {
stop();
}
@Override
public boolean isRunning() {
return running;
}
@Override
public boolean isRunning() {
return this.running;
}
@Override
public int getOrder() {
return order;
}
@Override
public int getOrder() {
return this.order;
}
@Override
public int getPhase() {
return 0;
}
@Override
public int getPhase() {
return 0;
}
}

View File

@@ -1,32 +1,32 @@
package org.springframework.cloud.client.discovery;
import org.springframework.cloud.client.ServiceInstance;
import java.util.List;
import org.springframework.cloud.client.ServiceInstance;
/**
* @author Spencer Gibb
*/
//TODO: merge with LoadBalancerClient?
// TODO: merge with LoadBalancerClient?
public interface DiscoveryClient {
public String description();
/**
* @return ServiceInstance with information used to register the local service
*/
public ServiceInstance getLocalServiceInstance();
/**
* @return ServiceInstance with information used to register the local service
*/
public ServiceInstance getLocalServiceInstance();
/**
* Get all ServiceInstance's associated with a particular serviceId
* @param serviceId the serviceId to query
* @return a List of ServiceInstance
*/
public List<ServiceInstance> getInstances(String serviceId);
/**
* Get all ServiceInstance's associated with a particular serviceId
* @param serviceId the serviceId to query
* @return a List of ServiceInstance
*/
public List<ServiceInstance> getInstances(String serviceId);
public List<ServiceInstance> getAllInstances();
public List<ServiceInstance> getAllInstances();
/**
* @return all known service id's
*/
public List<String> getServices();
/**
* @return all known service id's
*/
public List<String> getServices();
}

View File

@@ -24,16 +24,17 @@ public class DiscoveryClientHealthIndicator implements DiscoveryHealthIndicator,
@Override
public Health health() {
Health.Builder builder = new Health.Builder();
try {
List<String> services = discoveryClient.getServices();
builder.status(new Status("UP", discoveryClient.description()))
try {
List<String> services = this.discoveryClient.getServices();
builder.status(new Status("UP", this.discoveryClient.description()))
.withDetail("services", services);
} catch (Exception e) {
log.error("Error", e);
builder.down(e);
}
}
catch (Exception e) {
log.error("Error", e);
builder.down(e);
}
return builder.build();
}
}
@Override
public String getName() {
@@ -42,7 +43,7 @@ public class DiscoveryClientHealthIndicator implements DiscoveryHealthIndicator,
@Override
public int getOrder() {
return order;
return this.order;
}
public void setOrder(int order) {

View File

@@ -14,7 +14,8 @@ import org.springframework.boot.actuate.health.HealthIndicator;
public class DiscoveryCompositeHealthIndicator extends CompositeHealthIndicator {
@Autowired
public DiscoveryCompositeHealthIndicator(HealthAggregator healthAggregator, List<DiscoveryHealthIndicator> indicators) {
public DiscoveryCompositeHealthIndicator(HealthAggregator healthAggregator,
List<DiscoveryHealthIndicator> indicators) {
super(healthAggregator);
for (DiscoveryHealthIndicator indicator : indicators) {
addHealthIndicator(indicator.getName(), new Holder(indicator));
@@ -30,7 +31,7 @@ public class DiscoveryCompositeHealthIndicator extends CompositeHealthIndicator
@Override
public Health health() {
return delegate.health();
return this.delegate.health();
}
}
}

View File

@@ -16,6 +16,6 @@ public class DiscoveryHeartbeatEvent extends ApplicationEvent {
}
public Object getValue() {
return value;
return this.value;
}
}

View File

@@ -4,7 +4,12 @@ package org.springframework.cloud.client.discovery;
* @author Spencer Gibb
*/
import java.lang.annotation.*;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;

View File

@@ -3,23 +3,24 @@ package org.springframework.cloud.client.discovery;
import org.springframework.context.ApplicationEvent;
/**
* Event to be published after the local service instance registers itself with a discovery service
* Event to be published after the local service instance registers itself with a
* discovery service
* @author Spencer Gibb
*/
@SuppressWarnings("serial")
public class InstanceRegisteredEvent<T> extends ApplicationEvent {
private T config;
private T config;
/**
* @param source the component that published the event (never {@code null})
* @param config the configuration of the instance
*/
public InstanceRegisteredEvent(Object source, T config) {
super(source);
this.config = config;
}
/**
* @param source the component that published the event (never {@code null})
* @param config the configuration of the instance
*/
public InstanceRegisteredEvent(Object source, T config) {
super(source);
this.config = config;
}
public T getConfig() {
return config;
}
public T getConfig() {
return this.config;
}
}

View File

@@ -11,58 +11,58 @@ import org.springframework.web.context.WebApplicationContext;
*/
public class ManagementServerPortUtils {
//TODO: copied from EndpointWebMvcAutoConfiguration.ManagementServerPort
public static enum ManagementServerPort {
// TODO: copied from EndpointWebMvcAutoConfiguration.ManagementServerPort
public static enum ManagementServerPort {
DISABLE, SAME, DIFFERENT;
DISABLE, SAME, DIFFERENT;
public static ManagementServerPort get(BeanFactory beanFactory) {
public static ManagementServerPort get(BeanFactory beanFactory) {
ServerProperties serverProperties;
try {
serverProperties = beanFactory.getBean(ServerProperties.class);
}
catch (NoSuchBeanDefinitionException ex) {
serverProperties = new ServerProperties();
}
ServerProperties serverProperties;
try {
serverProperties = beanFactory.getBean(ServerProperties.class);
}
catch (NoSuchBeanDefinitionException ex) {
serverProperties = new ServerProperties();
}
ManagementServerProperties managementServerProperties;
try {
managementServerProperties = beanFactory
.getBean(ManagementServerProperties.class);
}
catch (NoSuchBeanDefinitionException ex) {
managementServerProperties = new ManagementServerProperties();
}
ManagementServerProperties managementServerProperties;
try {
managementServerProperties = beanFactory
.getBean(ManagementServerProperties.class);
}
catch (NoSuchBeanDefinitionException ex) {
managementServerProperties = new ManagementServerProperties();
}
Integer port = managementServerProperties.getPort();
if (port != null && port < 0) {
return DISABLE;
}
if (!(beanFactory instanceof WebApplicationContext)) {
// Current context is not a webapp
return DIFFERENT;
}
return ((port == null)
|| (serverProperties.getPort() == null && port.equals(8080))
|| (port != 0 && port.equals(serverProperties.getPort())) ? SAME
: DIFFERENT);
}
};
Integer port = managementServerProperties.getPort();
if (port != null && port < 0) {
return DISABLE;
}
if (!(beanFactory instanceof WebApplicationContext)) {
// Current context is not a webapp
return DIFFERENT;
}
return ((port == null)
|| (serverProperties.getPort() == null && port.equals(8080))
|| (port != 0 && port.equals(serverProperties.getPort())) ? SAME
: DIFFERENT);
}
};
public static ManagementServerPort get(BeanFactory beanFactory) {
return ManagementServerPort.get(beanFactory);
}
public static ManagementServerPort get(BeanFactory beanFactory) {
return ManagementServerPort.get(beanFactory);
}
public static boolean isDifferent(BeanFactory beanFactory) {
return get(beanFactory) == ManagementServerPort.DIFFERENT;
}
public static boolean isDifferent(BeanFactory beanFactory) {
return get(beanFactory) == ManagementServerPort.DIFFERENT;
}
public static boolean isDisabled(BeanFactory beanFactory) {
return get(beanFactory) == ManagementServerPort.DISABLE;
}
public static boolean isDisabled(BeanFactory beanFactory) {
return get(beanFactory) == ManagementServerPort.DISABLE;
}
public static boolean isSame(BeanFactory beanFactory) {
return get(beanFactory) == ManagementServerPort.SAME;
}
public static boolean isSame(BeanFactory beanFactory) {
return get(beanFactory) == ManagementServerPort.SAME;
}
}

View File

@@ -27,7 +27,7 @@ import org.springframework.cloud.client.ServiceInstance;
public class NoopDiscoveryClient implements DiscoveryClient {
private final ServiceInstance instance;
public NoopDiscoveryClient(ServiceInstance instance) {
this.instance = instance;
}
@@ -39,7 +39,7 @@ public class NoopDiscoveryClient implements DiscoveryClient {
@Override
public ServiceInstance getLocalServiceInstance() {
return instance;
return this.instance;
}
@Override

View File

@@ -45,7 +45,8 @@ import org.springframework.core.env.Environment;
@EnableConfigurationProperties
@ConditionalOnMissingClass(name = "com.netflix.discovery.EurekaClientConfig")
@ConditionalOnExpression("!${eureka.client.enabled:false}")
public class NoopDiscoveryClientConfiguration implements ApplicationListener<ContextRefreshedEvent> {
public class NoopDiscoveryClientConfiguration implements
ApplicationListener<ContextRefreshedEvent> {
private static final Logger logger = LoggerFactory
.getLogger(NoopDiscoveryClientConfiguration.class);
@@ -71,29 +72,30 @@ public class NoopDiscoveryClientConfiguration implements ApplicationListener<Con
logger.error("Cannot get host info", e);
}
int port = 0;
if (server != null && server.getPort() != null) {
port = server.getPort();
if (this.server != null && this.server.getPort() != null) {
port = this.server.getPort();
}
if (context instanceof EmbeddedWebApplicationContext) {
EmbeddedServletContainer container = ((EmbeddedWebApplicationContext) context)
if (this.context instanceof EmbeddedWebApplicationContext) {
EmbeddedServletContainer container = ((EmbeddedWebApplicationContext) this.context)
.getEmbeddedServletContainer();
if (container != null) {
// TODO: why is it null
port = container.getPort();
}
}
serviceInstance = new DefaultServiceInstance(environment.getProperty(
this.serviceInstance = new DefaultServiceInstance(this.environment.getProperty(
"spring.application.name", "application"), host, port);
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
context.publishEvent(new InstanceRegisteredEvent<Environment>(this, environment));
this.context.publishEvent(new InstanceRegisteredEvent<Environment>(this,
this.environment));
}
@Bean
public DiscoveryClient discoveryClient() {
return new NoopDiscoveryClient(serviceInstance);
return new NoopDiscoveryClient(this.serviceInstance);
}
}

View File

@@ -1,28 +1,31 @@
package org.springframework.cloud.client.loadbalancer;
import org.springframework.cloud.client.ServiceInstance;
import java.net.URI;
import org.springframework.cloud.client.ServiceInstance;
/**
* @author Spencer Gibb
*/
public interface LoadBalancerClient {
/**
* Choose a ServiceInstance from the LoadBalancer for the specified service
* @param serviceId the service id to look up the LoadBalancer
* @return a ServiceInstance that matches the serviceId
*/
public ServiceInstance choose(String serviceId);
/**
* Choose a ServiceInstance from the LoadBalancer for the specified service
* @param serviceId the service id to look up the LoadBalancer
* @return a ServiceInstance that matches the serviceId
*/
public ServiceInstance choose(String serviceId);
/**
* execute request using a ServiceInstance from the LoadBalancer for the specified service
* @param serviceId the service id to look up the LoadBalancer
* @param request allows implementations to execute pre and post actions such as incrementing metrics
* @return the result of the LoadBalancerRequest callback on the selected ServiceInstance
*/
public <T> T execute(String serviceId, LoadBalancerRequest<T> request);
/**
* execute request using a ServiceInstance from the LoadBalancer for the specified
* service
* @param serviceId the service id to look up the LoadBalancer
* @param request allows implementations to execute pre and post actions such as
* incrementing metrics
* @return the result of the LoadBalancerRequest callback on the selected
* ServiceInstance
*/
public <T> T execute(String serviceId, LoadBalancerRequest<T> request);
public URI reconstructURI(ServiceInstance instance, URI original);
public URI reconstructURI(ServiceInstance instance, URI original);
}

View File

@@ -6,5 +6,5 @@ import org.springframework.cloud.client.ServiceInstance;
* @author Spencer Gibb
*/
public interface LoadBalancerRequest<T> {
public T apply(ServiceInstance instance) throws Exception;
public T apply(ServiceInstance instance) throws Exception;
}

View File

@@ -2,25 +2,29 @@ package org.springframework.cloud.client;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
/**
* @author Spencer Gibb
*/
public class SingleImplementationImportSelectorTests {
@Test
public void testFindAnnotation() {
MyAnnotationImportSelector selector = new MyAnnotationImportSelector();
assertEquals("annotationClass was wrong", MyAnnotation.class, selector.getAnnotationClass());
}
@Test
public void testFindAnnotation() {
MyAnnotationImportSelector selector = new MyAnnotationImportSelector();
assertEquals("annotationClass was wrong", MyAnnotation.class,
selector.getAnnotationClass());
}
public static @interface MyAnnotation {}
public static class MyAnnotationImportSelector extends SingleImplementationImportSelector<MyAnnotation> {
@Override
protected boolean isEnabled() {
return true;
}
public static @interface MyAnnotation {
}
}
public static class MyAnnotationImportSelector extends
SingleImplementationImportSelector<MyAnnotation> {
@Override
protected boolean isEnabled() {
return true;
}
}
}

View File

@@ -1,6 +1,5 @@
package org.springframework.cloud.client.discovery;
import com.google.common.collect.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@@ -14,14 +13,19 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;
import com.google.common.collect.Lists;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Spencer Gibb
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {DiscoveryCompositeHealthIndicatorTests.Config.class, CommonsClientAutoConfiguration.class})
@ContextConfiguration(classes = { DiscoveryCompositeHealthIndicatorTests.Config.class,
CommonsClientAutoConfiguration.class })
public class DiscoveryCompositeHealthIndicatorTests {
@Autowired
@@ -60,12 +64,13 @@ public class DiscoveryCompositeHealthIndicatorTests {
@Test
public void testHealthIndicator() {
assertNotNull("healthIndicator was null", healthIndicator);
Health health = healthIndicator.health();
assertNotNull("healthIndicator was null", this.healthIndicator);
Health health = this.healthIndicator.health();
assertNotNull("health was null", health);
Status status = health.getStatus();
assertNotNull("status was null", status);
assertEquals("status code was wrong", "UP", status.getCode());
assertEquals("status desciption was wrong", "TestDiscoveryClient", status.getDescription());
assertEquals("status desciption was wrong", "TestDiscoveryClient",
status.getDescription());
}
}