diff --git a/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/ConsulBinder.java b/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/ConsulBinder.java index a37d142a..76a5962b 100644 --- a/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/ConsulBinder.java +++ b/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/ConsulBinder.java @@ -29,8 +29,7 @@ import org.springframework.util.Assert; /** * @author Spencer Gibb */ -public class ConsulBinder - extends AbstractBinder { +public class ConsulBinder extends AbstractBinder { private static final String BEAN_NAME_TEMPLATE = "outbound.%s"; @@ -41,10 +40,9 @@ public class ConsulBinder } @Override - protected Binding doBindConsumer(String name, String group, - MessageChannel inputChannel, ConsumerProperties properties) { - ConsulInboundMessageProducer messageProducer = new ConsulInboundMessageProducer( - this.eventService); + protected Binding doBindConsumer(String name, String group, MessageChannel inputChannel, + ConsumerProperties properties) { + ConsulInboundMessageProducer messageProducer = new ConsulInboundMessageProducer(this.eventService); messageProducer.setOutputChannel(inputChannel); messageProducer.setBeanFactory(this.getBeanFactory()); messageProducer.afterPropertiesSet(); @@ -59,11 +57,9 @@ public class ConsulBinder Assert.isInstanceOf(SubscribableChannel.class, channel); this.logger.debug("Binding Consul client to eventName " + name); - ConsulSendingHandler sendingHandler = new ConsulSendingHandler( - this.eventService.getConsulClient(), name); + ConsulSendingHandler sendingHandler = new ConsulSendingHandler(this.eventService.getConsulClient(), name); - EventDrivenConsumer consumer = new EventDrivenConsumer( - (SubscribableChannel) channel, sendingHandler); + EventDrivenConsumer consumer = new EventDrivenConsumer((SubscribableChannel) channel, sendingHandler); consumer.setBeanFactory(getBeanFactory()); consumer.setBeanName(String.format(BEAN_NAME_TEMPLATE, name)); consumer.afterPropertiesSet(); diff --git a/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/ConsulInboundMessageProducer.java b/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/ConsulInboundMessageProducer.java index c00bfb37..74e234d7 100644 --- a/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/ConsulInboundMessageProducer.java +++ b/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/ConsulInboundMessageProducer.java @@ -39,8 +39,7 @@ import static org.springframework.util.Base64Utils.decodeFromString; */ public class ConsulInboundMessageProducer extends MessageProducerSupport { - protected static final Log logger = LogFactory - .getLog(ConsulInboundMessageProducer.class); + protected static final Log logger = LogFactory.getLog(ConsulInboundMessageProducer.class); private final ScheduledExecutorService scheduler; @@ -81,8 +80,7 @@ public class ConsulInboundMessageProducer extends MessageProducerSupport { @Override protected void doStart() { // TODO: make configurable - this.eventsHandle = this.scheduler.scheduleWithFixedDelay(this.eventsRunnable, - 500, 500, TimeUnit.MILLISECONDS); + this.eventsHandle = this.scheduler.scheduleWithFixedDelay(this.eventsRunnable, 500, 500, TimeUnit.MILLISECONDS); } @Override diff --git a/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/ConsulSendingHandler.java b/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/ConsulSendingHandler.java index ce74929f..3ebd85a1 100644 --- a/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/ConsulSendingHandler.java +++ b/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/ConsulSendingHandler.java @@ -56,8 +56,8 @@ public class ConsulSendingHandler extends AbstractMessageHandler { // TODO: support headers // TODO: support consul event filters: NodeFilter, ServiceFilter, TagFilter - Response event = this.consul.eventFire(this.eventName, (String) payload, - new EventParams(), QueryParams.DEFAULT); + Response event = this.consul.eventFire(this.eventName, (String) payload, new EventParams(), + QueryParams.DEFAULT); // TODO: return event? } diff --git a/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/EventService.java b/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/EventService.java index 75e36336..bfbdf21c 100644 --- a/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/EventService.java +++ b/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/EventService.java @@ -44,8 +44,7 @@ public class EventService { private AtomicReference lastIndex = new AtomicReference<>(); - public EventService(ConsulBinderProperties properties, ConsulClient consul, - ObjectMapper objectMapper) { + public EventService(ConsulBinderProperties properties, ConsulClient consul, ObjectMapper objectMapper) { this.properties = properties; this.consul = consul; this.objectMapper = objectMapper; @@ -72,14 +71,12 @@ public class EventService { } public Event fire(String name, String payload) { - Response response = this.consul.eventFire(name, payload, new EventParams(), - QueryParams.DEFAULT); + Response response = this.consul.eventFire(name, payload, new EventParams(), QueryParams.DEFAULT); return response.getValue(); } public Response> getEventsResponse() { - return this.consul.eventList(EventListRequest.newBuilder() - .setQueryParams(QueryParams.DEFAULT).build()); + return this.consul.eventList(EventListRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build()); } public List getEvents() { @@ -104,8 +101,8 @@ public class EventService { if (this.properties != null) { eventTimeout = this.properties.getEventTimeout(); } - Response> watch = this.consul.eventList(EventListRequest.newBuilder() - .setQueryParams(new QueryParams(eventTimeout, index)).build()); + Response> watch = this.consul + .eventList(EventListRequest.newBuilder().setQueryParams(new QueryParams(eventTimeout, index)).build()); return filterEvents(readEvents(watch), lastIndex); } diff --git a/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/config/ConsulBinderConfiguration.java b/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/config/ConsulBinderConfiguration.java index 397abd9d..e4e4c780 100644 --- a/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/config/ConsulBinderConfiguration.java +++ b/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/config/ConsulBinderConfiguration.java @@ -53,8 +53,7 @@ public class ConsulBinderConfiguration { @Bean @ConditionalOnMissingBean public EventService eventService(ConsulClient consulClient) { - return new EventService(null/* consulBinderProperties */, consulClient, - this.objectMapper); + return new EventService(null/* consulBinderProperties */, consulClient, this.objectMapper); } @Bean diff --git a/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/config/ConsulBinderProperties.java b/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/config/ConsulBinderProperties.java index 62ccebcf..2852b3ac 100644 --- a/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/config/ConsulBinderProperties.java +++ b/spring-cloud-consul-binder/src/main/java/org/springframework/cloud/consul/binder/config/ConsulBinderProperties.java @@ -40,8 +40,7 @@ public class ConsulBinderProperties { @Override public String toString() { - return new ToStringCreator(this).append("eventTimeout", this.eventTimeout) - .toString(); + return new ToStringCreator(this).append("eventTimeout", this.eventTimeout).toString(); } } diff --git a/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/ConsulBinderApplicationTests.java b/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/ConsulBinderApplicationTests.java index dfa070ef..b85c4a9e 100644 --- a/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/ConsulBinderApplicationTests.java +++ b/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/ConsulBinderApplicationTests.java @@ -69,8 +69,7 @@ public class ConsulBinderApplicationTests { @Before public void setUp() throws Exception { - this.wireMock.stubFor(put(urlPathMatching("/v1/event/fire/purchases")) - .willReturn(aResponse().withStatus(200))); + this.wireMock.stubFor(put(urlPathMatching("/v1/event/fire/purchases")).willReturn(aResponse().withStatus(200))); /* * wireMock.stubFor(get(urlPathMatching("/v1/event/list")) @@ -89,8 +88,7 @@ public class ConsulBinderApplicationTests { public void shouldPublishTextConsulMessage() { // given - final Message message = MessageBuilder.withPayload("Hello Consul!") - .build(); + final Message message = MessageBuilder.withPayload("Hello Consul!").build(); // when this.events.purchases().send(message); diff --git a/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/ConsulBinderTests.java b/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/ConsulBinderTests.java index bf28a1d3..15a16662 100644 --- a/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/ConsulBinderTests.java +++ b/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/ConsulBinderTests.java @@ -164,9 +164,7 @@ public class ConsulBinderTests { if (groups != null) { args.add(String.format("--group=%s", groups[i])); } - consumers.add( - new AppId(launchApplication(TestConsumer.class, appProperties, args), - consumerPort)); + consumers.add(new AppId(launchApplication(TestConsumer.class, appProperties, args), consumerPort)); } for (AppId app : consumers) { waitForConsumer(app.port); @@ -191,8 +189,7 @@ public class ConsulBinderTests { args.add(String.format("--partitioned=%b", false)); args.add("--debug"); - return new AppId(launchApplication(TestProducer.class, appProperties, args), - producerPort); + return new AppId(launchApplication(TestProducer.class, appProperties, args), producerPort); } /** @@ -222,8 +219,7 @@ public class ConsulBinderTests { */ private boolean isConsumerBound(int port) { try { - return this.restTemplate.getForObject( - String.format("http://localhost:%d/is-bound", port), Boolean.class); + return this.restTemplate.getForObject(String.format("http://localhost:%d/is-bound", port), Boolean.class); } catch (ResourceAccessException e) { logger.trace("isConsumerBound", e); @@ -238,8 +234,7 @@ public class ConsulBinderTests { */ private String getConsumerMessagePayload(int port) { try { - return this.restTemplate.getForObject( - String.format("http://localhost:%d/message-payload", port), + return this.restTemplate.getForObject(String.format("http://localhost:%d/message-payload", port), String.class); } catch (ResourceAccessException e) { @@ -255,8 +250,7 @@ public class ConsulBinderTests { */ private boolean partitionSelectorUsed(int port) { try { - return this.restTemplate.getForObject( - String.format("http://localhost:%d/partition-strategy-invoked", port), + return this.restTemplate.getForObject(String.format("http://localhost:%d/partition-strategy-invoked", port), Boolean.class); } catch (ResourceAccessException e) { @@ -294,21 +288,17 @@ public class ConsulBinderTests { * @param args the command line arguments for the application * @return a string identifier for the application */ - private String launchApplication(Class clz, Map properties, - List args) { - Resource resource = new UrlResource( - clz.getProtectionDomain().getCodeSource().getLocation()); + private String launchApplication(Class clz, Map properties, List args) { + Resource resource = new UrlResource(clz.getProtectionDomain().getCodeSource().getLocation()); properties.put(AppDeployer.GROUP_PROPERTY_KEY, "test-group"); properties.put("main", clz.getName()); properties.put("classpath", System.getProperty("java.class.path")); - String appName = String.format("%s-%s", clz.getSimpleName(), - properties.get("server.port")); + String appName = String.format("%s-%s", clz.getSimpleName(), properties.get("server.port")); AppDefinition definition = new AppDefinition(appName, properties); - AppDeploymentRequest request = new AppDeploymentRequest(definition, resource, - properties, args); + AppDeploymentRequest request = new AppDeploymentRequest(definition, resource, properties, args); return this.deployer.deploy(request); } @@ -336,8 +326,7 @@ public class ConsulBinderTests { * @param request the request * @return the string[] */ - protected String[] buildJarExecutionCommand(String jarPath, - AppDeploymentRequest request) { + protected String[] buildJarExecutionCommand(String jarPath, AppDeploymentRequest request) { ArrayList commands = new ArrayList<>(); commands.add(super.getLocalDeployerProperties().getJavaCmd()); diff --git a/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/ConsulInboundMessageProducerTests.java b/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/ConsulInboundMessageProducerTests.java index b8cb47b1..5d828866 100644 --- a/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/ConsulInboundMessageProducerTests.java +++ b/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/ConsulInboundMessageProducerTests.java @@ -33,8 +33,7 @@ public class ConsulInboundMessageProducerTests { EventService eventService = mock(EventService.class); when(eventService.watch()).thenThrow(new OperationException(500, "error", "")); - ConsulInboundMessageProducer producer = new ConsulInboundMessageProducer( - eventService); + ConsulInboundMessageProducer producer = new ConsulInboundMessageProducer(eventService); try { producer.getEvents(); diff --git a/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/config/ConsulBinderConfigurationTests.java b/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/config/ConsulBinderConfigurationTests.java index 03ea44c0..89e454dc 100644 --- a/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/config/ConsulBinderConfigurationTests.java +++ b/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/config/ConsulBinderConfigurationTests.java @@ -43,8 +43,7 @@ public class ConsulBinderConfigurationTests { @Ignore // FIXME 2.0.0 need stream fix public void consulBinderDisabledWorks() { this.exception.expectMessage(containsString("no proper implementation found")); - new SpringApplicationBuilder(Application.class) - .initializers(new ConsulTestcontainers()) + new SpringApplicationBuilder(Application.class).initializers(new ConsulTestcontainers()) .properties("spring.cloud.consul.binder.enabled=false").run(); } @@ -52,8 +51,7 @@ public class ConsulBinderConfigurationTests { @Ignore // FIXME 2.0.0 need stream fix public void consulDisabledDisablesBinder() { this.exception.expectMessage(containsString("no proper implementation found")); - new SpringApplicationBuilder(Application.class) - .initializers(new ConsulTestcontainers()) + new SpringApplicationBuilder(Application.class).initializers(new ConsulTestcontainers()) .properties("spring.cloud.consul.enabled=false").run(); } diff --git a/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/test/consumer/TestConsumer.java b/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/test/consumer/TestConsumer.java index ba772322..f46b8482 100644 --- a/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/test/consumer/TestConsumer.java +++ b/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/test/consumer/TestConsumer.java @@ -88,8 +88,7 @@ public class TestConsumer implements ApplicationRunner { group = args.getOptionValues("group").get(0); } - this.binder.bindConsumer(ConsulBinderTests.BINDING_NAME, group, consumerChannel, - new ConsumerProperties()); + this.binder.bindConsumer(ConsulBinderTests.BINDING_NAME, group, consumerChannel, new ConsumerProperties()); this.isBound = true; } diff --git a/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/test/producer/TestProducer.java b/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/test/producer/TestProducer.java index 71c4847d..d9e37c31 100644 --- a/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/test/producer/TestProducer.java +++ b/spring-cloud-consul-binder/src/test/java/org/springframework/cloud/consul/binder/test/producer/TestProducer.java @@ -68,10 +68,8 @@ public class TestProducer implements ApplicationRunner { */ SubscribableChannel producerChannel = producerChannel(); ProducerProperties properties = new ProducerProperties(); - properties.setPartitionKeyExpression( - new SpelExpressionParser().parseExpression("payload")); - this.binder.bindProducer(ConsulBinderTests.BINDING_NAME, producerChannel, - properties); + properties.setPartitionKeyExpression(new SpelExpressionParser().parseExpression("payload")); + this.binder.bindProducer(ConsulBinderTests.BINDING_NAME, producerChannel, properties); Message message = new GenericMessage<>(ConsulBinderTests.MESSAGE_PAYLOAD); logger.info("Writing message to binder {}", this.binder); @@ -93,15 +91,13 @@ public class TestProducer implements ApplicationRunner { return stubPartitionSelectorStrategy().invoked; } - public static class StubPartitionSelectorStrategy - implements PartitionSelectorStrategy { + public static class StubPartitionSelectorStrategy implements PartitionSelectorStrategy { public volatile boolean invoked = false; @Override public int selectPartition(Object key, int partitionCount) { - logger.info("Selecting partition for key {}; partition count: {}", key, - partitionCount); + logger.info("Selecting partition for key {}; partition count: {}", key, partitionCount); this.invoked = true; return 1; } diff --git a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConfigWatch.java b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConfigWatch.java index 1ec886e6..d28636dc 100644 --- a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConfigWatch.java +++ b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConfigWatch.java @@ -92,8 +92,8 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc @Override public void start() { if (this.running.compareAndSet(false, true)) { - this.watchFuture = this.taskScheduler.scheduleWithFixedDelay( - this::watchConfigKeyValues, this.properties.getWatch().getDelay()); + this.watchFuture = this.taskScheduler.scheduleWithFixedDelay(this::watchConfigKeyValues, + this.properties.getWatch().getDelay()); } } @@ -145,8 +145,7 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc } if (log.isTraceEnabled()) { - log.trace("watching consul for context '" + context + "' with index " - + currentIndex); + log.trace("watching consul for context '" + context + "' with index " + currentIndex); } // use the consul ACL token if found @@ -155,9 +154,8 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc aclToken = null; } - Response> response = this.consul.getKVValues(context, - aclToken, new QueryParams( - this.properties.getWatch().getWaitTime(), currentIndex)); + Response> response = this.consul.getKVValues(context, aclToken, + new QueryParams(this.properties.getWatch().getWaitTime(), currentIndex)); // if response.value == null, response was a 404, otherwise it was a // 200, reducing churn if there wasn't anything @@ -167,20 +165,15 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc if (newIndex != null && !newIndex.equals(currentIndex)) { // don't publish the same index again, don't publish the first // time (-1) so index can be primed - if (!this.consulIndexes.containsValue(newIndex) - && !currentIndex.equals(-1L)) { + if (!this.consulIndexes.containsValue(newIndex) && !currentIndex.equals(-1L)) { if (log.isTraceEnabled()) { - log.trace("Context " + context + " has new index " - + newIndex); + log.trace("Context " + context + " has new index " + newIndex); } - RefreshEventData data = new RefreshEventData(context, - currentIndex, newIndex); - this.publisher.publishEvent( - new RefreshEvent(this, data, data.toString())); + RefreshEventData data = new RefreshEventData(context, currentIndex, newIndex); + this.publisher.publishEvent(new RefreshEvent(this, data, data.toString())); } else if (log.isTraceEnabled()) { - log.trace("Event for index already published for context " - + context); + log.trace("Event for index already published for context " + context); } this.consulIndexes.put(context, newIndex); } @@ -196,19 +189,17 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc catch (Exception e) { // only fail fast on the initial query, otherwise just log the error if (this.firstTime && this.properties.isFailFast()) { - log.error( - "Fail fast is set and there was an error reading configuration from consul."); + log.error("Fail fast is set and there was an error reading configuration from consul."); ReflectionUtils.rethrowRuntimeException(e); } else if (log.isTraceEnabled()) { - log.trace("Error querying consul Key/Values for context '" + context - + "'", e); + log.trace("Error querying consul Key/Values for context '" + context + "'", e); } else if (log.isWarnEnabled()) { // simplified one line log message in the event of an agent // failure - log.warn("Error querying consul Key/Values for context '" + context - + "'. Message: " + e.getMessage()); + log.warn("Error querying consul Key/Values for context '" + context + "'. Message: " + + e.getMessage()); } } } @@ -250,8 +241,7 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc return false; } RefreshEventData that = (RefreshEventData) o; - return Objects.equals(this.context, that.context) - && Objects.equals(this.prevIndex, that.prevIndex) + return Objects.equals(this.context, that.context) && Objects.equals(this.prevIndex, that.prevIndex) && Objects.equals(this.newIndex, that.newIndex); } @@ -262,9 +252,8 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc @Override public String toString() { - return new ToStringCreator(this).append("context", this.context) - .append("prevIndex", this.prevIndex).append("newIndex", this.newIndex) - .toString(); + return new ToStringCreator(this).append("context", this.context).append("prevIndex", this.prevIndex) + .append("newIndex", this.newIndex).toString(); } } diff --git a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigAutoConfiguration.java b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigAutoConfiguration.java index f9ebf899..5a1b00af 100644 --- a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigAutoConfiguration.java +++ b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigAutoConfiguration.java @@ -53,17 +53,14 @@ public class ConsulConfigAutoConfiguration { @Configuration(proxyBeanMethods = false) @ConditionalOnClass(RefreshEndpoint.class) - @ConditionalOnProperty(name = "spring.cloud.consul.config.watch.enabled", - matchIfMissing = true) + @ConditionalOnProperty(name = "spring.cloud.consul.config.watch.enabled", matchIfMissing = true) protected static class ConsulRefreshConfiguration { @Bean @ConditionalOnBean(ConsulConfigIndexes.class) - public ConfigWatch configWatch(ConsulConfigProperties properties, - ConsulConfigIndexes indexes, ConsulClient consul, - @Qualifier(CONFIG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) { - return new ConfigWatch(properties, consul, indexes.getIndexes(), - taskScheduler); + public ConfigWatch configWatch(ConsulConfigProperties properties, ConsulConfigIndexes indexes, + ConsulClient consul, @Qualifier(CONFIG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) { + return new ConfigWatch(properties, consul, indexes.getIndexes(), taskScheduler); } @Bean(name = CONFIG_WATCH_TASK_SCHEDULER_NAME) diff --git a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigBootstrapConfiguration.java b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigBootstrapConfiguration.java index fe698973..f1278bbc 100644 --- a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigBootstrapConfiguration.java +++ b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigBootstrapConfiguration.java @@ -39,8 +39,7 @@ public class ConsulConfigBootstrapConfiguration { @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties @Import(ConsulAutoConfiguration.class) - @ConditionalOnProperty(name = "spring.cloud.consul.config.enabled", - matchIfMissing = true) + @ConditionalOnProperty(name = "spring.cloud.consul.config.enabled", matchIfMissing = true) protected static class ConsulPropertySourceConfiguration { @Autowired @@ -53,8 +52,7 @@ public class ConsulConfigBootstrapConfiguration { } @Bean - public ConsulPropertySourceLocator consulPropertySourceLocator( - ConsulConfigProperties consulConfigProperties) { + public ConsulPropertySourceLocator consulPropertySourceLocator(ConsulConfigProperties consulConfigProperties) { return new ConsulPropertySourceLocator(this.consul, consulConfigProperties); } diff --git a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigDataLoader.java b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigDataLoader.java index e181e24d..44a407e1 100644 --- a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigDataLoader.java +++ b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigDataLoader.java @@ -32,26 +32,23 @@ import org.springframework.boot.env.BootstrapRegistry.Registration; import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.FILES; -public class ConsulConfigDataLoader - implements ConfigDataLoader { +public class ConsulConfigDataLoader implements ConfigDataLoader { private static final Log log = LogFactory.getLog(ConsulConfigDataLoader.class); @Override - public ConfigData load(ConfigDataLoaderContext context, - ConsulConfigDataLocation location) { + public ConfigData load(ConfigDataLoaderContext context, ConsulConfigDataLocation location) { try { ConsulClient consul = getBean(context, ConsulClient.class); ConsulConfigProperties properties = location.getProperties(); ConsulPropertySource propertySource = null; if (properties.getFormat() == FILES) { - Response response = consul.getKVValue(location.getContext(), - properties.getAclToken()); + Response response = consul.getKVValue(location.getContext(), properties.getAclToken()); addIndex(context, location, response.getConsulIndex()); if (response.getValue() != null) { - ConsulFilesPropertySource filesPropertySource = new ConsulFilesPropertySource( - location.getContext(), consul, properties); + ConsulFilesPropertySource filesPropertySource = new ConsulFilesPropertySource(location.getContext(), + consul, properties); filesPropertySource.init(response.getValue()); propertySource = filesPropertySource; } @@ -79,26 +76,22 @@ public class ConsulConfigDataLoader } protected T getBean(ConfigDataLoaderContext context, Class type) { - Registration registration = context.getBootstrapRegistry() - .getRegistration(type); + Registration registration = context.getBootstrapRegistry().getRegistration(type); if (registration == null) { return null; } return registration.get(); } - protected ConsulPropertySource create(ConfigDataLoaderContext context, - ConsulConfigDataLocation location) { - ConsulPropertySource propertySource = new ConsulPropertySource( - location.getContext(), getBean(context, ConsulClient.class), - location.getProperties()); + protected ConsulPropertySource create(ConfigDataLoaderContext context, ConsulConfigDataLocation location) { + ConsulPropertySource propertySource = new ConsulPropertySource(location.getContext(), + getBean(context, ConsulClient.class), location.getProperties()); propertySource.init(); addIndex(context, location, propertySource.getInitialIndex()); return propertySource; } - private void addIndex(ConfigDataLoaderContext context, - ConsulConfigDataLocation location, Long consulIndex) { + private void addIndex(ConfigDataLoaderContext context, ConsulConfigDataLocation location, Long consulIndex) { ConsulConfigIndexes indexes = getBean(context, ConsulConfigIndexes.class); if (indexes != null) { // should never be the case indexes.getIndexes().put(location.getContext(), consulIndex); diff --git a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigDataLocation.java b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigDataLocation.java index 4988019d..5ca2503d 100644 --- a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigDataLocation.java +++ b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigDataLocation.java @@ -29,8 +29,7 @@ public class ConsulConfigDataLocation extends ConfigDataLocation { private final boolean optional; - public ConsulConfigDataLocation(ConsulConfigProperties properties, String context, - boolean optional) { + public ConsulConfigDataLocation(ConsulConfigProperties properties, String context, boolean optional) { this.properties = properties; this.context = context; this.optional = optional; @@ -68,8 +67,8 @@ public class ConsulConfigDataLocation extends ConfigDataLocation { @Override public String toString() { - return new ToStringCreator(this).append("context", context) - .append("optional", optional).append("properties", properties).toString(); + return new ToStringCreator(this).append("context", context).append("optional", optional) + .append("properties", properties).toString(); } diff --git a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigDataLocationResolver.java b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigDataLocationResolver.java index 22be2ae9..f12214be 100644 --- a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigDataLocationResolver.java +++ b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigDataLocationResolver.java @@ -42,8 +42,7 @@ import org.springframework.web.util.UriComponentsBuilder; import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.FILES; -public class ConsulConfigDataLocationResolver - implements ConfigDataLocationResolver { +public class ConsulConfigDataLocationResolver implements ConfigDataLocationResolver { /** * Consul ConfigData prefix. @@ -56,55 +55,44 @@ public class ConsulConfigDataLocationResolver .unmodifiableList(Arrays.asList(".yml", ".yaml", ".properties")); @Override - public boolean isResolvable(ConfigDataLocationResolverContext context, - String location) { + public boolean isResolvable(ConfigDataLocationResolverContext context, String location) { if (!location.startsWith(PREFIX)) { return false; } // only bind if correct prefix - boolean enabled = context.getBinder() - .bind(ConsulProperties.PREFIX + ".enabled", Boolean.class).orElse(true); - boolean configEnabled = context.getBinder() - .bind(ConsulConfigProperties.PREFIX + ".enabled", Boolean.class) + boolean enabled = context.getBinder().bind(ConsulProperties.PREFIX + ".enabled", Boolean.class).orElse(true); + boolean configEnabled = context.getBinder().bind(ConsulConfigProperties.PREFIX + ".enabled", Boolean.class) .orElse(true); return configEnabled && enabled; } @Override - public List resolve( - ConfigDataLocationResolverContext context, String location, boolean optional) - throws ConfigDataLocationNotFoundException { + public List resolve(ConfigDataLocationResolverContext context, String location, + boolean optional) throws ConfigDataLocationNotFoundException { return Collections.emptyList(); } @Override - public List resolveProfileSpecific( - ConfigDataLocationResolverContext context, String location, boolean optional, - Profiles profiles) throws ConfigDataLocationNotFoundException { + public List resolveProfileSpecific(ConfigDataLocationResolverContext context, + String location, boolean optional, Profiles profiles) throws ConfigDataLocationNotFoundException { UriComponents locationUri = parseLocation(context, location); - ConsulConfigProperties properties = loadConfigProperties(context.getBinder(), - locationUri); + ConsulConfigProperties properties = loadConfigProperties(context.getBinder(), locationUri); - List contexts = (locationUri == null - || CollectionUtils.isEmpty(locationUri.getPathSegments())) - ? getAutomaticContexts(profiles, properties) - : getCustomContexts(locationUri, properties); + List contexts = (locationUri == null || CollectionUtils.isEmpty(locationUri.getPathSegments())) + ? getAutomaticContexts(profiles, properties) : getCustomContexts(locationUri, properties); - registerBean(context, ConsulClient.class, - () -> createConsulClient(context, locationUri)); + registerBean(context, ConsulClient.class, () -> createConsulClient(context, locationUri)); registerBean(context, ConsulConfigIndexes.class, ConsulConfigDataIndexes::new); return contexts.stream() - .map(propertySourceContext -> new ConsulConfigDataLocation(properties, - propertySourceContext, optional)) + .map(propertySourceContext -> new ConsulConfigDataLocation(properties, propertySourceContext, optional)) .collect(Collectors.toList()); } - private List getCustomContexts(UriComponents uriComponents, - ConsulConfigProperties properties) { + private List getCustomContexts(UriComponents uriComponents, ConsulConfigProperties properties) { if (StringUtils.isEmpty(uriComponents.getPath())) { return Collections.emptyList(); } @@ -126,8 +114,7 @@ public class ConsulConfigDataLocationResolver return DIR_SUFFIXES; } - protected List getAutomaticContexts(Profiles profiles, - ConsulConfigProperties properties) { + protected List getAutomaticContexts(Profiles profiles, ConsulConfigProperties properties) { List contexts = new ArrayList<>(); String prefix = properties.getPrefix(); @@ -162,17 +149,15 @@ public class ConsulConfigDataLocationResolver } } - protected void addProfiles(List contexts, String baseContext, - Profiles profiles, String suffix, ConsulConfigProperties properties) { + protected void addProfiles(List contexts, String baseContext, Profiles profiles, String suffix, + ConsulConfigProperties properties) { for (String profile : profiles.getAccepted()) { - contexts.add( - baseContext + properties.getProfileSeparator() + profile + suffix); + contexts.add(baseContext + properties.getProfileSeparator() + profile + suffix); } } @Nullable - protected UriComponents parseLocation(ConfigDataLocationResolverContext context, - String location) { + protected UriComponents parseLocation(ConfigDataLocationResolverContext context, String location) { String uri = location.substring(PREFIX.length()); if (!StringUtils.hasText(uri)) { return null; @@ -186,23 +171,19 @@ public class ConsulConfigDataLocationResolver return UriComponentsBuilder.fromUriString(uri).build(); } - protected void registerBean(ConfigDataLocationResolverContext context, - Class type, Supplier supplier) { + protected void registerBean(ConfigDataLocationResolverContext context, Class type, Supplier supplier) { context.getBootstrapRegistry().register(type, supplier) - .onApplicationContextPrepared( - (ctxt, consulClient) -> ctxt.getBeanFactory().registerSingleton( - "configData" + type.getSimpleName(), consulClient)); + .onApplicationContextPrepared((ctxt, consulClient) -> ctxt.getBeanFactory() + .registerSingleton("configData" + type.getSimpleName(), consulClient)); } - protected ConsulClient createConsulClient(ConfigDataLocationResolverContext context, - UriComponents location) { + protected ConsulClient createConsulClient(ConfigDataLocationResolverContext context, UriComponents location) { ConsulProperties properties = loadProperties(context.getBinder(), location); return ConsulAutoConfiguration.createConsulClient(properties); } protected ConsulProperties loadProperties(Binder binder, UriComponents location) { - ConsulProperties consulProperties = binder - .bind(ConsulProperties.PREFIX, Bindable.of(ConsulProperties.class)) + ConsulProperties consulProperties = binder.bind(ConsulProperties.PREFIX, Bindable.of(ConsulProperties.class)) .orElse(new ConsulProperties()); if (location != null) { @@ -217,16 +198,13 @@ public class ConsulConfigDataLocationResolver return consulProperties; } - protected ConsulConfigProperties loadConfigProperties(Binder binder, - UriComponents location) { + protected ConsulConfigProperties loadConfigProperties(Binder binder, UriComponents location) { ConsulConfigProperties properties = binder - .bind(ConsulConfigProperties.PREFIX, - Bindable.of(ConsulConfigProperties.class)) + .bind(ConsulConfigProperties.PREFIX, Bindable.of(ConsulConfigProperties.class)) .orElse(new ConsulConfigProperties()); if (StringUtils.isEmpty(properties.getName())) { - properties.setName(binder.bind("spring.application.name", String.class) - .orElse("application")); + properties.setName(binder.bind("spring.application.name", String.class).orElse("application")); } return properties; } diff --git a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigProperties.java b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigProperties.java index 8046abfb..a2413b30 100644 --- a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigProperties.java +++ b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulConfigProperties.java @@ -166,13 +166,10 @@ public class ConsulConfigProperties { @Override public String toString() { - return new ToStringCreator(this).append("enabled", this.enabled) - .append("prefix", this.prefix) - .append("defaultContext", this.defaultContext) - .append("profileSeparator", this.profileSeparator) - .append("format", this.format).append("dataKey", this.dataKey) - .append("aclToken", this.aclToken).append("watch", this.watch) - .append("failFast", this.failFast).append("name", this.name).toString(); + return new ToStringCreator(this).append("enabled", this.enabled).append("prefix", this.prefix) + .append("defaultContext", this.defaultContext).append("profileSeparator", this.profileSeparator) + .append("format", this.format).append("dataKey", this.dataKey).append("aclToken", this.aclToken) + .append("watch", this.watch).append("failFast", this.failFast).append("name", this.name).toString(); } /** @@ -273,9 +270,8 @@ public class ConsulConfigProperties { @Override public String toString() { - return new ToStringCreator(this).append("waitTime", this.waitTime) - .append("enabled", this.enabled).append("delay", this.delay) - .toString(); + return new ToStringCreator(this).append("waitTime", this.waitTime).append("enabled", this.enabled) + .append("delay", this.delay).toString(); } } diff --git a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulFilesPropertySource.java b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulFilesPropertySource.java index 77e21207..b6bbb4bf 100644 --- a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulFilesPropertySource.java +++ b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulFilesPropertySource.java @@ -27,8 +27,7 @@ import static org.springframework.cloud.consul.config.ConsulConfigProperties.For */ public class ConsulFilesPropertySource extends ConsulPropertySource { - public ConsulFilesPropertySource(String context, ConsulClient source, - ConsulConfigProperties configProperties) { + public ConsulFilesPropertySource(String context, ConsulClient source, ConsulConfigProperties configProperties) { super(context, source, configProperties); } @@ -45,8 +44,7 @@ public class ConsulFilesPropertySource extends ConsulPropertySource { parseValue(value, PROPERTIES); } else { - throw new IllegalStateException( - "Unknown files extension for context " + this.getContext()); + throw new IllegalStateException("Unknown files extension for context " + this.getContext()); } } diff --git a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulPropertySource.java b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulPropertySource.java index 9332a659..983c931b 100644 --- a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulPropertySource.java +++ b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulPropertySource.java @@ -52,8 +52,7 @@ public class ConsulPropertySource extends EnumerablePropertySource private Long initialIndex; - public ConsulPropertySource(String context, ConsulClient source, - ConsulConfigProperties configProperties) { + public ConsulPropertySource(String context, ConsulClient source, ConsulConfigProperties configProperties) { super(context, source); this.context = context; this.configProperties = configProperties; @@ -65,8 +64,8 @@ public class ConsulPropertySource extends EnumerablePropertySource this.context = this.context + "/"; } - Response> response = this.source.getKVValues(this.context, - this.configProperties.getAclToken(), QueryParams.DEFAULT); + Response> response = this.source.getKVValues(this.context, this.configProperties.getAclToken(), + QueryParams.DEFAULT); this.initialIndex = response.getConsulIndex(); @@ -112,8 +111,7 @@ public class ConsulPropertySource extends EnumerablePropertySource * @param values values to parse * @param format format in which the values should be parsed */ - protected void parsePropertiesWithNonKeyValueFormat(List values, - ConsulConfigProperties.Format format) { + protected void parsePropertiesWithNonKeyValueFormat(List values, ConsulConfigProperties.Format format) { if (values == null) { return; } @@ -139,8 +137,7 @@ public class ConsulPropertySource extends EnumerablePropertySource } } - protected Properties generateProperties(String value, - ConsulConfigProperties.Format format) { + protected Properties generateProperties(String value, ConsulConfigProperties.Format format) { final Properties props = new Properties(); if (format == PROPERTIES) { @@ -150,16 +147,14 @@ public class ConsulPropertySource extends EnumerablePropertySource props.load(new ByteArrayInputStream(value.getBytes("ISO-8859-1"))); } catch (IOException e) { - throw new IllegalArgumentException( - value + " can't be encoded using ISO-8859-1"); + throw new IllegalArgumentException(value + " can't be encoded using ISO-8859-1"); } return props; } else if (format == YAML) { final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean(); - yaml.setResources( - new ByteArrayResource(value.getBytes(Charset.forName("UTF-8")))); + yaml.setResources(new ByteArrayResource(value.getBytes(Charset.forName("UTF-8")))); return yaml.getObject(); } diff --git a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocator.java b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocator.java index 7b003afa..51578fee 100644 --- a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocator.java +++ b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocator.java @@ -46,8 +46,7 @@ import static org.springframework.cloud.consul.config.ConsulConfigProperties.For * @author Spencer Gibb */ @Order(0) -public class ConsulPropertySourceLocator - implements PropertySourceLocator, ConsulConfigIndexes { +public class ConsulPropertySourceLocator implements PropertySourceLocator, ConsulConfigIndexes { private static final Log log = LogFactory.getLog(ConsulPropertySourceLocator.class); @@ -59,8 +58,7 @@ public class ConsulPropertySourceLocator private final LinkedHashMap contextIndex = new LinkedHashMap<>(); - public ConsulPropertySourceLocator(ConsulClient consul, - ConsulConfigProperties properties) { + public ConsulPropertySourceLocator(ConsulClient consul, ConsulConfigProperties properties) { this.consul = consul; this.properties = properties; } @@ -106,8 +104,7 @@ public class ConsulPropertySourceLocator suffixes.add(".properties"); } - String defaultContext = getContext(prefix, - this.properties.getDefaultContext()); + String defaultContext = getContext(prefix, this.properties.getDefaultContext()); for (String suffix : suffixes) { this.contexts.add(defaultContext + suffix); @@ -133,8 +130,8 @@ public class ConsulPropertySourceLocator try { ConsulPropertySource propertySource = null; if (this.properties.getFormat() == FILES) { - Response response = this.consul.getKVValue( - propertySourceContext, this.properties.getAclToken()); + Response response = this.consul.getKVValue(propertySourceContext, + this.properties.getAclToken()); addIndex(propertySourceContext, response.getConsulIndex()); if (response.getValue() != null) { ConsulFilesPropertySource filesPropertySource = new ConsulFilesPropertySource( @@ -152,13 +149,11 @@ public class ConsulPropertySourceLocator } catch (Exception e) { if (this.properties.isFailFast()) { - log.error( - "Fail fast is set and there was an error reading configuration from consul."); + log.error("Fail fast is set and there was an error reading configuration from consul."); ReflectionUtils.rethrowRuntimeException(e); } else { - log.warn("Unable to load consul config from " - + propertySourceContext, e); + log.warn("Unable to load consul config from " + propertySourceContext, e); } } } @@ -182,18 +177,15 @@ public class ConsulPropertySourceLocator } private ConsulPropertySource create(String context, Map contextIndex) { - ConsulPropertySource propertySource = new ConsulPropertySource(context, - this.consul, this.properties); + ConsulPropertySource propertySource = new ConsulPropertySource(context, this.consul, this.properties); propertySource.init(); addIndex(context, propertySource.getInitialIndex()); return propertySource; } - private void addProfiles(List contexts, String baseContext, - List profiles, String suffix) { + private void addProfiles(List contexts, String baseContext, List profiles, String suffix) { for (String profile : profiles) { - contexts.add(baseContext + this.properties.getProfileSeparator() + profile - + suffix); + contexts.add(baseContext + this.properties.getProfileSeparator() + profile + suffix); } } diff --git a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/PropertySourcesLocatedEvent.java b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/PropertySourcesLocatedEvent.java index 70a27ce3..164d1dc6 100644 --- a/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/PropertySourcesLocatedEvent.java +++ b/spring-cloud-consul-config/src/main/java/org/springframework/cloud/consul/config/PropertySourcesLocatedEvent.java @@ -32,8 +32,7 @@ public class PropertySourcesLocatedEvent extends ApplicationEvent { * @param source the object on which the event initially occurred (never {@code null}) * @param contextsToIndexes contexts to indexes */ - public PropertySourcesLocatedEvent(Object source, - LinkedHashMap contextsToIndexes) { + public PropertySourcesLocatedEvent(Object source, LinkedHashMap contextsToIndexes) { super(source); this.contextsToIndexes = contextsToIndexes; } diff --git a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConfigWatchTests.java b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConfigWatchTests.java index b482abe8..7b337ec3 100644 --- a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConfigWatchTests.java +++ b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConfigWatchTests.java @@ -60,8 +60,7 @@ public class ConfigWatchTests { public void watchPublishesEventWithAcl() { ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class); - setupWatch(eventPublisher, new GetValue(), "/app/", - "2ee647bd-bd69-4118-9f34-b9a6e9e60746"); + setupWatch(eventPublisher, new GetValue(), "/app/", "2ee647bd-bd69-4118-9f34-b9a6e9e60746"); verify(eventPublisher, atLeastOnce()).publishEvent(any(RefreshEvent.class)); } @@ -94,13 +93,12 @@ public class ConfigWatchTests { verify(eventPublisher, atLeastOnce()).publishEvent(any(RefreshEvent.class)); } - private void setupWatch(ApplicationEventPublisher eventPublisher, GetValue getValue, - String context) { + private void setupWatch(ApplicationEventPublisher eventPublisher, GetValue getValue, String context) { setupWatch(eventPublisher, getValue, context, null); } - private void setupWatch(ApplicationEventPublisher eventPublisher, GetValue getValue, - String context, String aclToken) { + private void setupWatch(ApplicationEventPublisher eventPublisher, GetValue getValue, String context, + String aclToken) { ConsulClient consul = mock(ConsulClient.class); List getValues = null; @@ -109,8 +107,7 @@ public class ConfigWatchTests { } Response> response = new Response<>(getValues, 1L, false, 1L); - when(consul.getKVValues(eq(context), nullable(String.class), - any(QueryParams.class))).thenReturn(response); + when(consul.getKVValues(eq(context), nullable(String.class), any(QueryParams.class))).thenReturn(response); if (StringUtils.hasText(aclToken)) { this.configProperties.setAclToken(aclToken); @@ -118,8 +115,7 @@ public class ConfigWatchTests { LinkedHashMap initialIndexes = new LinkedHashMap<>(); initialIndexes.put(context, 0L); - ConfigWatch watch = new ConfigWatch(this.configProperties, consul, - initialIndexes); + ConfigWatch watch = new ConfigWatch(this.configProperties, consul, initialIndexes); watch.setApplicationEventPublisher(eventPublisher); watch.start(); @@ -137,11 +133,9 @@ public class ConfigWatchTests { List getValues = Collections.singletonList(getValue); Response> response = new Response<>(getValues, 1L, false, 1L); - when(consul.getKVValues(eq(context), anyString(), any(QueryParams.class))) - .thenReturn(response); + when(consul.getKVValues(eq(context), anyString(), any(QueryParams.class))).thenReturn(response); - ConfigWatch watch = new ConfigWatch(this.configProperties, consul, - new LinkedHashMap()); + ConfigWatch watch = new ConfigWatch(this.configProperties, consul, new LinkedHashMap()); watch.setApplicationEventPublisher(eventPublisher); watch.watchConfigKeyValues(); diff --git a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulConfigBootstrapConfigurationTests.java b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulConfigBootstrapConfigurationTests.java index 1f3b6278..fa666a3e 100644 --- a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulConfigBootstrapConfigurationTests.java +++ b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulConfigBootstrapConfigurationTests.java @@ -36,16 +36,11 @@ public class ConsulConfigBootstrapConfigurationTests { */ @Test public void testConfigPropsBeanBacksOff() { - this.contextRunner.withUserConfiguration(TestConfig.class) - .withInitializer(new ConsulTestcontainers()) - .withUserConfiguration(ConsulConfigBootstrapConfiguration.class) - .run(context -> { - ConsulConfigProperties config = context - .getBean(ConsulConfigProperties.class); - assertThat(config.getPrefix()).as("Prefix did not match") - .isEqualTo("platform-config"); - assertThat(config.getDefaultContext()) - .as("Default context did not match").isEqualTo("defaults"); + this.contextRunner.withUserConfiguration(TestConfig.class).withInitializer(new ConsulTestcontainers()) + .withUserConfiguration(ConsulConfigBootstrapConfiguration.class).run(context -> { + ConsulConfigProperties config = context.getBean(ConsulConfigProperties.class); + assertThat(config.getPrefix()).as("Prefix did not match").isEqualTo("platform-config"); + assertThat(config.getDefaultContext()).as("Default context did not match").isEqualTo("defaults"); }); } @@ -57,12 +52,9 @@ public class ConsulConfigBootstrapConfigurationTests { public void testConfigPropsBeanKicksIn() { this.contextRunner.withUserConfiguration(ConsulConfigBootstrapConfiguration.class) .withInitializer(new ConsulTestcontainers()).run(context -> { - ConsulConfigProperties config = context - .getBean(ConsulConfigProperties.class); - assertThat(config.getPrefix()).as("Prefix did not match") - .isEqualTo("config"); - assertThat(config.getDefaultContext()) - .as("Default context did not match").isEqualTo("application"); + ConsulConfigProperties config = context.getBean(ConsulConfigProperties.class); + assertThat(config.getPrefix()).as("Prefix did not match").isEqualTo("config"); + assertThat(config.getDefaultContext()).as("Default context did not match").isEqualTo("application"); }); } diff --git a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulConfigDataIntegrationTests.java b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulConfigDataIntegrationTests.java index 9ddd9de4..7e2d14a5 100644 --- a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulConfigDataIntegrationTests.java +++ b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulConfigDataIntegrationTests.java @@ -87,12 +87,11 @@ public class ConsulConfigDataIntegrationTests { client.setKVValue(KEY1, VALUE1); client.setKVValue(KEY2, VALUE2); - context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE) - .run("--spring.application.name=" + APP_NAME, - "--spring.config.import=consul:" + ConsulTestcontainers.getHost() - + ":" + ConsulTestcontainers.getPort(), - "--spring.cloud.consul.config.prefix=" + ROOT, - "--spring.cloud.consul.config.watch.delay=10"); + context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run( + "--spring.application.name=" + APP_NAME, + "--spring.config.import=consul:" + ConsulTestcontainers.getHost() + ":" + + ConsulTestcontainers.getPort(), + "--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.watch.delay=10"); client = context.getBean(ConsulClient.class); environment = context.getEnvironment(); @@ -124,8 +123,7 @@ public class ConsulConfigDataIntegrationTests { assertThat(receivedEvent).as("listener didn't receive event").isTrue(); testProp = environment.getProperty(TEST_PROP_CANONICAL); - assertThat(testProp).as("testProp was wrong after update") - .isEqualTo("testPropValUpdate"); + assertThat(testProp).as("testProp was wrong after update").isEqualTo("testPropValUpdate"); } @Test @@ -140,8 +138,7 @@ public class ConsulConfigDataIntegrationTests { assertThat(receivedEvent).as("listener didn't receive event").isTrue(); testProp = environment.getProperty(TEST_PROP3_CANONICAL); - assertThat(testProp).as(TEST_PROP3 + " was wrong after update") - .isEqualTo("testPropValInsert"); + assertThat(testProp).as(TEST_PROP3 + " was wrong after update").isEqualTo("testPropValInsert"); } @Configuration diff --git a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulConfigDataLocationResolverTests.java b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulConfigDataLocationResolverTests.java index e126df24..f61a63c1 100644 --- a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulConfigDataLocationResolverTests.java +++ b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulConfigDataLocationResolverTests.java @@ -40,14 +40,12 @@ public class ConsulConfigDataLocationResolverTests { @Test public void testParseLocation() { ConsulConfigDataLocationResolver resolver = new ConsulConfigDataLocationResolver(); - UriComponents uriComponents = resolver.parseLocation(null, - "consul:myhost:8501/mypath1;/mypath2;/mypath3"); - assertThat(uriComponents.toUri()).hasScheme("consul").hasHost("myhost") - .hasPort(8501).hasPath("/mypath1;/mypath2;/mypath3"); + UriComponents uriComponents = resolver.parseLocation(null, "consul:myhost:8501/mypath1;/mypath2;/mypath3"); + assertThat(uriComponents.toUri()).hasScheme("consul").hasHost("myhost").hasPort(8501) + .hasPath("/mypath1;/mypath2;/mypath3"); uriComponents = resolver.parseLocation(null, "consul:myhost:8501"); - assertThat(uriComponents.toUri()).hasScheme("consul").hasHost("myhost") - .hasPort(8501).hasPath(""); + assertThat(uriComponents.toUri()).hasScheme("consul").hasHost("myhost").hasPort(8501).hasPath(""); } @Test @@ -55,8 +53,7 @@ public class ConsulConfigDataLocationResolverTests { String location = "consul:myhost:8501/mypath1;/mypath2;/mypath3"; List locations = testResolveProfileSpecific(location); assertThat(locations).hasSize(3); - assertThat(toContexts(locations)).containsExactly("/mypath1/", "/mypath2/", - "/mypath3/"); + assertThat(toContexts(locations)).containsExactly("/mypath1/", "/mypath2/", "/mypath3/"); } @Test @@ -64,28 +61,25 @@ public class ConsulConfigDataLocationResolverTests { String location = "consul:myhost"; List locations = testResolveProfileSpecific(location); assertThat(locations).hasSize(4); - assertThat(toContexts(locations)).containsExactly("config/testapp,dev/", - "config/testapp/", "config/application,dev/", "config/application/"); + assertThat(toContexts(locations)).containsExactly("config/testapp,dev/", "config/testapp/", + "config/application,dev/", "config/application/"); } @Test public void testLoadProperties() { - ConsulProperties properties = createResolver().loadProperties( - Binder.get(new MockEnvironment()), + ConsulProperties properties = createResolver().loadProperties(Binder.get(new MockEnvironment()), UriComponentsBuilder.fromUriString("consul://myhost:8502").build()); assertThat(properties.getHost()).isEqualTo("myhost"); assertThat(properties.getPort()).isEqualTo(8502); } private List toContexts(List locations) { - return locations.stream().map(ConsulConfigDataLocation::getContext) - .collect(Collectors.toList()); + return locations.stream().map(ConsulConfigDataLocation::getContext).collect(Collectors.toList()); } private List testResolveProfileSpecific(String location) { ConsulConfigDataLocationResolver resolver = createResolver(); - ConfigDataLocationResolverContext context = mock( - ConfigDataLocationResolverContext.class); + ConfigDataLocationResolverContext context = mock(ConfigDataLocationResolverContext.class); MockEnvironment env = new MockEnvironment(); env.setProperty("spring.application.name", "testapp"); when(context.getBinder()).thenReturn(Binder.get(env)); @@ -97,8 +91,8 @@ public class ConsulConfigDataLocationResolverTests { private ConsulConfigDataLocationResolver createResolver() { ConsulConfigDataLocationResolver resolver = new ConsulConfigDataLocationResolver() { @Override - protected void registerBean(ConfigDataLocationResolverContext context, - Class type, Supplier supplier) { + protected void registerBean(ConfigDataLocationResolverContext context, Class type, + Supplier supplier) { // do nothing } }; diff --git a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertyPrefixTests.java b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertyPrefixTests.java index 7a9b36fb..41f63d1f 100644 --- a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertyPrefixTests.java +++ b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertyPrefixTests.java @@ -47,24 +47,18 @@ public class ConsulPropertyPrefixTests { this.client.setKVValue(kvContext + "/fooprop", "fookvval"); this.client.setKVValue(kvContext + "/bar/prop", "8080"); - ConsulPropertySource source = getConsulPropertySource( - new ConsulConfigProperties(), kvContext); + ConsulPropertySource source = getConsulPropertySource(new ConsulConfigProperties(), kvContext); assertProperties(source, "fookvval", "8080"); } - private void assertProperties(ConsulPropertySource source, Object fooval, - Object barval) { - assertThat(source.getProperty("fooprop")).as("fooprop was wrong") - .isEqualTo(fooval); - assertThat(source.getProperty("bar.prop")).as("bar.prop was wrong") - .isEqualTo(barval); + private void assertProperties(ConsulPropertySource source, Object fooval, Object barval) { + assertThat(source.getProperty("fooprop")).as("fooprop was wrong").isEqualTo(fooval); + assertThat(source.getProperty("bar.prop")).as("bar.prop was wrong").isEqualTo(barval); } @SuppressWarnings("Duplicates") - private ConsulPropertySource getConsulPropertySource( - ConsulConfigProperties configProperties, String context) { - ConsulPropertySource source = new ConsulPropertySource(context, this.client, - configProperties); + private ConsulPropertySource getConsulPropertySource(ConsulConfigProperties configProperties, String context) { + ConsulPropertySource source = new ConsulPropertySource(context, this.client, configProperties); source.init(); String[] names = source.getPropertyNames(); assertThat(names).as("names was null").isNotNull(); diff --git a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorAppNameCustomizedTests.java b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorAppNameCustomizedTests.java index 04d17d6e..376d8a40 100644 --- a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorAppNameCustomizedTests.java +++ b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorAppNameCustomizedTests.java @@ -72,14 +72,12 @@ public class ConsulPropertySourceLocatorAppNameCustomizedTests { this.client.setKVValue(KEY1, VALUE1); this.client.setKVValue(KEY2, VALUE2); - this.context = new SpringApplicationBuilder(Config.class) - .web(WebApplicationType.NONE) - .run("--spring.application.name=testConsulPropertySourceLocatorAppNameCustomized", - "--spring.config.use-legacy-processing=true", - "--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(), - "--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(), - "--spring.cloud.consul.config.name=" + CONFIG_NAME, - "--spring.cloud.consul.config.prefix=" + ROOT); + this.context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run( + "--spring.application.name=testConsulPropertySourceLocatorAppNameCustomized", + "--spring.config.use-legacy-processing=true", + "--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(), + "--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(), + "--spring.cloud.consul.config.name=" + CONFIG_NAME, "--spring.cloud.consul.config.prefix=" + ROOT); this.client = this.context.getBean(ConsulClient.class); this.environment = this.context.getEnvironment(); diff --git a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorFailFastTests.java b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorFailFastTests.java index 8def913b..4f3164ca 100644 --- a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorFailFastTests.java +++ b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorFailFastTests.java @@ -33,10 +33,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @SpringBootTest(classes = ConsulPropertySourceLocatorFailFastTests.Config.class, properties = { "spring.application.name=testConsulPropertySourceLocatorFailFast", "spring.config.use-legacy-processing=true", - "spring.cloud.consul.host=53210a7c-4809-42cb-8b30-057d2db85fcc", - "spring.cloud.consul.port=65530", - "spring.cloud.consul.retry.enabled=false", - "spring.cloud.consul.retry.maxAttempts=0", + "spring.cloud.consul.host=53210a7c-4809-42cb-8b30-057d2db85fcc", "spring.cloud.consul.port=65530", + "spring.cloud.consul.retry.enabled=false", "spring.cloud.consul.retry.maxAttempts=0", "spring.cloud.consul.config.failFast=false" }, webEnvironment = RANDOM_PORT) public class ConsulPropertySourceLocatorFailFastTests { diff --git a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorFilesTests.java b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorFilesTests.java index 2d6c2596..b74c1a0d 100644 --- a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorFilesTests.java +++ b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorFilesTests.java @@ -66,22 +66,17 @@ public class ConsulPropertySourceLocatorFilesTests { ConsulTestcontainers.start(); this.client = ConsulTestcontainers.client(); this.client.setKVValue(ROOT + APPLICATION_YML, "foo: bar\nmy.baz: ${foo}"); - this.client.setKVValue(ROOT + APPLICATION_DEV_YML, - "foo: bar-dev\nmy.baz: ${foo}"); + this.client.setKVValue(ROOT + APPLICATION_DEV_YML, "foo: bar-dev\nmy.baz: ${foo}"); this.client.setKVValue(ROOT + "/master.ref", UUID.randomUUID().toString()); this.client.setKVValue(ROOT + APP_NAME_PROPS, "foo: bar-app\nmy.baz: ${foo}"); - this.client.setKVValue(ROOT + APP_NAME_DEV_PROPS, - "foo: bar-app-dev\nmy.baz: ${foo}"); + this.client.setKVValue(ROOT + APP_NAME_DEV_PROPS, "foo: bar-app-dev\nmy.baz: ${foo}"); - this.context = new SpringApplicationBuilder(Config.class) - .web(WebApplicationType.NONE).run("--spring.application.name=" + APP_NAME, - "--spring.config.use-legacy-processing=true", - "--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(), - "--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(), - "--spring.cloud.consul.config.prefix=" + ROOT, - "--spring.cloud.consul.config.format=FILES", - "--spring.profiles.active=dev", - "spring.cloud.consul.config.watch.delay=1"); + this.context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run( + "--spring.application.name=" + APP_NAME, "--spring.config.use-legacy-processing=true", + "--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(), + "--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(), + "--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.format=FILES", + "--spring.profiles.active=dev", "spring.cloud.consul.config.watch.delay=1"); this.client = this.context.getBean(ConsulClient.class); this.environment = this.context.getEnvironment(); @@ -111,10 +106,8 @@ public class ConsulPropertySourceLocatorFilesTests { assertFilePropertySourceExists(propertySources, APPLICATION_YML); } - private void assertFilePropertySourceExists(MutablePropertySources propertySources, - String name) { - boolean found = propertySources.stream() - .anyMatch(propertySource -> propertySource.getName().endsWith(name)); + private void assertFilePropertySourceExists(MutablePropertySources propertySources, String name) { + boolean found = propertySources.stream().anyMatch(propertySource -> propertySource.getName().endsWith(name)); assertThat(found).as("missing consul filesource: " + name).isTrue(); } diff --git a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorRetryTests.java b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorRetryTests.java index 721f2c43..dec4b796 100644 --- a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorRetryTests.java +++ b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorRetryTests.java @@ -43,10 +43,8 @@ public class ConsulPropertySourceLocatorRetryTests { "spring.application.name=testConsulPropertySourceLocatorRetry", "spring.config.use-legacy-processing=true", "spring.cloud.consul.host=53210a7c-4809-42cb-8b30-057d2db85fcc", - "logging.level.org.springframework.retry=TRACE", "server.port=0", - "spring.cloud.consul.port=65530", - "spring.cloud.consul.retry.maxAttempts=1", - "spring.cloud.consul.config.failFast=true").run(); + "logging.level.org.springframework.retry=TRACE", "server.port=0", "spring.cloud.consul.port=65530", + "spring.cloud.consul.retry.maxAttempts=1", "spring.cloud.consul.config.failFast=true").run(); Assert.fail("Did not throw TransportException"); }); assertThat(output).contains("RetryContext retrieved"); diff --git a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorTests.java b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorTests.java index 21664a59..778446f3 100644 --- a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorTests.java +++ b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceLocatorTests.java @@ -87,13 +87,11 @@ public class ConsulPropertySourceLocatorTests { client.setKVValue(KEY1, VALUE1); client.setKVValue(KEY2, VALUE2); - context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE) - .run("--spring.application.name=" + APP_NAME, - "--spring.config.use-legacy-processing=true", - "--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(), - "--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(), - "--spring.cloud.consul.config.prefix=" + ROOT, - "--spring.cloud.consul.config.watch.delay=10"); + context = new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE).run( + "--spring.application.name=" + APP_NAME, "--spring.config.use-legacy-processing=true", + "--spring.cloud.consul.host=" + ConsulTestcontainers.getHost(), + "--spring.cloud.consul.port=" + ConsulTestcontainers.getPort(), + "--spring.cloud.consul.config.prefix=" + ROOT, "--spring.cloud.consul.config.watch.delay=10"); client = context.getBean(ConsulClient.class); environment = context.getEnvironment(); @@ -125,8 +123,7 @@ public class ConsulPropertySourceLocatorTests { assertThat(receivedEvent).as("listener didn't receive event").isTrue(); testProp = environment.getProperty(TEST_PROP_CANONICAL); - assertThat(testProp).as("testProp was wrong after update") - .isEqualTo("testPropValUpdate"); + assertThat(testProp).as("testProp was wrong after update").isEqualTo("testPropValUpdate"); } @Test @@ -141,8 +138,7 @@ public class ConsulPropertySourceLocatorTests { assertThat(receivedEvent).as("listener didn't receive event").isTrue(); testProp = environment.getProperty(TEST_PROP3_CANONICAL); - assertThat(testProp).as(TEST_PROP3 + " was wrong after update") - .isEqualTo("testPropValInsert"); + assertThat(testProp).as(TEST_PROP3 + " was wrong after update").isEqualTo("testPropValInsert"); } @Configuration diff --git a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceTests.java b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceTests.java index 72cf37d8..eeac72ba 100644 --- a/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceTests.java +++ b/spring-cloud-consul-config/src/test/java/org/springframework/cloud/consul/config/ConsulPropertySourceTests.java @@ -43,8 +43,7 @@ public class ConsulPropertySourceTests { @Before public void setup() { ConsulTestcontainers.start(); - this.prefix = "consulPropertySourceTests" - + new Random().nextInt(Integer.MAX_VALUE); + this.prefix = "consulPropertySourceTests" + new Random().nextInt(Integer.MAX_VALUE); this.client = ConsulTestcontainers.client(); } @@ -60,31 +59,25 @@ public class ConsulPropertySourceTests { this.client.setKVValue(this.kvContext + "/fooprop", "fookvval"); this.client.setKVValue(this.prefix + "/kv" + "/bar/prop", "8080"); - ConsulPropertySource source = getConsulPropertySource( - new ConsulConfigProperties(), this.kvContext); + ConsulPropertySource source = getConsulPropertySource(new ConsulConfigProperties(), this.kvContext); assertProperties(source, "fookvval", "8080"); } - private void assertProperties(ConsulPropertySource source, Object fooval, - Object barval) { - assertThat(source.getProperty("fooprop")).as("fooprop was wrong") - .isEqualTo(fooval); - assertThat(source.getProperty("bar.prop")).as("bar.prop was wrong") - .isEqualTo(barval); + private void assertProperties(ConsulPropertySource source, Object fooval, Object barval) { + assertThat(source.getProperty("fooprop")).as("fooprop was wrong").isEqualTo(fooval); + assertThat(source.getProperty("bar.prop")).as("bar.prop was wrong").isEqualTo(barval); } @Test public void testProperties() { // properties file property this.propertiesContext = this.prefix + "/properties"; - this.client.setKVValue(this.propertiesContext + "/data", - "fooprop=foopropval\nbar.prop=8080"); + this.client.setKVValue(this.propertiesContext + "/data", "fooprop=foopropval\nbar.prop=8080"); ConsulConfigProperties configProperties = new ConsulConfigProperties(); configProperties.setFormat(ConsulConfigProperties.Format.PROPERTIES); - ConsulPropertySource source = getConsulPropertySource(configProperties, - this.propertiesContext); + ConsulPropertySource source = getConsulPropertySource(configProperties, this.propertiesContext); assertProperties(source, "foopropval", "8080"); } @@ -93,13 +86,11 @@ public class ConsulPropertySourceTests { public void testYaml() { // yaml file property String yamlContext = this.prefix + "/yaml"; - this.client.setKVValue(yamlContext + "/data", - "fooprop: fooymlval\nbar:\n prop: 8080"); + this.client.setKVValue(yamlContext + "/data", "fooprop: fooymlval\nbar:\n prop: 8080"); ConsulConfigProperties configProperties = new ConsulConfigProperties(); configProperties.setFormat(ConsulConfigProperties.Format.YAML); - ConsulPropertySource source = getConsulPropertySource(configProperties, - yamlContext); + ConsulPropertySource source = getConsulPropertySource(configProperties, yamlContext); assertProperties(source, "fooymlval", 8080); } @@ -112,16 +103,13 @@ public class ConsulPropertySourceTests { ConsulConfigProperties configProperties = new ConsulConfigProperties(); configProperties.setFormat(ConsulConfigProperties.Format.YAML); - ConsulPropertySource source = new ConsulPropertySource(yamlContext, this.client, - configProperties); + ConsulPropertySource source = new ConsulPropertySource(yamlContext, this.client, configProperties); // Should NOT throw a NPE source.init(); } - private ConsulPropertySource getConsulPropertySource( - ConsulConfigProperties configProperties, String context) { - ConsulPropertySource source = new ConsulPropertySource(context, this.client, - configProperties); + private ConsulPropertySource getConsulPropertySource(ConsulConfigProperties configProperties, String context) { + ConsulPropertySource source = new ConsulPropertySource(context, this.client, configProperties); source.init(); String[] names = source.getPropertyNames(); assertThat(names).as("names was null").isNotNull(); diff --git a/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConditionalOnConsulEnabled.java b/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConditionalOnConsulEnabled.java index d617f517..898afb9e 100644 --- a/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConditionalOnConsulEnabled.java +++ b/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConditionalOnConsulEnabled.java @@ -49,8 +49,7 @@ public @interface ConditionalOnConsulEnabled { /** * Consul property is enabled. */ - @ConditionalOnProperty(value = "spring.cloud.consul.enabled", - matchIfMissing = true) + @ConditionalOnProperty(value = "spring.cloud.consul.enabled", matchIfMissing = true) static class FoundProperty { } diff --git a/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulAutoConfiguration.java b/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulAutoConfiguration.java index 3ae5d638..827e8710 100644 --- a/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulAutoConfiguration.java +++ b/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulAutoConfiguration.java @@ -60,14 +60,12 @@ public class ConsulAutoConfiguration { public static ConsulClient createConsulClient(ConsulProperties consulProperties) { final int agentPort = consulProperties.getPort(); final String agentHost = !StringUtils.isEmpty(consulProperties.getScheme()) - ? consulProperties.getScheme() + "://" + consulProperties.getHost() - : consulProperties.getHost(); + ? consulProperties.getScheme() + "://" + consulProperties.getHost() : consulProperties.getHost(); if (consulProperties.getTls() != null) { ConsulProperties.TLSConfig tls = consulProperties.getTls(); - TLSConfig tlsConfig = new TLSConfig(tls.getKeyStoreInstanceType(), - tls.getCertificatePath(), tls.getCertificatePassword(), - tls.getKeyStorePath(), tls.getKeyStorePassword()); + TLSConfig tlsConfig = new TLSConfig(tls.getKeyStoreInstanceType(), tls.getCertificatePath(), + tls.getCertificatePassword(), tls.getKeyStorePath(), tls.getKeyStorePassword()); return new ConsulClient(agentHost, agentPort, tlsConfig); } return new ConsulClient(agentHost, agentPort); @@ -98,18 +96,15 @@ public class ConsulAutoConfiguration { @EnableRetry(proxyTargetClass = true) @Import(AopAutoConfiguration.class) @EnableConfigurationProperties(RetryProperties.class) - @ConditionalOnProperty(value = "spring.cloud.consul.retry.enabled", - matchIfMissing = true) + @ConditionalOnProperty(value = "spring.cloud.consul.retry.enabled", matchIfMissing = true) protected static class RetryConfiguration { @Bean(name = "consulRetryInterceptor") @ConditionalOnMissingBean(name = "consulRetryInterceptor") - public RetryOperationsInterceptor consulRetryInterceptor( - RetryProperties properties) { - return RetryInterceptorBuilder.stateless() - .backOffOptions(properties.getInitialInterval(), - properties.getMultiplier(), properties.getMaxInterval()) - .maxAttempts(properties.getMaxAttempts()).build(); + public RetryOperationsInterceptor consulRetryInterceptor(RetryProperties properties) { + return RetryInterceptorBuilder.stateless().backOffOptions(properties.getInitialInterval(), + properties.getMultiplier(), properties.getMaxInterval()).maxAttempts(properties.getMaxAttempts()) + .build(); } } diff --git a/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulEndpoint.java b/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulEndpoint.java index 67ac0c70..eafaf1f5 100644 --- a/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulEndpoint.java +++ b/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulEndpoint.java @@ -54,19 +54,16 @@ public class ConsulEndpoint { data.setAgentServices(agentServices.getValue()); Response>> catalogServices = this.consul - .getCatalogServices(CatalogServicesRequest.newBuilder() - .setQueryParams(QueryParams.DEFAULT).build()); + .getCatalogServices(CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build()); for (String serviceId : catalogServices.getValue().keySet()) { - Response> response = this.consul - .getCatalogService(serviceId, CatalogServiceRequest.newBuilder() - .setQueryParams(QueryParams.DEFAULT).build()); + Response> response = this.consul.getCatalogService(serviceId, + CatalogServiceRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build()); data.getCatalogServices().put(serviceId, response.getValue()); } Response> catalogNodes = this.consul - .getCatalogNodes(CatalogNodesRequest.newBuilder() - .setQueryParams(QueryParams.DEFAULT).build()); + .getCatalogNodes(CatalogNodesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build()); data.setCatalogNodes(catalogNodes.getValue()); return data; @@ -90,8 +87,7 @@ public class ConsulEndpoint { return this.catalogServices; } - public void setCatalogServices( - Map> catalogServices) { + public void setCatalogServices(Map> catalogServices) { this.catalogServices = catalogServices; } @@ -113,10 +109,8 @@ public class ConsulEndpoint { @Override public String toString() { - return new ToStringCreator(this) - .append("catalogServices", this.catalogServices) - .append("agentServices", this.agentServices) - .append("catalogNodes", this.catalogNodes).toString(); + return new ToStringCreator(this).append("catalogServices", this.catalogServices) + .append("agentServices", this.agentServices).append("catalogNodes", this.catalogNodes).toString(); } } diff --git a/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulHealthIndicator.java b/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulHealthIndicator.java index 3f364dd1..3919db11 100644 --- a/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulHealthIndicator.java +++ b/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulHealthIndicator.java @@ -42,10 +42,8 @@ public class ConsulHealthIndicator extends AbstractHealthIndicator { protected void doHealthCheck(Health.Builder builder) throws Exception { final Response leaderStatus = this.consul.getStatusLeader(); final Response>> services = this.consul - .getCatalogServices(CatalogServicesRequest.newBuilder() - .setQueryParams(QueryParams.DEFAULT).build()); - builder.up().withDetail("leader", leaderStatus.getValue()).withDetail("services", - services.getValue()); + .getCatalogServices(CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build()); + builder.up().withDetail("leader", leaderStatus.getValue()).withDetail("services", services.getValue()); } } diff --git a/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulProperties.java b/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulProperties.java index 75dfcfb8..6045ef66 100644 --- a/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulProperties.java +++ b/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/ConsulProperties.java @@ -100,9 +100,8 @@ public class ConsulProperties { @Override public String toString() { - return "ConsulProperties{" + "host='" + this.host + '\'' + ", port=" + this.port - + ", scheme=" + this.scheme + ", tls=" + this.tls + ", enabled=" - + this.enabled + '}'; + return "ConsulProperties{" + "host='" + this.host + '\'' + ", port=" + this.port + ", scheme=" + this.scheme + + ", tls=" + this.tls + ", enabled=" + this.enabled + '}'; } /** @@ -128,9 +127,8 @@ public class ConsulProperties { public TLSConfig() { } - public TLSConfig(KeyStoreInstanceType keyStoreInstanceType, String keyStorePath, - String keyStorePassword, String certificatePath, - String certificatePassword) { + public TLSConfig(KeyStoreInstanceType keyStoreInstanceType, String keyStorePath, String keyStorePassword, + String certificatePath, String certificatePassword) { this.keyStoreInstanceType = keyStoreInstanceType; this.keyStorePath = keyStorePath; this.keyStorePassword = keyStorePassword; @@ -180,10 +178,8 @@ public class ConsulProperties { @Override public String toString() { - return new ToStringCreator(this) - .append("keyStoreInstanceType", this.keyStoreInstanceType) - .append("keyStorePath", this.keyStorePath) - .append("keyStorePassword", this.keyStorePassword) + return new ToStringCreator(this).append("keyStoreInstanceType", this.keyStoreInstanceType) + .append("keyStorePath", this.keyStorePath).append("keyStorePassword", this.keyStorePassword) .append("certificatePath", this.certificatePath) .append("certificatePassword", this.certificatePassword).toString(); } diff --git a/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/RetryProperties.java b/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/RetryProperties.java index a13b00a8..8ff78c0c 100644 --- a/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/RetryProperties.java +++ b/spring-cloud-consul-core/src/main/java/org/springframework/cloud/consul/RetryProperties.java @@ -85,10 +85,8 @@ public class RetryProperties { @Override public String toString() { - return new ToStringCreator(this).append("enabled", this.enabled) - .append("initialInterval", this.initialInterval) - .append("multiplier", this.multiplier) - .append("maxInterval", this.maxInterval) + return new ToStringCreator(this).append("enabled", this.enabled).append("initialInterval", this.initialInterval) + .append("multiplier", this.multiplier).append("maxInterval", this.maxInterval) .append("maxAttempts", this.maxAttempts).toString(); } diff --git a/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/ConsulAutoConfigurationTests.java b/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/ConsulAutoConfigurationTests.java index 53331c74..db571766 100644 --- a/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/ConsulAutoConfigurationTests.java +++ b/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/ConsulAutoConfigurationTests.java @@ -49,12 +49,10 @@ public class ConsulAutoConfigurationTests { @Test public void tlsConfigured() { - CatalogConsulClient client = (CatalogConsulClient) ReflectionTestUtils - .getField(this.consulClient, "catalogClient"); - ConsulRawClient rawClient = (ConsulRawClient) ReflectionTestUtils.getField(client, - "rawClient"); - HttpTransport httpTransport = (HttpTransport) ReflectionTestUtils - .getField(rawClient, "httpTransport"); + CatalogConsulClient client = (CatalogConsulClient) ReflectionTestUtils.getField(this.consulClient, + "catalogClient"); + ConsulRawClient rawClient = (ConsulRawClient) ReflectionTestUtils.getField(client, "rawClient"); + HttpTransport httpTransport = (HttpTransport) ReflectionTestUtils.getField(rawClient, "httpTransport"); assertThat(httpTransport).isInstanceOf(DefaultHttpsTransport.class); } diff --git a/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/ConsulHealthIndicatorDownTest.java b/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/ConsulHealthIndicatorDownTest.java index cd610a16..b84c487a 100644 --- a/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/ConsulHealthIndicatorDownTest.java +++ b/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/ConsulHealthIndicatorDownTest.java @@ -41,8 +41,7 @@ public class ConsulHealthIndicatorDownTest { @Test public void doHealthCheck() { - assertThat(this.healthEndpoint.health().getStatus()) - .as("health status was not DOWN").isEqualTo(Status.DOWN); + assertThat(this.healthEndpoint.health().getStatus()).as("health status was not DOWN").isEqualTo(Status.DOWN); } @EnableAutoConfiguration diff --git a/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/ConsulHealthIndicatorUpTest.java b/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/ConsulHealthIndicatorUpTest.java index 6d63577e..087b06db 100644 --- a/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/ConsulHealthIndicatorUpTest.java +++ b/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/ConsulHealthIndicatorUpTest.java @@ -44,8 +44,7 @@ public class ConsulHealthIndicatorUpTest { @Test public void doHealthCheck() { - assertThat(this.healthEndpoint.health().getStatus()) - .as("health status was not UP").isEqualTo(Status.UP); + assertThat(this.healthEndpoint.health().getStatus()).as("health status was not UP").isEqualTo(Status.UP); } @EnableAutoConfiguration diff --git a/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/test/ConsulTestcontainers.java b/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/test/ConsulTestcontainers.java index ed31bc63..d1fb72e7 100644 --- a/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/test/ConsulTestcontainers.java +++ b/spring-cloud-consul-core/src/test/java/org/springframework/cloud/consul/test/ConsulTestcontainers.java @@ -31,16 +31,14 @@ import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; -public class ConsulTestcontainers - implements ApplicationContextInitializer { +public class ConsulTestcontainers implements ApplicationContextInitializer { static final Logger logger = LoggerFactory.getLogger(ConsulTestcontainers.class); public static GenericContainer consul = new GenericContainer<>("consul:1.7.2") .withLogConsumer(new Slf4jLogConsumer(logger).withSeparateOutputStreams()) .waitingFor(Wait.forHttp("/v1/status/leader")).withExposedPorts(8500) - .withCommand("agent", "-dev", "-server", "-bootstrap", "-client", "0.0.0.0", - "-log-level", "trace"); + .withCommand("agent", "-dev", "-server", "-bootstrap", "-client", "0.0.0.0", "-log-level", "trace"); @Override public void initialize(ConfigurableApplicationContext context) { diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConditionalOnConsulDiscoveryEnabled.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConditionalOnConsulDiscoveryEnabled.java index ffa56614..658cf8bf 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConditionalOnConsulDiscoveryEnabled.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConditionalOnConsulDiscoveryEnabled.java @@ -36,8 +36,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited -@ConditionalOnProperty(value = "spring.cloud.consul.discovery.enabled", - matchIfMissing = true) +@ConditionalOnProperty(value = "spring.cloud.consul.discovery.enabled", matchIfMissing = true) public @interface ConditionalOnConsulDiscoveryEnabled { } diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulCatalogWatch.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulCatalogWatch.java index 95c475c9..332fa106 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulCatalogWatch.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulCatalogWatch.java @@ -41,8 +41,7 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; /** * @author Spencer Gibb */ -public class ConsulCatalogWatch - implements ApplicationEventPublisherAware, SmartLifecycle { +public class ConsulCatalogWatch implements ApplicationEventPublisherAware, SmartLifecycle { private static final Log log = LogFactory.getLog(ConsulDiscoveryClient.class); @@ -64,8 +63,7 @@ public class ConsulCatalogWatch this(properties, consul, getTaskScheduler()); } - public ConsulCatalogWatch(ConsulDiscoveryProperties properties, ConsulClient consul, - TaskScheduler taskScheduler) { + public ConsulCatalogWatch(ConsulDiscoveryProperties properties, ConsulClient consul, TaskScheduler taskScheduler) { this.properties = properties; this.consul = consul; this.taskScheduler = taskScheduler; @@ -96,8 +94,7 @@ public class ConsulCatalogWatch @Override public void start() { if (this.running.compareAndSet(false, true)) { - this.watchFuture = this.taskScheduler.scheduleWithFixedDelay( - this::catalogServicesWatch, + this.watchFuture = this.taskScheduler.scheduleWithFixedDelay(this::catalogServicesWatch, this.properties.getCatalogServicesWatchDelay()); } } @@ -128,19 +125,16 @@ public class ConsulCatalogWatch } CatalogServicesRequest request = CatalogServicesRequest.newBuilder() - .setQueryParams(new QueryParams( - this.properties.getCatalogServicesWatchTimeout(), index)) + .setQueryParams(new QueryParams(this.properties.getCatalogServicesWatchTimeout(), index)) .setToken(this.properties.getAclToken()).build(); - Response>> response = this.consul - .getCatalogServices(request); + Response>> response = this.consul.getCatalogServices(request); Long consulIndex = response.getConsulIndex(); if (consulIndex != null) { this.catalogServicesIndex.set(BigInteger.valueOf(consulIndex)); } if (log.isTraceEnabled()) { - log.trace("Received services update from consul: " + response.getValue() - + ", index: " + consulIndex); + log.trace("Received services update from consul: " + response.getValue() + ", index: " + consulIndex); } this.publisher.publishEvent(new HeartbeatEvent(this, consulIndex)); } diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulCatalogWatchAutoConfiguration.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulCatalogWatchAutoConfiguration.java index ec5a3190..09649e42 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulCatalogWatchAutoConfiguration.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulCatalogWatchAutoConfiguration.java @@ -37,9 +37,7 @@ import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; */ @Configuration(proxyBeanMethods = false) @ConditionalOnConsulEnabled -@ConditionalOnProperty( - value = "spring.cloud.consul.discovery.catalog-services-watch.enabled", - matchIfMissing = true) +@ConditionalOnProperty(value = "spring.cloud.consul.discovery.catalog-services-watch.enabled", matchIfMissing = true) @ConditionalOnDiscoveryEnabled @AutoConfigureAfter({ ConsulDiscoveryClientConfiguration.class }) @ConditionalOnBean(ConsulDiscoveryProperties.class) @@ -52,9 +50,8 @@ public class ConsulCatalogWatchAutoConfiguration { @Bean @ConditionalOnMissingBean - public ConsulCatalogWatch consulCatalogWatch( - ConsulDiscoveryProperties discoveryProperties, ConsulClient consulClient, - @Qualifier(CATALOG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) { + public ConsulCatalogWatch consulCatalogWatch(ConsulDiscoveryProperties discoveryProperties, + ConsulClient consulClient, @Qualifier(CATALOG_WATCH_TASK_SCHEDULER_NAME) TaskScheduler taskScheduler) { return new ConsulCatalogWatch(discoveryProperties, consulClient, taskScheduler); } diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClient.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClient.java index 13e43cd9..9f1c5e8f 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClient.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClient.java @@ -49,8 +49,7 @@ public class ConsulDiscoveryClient implements DiscoveryClient { private final ConsulDiscoveryProperties properties; - public ConsulDiscoveryClient(ConsulClient client, - ConsulDiscoveryProperties properties) { + public ConsulDiscoveryClient(ConsulClient client, ConsulDiscoveryProperties properties) { this.client = client; this.properties = properties; } @@ -62,12 +61,10 @@ public class ConsulDiscoveryClient implements DiscoveryClient { @Override public List getInstances(final String serviceId) { - return getInstances(serviceId, - new QueryParams(this.properties.getConsistencyMode())); + return getInstances(serviceId, new QueryParams(this.properties.getConsistencyMode())); } - public List getInstances(final String serviceId, - final QueryParams queryParams) { + public List getInstances(final String serviceId, final QueryParams queryParams) { List instances = new ArrayList<>(); addInstancesToList(instances, serviceId, queryParams); @@ -75,15 +72,12 @@ public class ConsulDiscoveryClient implements DiscoveryClient { return instances; } - private void addInstancesToList(List instances, String serviceId, - QueryParams queryParams) { + private void addInstancesToList(List instances, String serviceId, QueryParams queryParams) { - HealthServicesRequest request = HealthServicesRequest.newBuilder() - .setTag(this.properties.getDefaultQueryTag()) + HealthServicesRequest request = HealthServicesRequest.newBuilder().setTag(this.properties.getDefaultQueryTag()) .setPassing(this.properties.isQueryPassing()).setQueryParams(queryParams) .setToken(this.properties.getAclToken()).build(); - Response> services = this.client.getHealthServices(serviceId, - request); + Response> services = this.client.getHealthServices(serviceId, request); for (HealthService service : services.getValue()) { String host = findHost(service); @@ -96,8 +90,8 @@ public class ConsulDiscoveryClient implements DiscoveryClient { if (metadata.containsKey("secure")) { secure = Boolean.parseBoolean(metadata.get("secure")); } - instances.add(new DefaultServiceInstance(service.getService().getId(), - serviceId, host, service.getService().getPort(), secure, metadata)); + instances.add(new DefaultServiceInstance(service.getService().getId(), serviceId, host, + service.getService().getPort(), secure, metadata)); } } @@ -105,8 +99,7 @@ public class ConsulDiscoveryClient implements DiscoveryClient { List instances = new ArrayList<>(); Response>> services = this.client - .getCatalogServices(CatalogServicesRequest.newBuilder() - .setQueryParams(QueryParams.DEFAULT).build()); + .getCatalogServices(CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build()); for (String serviceId : services.getValue().keySet()) { addInstancesToList(instances, serviceId, QueryParams.DEFAULT); } @@ -115,11 +108,9 @@ public class ConsulDiscoveryClient implements DiscoveryClient { @Override public List getServices() { - CatalogServicesRequest request = CatalogServicesRequest.newBuilder() - .setQueryParams(QueryParams.DEFAULT) + CatalogServicesRequest request = CatalogServicesRequest.newBuilder().setQueryParams(QueryParams.DEFAULT) .setToken(this.properties.getAclToken()).build(); - return new ArrayList<>( - this.client.getCatalogServices(request).getValue().keySet()); + return new ArrayList<>(this.client.getCatalogServices(request).getValue().keySet()); } @Override diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientConfiguration.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientConfiguration.java index 7bb5e2e4..1ab56866 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientConfiguration.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientConfiguration.java @@ -44,8 +44,7 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnConsulEnabled @ConditionalOnConsulDiscoveryEnabled @EnableConfigurationProperties -@AutoConfigureBefore({ SimpleDiscoveryClientAutoConfiguration.class, - CommonsClientAutoConfiguration.class }) +@AutoConfigureBefore({ SimpleDiscoveryClientAutoConfiguration.class, CommonsClientAutoConfiguration.class }) @AutoConfigureAfter({ UtilAutoConfiguration.class, ConsulAutoConfiguration.class }) public class ConsulDiscoveryClientConfiguration { diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryProperties.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryProperties.java index 7bd1b7e8..4f2abfe5 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryProperties.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryProperties.java @@ -580,40 +580,29 @@ public class ConsulDiscoveryProperties { return new ToStringCreator(this).append("aclToken", this.aclToken) .append("catalogServicesWatchDelay", this.catalogServicesWatchDelay) .append("catalogServicesWatchTimeout", this.catalogServicesWatchTimeout) - .append("consistencyMode", this.consistencyMode) - .append("datacenters", this.datacenters) + .append("consistencyMode", this.consistencyMode).append("datacenters", this.datacenters) .append("defaultQueryTag", this.defaultQueryTag) - .append("defaultZoneMetadataName", this.defaultZoneMetadataName) - .append("deregister", this.deregister).append("enabled", this.enabled) - .append("enableTagOverride", this.enableTagOverride) + .append("defaultZoneMetadataName", this.defaultZoneMetadataName).append("deregister", this.deregister) + .append("enabled", this.enabled).append("enableTagOverride", this.enableTagOverride) .append("failFast", this.failFast).append("hostInfo", this.hostInfo) .append("healthCheckCriticalTimeout", this.healthCheckCriticalTimeout) .append("healthCheckHeaders", this.healthCheckHeaders) - .append("healthCheckInterval", this.healthCheckInterval) - .append("healthCheckPath", this.healthCheckPath) + .append("healthCheckInterval", this.healthCheckInterval).append("healthCheckPath", this.healthCheckPath) .append("healthCheckTimeout", this.healthCheckTimeout) .append("healthCheckTlsSkipVerify", this.healthCheckTlsSkipVerify) - .append("healthCheckUrl", this.healthCheckUrl) - .append("hostname", this.hostname) + .append("healthCheckUrl", this.healthCheckUrl).append("hostname", this.hostname) .append("includeHostnameInInstanceId", this.includeHostnameInInstanceId) - .append("instanceId", this.instanceId) - .append("instanceGroup", this.instanceGroup) - .append("instanceZone", this.instanceZone) - .append("ipAddress", this.ipAddress).append("lifecycle", this.lifecycle) - .append("metadata", this.metadata) + .append("instanceId", this.instanceId).append("instanceGroup", this.instanceGroup) + .append("instanceZone", this.instanceZone).append("ipAddress", this.ipAddress) + .append("lifecycle", this.lifecycle).append("metadata", this.metadata) .append("managementEnableTagOverride", this.managementEnableTagOverride) - .append("managementMetadata", this.managementMetadata) - .append("managementPort", this.managementPort) - .append("managementSuffix", this.managementSuffix) - .append("managementTags", this.managementTags).append("order", this.order) - .append("port", this.port) - .append("preferAgentAddress", this.preferAgentAddress) - .append("preferIpAddress", this.preferIpAddress) - .append("queryPassing", this.queryPassing) - .append("register", this.register) - .append("registerHealthCheck", this.registerHealthCheck) - .append("scheme", this.scheme).append("serviceName", this.serviceName) - .append("serverListQueryTags", this.serverListQueryTags) + .append("managementMetadata", this.managementMetadata).append("managementPort", this.managementPort) + .append("managementSuffix", this.managementSuffix).append("managementTags", this.managementTags) + .append("order", this.order).append("port", this.port) + .append("preferAgentAddress", this.preferAgentAddress).append("preferIpAddress", this.preferIpAddress) + .append("queryPassing", this.queryPassing).append("register", this.register) + .append("registerHealthCheck", this.registerHealthCheck).append("scheme", this.scheme) + .append("serviceName", this.serviceName).append("serverListQueryTags", this.serverListQueryTags) .append("tags", this.tags).toString(); } diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/HeartbeatProperties.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/HeartbeatProperties.java index a5842e42..ba715037 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/HeartbeatProperties.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/HeartbeatProperties.java @@ -38,8 +38,7 @@ import org.springframework.validation.annotation.Validated; @Validated public class HeartbeatProperties { - private static final Log log = org.apache.commons.logging.LogFactory - .getLog(HeartbeatProperties.class); + private static final Log log = org.apache.commons.logging.LogFactory.getLog(HeartbeatProperties.class); // TODO: change enabled to default to true when I stop seeing messages like // [WARN] agent: Check 'service:testConsulApp:xtest:8080' missed TTL, is now critical @@ -87,16 +86,14 @@ public class HeartbeatProperties { return this.intervalRatio; } - public void setIntervalRatio( - @DecimalMin("0.1") @DecimalMax("0.9") double intervalRatio) { + public void setIntervalRatio(@DecimalMin("0.1") @DecimalMax("0.9") double intervalRatio) { this.intervalRatio = intervalRatio; } @Override public String toString() { - return new ToStringCreator(this).append("enabled", this.enabled) - .append("ttl", this.ttl).append("intervalRatio", this.intervalRatio) - .toString(); + return new ToStringCreator(this).append("enabled", this.enabled).append("ttl", this.ttl) + .append("intervalRatio", this.intervalRatio).toString(); } } diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/TtlScheduler.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/TtlScheduler.java index fe82e539..684240e1 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/TtlScheduler.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/TtlScheduler.java @@ -40,8 +40,7 @@ public class TtlScheduler { private final Map serviceHeartbeats = new ConcurrentHashMap<>(); - private final TaskScheduler scheduler = new ConcurrentTaskScheduler( - Executors.newSingleThreadScheduledExecutor()); + private final TaskScheduler scheduler = new ConcurrentTaskScheduler(Executors.newSingleThreadScheduledExecutor()); private HeartbeatProperties configuration; @@ -62,8 +61,7 @@ public class TtlScheduler { * @param instanceId instance id */ public void add(String instanceId) { - ScheduledFuture task = this.scheduler.scheduleAtFixedRate( - new ConsulHeartbeatTask(instanceId), + ScheduledFuture task = this.scheduler.scheduleAtFixedRate(new ConsulHeartbeatTask(instanceId), this.configuration.computeHeartbeatInterval().toMillis()); ScheduledFuture previousTask = this.serviceHeartbeats.put(instanceId, task); if (previousTask != null) { diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/configclient/ConsulConfigServerAutoConfiguration.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/configclient/ConsulConfigServerAutoConfiguration.java index cbbf8a0f..5ce9a1c3 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/configclient/ConsulConfigServerAutoConfiguration.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/configclient/ConsulConfigServerAutoConfiguration.java @@ -35,8 +35,7 @@ import org.springframework.util.StringUtils; */ @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties -@ConditionalOnClass({ ConsulDiscoveryProperties.class, ConsulClient.class, - ConfigServerProperties.class }) +@ConditionalOnClass({ ConsulDiscoveryProperties.class, ConsulClient.class, ConfigServerProperties.class }) public class ConsulConfigServerAutoConfiguration { /** diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/configclient/ConsulDiscoveryClientConfigServiceBootstrapConfiguration.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/configclient/ConsulDiscoveryClientConfigServiceBootstrapConfiguration.java index a870b224..633ec97d 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/configclient/ConsulDiscoveryClientConfigServiceBootstrapConfiguration.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/configclient/ConsulDiscoveryClientConfigServiceBootstrapConfiguration.java @@ -34,8 +34,7 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnClass(ConfigServicePropertySourceLocator.class) @ConditionalOnProperty("spring.cloud.config.discovery.enabled") @Configuration(proxyBeanMethods = false) -@ImportAutoConfiguration({ ConsulAutoConfiguration.class, - ConsulDiscoveryClientConfiguration.class, +@ImportAutoConfiguration({ ConsulAutoConfiguration.class, ConsulDiscoveryClientConfiguration.class, ConsulReactiveDiscoveryClientConfiguration.class }) public class ConsulDiscoveryClientConfigServiceBootstrapConfiguration { diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClient.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClient.java index a46cb3c0..a04b2fdf 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClient.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClient.java @@ -47,15 +47,13 @@ import static org.springframework.cloud.consul.discovery.ConsulServerUtils.findH */ public class ConsulReactiveDiscoveryClient implements ReactiveDiscoveryClient { - private static final Logger logger = LoggerFactory - .getLogger(ConsulReactiveDiscoveryClient.class); + private static final Logger logger = LoggerFactory.getLogger(ConsulReactiveDiscoveryClient.class); private final ConsulClient client; private final ConsulDiscoveryProperties properties; - public ConsulReactiveDiscoveryClient(ConsulClient client, - ConsulDiscoveryProperties properties) { + public ConsulReactiveDiscoveryClient(ConsulClient client, ConsulDiscoveryProperties properties) { this.client = client; this.properties = properties; } @@ -80,19 +78,15 @@ public class ConsulReactiveDiscoveryClient implements ReactiveDiscoveryClient { } private List getHealthServices(String serviceId) { - HealthServicesRequest request = HealthServicesRequest.newBuilder() - .setTag(this.properties.getDefaultQueryTag()) - .setPassing(this.properties.isQueryPassing()) - .setQueryParams(QueryParams.DEFAULT) + HealthServicesRequest request = HealthServicesRequest.newBuilder().setTag(this.properties.getDefaultQueryTag()) + .setPassing(this.properties.isQueryPassing()).setQueryParams(QueryParams.DEFAULT) .setToken(this.properties.getAclToken()).build(); - Response> services = client.getHealthServices(serviceId, - request); + Response> services = client.getHealthServices(serviceId, request); return services == null ? Collections.emptyList() : services.getValue(); } - private ServiceInstance mapToServiceInstance(HealthService service, - String serviceId) { + private ServiceInstance mapToServiceInstance(HealthService service, String serviceId) { String host = findHost(service); Map metadata = service.getService().getMeta(); if (metadata == null) { @@ -102,20 +96,17 @@ public class ConsulReactiveDiscoveryClient implements ReactiveDiscoveryClient { if (metadata.containsKey("secure")) { secure = Boolean.parseBoolean(metadata.get("secure")); } - return new DefaultServiceInstance(service.getService().getId(), serviceId, host, - service.getService().getPort(), secure, metadata); + return new DefaultServiceInstance(service.getService().getId(), serviceId, host, service.getService().getPort(), + secure, metadata); } @Override public Flux getServices() { return Flux.defer(() -> { - CatalogServicesRequest request = CatalogServicesRequest.newBuilder() - .setToken(properties.getAclToken()) + CatalogServicesRequest request = CatalogServicesRequest.newBuilder().setToken(properties.getAclToken()) .setQueryParams(QueryParams.DEFAULT).build(); - Response>> services = client - .getCatalogServices(request); - return services == null ? Flux.empty() - : Flux.fromIterable(services.getValue().keySet()); + Response>> services = client.getCatalogServices(request); + return services == null ? Flux.empty() : Flux.fromIterable(services.getValue().keySet()); }).onErrorResume(exception -> { logger.error("Error getting services from Consul.", exception); return Flux.empty(); diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClientConfiguration.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClientConfiguration.java index 4c317d3b..10867ebd 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClientConfiguration.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClientConfiguration.java @@ -49,8 +49,7 @@ import org.springframework.context.annotation.Configuration; @ConditionalOnConsulDiscoveryEnabled @EnableConfigurationProperties(DiscoveryClientHealthIndicatorProperties.class) @AutoConfigureBefore(ReactiveCommonsClientAutoConfiguration.class) -@AutoConfigureAfter({ UtilAutoConfiguration.class, - ReactiveCompositeDiscoveryClientAutoConfiguration.class, +@AutoConfigureAfter({ UtilAutoConfiguration.class, ReactiveCompositeDiscoveryClientAutoConfiguration.class, ConsulAutoConfiguration.class }) public class ConsulReactiveDiscoveryClientConfiguration { @@ -62,18 +61,16 @@ public class ConsulReactiveDiscoveryClientConfiguration { @Bean @ConditionalOnMissingBean - public ConsulReactiveDiscoveryClient consulReactiveDiscoveryClient( - ConsulClient client, ConsulDiscoveryProperties discoveryProperties) { + public ConsulReactiveDiscoveryClient consulReactiveDiscoveryClient(ConsulClient client, + ConsulDiscoveryProperties discoveryProperties) { return new ConsulReactiveDiscoveryClient(client, discoveryProperties); } @Bean - @ConditionalOnClass( - name = "org.springframework.boot.actuate.health.ReactiveHealthIndicator") + @ConditionalOnClass(name = "org.springframework.boot.actuate.health.ReactiveHealthIndicator") @ConditionalOnDiscoveryHealthIndicatorEnabled public ReactiveDiscoveryClientHealthIndicator consulReactiveDiscoveryClientHealthIndicator( - ConsulReactiveDiscoveryClient client, - DiscoveryClientHealthIndicatorProperties properties) { + ConsulReactiveDiscoveryClient client, DiscoveryClientHealthIndicatorProperties properties) { return new ReactiveDiscoveryClientHealthIndicator(client, properties); } diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistration.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistration.java index d07a01f6..34ec74d9 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistration.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistration.java @@ -56,17 +56,15 @@ public class ConsulAutoRegistration extends ConsulRegistration { @Deprecated public ConsulAutoRegistration(NewService service, - AutoServiceRegistrationProperties autoServiceRegistrationProperties, - ConsulDiscoveryProperties properties, ApplicationContext context, - HeartbeatProperties heartbeatProperties) { - this(service, autoServiceRegistrationProperties, properties, context, - heartbeatProperties, Collections.emptyList()); + AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, + ApplicationContext context, HeartbeatProperties heartbeatProperties) { + this(service, autoServiceRegistrationProperties, properties, context, heartbeatProperties, + Collections.emptyList()); } public ConsulAutoRegistration(NewService service, - AutoServiceRegistrationProperties autoServiceRegistrationProperties, - ConsulDiscoveryProperties properties, ApplicationContext context, - HeartbeatProperties heartbeatProperties, + AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, + ApplicationContext context, HeartbeatProperties heartbeatProperties, List managementRegistrationCustomizers) { super(service, properties); this.autoServiceRegistrationProperties = autoServiceRegistrationProperties; @@ -76,9 +74,8 @@ public class ConsulAutoRegistration extends ConsulRegistration { } public static ConsulAutoRegistration registration( - AutoServiceRegistrationProperties autoServiceRegistrationProperties, - ConsulDiscoveryProperties properties, ApplicationContext context, - List registrationCustomizers, + AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, + ApplicationContext context, List registrationCustomizers, List managementRegistrationCustomizers, HeartbeatProperties heartbeatProperties) { @@ -96,19 +93,16 @@ public class ConsulAutoRegistration extends ConsulRegistration { if (properties.getPort() != null) { service.setPort(properties.getPort()); // we know the port and can set the check - setCheck(service, autoServiceRegistrationProperties, properties, context, - heartbeatProperties); + setCheck(service, autoServiceRegistrationProperties, properties, context, heartbeatProperties); } - ConsulAutoRegistration registration = new ConsulAutoRegistration(service, - autoServiceRegistrationProperties, properties, context, - heartbeatProperties, managementRegistrationCustomizers); + ConsulAutoRegistration registration = new ConsulAutoRegistration(service, autoServiceRegistrationProperties, + properties, context, heartbeatProperties, managementRegistrationCustomizers); customize(registrationCustomizers, registration); return registration; } - public static void customize( - List registrationCustomizers, + public static void customize(List registrationCustomizers, ConsulAutoRegistration registration) { if (registrationCustomizers != null) { for (ConsulRegistrationCustomizer customizer : registrationCustomizers) { @@ -117,14 +111,11 @@ public class ConsulAutoRegistration extends ConsulRegistration { } } - public static void setCheck(NewService service, - AutoServiceRegistrationProperties autoServiceRegistrationProperties, - ConsulDiscoveryProperties properties, ApplicationContext context, - HeartbeatProperties heartbeatProperties) { + public static void setCheck(NewService service, AutoServiceRegistrationProperties autoServiceRegistrationProperties, + ConsulDiscoveryProperties properties, ApplicationContext context, HeartbeatProperties heartbeatProperties) { if (properties.isRegisterHealthCheck() && service.getCheck() == null) { Integer checkPort; - if (shouldRegisterManagement(autoServiceRegistrationProperties, properties, - context)) { + if (shouldRegisterManagement(autoServiceRegistrationProperties, properties, context)) { checkPort = getManagementPort(properties, context); } else { @@ -136,32 +127,27 @@ public class ConsulAutoRegistration extends ConsulRegistration { } public static ConsulAutoRegistration managementRegistration( - AutoServiceRegistrationProperties autoServiceRegistrationProperties, - ConsulDiscoveryProperties properties, ApplicationContext context, - List managementRegistrationCustomizers, + AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, + ApplicationContext context, List managementRegistrationCustomizers, HeartbeatProperties heartbeatProperties) { NewService management = new NewService(); management.setId(getManagementServiceId(properties, context)); management.setAddress(properties.getHostname()); - management - .setName(getManagementServiceName(properties, context.getEnvironment())); + management.setName(getManagementServiceName(properties, context.getEnvironment())); management.setPort(getManagementPort(properties, context)); management.setTags(properties.getManagementTags()); management.setEnableTagOverride(properties.getManagementEnableTagOverride()); management.setMeta(properties.getManagementMetadata()); if (properties.isRegisterHealthCheck()) { - management.setCheck(createCheck(getManagementPort(properties, context), - heartbeatProperties, properties)); + management.setCheck(createCheck(getManagementPort(properties, context), heartbeatProperties, properties)); } - ConsulAutoRegistration registration = new ConsulAutoRegistration(management, - autoServiceRegistrationProperties, properties, context, - heartbeatProperties, managementRegistrationCustomizers); + ConsulAutoRegistration registration = new ConsulAutoRegistration(management, autoServiceRegistrationProperties, + properties, context, heartbeatProperties, managementRegistrationCustomizers); managementCustomize(managementRegistrationCustomizers, registration); return registration; } - public static void managementCustomize( - List registrationCustomizers, + public static void managementCustomize(List registrationCustomizers, ConsulAutoRegistration registration) { if (registrationCustomizers != null) { for (ConsulManagementRegistrationCustomizer customizer : registrationCustomizers) { @@ -170,23 +156,19 @@ public class ConsulAutoRegistration extends ConsulRegistration { } } - public static String getInstanceId(ConsulDiscoveryProperties properties, - ApplicationContext context) { + public static String getInstanceId(ConsulDiscoveryProperties properties, ApplicationContext context) { if (!StringUtils.hasText(properties.getInstanceId())) { - return normalizeForDns(IdUtils.getDefaultInstanceId(context.getEnvironment(), - properties.isIncludeHostnameInInstanceId())); + return normalizeForDns( + IdUtils.getDefaultInstanceId(context.getEnvironment(), properties.isIncludeHostnameInInstanceId())); } return normalizeForDns(properties.getInstanceId()); } public static String normalizeForDns(String s) { - if (s == null || !Character.isLetter(s.charAt(0)) - || !Character.isLetterOrDigit(s.charAt(s.length() - 1))) { + if (s == null || !Character.isLetter(s.charAt(0)) || !Character.isLetterOrDigit(s.charAt(s.length() - 1))) { throw new IllegalArgumentException( - "Consul service ids must not be empty, must start " - + "with a letter, end with a letter or digit, " - + "and have as interior characters only letters, " - + "digits, and hyphen: " + s); + "Consul service ids must not be empty, must start " + "with a letter, end with a letter or digit, " + + "and have as interior characters only letters, " + "digits, and hyphen: " + s); } StringBuilder normalized = new StringBuilder(); @@ -216,8 +198,7 @@ public class ConsulAutoRegistration extends ConsulRegistration { // add metadata from other properties. See createTags above. if (!StringUtils.isEmpty(properties.getInstanceZone())) { - metadata.put(properties.getDefaultZoneMetadataName(), - properties.getInstanceZone()); + metadata.put(properties.getDefaultZoneMetadataName(), properties.getInstanceZone()); } if (!StringUtils.isEmpty(properties.getInstanceGroup())) { metadata.put("group", properties.getInstanceGroup()); @@ -225,18 +206,16 @@ public class ConsulAutoRegistration extends ConsulRegistration { // store the secure flag in the tags so that clients will be able to figure // out whether to use http or https automatically - metadata.put("secure", - Boolean.toString(properties.getScheme().equalsIgnoreCase("https"))); + metadata.put("secure", Boolean.toString(properties.getScheme().equalsIgnoreCase("https"))); return metadata; } - public static NewService.Check createCheck(Integer port, - HeartbeatProperties ttlConfig, ConsulDiscoveryProperties properties) { + public static NewService.Check createCheck(Integer port, HeartbeatProperties ttlConfig, + ConsulDiscoveryProperties properties) { NewService.Check check = new NewService.Check(); if (StringUtils.hasText(properties.getHealthCheckCriticalTimeout())) { - check.setDeregisterCriticalServiceAfter( - properties.getHealthCheckCriticalTimeout()); + check.setDeregisterCriticalServiceAfter(properties.getHealthCheckCriticalTimeout()); } if (ttlConfig.isEnabled()) { // FIXME 3.0.0 @@ -252,8 +231,8 @@ public class ConsulAutoRegistration extends ConsulRegistration { check.setHttp(properties.getHealthCheckUrl()); } else { - check.setHttp(String.format("%s://%s:%s%s", properties.getScheme(), - properties.getHostname(), port, properties.getHealthCheckPath())); + check.setHttp(String.format("%s://%s:%s%s", properties.getScheme(), properties.getHostname(), port, + properties.getHealthCheckPath())); } check.setHeader(properties.getHealthCheckHeaders()); check.setInterval(properties.getHealthCheckInterval()); @@ -267,8 +246,7 @@ public class ConsulAutoRegistration extends ConsulRegistration { * @param env Spring environment * @return the app name, currently the spring.application.name property */ - public static String getAppName(ConsulDiscoveryProperties properties, - Environment env) { + public static String getAppName(ConsulDiscoveryProperties properties, Environment env) { final String appName = properties.getServiceName(); if (StringUtils.hasText(appName)) { return appName; @@ -283,12 +261,10 @@ public class ConsulAutoRegistration extends ConsulRegistration { * @return if the management service should be registered with the * {@link ServiceRegistry} */ - public static boolean shouldRegisterManagement( - AutoServiceRegistrationProperties autoServiceRegistrationProperties, + public static boolean shouldRegisterManagement(AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, ApplicationContext context) { return autoServiceRegistrationProperties.isRegisterManagement() - && getManagementPort(properties, context) != null - && ManagementServerPortUtils.isDifferent(context); + && getManagementPort(properties, context) != null && ManagementServerPortUtils.isDifferent(context); } /** @@ -296,15 +272,12 @@ public class ConsulAutoRegistration extends ConsulRegistration { * @param context Spring application context * @return the serviceId of the Management Service */ - public static String getManagementServiceId(ConsulDiscoveryProperties properties, - ApplicationContext context) { + public static String getManagementServiceId(ConsulDiscoveryProperties properties, ApplicationContext context) { final String instanceId = properties.getInstanceId(); if (StringUtils.hasText(instanceId)) { - return normalizeForDns( - instanceId + SEPARATOR + properties.getManagementSuffix()); + return normalizeForDns(instanceId + SEPARATOR + properties.getManagementSuffix()); } - return normalizeForDns( - IdUtils.getDefaultInstanceId(context.getEnvironment(), false)) + SEPARATOR + return normalizeForDns(IdUtils.getDefaultInstanceId(context.getEnvironment(), false)) + SEPARATOR + properties.getManagementSuffix(); } @@ -313,15 +286,12 @@ public class ConsulAutoRegistration extends ConsulRegistration { * @param env Spring environment * @return the service name of the Management Service */ - public static String getManagementServiceName(ConsulDiscoveryProperties properties, - Environment env) { + public static String getManagementServiceName(ConsulDiscoveryProperties properties, Environment env) { final String appName = properties.getServiceName(); if (StringUtils.hasText(appName)) { - return normalizeForDns( - appName + SEPARATOR + properties.getManagementSuffix()); + return normalizeForDns(appName + SEPARATOR + properties.getManagementSuffix()); } - return normalizeForDns(getAppName(properties, env)) + SEPARATOR - + properties.getManagementSuffix(); + return normalizeForDns(getAppName(properties, env)) + SEPARATOR + properties.getManagementSuffix(); } /** @@ -329,8 +299,7 @@ public class ConsulAutoRegistration extends ConsulRegistration { * @param context Spring application context * @return the port of the Management Service */ - public static Integer getManagementPort(ConsulDiscoveryProperties properties, - ApplicationContext context) { + public static Integer getManagementPort(ConsulDiscoveryProperties properties, ApplicationContext context) { // If an alternate external port is specified, use it instead if (properties.getManagementPort() != null) { return properties.getManagementPort(); @@ -346,14 +315,13 @@ public class ConsulAutoRegistration extends ConsulRegistration { // we might not have a port until now, so this is the earliest we // can create a check - setCheck(getService(), this.autoServiceRegistrationProperties, getProperties(), - this.context, this.heartbeatProperties); - } - - public ConsulAutoRegistration managementRegistration() { - return managementRegistration(this.autoServiceRegistrationProperties, - getProperties(), this.context, this.managementRegistrationCustomizers, + setCheck(getService(), this.autoServiceRegistrationProperties, getProperties(), this.context, this.heartbeatProperties); } + public ConsulAutoRegistration managementRegistration() { + return managementRegistration(this.autoServiceRegistrationProperties, getProperties(), this.context, + this.managementRegistrationCustomizers, this.heartbeatProperties); + } + } diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistration.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistration.java index 191e5ee4..5187338d 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistration.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistration.java @@ -30,8 +30,7 @@ import org.springframework.util.StringUtils; /** * @author Spencer Gibb */ -public class ConsulAutoServiceRegistration - extends AbstractAutoServiceRegistration { +public class ConsulAutoServiceRegistration extends AbstractAutoServiceRegistration { private static Log log = LogFactory.getLog(ConsulAutoServiceRegistration.class); @@ -40,8 +39,8 @@ public class ConsulAutoServiceRegistration private ConsulAutoRegistration registration; public ConsulAutoServiceRegistration(ConsulServiceRegistry serviceRegistry, - AutoServiceRegistrationProperties autoServiceRegistrationProperties, - ConsulDiscoveryProperties properties, ConsulAutoRegistration registration) { + AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, + ConsulAutoRegistration registration) { super(serviceRegistry, autoServiceRegistrationProperties); this.properties = properties; this.registration = registration; @@ -53,12 +52,10 @@ public class ConsulAutoServiceRegistration @Override protected ConsulAutoRegistration getRegistration() { - if (this.registration.getService().getPort() == null - && this.getPort().get() > 0) { + if (this.registration.getService().getPort() == null && this.getPort().get() > 0) { this.registration.initializePort(this.getPort().get()); } - Assert.notNull(this.registration.getService().getPort(), - "service.port has not been set"); + Assert.notNull(this.registration.getService().getPort(), "service.port has not been set"); return this.registration; } diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationAutoConfiguration.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationAutoConfiguration.java index 40277b48..f2d13acb 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationAutoConfiguration.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationAutoConfiguration.java @@ -43,12 +43,10 @@ import org.springframework.context.annotation.Configuration; */ @Configuration(proxyBeanMethods = false) @ConditionalOnBean(AutoServiceRegistrationProperties.class) -@ConditionalOnMissingBean( - type = "org.springframework.cloud.consul.discovery.ConsulLifecycle") +@ConditionalOnMissingBean(type = "org.springframework.cloud.consul.discovery.ConsulLifecycle") @ConditionalOnConsulEnabled @Conditional(ConsulAutoServiceRegistrationAutoConfiguration.OnConsulRegistrationEnabledCondition.class) -@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class, - ConsulServiceRegistryAutoConfiguration.class }) +@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class, ConsulServiceRegistryAutoConfiguration.class }) public class ConsulAutoServiceRegistrationAutoConfiguration { @Autowired @@ -56,13 +54,11 @@ public class ConsulAutoServiceRegistrationAutoConfiguration { @Bean @ConditionalOnMissingBean - public ConsulAutoServiceRegistration consulAutoServiceRegistration( - ConsulServiceRegistry registry, - AutoServiceRegistrationProperties autoServiceRegistrationProperties, - ConsulDiscoveryProperties properties, + public ConsulAutoServiceRegistration consulAutoServiceRegistration(ConsulServiceRegistry registry, + AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, ConsulAutoRegistration consulRegistration) { - return new ConsulAutoServiceRegistration(registry, - autoServiceRegistrationProperties, properties, consulRegistration); + return new ConsulAutoServiceRegistration(registry, autoServiceRegistrationProperties, properties, + consulRegistration); } @Bean @@ -74,14 +70,14 @@ public class ConsulAutoServiceRegistrationAutoConfiguration { @Bean @ConditionalOnMissingBean public ConsulAutoRegistration consulRegistration( - AutoServiceRegistrationProperties autoServiceRegistrationProperties, - ConsulDiscoveryProperties properties, ApplicationContext applicationContext, + AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, + ApplicationContext applicationContext, ObjectProvider> registrationCustomizers, ObjectProvider> managementRegistrationCustomizers, HeartbeatProperties heartbeatProperties) { - return ConsulAutoRegistration.registration(autoServiceRegistrationProperties, - properties, applicationContext, registrationCustomizers.getIfAvailable(), - managementRegistrationCustomizers.getIfAvailable(), heartbeatProperties); + return ConsulAutoRegistration.registration(autoServiceRegistrationProperties, properties, applicationContext, + registrationCustomizers.getIfAvailable(), managementRegistrationCustomizers.getIfAvailable(), + heartbeatProperties); } @Configuration(proxyBeanMethods = false) @@ -89,42 +85,35 @@ public class ConsulAutoServiceRegistrationAutoConfiguration { protected static class ConsulServletConfiguration { @Bean - public ConsulRegistrationCustomizer servletConsulCustomizer( - ObjectProvider servletContext) { + public ConsulRegistrationCustomizer servletConsulCustomizer(ObjectProvider servletContext) { return new ConsulServletRegistrationCustomizer(servletContext); } } - protected static class OnConsulRegistrationEnabledCondition - extends AllNestedConditions { + protected static class OnConsulRegistrationEnabledCondition extends AllNestedConditions { OnConsulRegistrationEnabledCondition() { super(ConfigurationPhase.REGISTER_BEAN); } - @ConditionalOnProperty( - value = "spring.cloud.service-registry.auto-registration.enabled", - matchIfMissing = true) + @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) static class AutoRegistrationEnabledClass { } - @ConditionalOnProperty( - value = "spring.cloud.consul.service-registry.auto-registration.enabled", + @ConditionalOnProperty(value = "spring.cloud.consul.service-registry.auto-registration.enabled", matchIfMissing = true) static class ConsulAutoRegistrationEnabledClass { } - @ConditionalOnProperty(value = "spring.cloud.service-registry.enabled", - matchIfMissing = true) + @ConditionalOnProperty(value = "spring.cloud.service-registry.enabled", matchIfMissing = true) static class ServiceRegistryEnabledClass { } - @ConditionalOnProperty(value = "spring.cloud.consul.service-registry.enabled", - matchIfMissing = true) + @ConditionalOnProperty(value = "spring.cloud.consul.service-registry.enabled", matchIfMissing = true) static class ConsulServiceRegistryEnabledClass { } diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationListener.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationListener.java index 834274ae..183498a1 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationListener.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationListener.java @@ -31,8 +31,7 @@ public class ConsulAutoServiceRegistrationListener implements SmartApplicationLi private final ConsulAutoServiceRegistration autoServiceRegistration; - public ConsulAutoServiceRegistrationListener( - ConsulAutoServiceRegistration autoServiceRegistration) { + public ConsulAutoServiceRegistrationListener(ConsulAutoServiceRegistration autoServiceRegistration) { this.autoServiceRegistration = autoServiceRegistration; } @@ -53,9 +52,7 @@ public class ConsulAutoServiceRegistrationListener implements SmartApplicationLi ApplicationContext context = event.getApplicationContext(); if (context instanceof ConfigurableWebServerApplicationContext) { - if ("management" - .equals(((ConfigurableWebServerApplicationContext) context) - .getServerNamespace())) { + if ("management".equals(((ConfigurableWebServerApplicationContext) context).getServerNamespace())) { return; } } diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistry.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistry.java index 39f043c8..272ca94a 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistry.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistry.java @@ -52,8 +52,7 @@ public class ConsulServiceRegistry implements ServiceRegistry> response = this.client.getHealthChecksForService(serviceId, - HealthChecksForServiceRequest.newBuilder() - .setQueryParams(QueryParams.DEFAULT).build()); + HealthChecksForServiceRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build()); List checks = response.getValue(); for (Check check : checks) { diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryAutoConfiguration.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryAutoConfiguration.java index a33a0426..30ee6c46 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryAutoConfiguration.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryAutoConfiguration.java @@ -45,11 +45,9 @@ public class ConsulServiceRegistryAutoConfiguration { @Bean @ConditionalOnMissingBean - public ConsulServiceRegistry consulServiceRegistry(ConsulClient consulClient, - ConsulDiscoveryProperties properties, HeartbeatProperties heartbeatProperties, - @Autowired(required = false) TtlScheduler ttlScheduler) { - return new ConsulServiceRegistry(consulClient, properties, ttlScheduler, - heartbeatProperties); + public ConsulServiceRegistry consulServiceRegistry(ConsulClient consulClient, ConsulDiscoveryProperties properties, + HeartbeatProperties heartbeatProperties, @Autowired(required = false) TtlScheduler ttlScheduler) { + return new ConsulServiceRegistry(consulClient, properties, ttlScheduler, heartbeatProperties); } @Bean @@ -65,21 +63,18 @@ public class ConsulServiceRegistryAutoConfiguration { return new ConsulDiscoveryProperties(inetUtils); } - protected static class OnConsulRegistrationEnabledCondition - extends AllNestedConditions { + protected static class OnConsulRegistrationEnabledCondition extends AllNestedConditions { OnConsulRegistrationEnabledCondition() { super(ConfigurationPhase.REGISTER_BEAN); } - @ConditionalOnProperty(value = "spring.cloud.service-registry.enabled", - matchIfMissing = true) + @ConditionalOnProperty(value = "spring.cloud.service-registry.enabled", matchIfMissing = true) static class ServiceRegistryEnabledClass { } - @ConditionalOnProperty(value = "spring.cloud.consul.service-registry.enabled", - matchIfMissing = true) + @ConditionalOnProperty(value = "spring.cloud.consul.service-registry.enabled", matchIfMissing = true) static class ConsulServiceRegistryEnabledClass { } diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulServletRegistrationCustomizer.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulServletRegistrationCustomizer.java index fb72b448..1039422c 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulServletRegistrationCustomizer.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/serviceregistry/ConsulServletRegistrationCustomizer.java @@ -31,8 +31,7 @@ public class ConsulServletRegistrationCustomizer implements ConsulRegistrationCu private ObjectProvider servletContext; - public ConsulServletRegistrationCustomizer( - ObjectProvider servletContext) { + public ConsulServletRegistrationCustomizer(ObjectProvider servletContext) { this.servletContext = servletContext; } diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/support/ConsulHeartbeatAutoConfiguration.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/support/ConsulHeartbeatAutoConfiguration.java index 939355de..ed752b82 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/support/ConsulHeartbeatAutoConfiguration.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/support/ConsulHeartbeatAutoConfiguration.java @@ -52,8 +52,7 @@ public class ConsulHeartbeatAutoConfiguration { @Bean @ConditionalOnMissingBean - public TtlScheduler ttlScheduler(HeartbeatProperties heartbeatProperties, - ConsulClient consulClient) { + public TtlScheduler ttlScheduler(HeartbeatProperties heartbeatProperties, ConsulClient consulClient) { return new TtlScheduler(heartbeatProperties, consulClient); } diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientAclTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientAclTests.java index 717119eb..a967a93d 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientAclTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientAclTests.java @@ -52,8 +52,7 @@ public class ConsulDiscoveryClientAclTests { @Test public void getInstancesForThisServiceWorks() { - List instances = this.discoveryClient - .getInstances("testConsulDiscoveryAcl"); + List instances = this.discoveryClient.getInstances("testConsulDiscoveryAcl"); assertThat(instances).as("instances was null").isNotNull(); assertThat(instances.isEmpty()).as("instances was empty").isFalse(); } @@ -61,17 +60,14 @@ public class ConsulDiscoveryClientAclTests { @Test public void getInstancesForSecondServiceWorks() throws Exception { - new SpringApplicationBuilder(MyTestConfig.class) - .initializers(new ConsulTestcontainers()) - .run("--spring.application.name=testSecondServiceAcl", "--server.port=0", - "--spring.cloud.consul.discovery.preferIpAddress=true", - "--consul.token=2d2e6b3b-1c82-40ab-8171-54609d8ad304"); + new SpringApplicationBuilder(MyTestConfig.class).initializers(new ConsulTestcontainers()).run( + "--spring.application.name=testSecondServiceAcl", "--server.port=0", + "--spring.cloud.consul.discovery.preferIpAddress=true", + "--consul.token=2d2e6b3b-1c82-40ab-8171-54609d8ad304"); - List instances = this.discoveryClient - .getInstances("testSecondServiceAcl"); + List instances = this.discoveryClient.getInstances("testSecondServiceAcl"); assertThat(instances).as("second service instances was null").isNotNull(); - assertThat(instances.isEmpty()).as("second service instances was empty") - .isFalse(); + assertThat(instances.isEmpty()).as("second service instances was empty").isFalse(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientConfigurationTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientConfigurationTests.java index 3cbb2da5..356c14e6 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientConfigurationTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientConfigurationTests.java @@ -45,8 +45,7 @@ public class ConsulDiscoveryClientConfigurationTests { @Test public void consulConfigNotLoadedWhenDiscoveryClientDisabled() { - TestPropertyValues.of("spring.cloud.discovery.enabled=false") - .applyTo(this.context); + TestPropertyValues.of("spring.cloud.discovery.enabled=false").applyTo(this.context); setupContext(); assertBeanNotPresent(ConsulDiscoveryProperties.class); assertBeanNotPresent(ConsulDiscoveryClient.class); @@ -55,9 +54,8 @@ public class ConsulDiscoveryClientConfigurationTests { private void setupContext(Class... config) { ConfigurationPropertySources.attach(this.context.getEnvironment()); - this.context.register(UtilAutoConfiguration.class, - PropertyPlaceholderAutoConfiguration.class, ConsulAutoConfiguration.class, - ConsulDiscoveryClientConfiguration.class); + this.context.register(UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, + ConsulAutoConfiguration.class, ConsulDiscoveryClientConfiguration.class); for (Class value : config) { this.context.register(value); } diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientCustomizedTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientCustomizedTests.java index 1b55bc5f..10bbb8af 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientCustomizedTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientCustomizedTests.java @@ -46,8 +46,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen "spring.cloud.consul.discovery.instanceId=testConsulDiscovery2Id", "spring.cloud.consul.discovery.hostname=testConsulDiscovery2Host", "spring.cloud.consul.discovery.registerHealthCheck=false", - "spring.cloud.consul.discovery.tags=plaintag", - "spring.cloud.consul.discovery.metadata[foo]=bar", + "spring.cloud.consul.discovery.tags=plaintag", "spring.cloud.consul.discovery.metadata[foo]=bar", "spring.cloud.consul.discovery.metadata[foo2]=bar2" }, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) @@ -64,14 +63,12 @@ public class ConsulDiscoveryClientCustomizedTests { } private void assertNotIpAddress(ServiceInstance instance) { - assertThat(InetAddressUtils.isIPv4Address(instance.getHost())) - .as("host is an ip address").isFalse(); + assertThat(InetAddressUtils.isIPv4Address(instance.getHost())).as("host is an ip address").isFalse(); } @Test public void getMetadataWorks() throws InterruptedException { - List instances = this.discoveryClient - .getInstances("testConsulDiscovery2"); + List instances = this.discoveryClient.getInstances("testConsulDiscovery2"); assertThat(instances).as("instances was null").isNotNull(); assertThat(instances.isEmpty()).as("instances was empty").isFalse(); @@ -80,10 +77,8 @@ public class ConsulDiscoveryClientCustomizedTests { } private void assertInstance(ServiceInstance instance) { - assertThat(instance.getInstanceId()).as("instance id was wrong") - .isEqualTo("testConsulDiscovery2Id"); - assertThat(instance.getServiceId()).as("service id was wrong") - .isEqualTo("testConsulDiscovery2"); + assertThat(instance.getInstanceId()).as("instance id was wrong").isEqualTo("testConsulDiscovery2Id"); + assertThat(instance.getServiceId()).as("service id was wrong").isEqualTo("testConsulDiscovery2"); Map metadata = instance.getMetadata(); assertThat(metadata).as("metadata was null").isNotNull(); diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientDefaultQueryTagTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientDefaultQueryTagTests.java index 8cb21466..e6b0dd33 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientDefaultQueryTagTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientDefaultQueryTagTests.java @@ -44,8 +44,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Piotr Wielgolaski */ @RunWith(SpringRunner.class) -@SpringBootTest(webEnvironment = MOCK, - classes = ConsulDiscoveryClientDefaultQueryTagTests.TestConfig.class, +@SpringBootTest(webEnvironment = MOCK, classes = ConsulDiscoveryClientDefaultQueryTagTests.TestConfig.class, properties = { "spring.application.name=consulServiceDefaultTag", "spring.cloud.consul.discovery.catalogServicesWatch.enabled=false", "spring.cloud.consul.discovery.defaultQueryTag=intg" }) diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientHttpsTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientHttpsTests.java index a355a8d9..a2624d0c 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientHttpsTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientHttpsTests.java @@ -40,10 +40,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @RunWith(SpringRunner.class) @SpringBootTest( properties = { "spring.application.name=testConsulDiscoveryHttps", - "spring.cloud.consul.discovery.prefer-ip-address=true", - "spring.cloud.consul.discovery.scheme=https" }, - classes = ConsulDiscoveryClientHttpsTests.MyTestConfig.class, - webEnvironment = RANDOM_PORT) + "spring.cloud.consul.discovery.prefer-ip-address=true", "spring.cloud.consul.discovery.scheme=https" }, + classes = ConsulDiscoveryClientHttpsTests.MyTestConfig.class, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class ConsulDiscoveryClientHttpsTests { @@ -52,8 +50,7 @@ public class ConsulDiscoveryClientHttpsTests { @Test public void getInstancesForServiceWorks() { - List instances = this.discoveryClient - .getInstances("testConsulDiscoveryHttps"); + List instances = this.discoveryClient.getInstances("testConsulDiscoveryHttps"); assertThat(instances).as("instances was null").isNotNull(); assertThat(instances.isEmpty()).as("instances was empty").isFalse(); diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientTests.java index ccba1c18..9b77542f 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientTests.java @@ -42,12 +42,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Joe Athman */ @RunWith(SpringRunner.class) -@SpringBootTest( - properties = { "spring.application.name=testConsulDiscovery", - "spring.cloud.consul.discovery.prefer-ip-address=true", - "spring.cloud.consul.discovery.metadata[foo]=bar" }, - classes = ConsulDiscoveryClientTests.MyTestConfig.class, - webEnvironment = RANDOM_PORT) +@SpringBootTest(properties = { "spring.application.name=testConsulDiscovery", + "spring.cloud.consul.discovery.prefer-ip-address=true", "spring.cloud.consul.discovery.metadata[foo]=bar" }, + classes = ConsulDiscoveryClientTests.MyTestConfig.class, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class ConsulDiscoveryClientTests { @@ -59,8 +56,7 @@ public class ConsulDiscoveryClientTests { @Test public void getInstancesForServiceWorks() { - List instances = this.discoveryClient - .getInstances("testConsulDiscovery"); + List instances = this.discoveryClient.getInstances("testConsulDiscovery"); assertThat(instances).as("instances was null").isNotNull(); assertThat(instances.isEmpty()).as("instances was empty").isFalse(); @@ -72,13 +68,12 @@ public class ConsulDiscoveryClientTests { @Test public void getInstancesForServiceRespectsQueryParams() { - Response> catalogDatacenters = this.consulClient - .getCatalogDatacenters(); + Response> catalogDatacenters = this.consulClient.getCatalogDatacenters(); List dataCenterList = catalogDatacenters.getValue(); assertThat(dataCenterList.isEmpty()).as("no data centers found").isFalse(); - List instances = this.discoveryClient.getInstances( - "testConsulDiscovery", new QueryParams(dataCenterList.get(0))); + List instances = this.discoveryClient.getInstances("testConsulDiscovery", + new QueryParams(dataCenterList.get(0))); assertThat(instances.isEmpty()).as("instances was empty").isFalse(); ServiceInstance instance = instances.get(0); @@ -86,8 +81,7 @@ public class ConsulDiscoveryClientTests { } private void assertIpAddress(ServiceInstance instance) { - assertThat(Character.isDigit(instance.getHost().charAt(0))) - .as("host isn't an ip address").isTrue(); + assertThat(Character.isDigit(instance.getHost().charAt(0))).as("host isn't an ip address").isTrue(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryPropertiesTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryPropertiesTests.java index a9b99fcc..05227b75 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryPropertiesTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryPropertiesTests.java @@ -39,18 +39,15 @@ public class ConsulDiscoveryPropertiesTests { private static final String SERVICE_NAME_NOT_IN_MAP = "serviceNameNotInMap"; - private final Map serverListQueryTags = Collections - .singletonMap(SERVICE_NAME_IN_MAP, MAP_TAG); + private final Map serverListQueryTags = Collections.singletonMap(SERVICE_NAME_IN_MAP, MAP_TAG); - private final Map datacenters = Collections - .singletonMap(SERVICE_NAME_IN_MAP, MAP_DC); + private final Map datacenters = Collections.singletonMap(SERVICE_NAME_IN_MAP, MAP_DC); private ConsulDiscoveryProperties properties; @Before public void setUp() { - this.properties = new ConsulDiscoveryProperties( - new InetUtils(new InetUtilsProperties())); + this.properties = new ConsulDiscoveryProperties(new InetUtils(new InetUtilsProperties())); this.properties.setDefaultQueryTag(DEFAULT_TAG); this.properties.setServerListQueryTags(this.serverListQueryTags); this.properties.setDatacenters(this.datacenters); @@ -60,39 +57,33 @@ public class ConsulDiscoveryPropertiesTests { public void testReturnsNullWhenNoDefaultAndNotInMap() { this.properties.setDefaultQueryTag(null); - assertThat(this.properties.getQueryTagForService(SERVICE_NAME_NOT_IN_MAP)) - .isNull(); + assertThat(this.properties.getQueryTagForService(SERVICE_NAME_NOT_IN_MAP)).isNull(); } @Test public void testGetTagReturnsDefaultWhenNotInMap() { - assertThat(this.properties.getQueryTagForService(SERVICE_NAME_NOT_IN_MAP)) - .isEqualTo(DEFAULT_TAG); + assertThat(this.properties.getQueryTagForService(SERVICE_NAME_NOT_IN_MAP)).isEqualTo(DEFAULT_TAG); } @Test public void testGetTagReturnsMapValueWhenInMap() { - assertThat(this.properties.getQueryTagForService(SERVICE_NAME_IN_MAP)) - .isEqualTo(MAP_TAG); + assertThat(this.properties.getQueryTagForService(SERVICE_NAME_IN_MAP)).isEqualTo(MAP_TAG); } @Test public void testGetDcReturnsNullWhenNotInMap() { - assertThat(this.properties.getDatacenters().get(SERVICE_NAME_NOT_IN_MAP)) - .isNull(); + assertThat(this.properties.getDatacenters().get(SERVICE_NAME_NOT_IN_MAP)).isNull(); } @Test public void testGetDcReturnsMapValueWhenInMap() { - assertThat(this.properties.getDatacenters().get(SERVICE_NAME_IN_MAP)) - .isEqualTo(MAP_DC); + assertThat(this.properties.getDatacenters().get(SERVICE_NAME_IN_MAP)).isEqualTo(MAP_DC); } @Test public void testAddManagementTag() { this.properties.getManagementTags().add("newTag"); - assertThat(this.properties.getManagementTags()) - .containsOnly(ConsulDiscoveryProperties.MANAGEMENT, "newTag"); + assertThat(this.properties.getManagementTags()).containsOnly(ConsulDiscoveryProperties.MANAGEMENT, "newTag"); } } diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulLoadbalancerClientTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulLoadbalancerClientTests.java index 9f18f13f..bdd8727e 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulLoadbalancerClientTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulLoadbalancerClientTests.java @@ -40,8 +40,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @RunWith(SpringRunner.class) @SpringBootTest( properties = { "spring.application.name=testConsulLoadBalancer", - "spring.cloud.consul.discovery.prefer-ip-address=true", - "spring.cloud.consul.discovery.tags=foo=bar" }, + "spring.cloud.consul.discovery.prefer-ip-address=true", "spring.cloud.consul.discovery.tags=foo=bar" }, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class ConsulLoadbalancerClientTests { @@ -61,8 +60,7 @@ public class ConsulLoadbalancerClientTests { } private void assertIpAddress(ServiceInstance instance) { - assertThat(Character.isDigit(instance.getHost().charAt(0))) - .as("host isn't an ip address").isTrue(); + assertThat(Character.isDigit(instance.getHost().charAt(0))).as("host isn't an ip address").isTrue(); } @SpringBootConfiguration diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/TtlSchedulerRemoveTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/TtlSchedulerRemoveTests.java index cd6b1262..ba00e00d 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/TtlSchedulerRemoveTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/TtlSchedulerRemoveTests.java @@ -48,11 +48,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Stéphane Leroy */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = TtlSchedulerRemoveTests.TtlSchedulerRemoveTestConfig.class, - properties = { "spring.application.name=ttlSchedulerRemove", - "spring.cloud.consul.discovery.instance-id=ttlSchedulerRemove-id", - "spring.cloud.consul.discovery.heartbeat.enabled=true", - "spring.cloud.consul.discovery.heartbeat.ttlValue=2" }, +@SpringBootTest(classes = TtlSchedulerRemoveTests.TtlSchedulerRemoveTestConfig.class, properties = { + "spring.application.name=ttlSchedulerRemove", "spring.cloud.consul.discovery.instance-id=ttlSchedulerRemove-id", + "spring.cloud.consul.discovery.heartbeat.enabled=true", "spring.cloud.consul.discovery.heartbeat.ttlValue=2" }, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class TtlSchedulerRemoveTests { @@ -68,21 +66,18 @@ public class TtlSchedulerRemoveTests { public void should_not_send_check_if_service_removed() throws InterruptedException { Thread.sleep(1000); // wait for Ttlscheduler to send a check to consul. Check serviceCheck = getCheckForService("ttlSchedulerRemove"); - assertThat(serviceCheck.getStatus()).as("Service check is in wrong state") - .isEqualTo(PASSING); + assertThat(serviceCheck.getStatus()).as("Service check is in wrong state").isEqualTo(PASSING); // Remove service from TtlScheduler and wait for TTL to expired. this.ttlScheduler.remove("ttlSchedulerRemove-id"); Thread.sleep(2100); serviceCheck = getCheckForService("ttlSchedulerRemove"); - assertThat(serviceCheck.getStatus()).as("Service check is in wrong state") - .isEqualTo(CRITICAL); + assertThat(serviceCheck.getStatus()).as("Service check is in wrong state").isEqualTo(CRITICAL); } private Check getCheckForService(String serviceId) { - Response> checkResponse = this.consul - .getHealthChecksForService(serviceId, HealthChecksForServiceRequest - .newBuilder().setQueryParams(QueryParams.DEFAULT).build()); + Response> checkResponse = this.consul.getHealthChecksForService(serviceId, + HealthChecksForServiceRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build()); if (checkResponse.getValue().size() > 0) { return checkResponse.getValue().get(0); } @@ -92,8 +87,7 @@ public class TtlSchedulerRemoveTests { @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration @Import({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, - ConsulDiscoveryClientConfiguration.class, - ConsulHeartbeatAutoConfiguration.class }) + ConsulDiscoveryClientConfiguration.class, ConsulHeartbeatAutoConfiguration.class }) public static class TtlSchedulerRemoveTestConfig { } diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/TtlSchedulerTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/TtlSchedulerTests.java index 9e829722..e6284b72 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/TtlSchedulerTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/TtlSchedulerTests.java @@ -50,8 +50,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen properties = { "spring.application.name=ttlScheduler", "spring.cloud.consul.discovery.instance-id=ttlScheduler-id", "spring.cloud.consul.discovery.heartbeat.enabled=true", - "spring.cloud.consul.discovery.heartbeat.ttlValue=2", - "management.server.port=0" }, + "spring.cloud.consul.discovery.heartbeat.ttlValue=2", "management.server.port=0" }, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class TtlSchedulerTests { @@ -60,14 +59,12 @@ public class TtlSchedulerTests { private ConsulClient consul; @Test - public void should_send_a_check_before_ttl_for_all_services() - throws InterruptedException { + public void should_send_a_check_before_ttl_for_all_services() throws InterruptedException { Thread.sleep(2100); // Wait for TTL to expired (TTL is set to 2 seconds) Check serviceCheck = getCheckForService("ttlScheduler"); assertThat(serviceCheck).isNotNull(); - assertThat(serviceCheck.getStatus()).isEqualTo(PASSING) - .as("Service check is in wrong state"); + assertThat(serviceCheck.getStatus()).isEqualTo(PASSING).as("Service check is in wrong state"); Check serviceManagementCheck = getCheckForService("ttlScheduler-management"); assertThat(serviceManagementCheck).isNotNull(); assertThat(serviceManagementCheck.getStatus()).isEqualTo(PASSING) @@ -75,9 +72,8 @@ public class TtlSchedulerTests { } private Check getCheckForService(String serviceId) { - Response> checkResponse = this.consul - .getHealthChecksForService(serviceId, HealthChecksForServiceRequest - .newBuilder().setQueryParams(QueryParams.DEFAULT).build()); + Response> checkResponse = this.consul.getHealthChecksForService(serviceId, + HealthChecksForServiceRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build()); if (checkResponse.getValue().size() > 0) { return checkResponse.getValue().get(0); } @@ -87,8 +83,7 @@ public class TtlSchedulerTests { @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration @Import({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, - ConsulDiscoveryClientConfiguration.class, - ConsulHeartbeatAutoConfiguration.class }) + ConsulDiscoveryClientConfiguration.class, ConsulHeartbeatAutoConfiguration.class }) public static class TtlSchedulerTestConfig { } diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/configclient/ConsulConfigServerAutoConfigurationTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/configclient/ConsulConfigServerAutoConfigurationTests.java index 3fff5888..b8428e10 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/configclient/ConsulConfigServerAutoConfigurationTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/configclient/ConsulConfigServerAutoConfigurationTests.java @@ -45,31 +45,22 @@ public class ConsulConfigServerAutoConfigurationTests { @Test public void offByDefault() { - this.context = new AnnotationConfigApplicationContext( - ConsulConfigServerAutoConfiguration.class); - assertThat( - this.context.getBeanNamesForType(ConsulDiscoveryProperties.class).length) - .isEqualTo(0); + this.context = new AnnotationConfigApplicationContext(ConsulConfigServerAutoConfiguration.class); + assertThat(this.context.getBeanNamesForType(ConsulDiscoveryProperties.class).length).isEqualTo(0); } @Test public void onWhenRequested() { - setup("spring.cloud.config.server.prefix=/config", - "spring.cloud.consul.discovery.tags-as-metadata=false"); - assertThat( - this.context.getBeanNamesForType(ConsulDiscoveryProperties.class).length) - .isEqualTo(1); - ConsulDiscoveryProperties properties = this.context - .getBean(ConsulDiscoveryProperties.class); + setup("spring.cloud.config.server.prefix=/config", "spring.cloud.consul.discovery.tags-as-metadata=false"); + assertThat(this.context.getBeanNamesForType(ConsulDiscoveryProperties.class).length).isEqualTo(1); + ConsulDiscoveryProperties properties = this.context.getBean(ConsulDiscoveryProperties.class); assertThat(properties.getMetadata()).containsEntry("configPath", "/config"); } private void setup(String... env) { - this.context = new SpringApplicationBuilder( - PropertyPlaceholderAutoConfiguration.class, + this.context = new SpringApplicationBuilder(PropertyPlaceholderAutoConfiguration.class, ConsulConfigServerAutoConfiguration.class, ConfigServerProperties.class, - ConsulDiscoveryProperties.class).web(WebApplicationType.NONE) - .properties(env).run(); + ConsulDiscoveryProperties.class).web(WebApplicationType.NONE).properties(env).run(); } } diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/configclient/DiscoveryClientConfigServiceAutoConfigurationTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/configclient/DiscoveryClientConfigServiceAutoConfigurationTests.java index 03414c68..8d141595 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/configclient/DiscoveryClientConfigServiceAutoConfigurationTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/configclient/DiscoveryClientConfigServiceAutoConfigurationTests.java @@ -67,30 +67,23 @@ public class DiscoveryClientConfigServiceAutoConfigurationTests { ConsulTestcontainers.start(); Integer port = ConsulTestcontainers.getPort(); String host = ConsulTestcontainers.getHost(); - setup("server.port=0", "spring.cloud.config.discovery.enabled=true", - "spring.cloud.consul.port=" + port, "spring.cloud.consul.host=" + host, - "logging.level.org.springframework.cloud.config.client=DEBUG", + setup("server.port=0", "spring.cloud.config.discovery.enabled=true", "spring.cloud.consul.port=" + port, + "spring.cloud.consul.host=" + host, "logging.level.org.springframework.cloud.config.client=DEBUG", "spring.cloud.consul.discovery.catalog-services-watch.enabled=false", "spring.cloud.consul.discovery.test.enabled:true", - "spring.application.name=discoveryclientconfigservicetest", - "spring.jmx.enabled=false", "spring.cloud.consul.discovery.port:7001", - "spring.cloud.consul.discovery.hostname:foo", + "spring.application.name=discoveryclientconfigservicetest", "spring.jmx.enabled=false", + "spring.cloud.consul.discovery.port:7001", "spring.cloud.consul.discovery.hostname:foo", "spring.cloud.config.discovery.service-id:configserver"); - assertThat(this.context - .getBeanNamesForType(ConsulConfigServerAutoConfiguration.class).length) - .isEqualTo(1); - ConsulDiscoveryClient client = this.context.getParent() - .getBean(ConsulDiscoveryClient.class); + assertThat(this.context.getBeanNamesForType(ConsulConfigServerAutoConfiguration.class).length).isEqualTo(1); + ConsulDiscoveryClient client = this.context.getParent().getBean(ConsulDiscoveryClient.class); verify(client, atLeast(2)).getInstances("configserver"); - ConfigClientProperties locator = this.context - .getBean(ConfigClientProperties.class); + ConfigClientProperties locator = this.context.getBean(ConfigClientProperties.class); assertThat(locator.getUri()[0]).isEqualTo("http://foo:7001/"); } private void setup(String... env) { - this.context = new SpringApplicationBuilder(TestConfig.class).properties(env) - .run(); + this.context = new SpringApplicationBuilder(TestConfig.class).properties(env).run(); } @Configuration(proxyBeanMethods = false) diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/configclient/TestConsulDiscoveryClientBootstrapConfiguration.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/configclient/TestConsulDiscoveryClientBootstrapConfiguration.java index 80a89eaa..78f7b0c7 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/configclient/TestConsulDiscoveryClientBootstrapConfiguration.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/configclient/TestConsulDiscoveryClientBootstrapConfiguration.java @@ -29,17 +29,15 @@ import org.springframework.context.annotation.Configuration; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; -@ConditionalOnProperty(value = "spring.cloud.consul.discovery.test.enabled", - matchIfMissing = false) +@ConditionalOnProperty(value = "spring.cloud.consul.discovery.test.enabled", matchIfMissing = false) @Configuration(proxyBeanMethods = false) public class TestConsulDiscoveryClientBootstrapConfiguration { @Bean - public ConsulDiscoveryClient consulDiscoveryClient( - ConsulDiscoveryProperties properties) { + public ConsulDiscoveryClient consulDiscoveryClient(ConsulDiscoveryProperties properties) { ConsulDiscoveryClient client = mock(ConsulDiscoveryClient.class); - ServiceInstance instance = new DefaultServiceInstance("configserver1", - "configserver", properties.getHostname(), properties.getPort(), false); + ServiceInstance instance = new DefaultServiceInstance("configserver1", "configserver", properties.getHostname(), + properties.getPort(), false); given(client.getInstances("configserver")).willReturn(Arrays.asList(instance)); return client; } diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClientConfigurationTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClientConfigurationTests.java index eb960fec..2cc663b8 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClientConfigurationTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClientConfigurationTests.java @@ -34,87 +34,68 @@ import static org.assertj.core.api.Assertions.assertThat; */ class ConsulReactiveDiscoveryClientConfigurationTests { - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class, - ReactiveCommonsClientAutoConfiguration.class, - ConsulAutoConfiguration.class, - ConsulReactiveDiscoveryClientConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner().withConfiguration( + AutoConfigurations.of(UtilAutoConfiguration.class, ReactiveCommonsClientAutoConfiguration.class, + ConsulAutoConfiguration.class, ConsulReactiveDiscoveryClientConfiguration.class)); @Test public void shouldWorkWithDefaults() { contextRunner.run(context -> { assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class); - assertThat(context) - .hasSingleBean(ReactiveDiscoveryClientHealthIndicator.class); + assertThat(context).hasSingleBean(ReactiveDiscoveryClientHealthIndicator.class); }); } @Test public void shouldNotHaveDiscoveryClientWhenDiscoveryDisabled() { - contextRunner.withPropertyValues("spring.cloud.discovery.enabled=false") - .run(context -> { - assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient"); - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean( - ReactiveDiscoveryClientHealthIndicator.class); - }); + contextRunner.withPropertyValues("spring.cloud.discovery.enabled=false").run(context -> { + assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient"); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); + }); } @Test public void shouldNotHaveDiscoveryClientWhenReactiveDiscoveryDisabled() { - contextRunner.withPropertyValues("spring.cloud.discovery.reactive.enabled=false") - .run(context -> { - assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient"); - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean( - ReactiveDiscoveryClientHealthIndicator.class); - }); + contextRunner.withPropertyValues("spring.cloud.discovery.reactive.enabled=false").run(context -> { + assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient"); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); + }); } @Test public void shouldNotHaveDiscoveryClientWhenConsulDisabled() { - contextRunner.withPropertyValues("spring.cloud.consul.enabled=false") - .run(context -> { - assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient"); - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean( - ReactiveDiscoveryClientHealthIndicator.class); - }); + contextRunner.withPropertyValues("spring.cloud.consul.enabled=false").run(context -> { + assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient"); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); + }); } @Test public void shouldNotHaveDiscoveryClientWhenConsulDiscoveryDisabled() { - contextRunner.withPropertyValues("spring.cloud.consul.discovery.enabled=false") - .run(context -> { - assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient"); - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean( - ReactiveDiscoveryClientHealthIndicator.class); - }); + contextRunner.withPropertyValues("spring.cloud.consul.discovery.enabled=false").run(context -> { + assertThat(context).doesNotHaveBean("consulReactiveDiscoveryClient"); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); + }); } @Test public void worksWithoutWebflux() { - contextRunner - .withClassLoader( - new FilteredClassLoader("org.springframework.web.reactive")) - .run(context -> { - assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean( - ReactiveDiscoveryClientHealthIndicator.class); - }); + contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.web.reactive")).run(context -> { + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClient.class); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); + }); } @Test public void worksWithoutActuator() { - contextRunner - .withClassLoader( - new FilteredClassLoader("org.springframework.boot.actuate")) - .run(context -> { - assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class); - assertThat(context).doesNotHaveBean( - ReactiveDiscoveryClientHealthIndicator.class); - }); + contextRunner.withClassLoader(new FilteredClassLoader("org.springframework.boot.actuate")).run(context -> { + assertThat(context).hasSingleBean(ReactiveDiscoveryClient.class); + assertThat(context).doesNotHaveBean(ReactiveDiscoveryClientHealthIndicator.class); + }); } } diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClientTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClientTests.java index b10f4ec0..35009845 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClientTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/reactive/ConsulReactiveDiscoveryClientTests.java @@ -65,8 +65,7 @@ class ConsulReactiveDiscoveryClientTests { @Test public void verifyDefaults() { when(properties.getOrder()).thenReturn(1); - assertThat(client.description()) - .isEqualTo("Spring Cloud Consul Reactive Discovery Client"); + assertThat(client.description()).isEqualTo("Spring Cloud Consul Reactive Discovery Client"); assertThat(client.getOrder()).isEqualTo(1); } @@ -82,8 +81,7 @@ class ConsulReactiveDiscoveryClientTests { @Test public void shouldReturnFluxOfServices() { Flux services = client.getServices(); - when(consulClient.getCatalogServices(any(CatalogServicesRequest.class))) - .thenReturn(consulServicesResponse()); + when(consulClient.getCatalogServices(any(CatalogServicesRequest.class))).thenReturn(consulServicesResponse()); StepVerifier.create(services).expectNext("my-service").expectComplete().verify(); verify(properties).getAclToken(); verify(consulClient).getCatalogServices(any(CatalogServicesRequest.class)); @@ -92,8 +90,7 @@ class ConsulReactiveDiscoveryClientTests { @Test public void shouldReturnFluxOfServicesWithAclToken() { when(properties.getAclToken()).thenReturn("aclToken"); - when(consulClient.getCatalogServices(any(CatalogServicesRequest.class))) - .thenReturn(consulServicesResponse()); + when(consulClient.getCatalogServices(any(CatalogServicesRequest.class))).thenReturn(consulServicesResponse()); Flux services = client.getServices(); StepVerifier.create(services).expectNext("my-service").expectComplete().verify(); verify(properties, times(1)).getAclToken(); @@ -103,9 +100,8 @@ class ConsulReactiveDiscoveryClientTests { @Test public void shouldReturnEmptyFluxForNonExistingService() { configureCommonProperties(); - when(consulClient.getHealthServices(eq("nonexistent-service"), - any(HealthServicesRequest.class))) - .thenReturn(emptyConsulInstancesResponse()); + when(consulClient.getHealthServices(eq("nonexistent-service"), any(HealthServicesRequest.class))) + .thenReturn(emptyConsulInstancesResponse()); Flux instances = client.getInstances("nonexistent-service"); StepVerifier.create(instances).expectNextCount(0).expectComplete().verify(); verify(properties).getAclToken(); @@ -115,9 +111,8 @@ class ConsulReactiveDiscoveryClientTests { @Test public void shouldReturnEmptyFluxWhenConsulFails() { configureCommonProperties(); - when(consulClient.getHealthServices(eq("existing-service"), - any(HealthServicesRequest.class))) - .thenThrow(new RuntimeException("Possible runtime exception")); + when(consulClient.getHealthServices(eq("existing-service"), any(HealthServicesRequest.class))) + .thenThrow(new RuntimeException("Possible runtime exception")); Flux instances = client.getInstances("existing-service"); StepVerifier.create(instances).expectNextCount(0).expectComplete().verify(); verify(consulClient).getHealthServices(eq("existing-service"), any()); @@ -127,8 +122,8 @@ class ConsulReactiveDiscoveryClientTests { public void shouldReturnFluxOfServiceInstances() { configureCommonProperties(); Response> response = consulInstancesResponse(); - when(consulClient.getHealthServices(eq("existing-service"), - any(HealthServicesRequest.class))).thenReturn(response); + when(consulClient.getHealthServices(eq("existing-service"), any(HealthServicesRequest.class))) + .thenReturn(response); Flux instances = client.getInstances("existing-service"); StepVerifier.create(instances).expectNextCount(1).expectComplete().verify(); verify(properties).getAclToken(); @@ -142,8 +137,8 @@ class ConsulReactiveDiscoveryClientTests { configureCommonProperties(); when(properties.getAclToken()).thenReturn("aclToken"); Response> response = consulInstancesResponse(); - when(consulClient.getHealthServices(eq("existing-service"), - any(HealthServicesRequest.class))).thenReturn(response); + when(consulClient.getHealthServices(eq("existing-service"), any(HealthServicesRequest.class))) + .thenReturn(response); Flux instances = client.getInstances("existing-service"); StepVerifier.create(instances).expectNextCount(1).expectComplete().verify(); verify(properties, times(1)).getAclToken(); @@ -153,8 +148,7 @@ class ConsulReactiveDiscoveryClientTests { } private Response>> consulServicesResponse() { - return new Response<>(singletonMap("my-service", singletonList("")), 0L, true, - System.currentTimeMillis()); + return new Response<>(singletonMap("my-service", singletonList("")), 0L, true, System.currentTimeMillis()); } private void configureCommonProperties() { @@ -175,8 +169,7 @@ class ConsulReactiveDiscoveryClientTests { when(service.getPort()).thenReturn(443); lenient().when(service.getTags()).thenReturn(singletonList("secure=true")); - return new Response<>(singletonList(healthService), 0L, true, - System.currentTimeMillis()); + return new Response<>(singletonList(healthService), 0L, true, System.currentTimeMillis()); } } diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationCheckTtlDeregisterCriticalServiceTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationCheckTtlDeregisterCriticalServiceTests.java index f009a267..8fbe09c0 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationCheckTtlDeregisterCriticalServiceTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationCheckTtlDeregisterCriticalServiceTests.java @@ -38,10 +38,8 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Niko Tung */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = ConsulAutoRegistrationCheckTtlDeregisterCriticalServiceTests.TestConfig.class, - properties = { - "spring.application.name=myConsulServiceRegistryHealthCheckTtlDeregisterCriticalServiceAfter-N", +@SpringBootTest(classes = ConsulAutoRegistrationCheckTtlDeregisterCriticalServiceTests.TestConfig.class, + properties = { "spring.application.name=myConsulServiceRegistryHealthCheckTtlDeregisterCriticalServiceAfter-N", "spring.cloud.consul.discovery.health-check-critical-timeout=1m", "spring.cloud.consul.discovery.heartbeat.enabled=true" }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @@ -55,16 +53,13 @@ public class ConsulAutoRegistrationCheckTtlDeregisterCriticalServiceTests { public void contextLoads() { NewService service = registration.getService(); assertThat("1m".equals(service.getCheck().getDeregisterCriticalServiceAfter())) - .as("Service with heartbeat check and deregister critical timeout registered") - .isTrue(); + .as("Service with heartbeat check and deregister critical timeout registered").isTrue(); } @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, - ConsulAutoServiceRegistrationAutoConfiguration.class, - ConsulHeartbeatAutoConfiguration.class }) + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, + ConsulAutoServiceRegistrationAutoConfiguration.class, ConsulHeartbeatAutoConfiguration.class }) protected static class TestConfig { } diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationHealthCheckHeadersTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationHealthCheckHeadersTests.java index b347999e..6f8efe0c 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationHealthCheckHeadersTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationHealthCheckHeadersTests.java @@ -40,8 +40,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ConsulAutoRegistrationHealthCheckHeadersTests.TestConfig.class, - properties = { - "spring.application.name=myTestService-DiscoveryHealthCheckTlsSkipVerify", + properties = { "spring.application.name=myTestService-DiscoveryHealthCheckTlsSkipVerify", "spring.cloud.consul.discovery.health-check-headers.X-Config-Token=ACCESSTOKEN" }, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) @@ -62,16 +61,15 @@ public class ConsulAutoRegistrationHealthCheckHeadersTests { assertThat(check).as("check was null").isNotNull(); assertThat(check.getHeader()).as("header is null").isNotNull(); assertThat(check.getHeader()).as("header is empty").isNotEmpty(); - assertThat(check.getHeader().get("X-Config-Token").get(0)) - .as("expected header value not found").isEqualTo("ACCESSTOKEN"); + assertThat(check.getHeader().get("X-Config-Token").get(0)).as("expected header value not found") + .isEqualTo("ACCESSTOKEN"); // unable to call consul api to get health check details } @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationHealthCheckTlsSkipVerifyTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationHealthCheckTlsSkipVerifyTests.java index cdb3f100..cb4300ff 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationHealthCheckTlsSkipVerifyTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationHealthCheckTlsSkipVerifyTests.java @@ -39,10 +39,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Patrick Hi */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = ConsulAutoRegistrationHealthCheckTlsSkipVerifyTests.TestConfig.class, - properties = { - "spring.application.name=myTestService-DiscoveryHealthCheckTlsSkipVerify", +@SpringBootTest(classes = ConsulAutoRegistrationHealthCheckTlsSkipVerifyTests.TestConfig.class, + properties = { "spring.application.name=myTestService-DiscoveryHealthCheckTlsSkipVerify", "spring.cloud.consul.discovery.health-check-tls-skip-verify=true" }, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) @@ -61,16 +59,14 @@ public class ConsulAutoRegistrationHealthCheckTlsSkipVerifyTests { NewService.Check check = service.getCheck(); assertThat(check).as("check was null").isNotNull(); - assertThat(check.getTlsSkipVerify()).as("tls_skip_verify was wrong") - .isEqualTo(Boolean.TRUE); + assertThat(check.getTlsSkipVerify()).as("tls_skip_verify was wrong").isEqualTo(Boolean.TRUE); // unable to call consul api to get health check details } @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationIncludeHostnameInInstanceIdTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationIncludeHostnameInInstanceIdTests.java index f8733584..c2c625c3 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationIncludeHostnameInInstanceIdTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoRegistrationIncludeHostnameInInstanceIdTests.java @@ -39,10 +39,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author varnson */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = ConsulAutoRegistrationIncludeHostnameInInstanceIdTests.TestConfig.class, - properties = { - "spring.application.name=myTestService-IncludeHostnameInInstanceId", +@SpringBootTest(classes = ConsulAutoRegistrationIncludeHostnameInInstanceIdTests.TestConfig.class, + properties = { "spring.application.name=myTestService-IncludeHostnameInInstanceId", "spring.cloud.consul.discovery.include-hostname-in-instance-id=true", "spring.cloud.client.hostname=testhostname" }, webEnvironment = RANDOM_PORT) @@ -63,15 +61,13 @@ public class ConsulAutoRegistrationIncludeHostnameInInstanceIdTests { NewService.Check check = service.getCheck(); assertThat(service.getId()).as("id is null").isNotNull(); assertThat(service.getId()).as("id no include hostname").contains("testhostname"); - assertThat(service.getId()).as("service id was wrong") - .isEqualTo(this.registration.getInstanceId()); + assertThat(service.getId()).as("service id was wrong").isEqualTo(this.registration.getInstanceId()); } @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceDeRegistrationDisabledTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceDeRegistrationDisabledTests.java index e8f20c7f..de76b754 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceDeRegistrationDisabledTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceDeRegistrationDisabledTests.java @@ -62,10 +62,8 @@ public class ConsulAutoServiceDeRegistrationDisabledTests { @Test public void contextLoads() { - assertThat(this.autoServiceRegistration) - .as("ConsulAutoServiceRegistration was not created").isNotNull(); - assertThat(this.discoveryProperties) - .as("ConsulDiscoveryProperties was not created").isNotNull(); + assertThat(this.autoServiceRegistration).as("ConsulAutoServiceRegistration was not created").isNotNull(); + assertThat(this.discoveryProperties).as("ConsulDiscoveryProperties was not created").isNotNull(); checkService(true); this.autoServiceRegistration.deregister(); @@ -89,8 +87,7 @@ public class ConsulAutoServiceDeRegistrationDisabledTests { @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedAgentAddressTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedAgentAddressTests.java index b942bc28..d851e01f 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedAgentAddressTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedAgentAddressTests.java @@ -43,8 +43,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = ConsulAutoServiceRegistrationCustomizedAgentAddressTests.TestConfig.class, +@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedAgentAddressTests.TestConfig.class, properties = { "spring.application.name=myTestService-AA", "spring.cloud.consul.discovery.instanceId=myTestService1-AA", "spring.cloud.consul.discovery.serviceName=myprefix-${spring.application.name}", @@ -63,18 +62,14 @@ public class ConsulAutoServiceRegistrationCustomizedAgentAddressTests { Service service = services.get("myTestService1-AA"); assertThat(service).as("service was null").isNotNull(); assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0); - assertThat(service.getId()).as("service id was wrong") - .isEqualTo("myTestService1-AA"); - assertThat(service.getService()).as("service name was wrong") - .isEqualTo("myprefix-myTestService-AA"); - assertThat(StringUtils.isEmpty(service.getAddress())) - .as("service address must be empty").isTrue(); + assertThat(service.getId()).as("service id was wrong").isEqualTo("myTestService1-AA"); + assertThat(service.getService()).as("service name was wrong").isEqualTo("myprefix-myTestService-AA"); + assertThat(StringUtils.isEmpty(service.getAddress())).as("service address must be empty").isTrue(); } @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests.java index ef7f2545..1d5d2a7b 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests.java @@ -42,10 +42,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests.TestConfig.class, - properties = { "spring.application.name=myTestService-DiscoveryPort" }, - webEnvironment = DEFINED_PORT) +@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests.TestConfig.class, + properties = { "spring.application.name=myTestService-DiscoveryPort" }, webEnvironment = DEFINED_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests { @@ -77,9 +75,8 @@ public class ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests { NewService.Check check = service.getCheck(); assertThat(check).as("check was null").isNotNull(); - String httpCheck = String.format("%s://%s:%s%s", this.properties.getScheme(), - this.properties.getHostname(), this.properties.getPort(), - this.properties.getHealthCheckPath()); + String httpCheck = String.format("%s://%s:%s%s", this.properties.getScheme(), this.properties.getHostname(), + this.properties.getPort(), this.properties.getHealthCheckPath()); assertThat(check.getHttp()).as("http check was wrong").isEqualTo(httpCheck); // unable to call consul api to get health check details @@ -87,8 +84,7 @@ public class ConsulAutoServiceRegistrationCustomizedDiscoveryPortTests { @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedInstanceGroupTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedInstanceGroupTests.java index e773f00e..a6ada493 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedInstanceGroupTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedInstanceGroupTests.java @@ -44,8 +44,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Jin Zhang */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = ConsulAutoServiceRegistrationCustomizedInstanceGroupTests.TestConfig.class, +@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedInstanceGroupTests.TestConfig.class, properties = { "spring.application.name=myTestService-WithGroup", "spring.cloud.consul.discovery.instanceId=myTestService1-WithGroup", "spring.cloud.consul.discovery.instanceGroup=test" }, @@ -67,10 +66,8 @@ public class ConsulAutoServiceRegistrationCustomizedInstanceGroupTests { Service service = services.get("myTestService1-WithGroup"); assertThat(service).as("service was null").isNotNull(); assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0); - assertThat(service.getId()).as("service id was wrong") - .isEqualTo("myTestService1-WithGroup"); - assertThat(service.getTags().contains("group=test")).as("service group was wrong") - .isTrue(); + assertThat(service.getId()).as("service id was wrong").isEqualTo("myTestService1-WithGroup"); + assertThat(service.getTags().contains("group=test")).as("service group was wrong").isTrue(); // ConsulServerList serverList = new ConsulServerList(this.consul, // this.properties); @@ -86,8 +83,7 @@ public class ConsulAutoServiceRegistrationCustomizedInstanceGroupTests { @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedInstanceZoneTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedInstanceZoneTests.java index 999464ef..f7cc6893 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedInstanceZoneTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedInstanceZoneTests.java @@ -42,8 +42,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Sixian Liu */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = ConsulAutoServiceRegistrationCustomizedInstanceZoneTests.TestConfig.class, +@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedInstanceZoneTests.TestConfig.class, properties = { "spring.application.name=myTestService-WithZone", "spring.cloud.consul.discovery.instanceId=myTestService1-WithZone", "spring.cloud.consul.discovery.instanceZone=zone1", @@ -62,16 +61,13 @@ public class ConsulAutoServiceRegistrationCustomizedInstanceZoneTests { Service service = services.get("myTestService1-WithZone"); assertThat(service).as("service was null").isNotNull(); assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0); - assertThat(service.getId()).as("service id was wrong") - .isEqualTo("myTestService1-WithZone"); - assertThat(service.getMeta()).as("service zone was wrong").containsEntry("myZone", - "zone1"); + assertThat(service.getId()).as("service id was wrong").isEqualTo("myTestService1-WithZone"); + assertThat(service.getMeta()).as("service zone was wrong").containsEntry("myZone", "zone1"); } @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedManagementServicePortTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedManagementServicePortTests.java index 9c8320f7..42d6ad08 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedManagementServicePortTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedManagementServicePortTests.java @@ -47,8 +47,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Lomesh Patel (lomeshpatel) */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = ConsulAutoServiceRegistrationCustomizedManagementServicePortTests.TestConfig.class, +@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedManagementServicePortTests.TestConfig.class, properties = { "spring.application.name=myTestService-GG", "spring.cloud.consul.discovery.instanceId=myTestService1-GG", "spring.cloud.consul.discovery.registerHealthCheck=false", @@ -76,37 +75,30 @@ public class ConsulAutoServiceRegistrationCustomizedManagementServicePortTests { final Service service = services.get("myTestService1-GG"); assertThat(service).as("service was null").isNotNull(); assertThat(service.getPort().intValue()).as("service port was 0").isNotEqualTo(0); - assertThat(service.getId()).as("service id was wrong") - .isEqualTo("myTestService1-GG"); - assertThat(service.getService()).as("service name was wrong") - .isEqualTo("myprefix-myTestService-GG"); - assertThat(StringUtils.isEmpty(service.getAddress())) - .as("service address must not be empty").isFalse(); - assertThat(service.getAddress()) - .as("service address must equals hostname from discovery properties") + assertThat(service.getId()).as("service id was wrong").isEqualTo("myTestService1-GG"); + assertThat(service.getService()).as("service name was wrong").isEqualTo("myprefix-myTestService-GG"); + assertThat(StringUtils.isEmpty(service.getAddress())).as("service address must not be empty").isFalse(); + assertThat(service.getAddress()).as("service address must equals hostname from discovery properties") .isEqualTo(this.discoveryProperties.getHostname()); final Service managementService = services.get("myTestService1-GG-management"); assertThat(managementService).as("management service was null").isNotNull(); - assertThat(managementService.getPort().intValue()) - .as("management service port is not 4452").isEqualTo(4452); - assertThat(this.managementServerProperties.getPort().intValue()) - .as("management port is not 0").isEqualTo(0); + assertThat(managementService.getPort().intValue()).as("management service port is not 4452").isEqualTo(4452); + assertThat(this.managementServerProperties.getPort().intValue()).as("management port is not 0").isEqualTo(0); assertThat(managementService.getId()).as("management service id was wrong") .isEqualTo("myTestService1-GG-management"); assertThat(managementService.getService()).as("management service name was wrong") .isEqualTo("myprefix-myTestService-GG-management"); assertThat(StringUtils.isEmpty(managementService.getAddress())) .as("management service address must not be empty").isFalse(); - assertThat(managementService.getAddress()).as( - "management service address must equals hostname from discovery properties") + assertThat(managementService.getAddress()) + .as("management service address must equals hostname from discovery properties") .isEqualTo(this.discoveryProperties.getHostname()); } @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedPropsTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedPropsTests.java index 06bbabb8..845fe376 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedPropsTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedPropsTests.java @@ -49,22 +49,15 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Venil Noronha */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = ConsulAutoServiceRegistrationCustomizedPropsTests.TestPropsConfig.class, - properties = { "spring.application.name=myTestService-B", - "spring.cloud.consul.discovery.instanceId=myTestService1-B", - "spring.cloud.consul.discovery.port=4452", - "spring.cloud.consul.discovery.hostname=myhost", - "spring.cloud.consul.discovery.ipAddress=10.0.0.1", - "spring.cloud.consul.discovery.registerHealthCheck=false", - "spring.cloud.consul.discovery.failFast=false", - "spring.cloud.consul.discovery.default-zone-metadata-name=mydefaultzonemetadataname", - "spring.cloud.consul.discovery.instance-zone=myzone", - "spring.cloud.consul.discovery.instance-group=mygroup", - "spring.cloud.consul.discovery.tags[0]=mytag", - "spring.cloud.consul.discovery.enableTagOverride=true", - "spring.cloud.consul.discovery.metadata.key1=value1", - "spring.cloud.consul.discovery.metadata.key2=value2" }, +@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedPropsTests.TestPropsConfig.class, properties = { + "spring.application.name=myTestService-B", "spring.cloud.consul.discovery.instanceId=myTestService1-B", + "spring.cloud.consul.discovery.port=4452", "spring.cloud.consul.discovery.hostname=myhost", + "spring.cloud.consul.discovery.ipAddress=10.0.0.1", "spring.cloud.consul.discovery.registerHealthCheck=false", + "spring.cloud.consul.discovery.failFast=false", + "spring.cloud.consul.discovery.default-zone-metadata-name=mydefaultzonemetadataname", + "spring.cloud.consul.discovery.instance-zone=myzone", "spring.cloud.consul.discovery.instance-group=mygroup", + "spring.cloud.consul.discovery.tags[0]=mytag", "spring.cloud.consul.discovery.enableTagOverride=true", + "spring.cloud.consul.discovery.metadata.key1=value1", "spring.cloud.consul.discovery.metadata.key2=value2" }, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class ConsulAutoServiceRegistrationCustomizedPropsTests { @@ -81,22 +74,14 @@ public class ConsulAutoServiceRegistrationCustomizedPropsTests { Map services = response.getValue(); Service service = services.get("myTestService1-B"); assertThat(service).as("service was null").isNotNull(); - assertThat(service.getPort()).as("service port is discovery port") - .isEqualTo(4452); - assertThat("myTestService1-B").as("service id was wrong") - .isEqualTo(service.getId()); - assertThat("myTestService-B").as("service name was wrong") - .isEqualTo(service.getService()); - assertThat("myhost").as("property hostname was wrong") - .isEqualTo(this.properties.getHostname()); - assertThat("10.0.0.1").as("property ipAddress was wrong") - .isEqualTo(this.properties.getIpAddress()); - assertThat("myhost").as("service address was wrong") - .isEqualTo(service.getAddress()); - assertThat(service.getEnableTagOverride()) - .as("property enableTagOverride was wrong").isTrue(); - assertThat(service.getTags()).as("property tags contains the wrong values") - .containsExactly("mytag"); + assertThat(service.getPort()).as("service port is discovery port").isEqualTo(4452); + assertThat("myTestService1-B").as("service id was wrong").isEqualTo(service.getId()); + assertThat("myTestService-B").as("service name was wrong").isEqualTo(service.getService()); + assertThat("myhost").as("property hostname was wrong").isEqualTo(this.properties.getHostname()); + assertThat("10.0.0.1").as("property ipAddress was wrong").isEqualTo(this.properties.getIpAddress()); + assertThat("myhost").as("service address was wrong").isEqualTo(service.getAddress()); + assertThat(service.getEnableTagOverride()).as("property enableTagOverride was wrong").isTrue(); + assertThat(service.getTags()).as("property tags contains the wrong values").containsExactly("mytag"); HashMap entries = new HashMap<>(); entries.put("key1", "value1"); entries.put("key2", "value2"); @@ -106,23 +91,20 @@ public class ConsulAutoServiceRegistrationCustomizedPropsTests { assertThat(service.getMeta()).as("property metadata contains the wrong entries") .containsExactlyInAnyOrderEntriesOf(entries); - Response> checkResponse = this.consul.getHealthChecksForService( - "myTestService-B", HealthChecksForServiceRequest.newBuilder() - .setQueryParams(QueryParams.DEFAULT).build()); + Response> checkResponse = this.consul.getHealthChecksForService("myTestService-B", + HealthChecksForServiceRequest.newBuilder().setQueryParams(QueryParams.DEFAULT).build()); List checks = checkResponse.getValue(); assertThat(checks).as("checks was wrong size").hasSize(0); } @Test public void testFailFastDisabled() { - assertThat(this.properties.isFailFast()).as("property failFast was wrong") - .isFalse(); + assertThat(this.properties.isFailFast()).as("property failFast was wrong").isFalse(); } @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestPropsConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedServiceNameTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedServiceNameTests.java index 7c79cb51..4e443764 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedServiceNameTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedServiceNameTests.java @@ -42,8 +42,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = ConsulAutoServiceRegistrationCustomizedServiceNameTests.TestConfig.class, +@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedServiceNameTests.TestConfig.class, properties = { "spring.application.name=myTestService-CC", "spring.cloud.consul.discovery.instanceId=myTestService1-CC", "spring.cloud.consul.discovery.serviceName=myprefix-${spring.application.name}" }, @@ -61,16 +60,13 @@ public class ConsulAutoServiceRegistrationCustomizedServiceNameTests { Service service = services.get("myTestService1-CC"); assertThat(service).as("service was null").isNotNull(); assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0); - assertThat(service.getId()).as("service id was wrong") - .isEqualTo("myTestService1-CC"); - assertThat(service.getService()).as("service name was wrong") - .isEqualTo("myprefix-myTestService-CC"); + assertThat(service.getId()).as("service id was wrong").isEqualTo("myTestService1-CC"); + assertThat(service.getService()).as("service name was wrong").isEqualTo("myprefix-myTestService-CC"); } @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedServletContextTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedServletContextTests.java index 67b7f556..8b00ec57 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedServletContextTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedServletContextTests.java @@ -40,8 +40,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Piotr Wielgolaski */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = ConsulAutoServiceRegistrationCustomizedServletContextTests.TestConfig.class, +@SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedServletContextTests.TestConfig.class, properties = { "spring.application.name=myTestService-WithServletContext", "spring.cloud.consul.discovery.instanceId=myTestService1-WithServletContext", "server.servlet.context-path=/customContext" }, @@ -59,10 +58,8 @@ public class ConsulAutoServiceRegistrationCustomizedServletContextTests { Service service = services.get("myTestService1-WithServletContext"); assertThat(service).as("service was null").isNotNull(); assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0); - assertThat(service.getId()).as("service id was wrong") - .isEqualTo("myTestService1-WithServletContext"); - assertThat(service.getTags()).as("contextPath tag missing") - .contains("contextPath=/customContext"); + assertThat(service.getId()).as("service id was wrong").isEqualTo("myTestService1-WithServletContext"); + assertThat(service.getTags()).as("contextPath tag missing").contains("contextPath=/customContext"); } @EnableDiscoveryClient diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedTests.java index 4e9edad8..47bf1aa1 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationCustomizedTests.java @@ -41,8 +41,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ConsulAutoServiceRegistrationCustomizedTests.MyTestConfig.class, - properties = { "spring.application.name=testCustomAutoServiceRegistration" }, - webEnvironment = RANDOM_PORT) + properties = { "spring.application.name=testCustomAutoServiceRegistration" }, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class ConsulAutoServiceRegistrationCustomizedTests { @@ -57,27 +56,24 @@ public class ConsulAutoServiceRegistrationCustomizedTests { @Test public void usesCustomConsulLifecycle() { - assertThat(this.registration1.getConfiguration()) - .as("configuration is not customized").isEqualTo("customconfiguration"); - assertThat(this.registration2.getConfiguration()) - .as("configuration is not customized").isEqualTo("customconfiguration"); + assertThat(this.registration1.getConfiguration()).as("configuration is not customized") + .isEqualTo("customconfiguration"); + assertThat(this.registration2.getConfiguration()).as("configuration is not customized") + .isEqualTo("customconfiguration"); } @SpringBootConfiguration @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class MyTestConfig { @Bean - public CustomAutoRegistration consulAutoServiceRegistration( - ConsulServiceRegistry serviceRegistry, + public CustomAutoRegistration consulAutoServiceRegistration(ConsulServiceRegistry serviceRegistry, AutoServiceRegistrationProperties autoServiceRegistrationProperties, - ConsulDiscoveryProperties properties, - ConsulAutoRegistration registration) { - return new CustomAutoRegistration(serviceRegistry, - autoServiceRegistrationProperties, properties, registration); + ConsulDiscoveryProperties properties, ConsulAutoRegistration registration) { + return new CustomAutoRegistration(serviceRegistry, autoServiceRegistrationProperties, properties, + registration); } } @@ -87,10 +83,8 @@ public class ConsulAutoServiceRegistrationCustomizedTests { @Autowired public CustomAutoRegistration(ConsulServiceRegistry serviceRegistry, AutoServiceRegistrationProperties autoServiceRegistrationProperties, - ConsulDiscoveryProperties properties, - ConsulAutoRegistration registration) { - super(serviceRegistry, autoServiceRegistrationProperties, properties, - registration); + ConsulDiscoveryProperties properties, ConsulAutoRegistration registration) { + super(serviceRegistry, autoServiceRegistrationProperties, properties, registration); } @Override diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationDefaultPortTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationDefaultPortTests.java index 16cf3c43..0812b991 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationDefaultPortTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationDefaultPortTests.java @@ -42,9 +42,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = ConsulAutoServiceRegistrationDefaultPortTests.TestConfig.class, - properties = { "spring.application.name=myTestService2-DD", - "spring.cloud.consul.discovery.instanceId=myTestService2-DD" }, +@SpringBootTest(classes = ConsulAutoServiceRegistrationDefaultPortTests.TestConfig.class, properties = { + "spring.application.name=myTestService2-DD", "spring.cloud.consul.discovery.instanceId=myTestService2-DD" }, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class ConsulAutoServiceRegistrationDefaultPortTests { @@ -63,8 +62,7 @@ public class ConsulAutoServiceRegistrationDefaultPortTests { @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationDisabledTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationDisabledTests.java index a2ec4809..faa29247 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationDisabledTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationDisabledTests.java @@ -49,29 +49,23 @@ public class ConsulAutoServiceRegistrationDisabledTests { @Test public void disabledViaSpringCloudServiceRegistryProperty() { - testAutoRegistrationDisabled("myTestNotRegisteredService4", - "spring.cloud.service-registry.enabled"); + testAutoRegistrationDisabled("myTestNotRegisteredService4", "spring.cloud.service-registry.enabled"); } @Test public void disabledViaConsulServiceRegistryProperty() { - testAutoRegistrationDisabled("myTestNotRegisteredService5", - "spring.cloud.consul.service-registry.enabled"); + testAutoRegistrationDisabled("myTestNotRegisteredService5", "spring.cloud.consul.service-registry.enabled"); } private void testAutoRegistrationDisabled(String testName, String disableProperty) { new WebApplicationContextRunner().withUserConfiguration(TestConfig.class) - .withPropertyValues("spring.application.name=" + testName, - disableProperty + "=false", "server.port=0") + .withPropertyValues("spring.application.name=" + testName, disableProperty + "=false", "server.port=0") .withInitializer(new ConsulTestcontainers()).run(context -> { - assertThat(context) - .doesNotHaveBean(ConsulAutoServiceRegistration.class); - assertThat(context) - .doesNotHaveBean(ConsulAutoServiceRegistrationListener.class); + assertThat(context).doesNotHaveBean(ConsulAutoServiceRegistration.class); + assertThat(context).doesNotHaveBean(ConsulAutoServiceRegistrationListener.class); assertThat(context).doesNotHaveBean(ConsulAutoRegistration.class); - assertThat(context) - .doesNotHaveBean(ConsulRegistrationCustomizer.class); + assertThat(context).doesNotHaveBean(ConsulRegistrationCustomizer.class); ConsulClient consul = context.getBean(ConsulClient.class); diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationFailFastTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationFailFastTests.java index 9d598b3e..e83b00d2 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationFailFastTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationFailFastTests.java @@ -51,17 +51,14 @@ public class ConsulAutoServiceRegistrationFailFastTests { @Test public void testFailFastEnabled() { this.exception.expectCause(isA(ConsulException.class)); - new SpringApplicationBuilder(TestConfig.class) - .properties("spring.application.name=testregistrationfails-fast", - "spring.jmx.default-domain=testautoregfailfast", "server.port=0", - "spring.cloud.consul.discovery.failFast=true") - .run(); + new SpringApplicationBuilder(TestConfig.class).properties("spring.application.name=testregistrationfails-fast", + "spring.jmx.default-domain=testautoregfailfast", "server.port=0", + "spring.cloud.consul.discovery.failFast=true").run(); } @SpringBootConfiguration @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) protected static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationManagementCustomizerTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationManagementCustomizerTests.java index ef4cea89..ffccd924 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationManagementCustomizerTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationManagementCustomizerTests.java @@ -43,12 +43,11 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Alexey Savchuk (devpreview) */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = { - ConsulAutoServiceRegistrationManagementCustomizerTests.TestConfig.class, - ConsulAutoServiceRegistrationManagementCustomizerTests.ManagementConfig.class }, +@SpringBootTest( + classes = { ConsulAutoServiceRegistrationManagementCustomizerTests.TestConfig.class, + ConsulAutoServiceRegistrationManagementCustomizerTests.ManagementConfig.class }, properties = { "spring.application.name=myTestService-SS", - "spring.cloud.consul.discovery.registerHealthCheck=false", - "management.server.port=4453" }, + "spring.cloud.consul.discovery.registerHealthCheck=false", "management.server.port=4453" }, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class ConsulAutoServiceRegistrationManagementCustomizerTests { @@ -61,17 +60,11 @@ public class ConsulAutoServiceRegistrationManagementCustomizerTests { @Test public void contextLoads() { - ConsulAutoRegistration managementRegistration = this.autoRegistration - .managementRegistration(); + ConsulAutoRegistration managementRegistration = this.autoRegistration.managementRegistration(); List checks = managementRegistration.getService().getChecks(); - List ttls = checks.stream().map(NewService.Check::getTtl) - .collect(Collectors.toList()); - assertThat(ttls.contains("39s")) - .as("Management registration not customized with 'foo' customizer") - .isTrue(); - assertThat(ttls.contains("36s")) - .as("Management registration not customized with 'bar' customizer") - .isTrue(); + List ttls = checks.stream().map(NewService.Check::getTtl).collect(Collectors.toList()); + assertThat(ttls.contains("39s")).as("Management registration not customized with 'foo' customizer").isTrue(); + assertThat(ttls.contains("36s")).as("Management registration not customized with 'bar' customizer").isTrue(); } @Configuration(proxyBeanMethods = false) @@ -105,8 +98,7 @@ public class ConsulAutoServiceRegistrationManagementCustomizerTests { @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationManagementDisabledServiceTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationManagementDisabledServiceTests.java index b99293a1..e795b142 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationManagementDisabledServiceTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationManagementDisabledServiceTests.java @@ -44,13 +44,11 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Dmitry Zhikharev (jihor) */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = ConsulAutoServiceRegistrationManagementDisabledServiceTests.TestConfig.class, +@SpringBootTest(classes = ConsulAutoServiceRegistrationManagementDisabledServiceTests.TestConfig.class, properties = { "spring.application.name=myTestService-NM", "spring.cloud.consul.discovery.instanceId=myTestService1-NM", "spring.cloud.service-registry.auto-registration.register-management=false", - "spring.cloud.consul.discovery.managementPort=4453", - "management.port=0" }, + "spring.cloud.consul.discovery.managementPort=4453", "management.port=0" }, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class ConsulAutoServiceRegistrationManagementDisabledServiceTests { @@ -72,22 +70,17 @@ public class ConsulAutoServiceRegistrationManagementDisabledServiceTests { Service service = services.get("myTestService1-NM"); assertThat(service).as("Service was not null").isNotNull(); assertThat(service.getPort().intValue()).as("service port was 0").isNotEqualTo(0); - assertThat(service.getId()).as("service id was wrong") - .isEqualTo("myTestService1-NM"); - assertThat(service.getService()).as("service name was wrong") - .isEqualTo("myTestService-NM"); - assertThat(StringUtils.isEmpty(service.getAddress())) - .as("service address must not be empty").isFalse(); - assertThat(service.getAddress()) - .as("service address must equals hostname from discovery properties") + assertThat(service.getId()).as("service id was wrong").isEqualTo("myTestService1-NM"); + assertThat(service.getService()).as("service name was wrong").isEqualTo("myTestService-NM"); + assertThat(StringUtils.isEmpty(service.getAddress())).as("service address must not be empty").isFalse(); + assertThat(service.getAddress()).as("service address must equals hostname from discovery properties") .isEqualTo(this.discoveryProperties.getHostname()); } @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationManagementServiceTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationManagementServiceTests.java index 7a314e7f..eb2d9fe8 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationManagementServiceTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationManagementServiceTests.java @@ -45,11 +45,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Lomesh Patel (lomeshpatel) */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = ConsulAutoServiceRegistrationManagementServiceTests.TestConfig.class, +@SpringBootTest(classes = ConsulAutoServiceRegistrationManagementServiceTests.TestConfig.class, properties = { "spring.application.name=myTestService-EE", - "spring.cloud.consul.discovery.registerHealthCheck=false", - "management.server.port=4452" }, + "spring.cloud.consul.discovery.registerHealthCheck=false", "management.server.port=4452" }, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class ConsulAutoServiceRegistrationManagementServiceTests { @@ -68,35 +66,29 @@ public class ConsulAutoServiceRegistrationManagementServiceTests { final Service service = services.get("myTestService-EE-0"); assertThat(service).as("service was null").isNotNull(); assertThat(service.getPort().intValue()).as("service port was 0").isNotEqualTo(0); - assertThat(service.getId()).as("service id was wrong") - .isEqualTo("myTestService-EE-0"); - assertThat(service.getService()).as("service name was wrong") - .isEqualTo("myTestService-EE"); - assertThat(StringUtils.isEmpty(service.getAddress())) - .as("service address must not be empty").isFalse(); - assertThat(service.getAddress()) - .as("service address must equals hostname from discovery properties") + assertThat(service.getId()).as("service id was wrong").isEqualTo("myTestService-EE-0"); + assertThat(service.getService()).as("service name was wrong").isEqualTo("myTestService-EE"); + assertThat(StringUtils.isEmpty(service.getAddress())).as("service address must not be empty").isFalse(); + assertThat(service.getAddress()).as("service address must equals hostname from discovery properties") .isEqualTo(this.discoveryProperties.getHostname()); final Service managementService = services.get("myTestService-EE-0-management"); assertThat(managementService).as("management service was null").isNotNull(); - assertThat(managementService.getPort().intValue()) - .as("management service port was wrong").isEqualTo(4452); + assertThat(managementService.getPort().intValue()).as("management service port was wrong").isEqualTo(4452); assertThat(managementService.getId()).as("management service id was wrong") .isEqualTo("myTestService-EE-0-management"); assertThat(managementService.getService()).as("management service name was wrong") .isEqualTo("myTestService-EE-management"); assertThat(StringUtils.isEmpty(managementService.getAddress())) .as("management service address must not be empty").isFalse(); - assertThat(managementService.getAddress()).as( - "management service address must equals hostname from discovery properties") + assertThat(managementService.getAddress()) + .as("management service address must equals hostname from discovery properties") .isEqualTo(this.discoveryProperties.getHostname()); } @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) public static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationNonWebTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationNonWebTests.java index 9af5b4e4..60fd1508 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationNonWebTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationNonWebTests.java @@ -41,8 +41,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ConsulAutoServiceRegistrationNonWebTests.TestConfig.class, - properties = { "spring.application.name=consulNonWebTest", "server.port=32111" }, - webEnvironment = NONE) + properties = { "spring.application.name=consulNonWebTest", "server.port=32111" }, webEnvironment = NONE) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class ConsulAutoServiceRegistrationNonWebTests { @@ -54,8 +53,7 @@ public class ConsulAutoServiceRegistrationNonWebTests { @Test public void contextLoads() { - assertThat(this.autoServiceRegistration) - .as("ConsulAutoServiceRegistration was created").isNotNull(); + assertThat(this.autoServiceRegistration).as("ConsulAutoServiceRegistration was created").isNotNull(); Response> response = this.consul.getAgentServices(); Map services = response.getValue(); diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationRetryTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationRetryTests.java index 334ffa25..55debe76 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationRetryTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationRetryTests.java @@ -57,22 +57,18 @@ public class ConsulAutoServiceRegistrationRetryTests { @Test public void testRetry() { this.exception.expectCause(isA(ConsulException.class)); - try (ConfigurableApplicationContext context = new SpringApplicationBuilder( - TestConfig.class) - .properties("spring.application.name=testregistrationretry", - "spring.jmx.default-domain=testautoregretry", - "spring.cloud.consul.retry.max-attempts=2", - "logging.level.org.springframework.retry=DEBUG", - "server.port=0") - .run()) { + try (ConfigurableApplicationContext context = new SpringApplicationBuilder(TestConfig.class) + .properties("spring.application.name=testregistrationretry", + "spring.jmx.default-domain=testautoregretry", "spring.cloud.consul.retry.max-attempts=2", + "logging.level.org.springframework.retry=DEBUG", "server.port=0") + .run()) { this.output.expect(Matchers.containsString("Retry: count=")); } } @SpringBootConfiguration @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) protected static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationTests.java index 1d26105d..e2a3d61f 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulAutoServiceRegistrationTests.java @@ -46,8 +46,7 @@ import static org.springframework.cloud.consul.serviceregistry.ConsulAutoRegistr * @author Venil Noronha */ @RunWith(SpringRunner.class) -@SpringBootTest(properties = { "spring.application.name=myTestService1-FF::something" }, - webEnvironment = RANDOM_PORT) +@SpringBootTest(properties = { "spring.application.name=myTestService1-FF::something" }, webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class ConsulAutoServiceRegistrationTests { @@ -67,17 +66,12 @@ public class ConsulAutoServiceRegistrationTests { Service service = services.get(this.registration.getInstanceId()); assertThat(service).as("service was null").isNotNull(); assertThat(service.getPort().intValue()).as("service port is 0").isNotEqualTo(0); - assertThat(service.getId().contains(":")) - .as("service id contained invalid character: " + service.getId()) + assertThat(service.getId().contains(":")).as("service id contained invalid character: " + service.getId()) .isFalse(); - assertThat(service.getId()).as("service id was wrong") - .isEqualTo(this.registration.getInstanceId()); - assertThat(service.getService()).as("service name was wrong") - .isEqualTo("myTestService1-FF-something"); - assertThat(StringUtils.isEmpty(service.getAddress())) - .as("service address must not be empty").isFalse(); - assertThat(service.getAddress()) - .as("service address must equals hostname from discovery properties") + assertThat(service.getId()).as("service id was wrong").isEqualTo(this.registration.getInstanceId()); + assertThat(service.getService()).as("service name was wrong").isEqualTo("myTestService1-FF-something"); + assertThat(StringUtils.isEmpty(service.getAddress())).as("service address must not be empty").isFalse(); + assertThat(service.getAddress()).as("service address must equals hostname from discovery properties") .isEqualTo(this.discoveryProperties.getHostname()); } @@ -105,8 +99,7 @@ public class ConsulAutoServiceRegistrationTests { @SpringBootConfiguration @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, ConsulAutoServiceRegistrationAutoConfiguration.class }) protected static class TestConfig { diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryCheckTtlTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryCheckTtlTests.java index 6d88c7b0..360c3ccf 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryCheckTtlTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryCheckTtlTests.java @@ -45,8 +45,7 @@ import static org.assertj.core.api.Assertions.assertThat; */ @RunWith(SpringRunner.class) @SpringBootTest(classes = ConsulServiceRegistryCheckTtlTests.TestConfig.class, - properties = { - "spring.application.name=myConsulServiceRegistryCheckTtlTestService-S", + properties = { "spring.application.name=myConsulServiceRegistryCheckTtlTestService-S", "spring.cloud.consul.discovery.heartbeat.enabled=true" }, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) @@ -70,10 +69,8 @@ public class ConsulServiceRegistryCheckTtlTests { private ConsulRegistration createHttpRegistration() { NewService service = this.registration.getService(); NewService.Check httpCheck = new NewService.Check(); - httpCheck.setHttp( - String.format("%s://%s:%s%s", this.discoveryProperties.getScheme(), - this.discoveryProperties.getHostname(), this.port, - this.discoveryProperties.getHealthCheckPath())); + httpCheck.setHttp(String.format("%s://%s:%s%s", this.discoveryProperties.getScheme(), + this.discoveryProperties.getHostname(), this.port, this.discoveryProperties.getHealthCheckPath())); httpCheck.setInterval(this.discoveryProperties.getHealthCheckInterval()); NewService httpService = new NewService(); httpService.setId(service.getId() + "-http"); @@ -87,18 +84,13 @@ public class ConsulServiceRegistryCheckTtlTests { ConsulRegistration httpRegistration = createHttpRegistration(); try { this.consulServiceRegistry.register(httpRegistration); - Field serviceHeartbeatsField = TtlScheduler.class - .getDeclaredField("serviceHeartbeats"); + Field serviceHeartbeatsField = TtlScheduler.class.getDeclaredField("serviceHeartbeats"); serviceHeartbeatsField.setAccessible(true); Map serviceHeartbeats = (Map) serviceHeartbeatsField.get(this.ttlScheduler); - assertThat(serviceHeartbeats.keySet() - .contains(this.registration.getInstanceId())).as( - "Service with heartbeat check not registered in TTL scheduler") - .isTrue(); - assertThat( - serviceHeartbeats.keySet().contains(httpRegistration.getInstanceId())) - .as("Service with HTTP check registered in TTL scheduler") - .isFalse(); + assertThat(serviceHeartbeats.keySet().contains(this.registration.getInstanceId())) + .as("Service with heartbeat check not registered in TTL scheduler").isTrue(); + assertThat(serviceHeartbeats.keySet().contains(httpRegistration.getInstanceId())) + .as("Service with HTTP check registered in TTL scheduler").isFalse(); } finally { this.consulServiceRegistry.deregister(httpRegistration); @@ -107,10 +99,8 @@ public class ConsulServiceRegistryCheckTtlTests { @Configuration(proxyBeanMethods = false) @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - ConsulAutoConfiguration.class, - ConsulAutoServiceRegistrationAutoConfiguration.class, - ConsulHeartbeatAutoConfiguration.class }) + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, ConsulAutoConfiguration.class, + ConsulAutoServiceRegistrationAutoConfiguration.class, ConsulHeartbeatAutoConfiguration.class }) protected static class TestConfig { } diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryDisabledTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryDisabledTests.java index 58a61e4e..b92ada62 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryDisabledTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryDisabledTests.java @@ -38,20 +38,17 @@ public class ConsulServiceRegistryDisabledTests { @Test public void disabledViaSpringCloudProperty() { - testAutoRegistrationDisabled("serviceRegistryDisabledTest1", - "spring.cloud.service-registry.enabled"); + testAutoRegistrationDisabled("serviceRegistryDisabledTest1", "spring.cloud.service-registry.enabled"); } @Test public void disabledViaConsulProperty() { - testAutoRegistrationDisabled("serviceRegistryDisabledTest2", - "spring.cloud.consul.service-registry.enabled"); + testAutoRegistrationDisabled("serviceRegistryDisabledTest2", "spring.cloud.consul.service-registry.enabled"); } private void testAutoRegistrationDisabled(String testName, String disableProperty) { new WebApplicationContextRunner().withUserConfiguration(TestConfig.class) - .withPropertyValues("spring.application.name=" + testName, - disableProperty + "=false", "server.port=0") + .withPropertyValues("spring.application.name=" + testName, disableProperty + "=false", "server.port=0") .withInitializer(new ConsulTestcontainers()).run(context -> { assertThat(context).doesNotHaveBean(ConsulServiceRegistry.class); assertThat(context).doesNotHaveBean(HeartbeatProperties.class); diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryTests.java index 5497cd9b..f19c7ef8 100644 --- a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryTests.java +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/serviceregistry/ConsulServiceRegistryTests.java @@ -43,8 +43,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author Spencer Gibb */ @RunWith(SpringRunner.class) -@SpringBootTest(properties = "spring.cloud.consul.discovery.query-passing=true", - webEnvironment = RANDOM_PORT) +@SpringBootTest(properties = "spring.cloud.consul.discovery.query-passing=true", webEnvironment = RANDOM_PORT) @ContextConfiguration(initializers = ConsulTestcontainers.class) public class ConsulServiceRegistryTests { @@ -66,8 +65,7 @@ public class ConsulServiceRegistryTests { @Test public void contextLoads() { - assertThat(this.autoRegistration).as("autoRegistration created erroneously") - .isNull(); + assertThat(this.autoRegistration).as("autoRegistration created erroneously").isNull(); String serviceId = "myNonAutoRegisteredService"; @@ -78,8 +76,7 @@ public class ConsulServiceRegistryTests { service.setPort(this.port); service.setTags(Collections.singletonList("mytag")); - ConsulRegistration registration = new ConsulRegistration(service, - this.properties); + ConsulRegistration registration = new ConsulRegistration(service, this.properties); Throwable t = null; try { this.serviceRegistry.register(registration); diff --git a/spring-cloud-consul-sample/src/main/java/org/springframework/cloud/consul/sample/SampleConsulApplication.java b/spring-cloud-consul-sample/src/main/java/org/springframework/cloud/consul/sample/SampleConsulApplication.java index 4c475d58..43bb6bbd 100644 --- a/spring-cloud-consul-sample/src/main/java/org/springframework/cloud/consul/sample/SampleConsulApplication.java +++ b/spring-cloud-consul-sample/src/main/java/org/springframework/cloud/consul/sample/SampleConsulApplication.java @@ -92,8 +92,7 @@ public class SampleConsulApplication /* @RequestMapping("/rest") public String rest() { - return this.restTemplate.getForObject("http://" + this.appName + "/me", - String.class); + return this.restTemplate.getForObject("http://" + this.appName + "/me", String.class); } @RequestMapping("/choose")