Added checkstyle rules

This commit is contained in:
Marcin Grzejszczak
2019-02-07 15:03:44 +01:00
parent ddd9961120
commit 999fb6c9e8
157 changed files with 6633 additions and 3477 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,7 +29,8 @@ import org.springframework.util.Assert;
/**
* @author Spencer Gibb
*/
public class ConsulBinder extends AbstractBinder<MessageChannel, ConsumerProperties, ProducerProperties> {
public class ConsulBinder
extends AbstractBinder<MessageChannel, ConsumerProperties, ProducerProperties> {
private static final String BEAN_NAME_TEMPLATE = "outbound.%s";
@@ -40,8 +41,10 @@ public class ConsulBinder extends AbstractBinder<MessageChannel, ConsumerPropert
}
@Override
protected Binding<MessageChannel> doBindConsumer(String name, String group, MessageChannel inputChannel, ConsumerProperties properties) {
ConsulInboundMessageProducer messageProducer = new ConsulInboundMessageProducer(this.eventService);
protected Binding<MessageChannel> doBindConsumer(String name, String group,
MessageChannel inputChannel, ConsumerProperties properties) {
ConsulInboundMessageProducer messageProducer = new ConsulInboundMessageProducer(
this.eventService);
messageProducer.setOutputChannel(inputChannel);
messageProducer.setBeanFactory(this.getBeanFactory());
messageProducer.afterPropertiesSet();
@@ -51,13 +54,16 @@ public class ConsulBinder extends AbstractBinder<MessageChannel, ConsumerPropert
}
@Override
protected Binding<MessageChannel> doBindProducer(String name, MessageChannel channel, ProducerProperties properties) {
protected Binding<MessageChannel> doBindProducer(String name, MessageChannel channel,
ProducerProperties properties) {
Assert.isInstanceOf(SubscribableChannel.class, channel);
logger.debug("Binding Consul client to eventName " + name);
ConsulSendingHandler sendingHandler = new ConsulSendingHandler(this.eventService.getConsulClient(), name);
this.logger.debug("Binding Consul client to eventName " + 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();
@@ -65,4 +71,5 @@ public class ConsulBinder extends AbstractBinder<MessageChannel, ConsumerPropert
return new DefaultBinding<>(name, null, channel, consumer);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,6 @@
package org.springframework.cloud.consul.binder;
import static org.springframework.util.Base64Utils.decodeFromString;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@@ -25,24 +23,31 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import com.ecwid.consul.v1.OperationException;
import com.ecwid.consul.v1.event.model.Event;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.integration.endpoint.MessageProducerSupport;
import com.ecwid.consul.v1.event.model.Event;
import static org.springframework.util.Base64Utils.decodeFromString;
/**
* Adapter that receives Messages from Consul Events, converts them into Spring
* Integration Messages, and sends the results to a Message Channel.
*
* @author Spencer Gibb
*/
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;
private final Runnable eventsRunnable;
private EventService eventService;
private final ScheduledExecutorService scheduler;
private final Runnable eventsRunnable;
private ScheduledFuture<?> eventsHandle;
public ConsulInboundMessageProducer(EventService eventService) {
@@ -75,8 +80,9 @@ public class ConsulInboundMessageProducer extends MessageProducerSupport {
@Override
protected void doStart() {
//TODO: make configurable
eventsHandle = this.scheduler.scheduleWithFixedDelay(eventsRunnable, 500, 500, TimeUnit.MILLISECONDS);
// TODO: make configurable
this.eventsHandle = this.scheduler.scheduleWithFixedDelay(this.eventsRunnable,
500, 500, TimeUnit.MILLISECONDS);
}
@Override
@@ -90,20 +96,22 @@ public class ConsulInboundMessageProducer extends MessageProducerSupport {
// @Scheduled(fixedDelayString = "${spring.cloud.consul.binder.eventDelay:30000}")
public void getEvents() {
try {
List<Event> events = eventService.watch();
List<Event> events = this.eventService.watch();
for (Event event : events) {
// Map<String, Object> headers = new HashMap<>();
// headers.put(MessageHeaders.REPLY_CHANNEL, outputChannel.)
String decoded = new String(decodeFromString(event.getPayload()));
sendMessage(getMessageBuilderFactory().withPayload(decoded)
// TODO: support headers
// TODO: support headers
.build());
}
} catch (OperationException e) {
}
catch (OperationException e) {
if (logger.isErrorEnabled()) {
logger.error("Error getting consul events: " + e);
}
} catch (Exception e) {
}
catch (Exception e) {
if (logger.isErrorEnabled()) {
logger.error("Error getting consul events: " + e.getMessage());
}
@@ -112,4 +120,5 @@ public class ConsulInboundMessageProducer extends MessageProducerSupport {
}
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,23 +16,24 @@
package org.springframework.cloud.consul.binder;
import org.springframework.integration.handler.AbstractMessageHandler;
import org.springframework.integration.handler.AbstractReplyProducingMessageHandler;
import org.springframework.messaging.Message;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
import com.ecwid.consul.v1.event.model.Event;
import com.ecwid.consul.v1.event.model.EventParams;
import org.springframework.integration.handler.AbstractMessageHandler;
import org.springframework.messaging.Message;
/**
* Adapter that converts and sends Messages as Consul events
* Adapter that converts and sends Messages as Consul events.
*
* @author Spencer Gibb
*/
public class ConsulSendingHandler extends AbstractMessageHandler {
private final ConsulClient consul;
private final String eventName;
public ConsulSendingHandler(ConsulClient consul, String eventName) {
@@ -42,16 +43,17 @@ public class ConsulSendingHandler extends AbstractMessageHandler {
@Override
protected void handleMessageInternal(Message<?> message) throws Exception {
if (logger.isTraceEnabled()) {
logger.trace("Publishing message" + message);
if (this.logger.isTraceEnabled()) {
this.logger.trace("Publishing message" + message);
}
Object payload = message.getPayload();
// TODO: support headers
// TODO: support consul event filters: NodeFilter, ServiceFilter, TagFilter
Response<Event> event = consul.eventFire(this.eventName, (String) payload,
Response<Event> event = this.consul.eventFire(this.eventName, (String) payload,
new EventParams(), QueryParams.DEFAULT);
// TODO: return event?
// return null;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,8 +21,6 @@ import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.PostConstruct;
import org.springframework.cloud.consul.binder.config.ConsulBinderProperties;
import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.QueryParams;
import com.ecwid.consul.v1.Response;
@@ -30,6 +28,8 @@ import com.ecwid.consul.v1.event.model.Event;
import com.ecwid.consul.v1.event.model.EventParams;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.consul.binder.config.ConsulBinderProperties;
/**
* @author Spencer Gibb
*/
@@ -43,14 +43,15 @@ public class EventService {
private AtomicReference<Long> 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;
}
public ConsulClient getConsulClient() {
return consul;
return this.consul;
}
@PostConstruct
@@ -58,25 +59,25 @@ public class EventService {
setLastIndex(getEventsResponse());
}
public Long getLastIndex() {
return this.lastIndex.get();
}
private void setLastIndex(Response<?> response) {
Long consulIndex = response.getConsulIndex();
if (consulIndex != null) {
lastIndex.set(response.getConsulIndex());
this.lastIndex.set(response.getConsulIndex());
}
}
public Long getLastIndex() {
return lastIndex.get();
}
public Event fire(String name, String payload) {
Response<Event> response = consul.eventFire(name, payload, new EventParams(),
Response<Event> response = this.consul.eventFire(name, payload, new EventParams(),
QueryParams.DEFAULT);
return response.getValue();
}
public Response<List<Event>> getEventsResponse() {
return consul.eventList(QueryParams.DEFAULT);
return this.consul.eventList(QueryParams.DEFAULT);
}
public List<Event> getEvents() {
@@ -88,7 +89,7 @@ public class EventService {
}
public List<Event> watch() {
return watch(lastIndex.get());
return watch(this.lastIndex.get());
}
public List<Event> watch(Long lastIndex) {
@@ -98,10 +99,11 @@ public class EventService {
index = lastIndex;
}
int eventTimeout = 5;
if (properties != null) {
eventTimeout = properties.getEventTimeout();
if (this.properties != null) {
eventTimeout = this.properties.getEventTimeout();
}
Response<List<Event>> watch = consul.eventList(new QueryParams(eventTimeout, index));
Response<List<Event>> watch = this.consul
.eventList(new QueryParams(eventTimeout, index));
return filterEvents(readEvents(watch), lastIndex);
}
@@ -111,7 +113,10 @@ public class EventService {
}
/**
* from https://github.com/hashicorp/consul/blob/master/watch/funcs.go#L169-L194
* from https://github.com/hashicorp/consul/blob/master/watch/funcs.go#L169-L194 .
* @param toFilter events to filter
* @param lastIndex last index to pick from the list of events
* @return filtered list of events
*/
protected List<Event> filterEvents(List<Event> toFilter, Long lastIndex) {
List<Event> events = toFilter;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,11 +16,13 @@
package org.springframework.cloud.consul.binder.config;
import com.ecwid.consul.v1.ConsulClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.consul.ConditionalOnConsulEnabled;
import org.springframework.cloud.consul.binder.ConsulBinder;
import org.springframework.cloud.consul.binder.EventService;
@@ -29,9 +31,6 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import com.ecwid.consul.v1.ConsulClient;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Configures the Consul binder.
*
@@ -42,7 +41,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
@Import({ PropertyPlaceholderAutoConfiguration.class })
@ConditionalOnConsulEnabled
@ConditionalOnProperty(name = "spring.cloud.consul.binder.enabled", matchIfMissing = true)
//FIXME: boot 2.0.0 @EnableConfigurationProperties({ConsulBinderProperties.class})
// FIXME: boot 2.0.0 @EnableConfigurationProperties({ConsulBinderProperties.class})
public class ConsulBinderConfiguration {
// @Autowired
@@ -54,7 +53,8 @@ public class ConsulBinderConfiguration {
@Bean
@ConditionalOnMissingBean
public EventService eventService(ConsulClient consulClient) {
return new EventService(null/*consulBinderProperties*/, consulClient, objectMapper);
return new EventService(null/* consulBinderProperties */, consulClient,
this.objectMapper);
}
@Bean
@@ -63,5 +63,6 @@ public class ConsulBinderConfiguration {
return new ConsulBinder(eventService);
}
//TODO: create consul client if needed
// TODO: create consul client if needed
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,6 +24,7 @@ import org.springframework.core.style.ToStringCreator;
*/
@ConfigurationProperties("spring.cloud.stream.consul.binder")
public class ConsulBinderProperties {
private int eventTimeout = 5;
public ConsulBinderProperties() {
@@ -39,8 +40,8 @@ public class ConsulBinderProperties {
@Override
public String toString() {
return new ToStringCreator(this)
.append("eventTimeout", eventTimeout)
return new ToStringCreator(this).append("eventTimeout", this.eventTimeout)
.toString();
}
}

View File

@@ -13,6 +13,5 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
spring.cloud.stream.binder.consul.default.host=localhost
spring.cloud.stream.binder.consul.default.port=8500

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,11 +18,14 @@ package org.springframework.cloud.consul.binder;
import java.util.concurrent.TimeUnit;
import com.ecwid.consul.v1.ConsulClient;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
@@ -36,19 +39,17 @@ import org.springframework.messaging.support.MessageBuilder;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import com.ecwid.consul.v1.ConsulClient;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
import static org.assertj.core.api.Assertions.assertThat;
import static org.awaitility.Awaitility.await;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD;
/**
* @author Spencer Gibb
*/
@@ -56,33 +57,35 @@ import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER
@SpringBootTest(classes = ConsulBinderApplicationTests.Application.class)
@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)
public class ConsulBinderApplicationTests {
@Autowired
private Events events;
@Rule
public final WireMockRule wireMock = new WireMockRule(18500);
@Autowired
private Events events;
@Before
public void setUp() throws Exception {
wireMock.stubFor(put(urlPathMatching("/v1/event/fire/purchases"))
this.wireMock.stubFor(put(urlPathMatching("/v1/event/fire/purchases"))
.willReturn(aResponse().withStatus(200)));
/*wireMock.stubFor(get(urlPathMatching("/v1/event/list"))
.willReturn(aResponse().withBody("[]")
.withStatus(200)
.withHeader("X-Consul-Index", "1")));*/
/*
* wireMock.stubFor(get(urlPathMatching("/v1/event/list"))
* .willReturn(aResponse().withBody("[]") .withStatus(200)
* .withHeader("X-Consul-Index", "1")));
*/
}
@Test
@Ignore //FIXME: 2.0.0 need stream fix
@Ignore // FIXME: 2.0.0 need stream fix
public void shouldInitializeConsulSource() {
assertNotNull(events);
assertThat(this.events).isNotNull();
}
@Test
@Ignore //FIXME: 2.0.0 need stream fix
@Ignore // FIXME: 2.0.0 need stream fix
public void shouldPublishTextConsulMessage() {
// given
@@ -90,7 +93,7 @@ public class ConsulBinderApplicationTests {
.build();
// when
events.purchases().send(message);
this.events.purchases().send(message);
// then
await().atMost(1, TimeUnit.SECONDS);
@@ -101,12 +104,14 @@ public class ConsulBinderApplicationTests {
@Output
MessageChannel purchases();
}
@Configuration
@EnableAutoConfiguration
@EnableBinding(Events.class)
public static class Application {
@Bean
public ConsulClient consulClient() {
return new ConsulClient("localhost", 18500);
@@ -118,5 +123,7 @@ public class ConsulBinderApplicationTests {
when(eventService.getConsulClient()).thenReturn(consulClient);
return eventService;
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,6 +27,7 @@ import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.consul.binder.test.consumer.TestConsumer;
import org.springframework.cloud.consul.binder.test.producer.TestProducer;
import org.springframework.cloud.deployer.spi.app.AppDeployer;
@@ -40,8 +41,7 @@ import org.springframework.util.SocketUtils;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link org.springframework.cloud.consul.binder.ConsulBinder}.
@@ -49,12 +49,6 @@ import static org.junit.Assert.assertTrue;
* @author Spencer Gibb
*/
public class ConsulBinderTests {
private static final Logger logger = LoggerFactory.getLogger(ConsulBinderTests.class);
/**
* Timeout value in milliseconds for operations to complete.
*/
private static final long TIMEOUT = 30000;
/**
* Payload of test message.
@@ -66,6 +60,13 @@ public class ConsulBinderTests {
*/
public static final String BINDING_NAME = "test";
private static final Logger logger = LoggerFactory.getLogger(ConsulBinderTests.class);
/**
* Timeout value in milliseconds for operations to complete.
*/
private static final long TIMEOUT = 30000;
/**
* Deployer to launch producer and consumer test applications.
*/
@@ -76,7 +77,6 @@ public class ConsulBinderTests {
*/
private final RestTemplate restTemplate = new RestTemplate();
public ConsulBinderTests() {
LocalDeployerProperties properties = new LocalDeployerProperties();
properties.setDeleteFilesOnExit(false);
@@ -85,43 +85,38 @@ public class ConsulBinderTests {
/**
* Test basic message sending functionality.
*
* @throws Exception
* @throws InterruptedException when waiting for message was interrupted
*/
@Test
@Ignore //FIXME: 2.0.0 need stream fix
public void testMessageSendReceive() throws Exception {
@Ignore // FIXME: 2.0.0 need stream fix
public void testMessageSendReceive() throws InterruptedException {
testMessageSendReceive(null);
}
/**
* Test usage of partition selector.
*
* @throws Exception
*/
/*@Test
public void testPartitionedMessageSendReceive() throws Exception {
testMessageSendReceive(null, true);
}*/
/*
* @Test public void testPartitionedMessageSendReceive() throws Exception {
* testMessageSendReceive(null, true); }
*/
/**
* Test consumer group functionality.
*
* @throws Exception
*/
/*@Test
public void testMessageSendReceiveConsumerGroups() throws Exception {
testMessageSendReceive(new String[]{"a", "b"}, false);
}*/
/*
* @Test public void testMessageSendReceiveConsumerGroups() throws Exception {
* testMessageSendReceive(new String[]{"a", "b"}, false); }
*/
/**
* Test message sending functionality.
*
* @param groups consumer groups; may be {@code null}
* @param partitioned if true, execute test with a partition selector
* @throws Exception
* @throws InterruptedException when waiting for message was interrupted
*/
private void testMessageSendReceive(String[] groups) throws Exception {
private void testMessageSendReceive(String[] groups) throws InterruptedException {
Set<AppId> consumers = null;
AppId producer = null;
@@ -130,7 +125,7 @@ public class ConsulBinderTests {
producer = launchProducer();
for (AppId consumer : consumers) {
assertEquals(MESSAGE_PAYLOAD, waitForMessage(consumer.port));
assertThat(waitForMessage(consumer.port)).isEqualTo(MESSAGE_PAYLOAD);
}
}
finally {
@@ -146,12 +141,11 @@ public class ConsulBinderTests {
}
/**
* Launch one or more consumers based on the number of consumer groups.
* Blocks execution until the consumers are bound.
*
* Launch one or more consumers based on the number of consumer groups. Blocks
* execution until the consumers are bound.
* @param groups consumer groups; may be {@code null}
* @return a set of {@link AppId}s for the consumers
* @throws InterruptedException
* @throws InterruptedException when waiting for message was interrupted
*/
private Set<AppId> launchConsumers(String[] groups) throws InterruptedException {
Set<AppId> consumers = new HashSet<>();
@@ -170,7 +164,9 @@ 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);
@@ -181,7 +177,6 @@ public class ConsulBinderTests {
/**
* Launch a producer that publishes a test message.
*
* @return {@link AppId} for producer
*/
private AppId launchProducer() {
@@ -196,16 +191,16 @@ 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);
}
/**
* Block the executing thread until the consumer is bound.
*
* @param port server port of the consumer application
* @throws InterruptedException if the thread is interrupted
* @throws AssertionError if the consumer is not bound after
* {@value #TIMEOUT} milliseconds
* @throws AssertionError if the consumer is not bound after {@value #TIMEOUT}
* milliseconds
*/
private void waitForConsumer(int port) throws InterruptedException {
long start = System.currentTimeMillis();
@@ -217,18 +212,17 @@ public class ConsulBinderTests {
Thread.sleep(1000);
}
}
assertTrue("Consumer not bound", isConsumerBound(port));
assertThat(isConsumerBound(port)).as("Consumer not bound").isTrue();
}
/**
* Return {@code true} if the consumer at the provided port is bound.
*
* @param port http port for consumer
* @return true if consumer is bound
*/
private boolean isConsumerBound(int port) {
try {
return restTemplate.getForObject(
return this.restTemplate.getForObject(
String.format("http://localhost:%d/is-bound", port), Boolean.class);
}
catch (ResourceAccessException e) {
@@ -239,15 +233,14 @@ public class ConsulBinderTests {
/**
* Return the most recent payload message a consumer received.
*
* @param port http port for consumer
* @return the most recent payload message a consumer received;
* may be {@code null}
* @return the most recent payload message a consumer received; may be {@code null}
*/
private String getConsumerMessagePayload(int port) {
try {
return restTemplate.getForObject(
String.format("http://localhost:%d/message-payload", port), String.class);
return this.restTemplate.getForObject(
String.format("http://localhost:%d/message-payload", port),
String.class);
}
catch (ResourceAccessException e) {
logger.debug("getConsumerMessagePayload", e);
@@ -257,13 +250,12 @@ public class ConsulBinderTests {
/**
* Return {@code true} if the producer made use of a custom partition selector.
*
* @param port http port for producer
* @return true if the producer used a custom partition selector
*/
private boolean partitionSelectorUsed(int port) throws InterruptedException {
private boolean partitionSelectorUsed(int port) {
try {
return restTemplate.getForObject(
return this.restTemplate.getForObject(
String.format("http://localhost:%d/partition-strategy-invoked", port),
Boolean.class);
}
@@ -274,9 +266,8 @@ public class ConsulBinderTests {
}
/**
* Block the executing thread until a message is received by the
* consumer application, or until {@value #TIMEOUT} milliseconds elapses.
*
* Block the executing thread until a message is received by the consumer application,
* or until {@value #TIMEOUT} milliseconds elapses.
* @param port server port of the consumer application
* @return the message payload that was received
* @throws InterruptedException if the thread is interrupted
@@ -298,29 +289,31 @@ public class ConsulBinderTests {
/**
* Launch an application in a separate JVM.
*
* @param clz the main class to launch
* @param properties the properties to pass to the application
* @param args the command line arguments for the application
* @return a string identifier for the application
*/
private String launchApplication(Class<?> clz, Map<String, String> properties, List<String> args) {
Resource resource = new UrlResource(clz.getProtectionDomain().getCodeSource().getLocation());
private String launchApplication(Class<?> clz, Map<String, String> properties,
List<String> 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);
}
/**
* Shut down the application with the provided id.
*
* @param id id of application to shut down
*/
private void shutdownApplication(String id) {
@@ -331,7 +324,6 @@ public class ConsulBinderTests {
/**
* Instantiates a new local app deployer.
*
* @param properties the properties
*/
ClasspathDeployer(LocalDeployerProperties properties) {
@@ -340,12 +332,12 @@ public class ConsulBinderTests {
/**
* Builds the jar execution command.
*
* @param jarPath the jar path
* @param request the request
* @return the string[]
*/
protected String[] buildJarExecutionCommand(String jarPath, AppDeploymentRequest request) {
protected String[] buildJarExecutionCommand(String jarPath,
AppDeploymentRequest request) {
ArrayList<String> commands = new ArrayList<>();
commands.add(super.getLocalDeployerProperties().getJavaCmd());
@@ -356,14 +348,16 @@ public class ConsulBinderTests {
return commands.toArray(new String[commands.size()]);
}
}
}
/**
* String identification and http port for a launched application.
*/
private static class AppId {
final String id;
final int port;
AppId(String id, int port) {
@@ -381,15 +375,16 @@ public class ConsulBinderTests {
}
AppId appId = (AppId) o;
return port == appId.port && id.equals(appId.id);
return this.port == appId.port && this.id.equals(appId.id);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = 31 * result + port;
int result = this.id.hashCode();
result = 31 * result + this.port;
return result;
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,11 +16,10 @@
package org.springframework.cloud.consul.binder;
import com.ecwid.consul.v1.OperationException;
import org.junit.Test;
import com.ecwid.consul.v1.OperationException;
import static org.junit.Assert.fail;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -34,15 +33,16 @@ 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();
} catch (Exception e) {
fail("ConsulInboundMessageProducer threw unexpected exception: "+e);
}
catch (Exception e) {
fail("ConsulInboundMessageProducer threw unexpected exception: " + e);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@ import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.stream.annotation.EnableBinding;
@@ -38,31 +39,33 @@ public class ConsulBinderConfigurationTests {
public ExpectedException exception = ExpectedException.none();
@Test
@Ignore //FIXME 2.0.0 need stream fix
@Ignore // FIXME 2.0.0 need stream fix
public void consulBinderDisabledWorks() {
this.exception.expectMessage(containsString("no proper implementation found"));
new SpringApplicationBuilder(Application.class)
.properties("spring.cloud.consul.binder.enabled=false")
.run();
.properties("spring.cloud.consul.binder.enabled=false").run();
}
@Test
@Ignore //FIXME 2.0.0 need stream fix
@Ignore // FIXME 2.0.0 need stream fix
public void consulDisabledDisablesBinder() {
this.exception.expectMessage(containsString("no proper implementation found"));
new SpringApplicationBuilder(Application.class)
.properties("spring.cloud.consul.enabled=false")
.run();
.properties("spring.cloud.consul.enabled=false").run();
}
interface Events {
@Output
MessageChannel purchases();
}
@Configuration
@EnableAutoConfiguration
@EnableBinding(Events.class)
public static class Application {
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.cloud.consul.binder.test.consumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
@@ -27,7 +28,6 @@ import org.springframework.cloud.consul.binder.ConsulBinder;
import org.springframework.cloud.consul.binder.ConsulBinderTests;
import org.springframework.cloud.consul.binder.config.ConsulBinderConfiguration;
import org.springframework.cloud.stream.binder.ConsumerProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.messaging.Message;
@@ -39,14 +39,15 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Consumer application that binds a channel to a {@link ConsulBinder}
* and stores the received message payload.
* Consumer application that binds a channel to a {@link ConsulBinder} and stores the
* received message payload.
*/
@RestController
@Import(ConsulBinderConfiguration.class)
@Configuration
@EnableAutoConfiguration
public class TestConsumer implements ApplicationRunner {
private static final Logger logger = LoggerFactory.getLogger(TestConsumer.class);
/**
@@ -64,23 +65,21 @@ public class TestConsumer implements ApplicationRunner {
/**
* Main method.
*
* @param args if present, first arg is consumer group name
* @throws Exception
*/
public static void main(String[] args) throws Exception {
public static void main(String[] args) {
SpringApplication.run(TestConsumer.class, args);
}
@Override
public void run(ApplicationArguments args) throws Exception {
logger.info("Consumer running with binder {}", binder);
logger.info("Consumer running with binder {}", this.binder);
SubscribableChannel consumerChannel = new ExecutorSubscribableChannel();
consumerChannel.subscribe(new MessageHandler() {
@Override
public void handleMessage(Message<?> message) throws MessagingException {
messagePayload = (String) message.getPayload();
logger.info("Received message: {}", messagePayload);
TestConsumer.this.messagePayload = (String) message.getPayload();
logger.info("Received message: {}", TestConsumer.this.messagePayload);
}
});
String group = null;
@@ -89,19 +88,19 @@ public class TestConsumer implements ApplicationRunner {
group = args.getOptionValues("group").get(0);
}
binder.bindConsumer(ConsulBinderTests.BINDING_NAME, group, consumerChannel,
this.binder.bindConsumer(ConsulBinderTests.BINDING_NAME, group, consumerChannel,
new ConsumerProperties());
isBound = true;
this.isBound = true;
}
@RequestMapping("/is-bound")
public boolean isBound() {
return isBound;
return this.isBound;
}
@RequestMapping("/message-payload")
public String getMessagePayload() {
return messagePayload;
return this.messagePayload;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.cloud.consul.binder.test.producer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
@@ -40,8 +41,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Producer application that binds a channel to a {@link ConsulBinder}
* and sends a test message.
* Producer application that binds a channel to a {@link ConsulBinder} and sends a test
* message.
*/
@RestController
@Import(ConsulBinderConfiguration.class)
@@ -60,17 +61,20 @@ public class TestProducer implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
/*if (args.containsOption("partitioned")
&& Boolean.valueOf(args.getOptionValues("partitioned").get(0))) {
binder.setPartitionSelector(stubPartitionSelectorStrategy());
}*/
/*
* if (args.containsOption("partitioned") &&
* Boolean.valueOf(args.getOptionValues("partitioned").get(0))) {
* binder.setPartitionSelector(stubPartitionSelectorStrategy()); }
*/
SubscribableChannel producerChannel = producerChannel();
ProducerProperties properties = new ProducerProperties();
properties.setPartitionKeyExpression(new SpelExpressionParser().parseExpression("payload"));
binder.bindProducer(ConsulBinderTests.BINDING_NAME, producerChannel, properties);
properties.setPartitionKeyExpression(
new SpelExpressionParser().parseExpression("payload"));
this.binder.bindProducer(ConsulBinderTests.BINDING_NAME, producerChannel,
properties);
Message<String> message = new GenericMessage<>(ConsulBinderTests.MESSAGE_PAYLOAD);
logger.info("Writing message to binder {}", binder);
logger.info("Writing message to binder {}", this.binder);
producerChannel.send(message);
}
@@ -89,16 +93,19 @@ 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);
invoked = true;
logger.info("Selecting partition for key {}; partition count: {}", key,
partitionCount);
this.invoked = true;
return 1;
}
}
}

View File

@@ -1,4 +1,3 @@
spring:
cloud:
stream: