From bd002e4aaf05f2f4e31cb09d706910b470f960a3 Mon Sep 17 00:00:00 2001 From: Ilayaperumal Gopinathan Date: Fri, 12 May 2017 21:34:39 +0530 Subject: [PATCH] Add code formatting guidelines Add 'eclipse' folder containing Eclipse code formatter configuration and instructions how to use it. Update rule for join_wrapped_lines - Set to `false` Resolves #930 Update README Address review comments --- README.adoc | 13 + eclipse/eclipse-code-formatter.xml | 397 ++++++++++++++++++ eclipse/eclipse.importorder | 7 + .../stream/binder/AbstractBinderTests.java | 24 +- .../stream/binder/AbstractTestBinder.java | 26 +- .../BinderTestEnvironmentPostProcessor.java | 3 +- .../cloud/stream/binder/BinderTestUtils.java | 5 +- .../binder/PartitionCapableBinderTests.java | 3 +- .../stream/binder/PartitionTestSupport.java | 1 - .../cloud/stream/binder/Spy.java | 5 +- .../MessageChannelBinderSupportTests.java | 31 +- .../kryo/KryoCodecAutoConfiguration.java | 4 +- .../ContentTypeOutboundSourceTests.java | 8 +- .../config/CustomMessageConverterTests.java | 6 +- .../DeserializeJSONToJavaTypeTests.java | 3 +- .../stream/config/ErrorChannelTests.java | 4 +- .../InboundJsonToTupleConversionTest.java | 3 +- .../config/MessageChannelConfigurerTests.java | 11 +- ...ListenerAnnotatedMethodArgumentsTests.java | 5 +- ...notationBeanPostProcessorOverrideTest.java | 16 +- .../StreamListenerAsMetaAnnotationTests.java | 66 +-- ...eamListenerContentTypeConversionTests.java | 1 + .../StreamListenerDuplicateMappingTests.java | 20 +- .../StreamListenerHandlerMethodTests.java | 87 ++-- .../StreamListenerMessageArgumentTests.java | 2 +- ...stenerMethodReturnWithConversionTests.java | 22 +- ...mListenerMethodWithReturnMessageTests.java | 2 +- ...eamListenerMethodWithReturnValueTests.java | 2 +- .../config/StreamListenerTestUtils.java | 36 +- ...enerWithAnnotatedInputOutputArgsTests.java | 19 +- .../StreamListenerWithConditionsTest.java | 15 +- .../config/TextPlainConversionTest.java | 4 +- .../aggregate/AggregateApplicationTests.java | 9 +- .../stream/metrics/ApplicationMetrics.java | 2 +- .../metrics/ApplicationMetricsProperties.java | 27 +- .../BinderMetricsAutoConfiguration.java | 23 +- .../metrics/config/MetricJsonSerializer.java | 12 +- .../ApplicationMetricsExporterTests.java | 21 +- .../metrics/RelaxedPropertiesUtilsTests.java | 6 +- .../config/MetricJsonSerializerTests.java | 13 +- .../FluxToMessageChannelResultAdapter.java | 4 +- ...geChannelToFluxSenderParameterAdapter.java | 5 +- ...nelToObservableSenderParameterAdapter.java | 3 +- ...servableToMessageChannelResultAdapter.java | 4 +- .../ReactiveSupportAutoConfiguration.java | 3 +- ...icFluxInputOutputArgsWithMessageTests.java | 31 +- .../StreamListenerInterruptionTests.java | 4 +- ...mListenerReactiveInputOutputArgsTests.java | 19 +- ...activeInputOutputArgsWithMessageTests.java | 17 +- ...utOutputArgsWithSenderAndFailureTests.java | 28 +- ...eactiveInputOutputArgsWithSenderTests.java | 33 +- .../StreamListenerReactiveMethodTests.java | 40 +- ...enerReactiveMethodWithReturnTypeTests.java | 44 +- ...istenerReactiveReturnWithFailureTests.java | 62 ++- ...istenerReactiveReturnWithMessageTests.java | 57 +-- ...amListenerReactiveReturnWithPojoTests.java | 38 +- ...rdFluxInputOutputArgsWithMessageTests.java | 25 +- .../rxjava/EnableRxJavaProcessor.java | 8 +- .../annotation/rxjava/RxJavaProcessor.java | 3 +- .../rxjava/SubjectMessageHandler.java | 41 +- .../config/SchemaServerConfiguration.java | 9 +- .../server/config/SchemaServerProperties.java | 1 - .../server/controllers/ServerController.java | 7 +- .../schema/server/model/Compatibility.java | 6 +- .../server/SchemaRegistryServerAvroTests.java | 14 +- .../entityScanning/EntityScanningTests.java | 3 +- .../EntityScanningTestsWithEntityScan.java | 3 +- .../cloud/stream/schema/ParsedSchema.java | 15 +- .../avro/AbstractAvroMessageConverter.java | 4 +- ...AvroMessageConverterAutoConfiguration.java | 8 +- .../avro/AvroSchemaMessageConverter.java | 25 +- ...oSchemaRegistryClientMessageConverter.java | 13 +- .../schema/client/CachingRegistryClient.java | 6 +- .../client/DefaultSchemaRegistryClient.java | 4 +- .../client/EnableSchemaRegistryClient.java | 2 +- .../schema/client/SchemaRegistryClient.java | 9 +- .../SchemaRegistryClientConfiguration.java | 3 +- ...vroMessageConverterSerializationTests.java | 28 +- .../avro/AvroSchemaMessageConverterTests.java | 15 +- ...maRegistryClientMessageConverterTests.java | 23 +- ...maRegistryClientMessageConverterTests.java | 4 - .../AbstractExternalResourceTestSupport.java | 4 +- .../stream/test/binder/MessageCollector.java | 4 +- .../TestBinderEnvironmentPostProcessor.java | 3 +- .../stream/test/binder/TestSupportBinder.java | 18 +- .../TestSupportBinderAutoConfiguration.java | 13 +- .../test/matcher/MessageQueueMatcher.java | 58 +-- .../test/aggregate/AggregateWithBeanTest.java | 2 +- .../test/aggregate/AggregateWithMainTest.java | 6 +- .../stream/test/example/ExampleTest.java | 6 +- .../aggregate/AggregateApplication.java | 7 +- .../AggregateApplicationBuilder.java | 85 ++-- ...aceAwareSpringIntegrationMetricReader.java | 9 +- .../cloud/stream/annotation/Bindings.java | 8 +- .../cloud/stream/annotation/Input.java | 2 +- .../stream/annotation/StreamListener.java | 2 +- .../cloud/stream/binder/AbstractBinder.java | 24 +- .../binder/AbstractMessageChannelBinder.java | 108 ++--- .../cloud/stream/binder/BinderException.java | 4 +- .../cloud/stream/binder/BinderHeaders.java | 45 +- .../cloud/stream/binder/BinderType.java | 10 +- .../stream/binder/BinderTypeRegistry.java | 7 +- .../cloud/stream/binder/Binding.java | 16 +- .../cloud/stream/binder/BindingCleaner.java | 6 +- .../stream/binder/ConsumerProperties.java | 21 +- .../stream/binder/DefaultBinderFactory.java | 38 +- .../cloud/stream/binder/DefaultBinding.java | 4 +- .../binder/ExtendedBindingProperties.java | 3 +- .../binder/ExtendedConsumerProperties.java | 3 +- .../binder/ExtendedPropertiesBinder.java | 10 +- .../cloud/stream/binder/MessageValues.java | 49 +-- .../cloud/stream/binder/PartitionHandler.java | 27 +- .../binder/PartitionSelectorStrategy.java | 11 +- .../cloud/stream/binding/BindableAdapter.java | 1 - .../stream/binding/BindableProxyFactory.java | 6 +- .../BinderAwareRouterBeanPostProcessor.java | 4 +- .../cloud/stream/binding/BindingService.java | 7 +- .../ContextStartAfterRefreshListener.java | 3 +- ...spatchingStreamListenerMessageHandler.java | 6 +- .../binding/DynamicDestinationsBindable.java | 5 +- .../binding/MessageChannelConfigurer.java | 7 +- ...ageChannelStreamListenerResultAdapter.java | 5 +- .../binding/MessageConverterConfigurer.java | 70 +-- ...amListenerAnnotationBeanPostProcessor.java | 30 +- .../binding/StreamListenerErrorMessages.java | 30 +- ...bscribableChannelBindingTargetFactory.java | 3 +- .../config/BinderFactoryConfiguration.java | 39 +- ...ndersHealthIndicatorAutoConfiguration.java | 6 +- .../stream/config/BindingProperties.java | 10 +- .../config/BindingServiceConfiguration.java | 70 +-- .../config/BindingServiceProperties.java | 3 +- .../CompositeMessageConverterFactory.java | 5 +- .../converter/CustomMimeTypeConverter.java | 4 +- .../converter/JsonUnmarshallingConverter.java | 7 +- .../converter/MessageConverterUtils.java | 6 +- .../ObjectStringMessageConverter.java | 7 +- .../converter/TupleJsonMessageConverter.java | 16 +- .../provisioning/ProducerDestination.java | 17 +- .../provisioning/ProvisioningException.java | 4 +- .../provisioning/ProvisioningProvider.java | 29 +- .../stream/reflection/GenericsUtils.java | 9 +- .../stream/aggregation/AggregationTest.java | 125 +++--- .../BinderAwareChannelResolverTests.java | 11 +- .../BinderFactoryConfigurationTests.java | 88 ++-- .../stream/binder/ErrorBindingTests.java | 15 +- ...ertiesBinderAwareChannelResolverTests.java | 7 +- .../HealthIndicatorsConfigurationTests.java | 36 +- .../binder/InputOutputBindingOrderTest.java | 2 +- .../stream/binder/MessageConverterTests.java | 18 +- ...ceBindingWithGlobalPropertiesOnlyTest.java | 2 +- ...SourceBindingWithGlobalPropertiesTest.java | 2 +- .../stream/binder/stub1/StubBinder1.java | 3 +- .../stream/binder/stub2/StubBinder2.java | 3 +- .../stream/binding/BindingServiceTests.java | 20 +- .../CustomPartitionedProducerTest.java | 19 +- .../BinderConfigurationParsingTests.java | 35 +- .../BoundChannelsInterceptedTest.java | 7 +- .../partitioning/PartitionedConsumerTest.java | 2 +- .../partitioning/PartitionedProducerTest.java | 1 - 159 files changed, 1770 insertions(+), 1283 deletions(-) create mode 100644 eclipse/eclipse-code-formatter.xml create mode 100644 eclipse/eclipse.importorder diff --git a/README.adoc b/README.adoc index 7ea969b85..1999c30ac 100644 --- a/README.adoc +++ b/README.adoc @@ -37,6 +37,19 @@ Any question that is not a bug or an issue should be asked on Stack Overflow, us We love contributions. Follow this https://github.com/spring-cloud/spring-cloud-commons#contributing[link] for more information on how to contribute. +=== Code formatting guidelines + +* The directory `eclipse` contains two files that can be used to configure the formatting rules in your IDE: `eclipse-code-formatter.xml` for the majority of the code formatting rules and `eclipse.importorder` to order the import statements. + +* In Eclipse you import these files by navigating `Windows -> Preferences` and then the menu items `Preferences > Java > Code Style > Formatter` and `Preferences > Java > Code Style > Organize Imports` respectively. + +* In `IntelliJ`, install the plugin `Eclipse Code Formatter`. +You can find it by searching the "Browse Repositories" under the plugin option within `IntelliJ` (Once installed you will need to reboot Intellij for it to take effect). +Then navigate to `Intellij IDEA > Preferences` and select the Eclipse Code Formatter. +Select the `eclipse-code-formatter.xml` file for the field `Eclipse Java Formatter config file` and the file `eclipse.importorder` for the field `Import order`. +Enable the `Eclipse code formatter` by clicking `Use the Eclipse code formatter` then click the *OK* button. +** NOTE: If you configure the `Eclipse Code Formatter` from `File > Other Settings > Default Settings` it will set this policy across all of your Intellij projects. + == Code of Conduct This project adheres to the Contributor Covenant link:CODE_OF_CONDUCT.adoc[code of conduct]. By participating, you are expected to uphold this code. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io. diff --git a/eclipse/eclipse-code-formatter.xml b/eclipse/eclipse-code-formatter.xml new file mode 100644 index 000000000..8dc32870a --- /dev/null +++ b/eclipse/eclipse-code-formatter.xml @@ -0,0 +1,397 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/eclipse/eclipse.importorder b/eclipse/eclipse.importorder new file mode 100644 index 000000000..080e73d9a --- /dev/null +++ b/eclipse/eclipse.importorder @@ -0,0 +1,7 @@ +#Organize Import Order +#Wed Apr 26 12:53:22 EDT 2017 +4=\# +3=org.springframework +2= +1=javax +0=java diff --git a/spring-cloud-stream-binder-test/src/main/java/org/springframework/cloud/stream/binder/AbstractBinderTests.java b/spring-cloud-stream-binder-test/src/main/java/org/springframework/cloud/stream/binder/AbstractBinderTests.java index 8b7c5f8c2..5338e04f8 100644 --- a/spring-cloud-stream-binder-test/src/main/java/org/springframework/cloud/stream/binder/AbstractBinderTests.java +++ b/spring-cloud-stream-binder-test/src/main/java/org/springframework/cloud/stream/binder/AbstractBinderTests.java @@ -57,23 +57,23 @@ public abstract class AbstractBinderTests receive(PollableChannel channel) { return receive(channel, 1); } /** - * Attempt to receive a message on the given channel, - * waiting up to 1s * additionalMultiplier * {@link #timeoutMultiplier}). + * Attempt to receive a message on the given channel, waiting up to 1s * + * additionalMultiplier * {@link #timeoutMultiplier}). * * Allows accomodating tests which are slower than normal (e.g. retry). */ @@ -170,7 +170,6 @@ public abstract class AbstractBinderTests[] messages = new Message[2]; messages[0] = receive(moduleInputChannel); messages[1] = receive(moduleInputChannel); @@ -211,7 +210,6 @@ public abstract class AbstractBinderTests, CP extends ConsumerProperties, PP extends ProducerProperties> implements Binder { +public abstract class AbstractTestBinder, CP extends ConsumerProperties, PP extends ProducerProperties> + implements Binder { protected Set queues = new HashSet(); private C binder; - public void setBinder(C binder) { - try { - binder.afterPropertiesSet(); - } - catch (Exception e) { - throw new RuntimeException("Failed to initialize binder", e); - } - this.binder = binder; - } - @Override - public Binding bindConsumer(String name, String group, MessageChannel moduleInputChannel, CP properties) { + public Binding bindConsumer(String name, String group, MessageChannel moduleInputChannel, + CP properties) { queues.add(name); return binder.bindConsumer(name, group, moduleInputChannel, properties); } @@ -66,4 +58,14 @@ public abstract class AbstractTestBinder, CP, PP>, CP extends ConsumerProperties, PP extends ProducerProperties> +public abstract class PartitionCapableBinderTests, CP, PP>, CP extends ConsumerProperties, PP extends ProducerProperties> extends AbstractBinderTests { protected static final SpelExpressionParser spelExpressionParser = new SpelExpressionParser(); diff --git a/spring-cloud-stream-binder-test/src/main/java/org/springframework/cloud/stream/binder/PartitionTestSupport.java b/spring-cloud-stream-binder-test/src/main/java/org/springframework/cloud/stream/binder/PartitionTestSupport.java index 6b1d8d59f..3531dc91a 100644 --- a/spring-cloud-stream-binder-test/src/main/java/org/springframework/cloud/stream/binder/PartitionTestSupport.java +++ b/spring-cloud-stream-binder-test/src/main/java/org/springframework/cloud/stream/binder/PartitionTestSupport.java @@ -18,7 +18,6 @@ package org.springframework.cloud.stream.binder; import org.springframework.messaging.Message; - /** * @author Gary Russell */ diff --git a/spring-cloud-stream-binder-test/src/main/java/org/springframework/cloud/stream/binder/Spy.java b/spring-cloud-stream-binder-test/src/main/java/org/springframework/cloud/stream/binder/Spy.java index 863674cc2..548a53ad0 100644 --- a/spring-cloud-stream-binder-test/src/main/java/org/springframework/cloud/stream/binder/Spy.java +++ b/spring-cloud-stream-binder-test/src/main/java/org/springframework/cloud/stream/binder/Spy.java @@ -17,9 +17,8 @@ package org.springframework.cloud.stream.binder; /** - * Represents an out-of-band connection to the underlying middleware, - * so that tests can check that some messages actually do (or do not) - * transit through it. + * Represents an out-of-band connection to the underlying middleware, so that tests can + * check that some messages actually do (or do not) transit through it. * * @author Eric Bottard */ diff --git a/spring-cloud-stream-binder-test/src/test/java/org/springframework/cloud/stream/binder/MessageChannelBinderSupportTests.java b/spring-cloud-stream-binder-test/src/test/java/org/springframework/cloud/stream/binder/MessageChannelBinderSupportTests.java index 584b422c8..0f10b2d1a 100644 --- a/spring-cloud-stream-binder-test/src/test/java/org/springframework/cloud/stream/binder/MessageChannelBinderSupportTests.java +++ b/spring-cloud-stream-binder-test/src/test/java/org/springframework/cloud/stream/binder/MessageChannelBinderSupportTests.java @@ -43,7 +43,6 @@ import org.springframework.util.MimeTypeUtils; import static org.assertj.core.api.Assertions.assertThat; - /** * @author Gary Russell * @author David Turanski @@ -132,7 +131,6 @@ public class MessageChannelBinderSupportTests { assertThat(reconstructed.get(MessageHeaders.CONTENT_TYPE)).isEqualTo(MimeTypeUtils.APPLICATION_JSON_VALUE); } - @Test public void testContentTypePreservedForNonSCStApp() { Message inbound = MessageBuilder.withPayload("{\"foo\":\"bar\"}") @@ -253,19 +251,6 @@ public class MessageChannelBinderSupportTests { } - public class TestMessageChannelBinder extends AbstractBinder { - - @Override - protected Binding doBindConsumer(String name, String group, MessageChannel channel, ConsumerProperties properties) { - return null; - } - - @Override - public Binding doBindProducer(String name, MessageChannel channel, ProducerProperties properties) { - return null; - } - } - private static class TupleRegistrar implements KryoRegistrar { private final TupleKryoRegistrar delegate = new TupleKryoRegistrar(); @@ -280,4 +265,20 @@ public class MessageChannelBinderSupportTests { } } + public class TestMessageChannelBinder + extends AbstractBinder { + + @Override + protected Binding doBindConsumer(String name, String group, MessageChannel channel, + ConsumerProperties properties) { + return null; + } + + @Override + public Binding doBindProducer(String name, MessageChannel channel, + ProducerProperties properties) { + return null; + } + } + } diff --git a/spring-cloud-stream-codec/src/main/java/org/springframework/cloud/stream/config/codec/kryo/KryoCodecAutoConfiguration.java b/spring-cloud-stream-codec/src/main/java/org/springframework/cloud/stream/config/codec/kryo/KryoCodecAutoConfiguration.java index 8985f06eb..dfe8f09de 100644 --- a/spring-cloud-stream-codec/src/main/java/org/springframework/cloud/stream/config/codec/kryo/KryoCodecAutoConfiguration.java +++ b/spring-cloud-stream-codec/src/main/java/org/springframework/cloud/stream/config/codec/kryo/KryoCodecAutoConfiguration.java @@ -33,7 +33,6 @@ import org.springframework.integration.codec.kryo.FileKryoRegistrar; import org.springframework.integration.codec.kryo.KryoRegistrar; import org.springframework.integration.codec.kryo.PojoCodec; - /** * Auto configures {@link PojoCodec} if Kryo is on the class path. * @author David Turanski @@ -53,8 +52,7 @@ public class KryoCodecAutoConfiguration { @Bean @ConditionalOnMissingBean(PojoCodec.class) public PojoCodec codec() { - Map kryoRegistrarMap = applicationContext.getBeansOfType(KryoRegistrar - .class); + Map kryoRegistrarMap = applicationContext.getBeansOfType(KryoRegistrar.class); return new PojoCodec(new ArrayList<>(kryoRegistrarMap.values()), kryoCodecProperties.isReferences()); } diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/ContentTypeOutboundSourceTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/ContentTypeOutboundSourceTests.java index d32e80505..4ea6ef9d2 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/ContentTypeOutboundSourceTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/ContentTypeOutboundSourceTests.java @@ -40,7 +40,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Ilayaperumal Gopinathan */ @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = {ContentTypeOutboundSourceTests.TestSource.class}) +@SpringBootTest(classes = { ContentTypeOutboundSourceTests.TestSource.class }) public class ContentTypeOutboundSourceTests { @Autowired @@ -54,8 +54,9 @@ public class ContentTypeOutboundSourceTests { @SuppressWarnings("unchecked") public void testMessageHeaderWhenNoExplicitContentTypeOnMessage() throws Exception { testSource.output().send(MessageBuilder.withPayload("{\"message\":\"Hi\"}").build()); - Message received = (Message) ((TestSupportBinder) binderFactory.getBinder(null, MessageChannel.class)) - .messageCollector().forChannel(testSource.output()).poll(); + Message received = (Message) ((TestSupportBinder) binderFactory.getBinder(null, + MessageChannel.class)) + .messageCollector().forChannel(testSource.output()).poll(); assertThat(received.getHeaders().get(MessageHeaders.CONTENT_TYPE).toString()).isEqualTo("application/json"); assertThat(received).hasFieldOrPropertyWithValue("payload", "{\"message\":\"Hi\"}"); } @@ -67,4 +68,3 @@ public class ContentTypeOutboundSourceTests { } } - diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/CustomMessageConverterTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/CustomMessageConverterTests.java index ef617c8a6..5bc8658fb 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/CustomMessageConverterTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/CustomMessageConverterTests.java @@ -71,8 +71,9 @@ public class CustomMessageConverterTests { BarConverter.class, DefaultDatatypeChannelMessageConverter.class); testSource.output().send(MessageBuilder.withPayload(new Foo("hi")).build()); @SuppressWarnings("unchecked") - Message received = (Message) ((TestSupportBinder) binderFactory.getBinder(null, MessageChannel.class)) - .messageCollector().forChannel(testSource.output()).poll(1, TimeUnit.SECONDS); + Message received = (Message) ((TestSupportBinder) binderFactory.getBinder(null, + MessageChannel.class)) + .messageCollector().forChannel(testSource.output()).poll(1, TimeUnit.SECONDS); Assert.assertThat(received, notNullValue()); assertThat(received.getHeaders().get(MessageHeaders.CONTENT_TYPE)).isEqualTo(MimeType.valueOf("test/foo")); } @@ -128,7 +129,6 @@ public class CustomMessageConverterTests { super(MimeType.valueOf("test/bar")); } - @Override protected boolean supports(Class clazz) { return clazz.equals(Bar.class); diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/DeserializeJSONToJavaTypeTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/DeserializeJSONToJavaTypeTests.java index 5f0fc97f2..af3a37858 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/DeserializeJSONToJavaTypeTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/DeserializeJSONToJavaTypeTests.java @@ -58,7 +58,8 @@ public class DeserializeJSONToJavaTypeTests { @Test public void testMessageDeserialized() throws Exception { - testProcessor.input().send(MessageBuilder.withPayload("{\"name\":\"Bar\"}").setHeader("contentType", "application/json").build()); + testProcessor.input().send( + MessageBuilder.withPayload("{\"name\":\"Bar\"}").setHeader("contentType", "application/json").build()); @SuppressWarnings("unchecked") Message received = ((TestSupportBinder) binderFactory.getBinder(null, MessageChannel.class)) .messageCollector().forChannel(testProcessor.output()).poll(1, TimeUnit.SECONDS); diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/ErrorChannelTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/ErrorChannelTests.java index 1bf7ac7c4..5cfe44214 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/ErrorChannelTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/ErrorChannelTests.java @@ -56,7 +56,8 @@ public class ErrorChannelTests { @Test public void testErrorChannelBinding() throws Exception { - Message message = ((TestSupportBinder) binderFactory.getBinder(null, MessageChannel.class)).messageCollector().forChannel(errorChannel).poll(10, TimeUnit.SECONDS); + Message message = ((TestSupportBinder) binderFactory.getBinder(null, MessageChannel.class)) + .messageCollector().forChannel(errorChannel).poll(10, TimeUnit.SECONDS); Assert.isTrue(message instanceof ErrorMessage, "Message should be an instance of ErrorMessage"); Assert.isTrue(message.getPayload() instanceof MessagingException, "Message payload should be an instance" + "of MessagingException"); @@ -81,4 +82,3 @@ public class ErrorChannelTests { } } } - diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/InboundJsonToTupleConversionTest.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/InboundJsonToTupleConversionTest.java index cb3044c99..6d1bd0a4c 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/InboundJsonToTupleConversionTest.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/InboundJsonToTupleConversionTest.java @@ -61,10 +61,9 @@ public class InboundJsonToTupleConversionTest { Message received = ((TestSupportBinder) binderFactory.getBinder(null, MessageChannel.class)) .messageCollector().forChannel(testProcessor.output()).poll(1, TimeUnit.SECONDS); assertThat(received).isNotNull(); - assertThat(received.getPayload()).isEqualTo(TupleBuilder.tuple().of("name","foo")); + assertThat(received.getPayload()).isEqualTo(TupleBuilder.tuple().of("name", "foo")); } - @EnableBinding(Processor.class) @EnableAutoConfiguration @PropertySource("classpath:/org/springframework/cloud/stream/config/inboundjsontuple/inbound-json-tuple.properties") diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/MessageChannelConfigurerTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/MessageChannelConfigurerTests.java index ac3da7a0a..302f0bf83 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/MessageChannelConfigurerTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/MessageChannelConfigurerTests.java @@ -21,7 +21,6 @@ import java.util.concurrent.TimeUnit; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; - import org.junit.Test; import org.junit.runner.RunWith; @@ -54,7 +53,8 @@ import static org.junit.Assert.assertNull; * @author Gary Russell */ @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = {MessageChannelConfigurerTests.TestSink.class, MessageChannelConfigurerTests.TestSource.class}) +@SpringBootTest(classes = { MessageChannelConfigurerTests.TestSink.class, + MessageChannelConfigurerTests.TestSource.class }) public class MessageChannelConfigurerTests { @Autowired @@ -92,12 +92,13 @@ public class MessageChannelConfigurerTests { @Test public void testObjectMapperConfig() throws Exception { - CompositeMessageConverter converters = (CompositeMessageConverter) messageConverterFactory.getMessageConverterForType(MimeTypeUtils - .APPLICATION_JSON); + CompositeMessageConverter converters = (CompositeMessageConverter) messageConverterFactory + .getMessageConverterForType(MimeTypeUtils.APPLICATION_JSON); for (MessageConverter converter : converters.getConverters()) { DirectFieldAccessor converterAccessor = new DirectFieldAccessor(converter); ObjectMapper objectMapper = (ObjectMapper) converterAccessor.getPropertyValue("objectMapper"); - // assert that the ObjectMapper used by the converters is compliant with the Boot configuration + // assert that the ObjectMapper used by the converters is compliant with the + // Boot configuration assertThat(!objectMapper.getSerializationConfig().isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) .withFailMessage("SerializationFeature 'WRITE_DATES_AS_TIMESTAMPS' should be disabled"); // assert that the globally set bean is used by the converters diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerAnnotatedMethodArgumentsTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerAnnotatedMethodArgumentsTests.java index dee6606c1..cc4ec8cf9 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerAnnotatedMethodArgumentsTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerAnnotatedMethodArgumentsTests.java @@ -61,7 +61,8 @@ public class StreamListenerAnnotatedMethodArgumentsTests { sink.input().send(MessageBuilder.withPayload("{\"foo\":\"barbar" + id + "\"}") .setHeader("contentType", "application/json").setHeader("testHeader", "testValue").build()); assertThat(testPojoWithAnnotatedArguments.receivedArguments).hasSize(3); - assertThat(testPojoWithAnnotatedArguments.receivedArguments.get(0)).isInstanceOf(StreamListenerTestUtils.FooPojo.class); + assertThat(testPojoWithAnnotatedArguments.receivedArguments.get(0)) + .isInstanceOf(StreamListenerTestUtils.FooPojo.class); assertThat(testPojoWithAnnotatedArguments.receivedArguments.get(0)).hasFieldOrPropertyWithValue("foo", "barbar" + id); assertThat(testPojoWithAnnotatedArguments.receivedArguments.get(1)).isInstanceOf(Map.class); @@ -77,7 +78,7 @@ public class StreamListenerAnnotatedMethodArgumentsTests { public void testInputAnnotationAtMethodParameter() throws Exception { try { SpringApplication.run(TestPojoWithInvalidInputAnnotatedArgument.class, "--server.port=0"); - fail("Exception expected: "+ INVALID_DECLARATIVE_METHOD_PARAMETERS); + fail("Exception expected: " + INVALID_DECLARATIVE_METHOD_PARAMETERS); } catch (BeanCreationException e) { assertThat(e.getCause().getMessage()).contains(INVALID_DECLARATIVE_METHOD_PARAMETERS); diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerAnnotationBeanPostProcessorOverrideTest.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerAnnotationBeanPostProcessorOverrideTest.java index 016ab779a..fd09a1ca5 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerAnnotationBeanPostProcessorOverrideTest.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerAnnotationBeanPostProcessorOverrideTest.java @@ -73,11 +73,6 @@ public class StreamListenerAnnotationBeanPostProcessorOverrideTest { public static class TestPojoWithAnnotatedArguments { List receivedFoo = new ArrayList<>(); - - @StreamListener(value = Sink.INPUT, condition = "foo") - public void receive(@Payload StreamListenerTestUtils.FooPojo fooPojo) { - this.receivedFoo.add(fooPojo); - } /** * Overrides the default {@link StreamListenerAnnotationBeanPostProcessor}. @@ -86,12 +81,19 @@ public class StreamListenerAnnotationBeanPostProcessorOverrideTest { public static BeanPostProcessor streamListenerAnnotationBeanPostProcessor() { return new StreamListenerAnnotationBeanPostProcessor() { @Override - protected StreamListener postProcessAnnotation(StreamListener originalAnnotation, Method annotatedMethod) { - Map attributes = new HashMap<>(AnnotationUtils.getAnnotationAttributes(originalAnnotation)); + protected StreamListener postProcessAnnotation(StreamListener originalAnnotation, + Method annotatedMethod) { + Map attributes = new HashMap<>( + AnnotationUtils.getAnnotationAttributes(originalAnnotation)); attributes.put("condition", "headers['type']=='" + originalAnnotation.condition() + "'"); return AnnotationUtils.synthesizeAnnotation(attributes, StreamListener.class, annotatedMethod); } }; } + + @StreamListener(value = Sink.INPUT, condition = "foo") + public void receive(@Payload StreamListenerTestUtils.FooPojo fooPojo) { + this.receivedFoo.add(fooPojo); + } } } diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerAsMetaAnnotationTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerAsMetaAnnotationTests.java index 13c85c708..d19e7c684 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerAsMetaAnnotationTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerAsMetaAnnotationTests.java @@ -40,11 +40,40 @@ import org.springframework.messaging.handler.annotation.Payload; import static org.assertj.core.api.Assertions.assertThat; +@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) +@Retention(RetentionPolicy.RUNTIME) +@MessageMapping +@Documented +@StreamListener +@interface EventHandler { + /** + * The name of the binding target (e.g. channel) that the method subscribes to. + * @return the name of the binding target. + */ + @AliasFor(annotation = StreamListener.class, attribute = "target") + String value() default ""; + + /** + * The name of the binding target (e.g. channel) that the method subscribes to. + * @return the name of the binding target. + */ + @AliasFor(annotation = StreamListener.class, attribute = "target") + String target() default ""; + + /** + * A condition that must be met by all items that are dispatched to this method. + * @return a SpEL expression that must evaluate to a {@code boolean} value. + */ + @AliasFor(annotation = StreamListener.class, attribute = "condition") + String condition() default ""; + +} + /** * @author David Turanski */ public class StreamListenerAsMetaAnnotationTests { - + @Test public void testCustomAnnotation() { ConfigurableApplicationContext context = SpringApplication.run(TestPojoWithCustomAnnotatedArguments.class, @@ -62,7 +91,7 @@ public class StreamListenerAsMetaAnnotationTests { "barbar" + id); context.close(); } - + @Test public void testAnnotation() { ConfigurableApplicationContext context = SpringApplication.run(TestPojoWithAnnotatedArguments.class, @@ -80,7 +109,7 @@ public class StreamListenerAsMetaAnnotationTests { "barbar" + id); context.close(); } - + @EnableBinding(Sink.class) @EnableAutoConfiguration public static class TestPojoWithCustomAnnotatedArguments { @@ -94,7 +123,7 @@ public class StreamListenerAsMetaAnnotationTests { this.receivedFoo.add(fooPojo); } } - + @EnableBinding(Sink.class) @EnableAutoConfiguration public static class TestPojoWithAnnotatedArguments { @@ -109,32 +138,3 @@ public class StreamListenerAsMetaAnnotationTests { } } } - -@Target({ ElementType.METHOD, ElementType.ANNOTATION_TYPE }) -@Retention(RetentionPolicy.RUNTIME) -@MessageMapping -@Documented -@StreamListener -@interface EventHandler { - /** - * The name of the binding target (e.g. channel) that the method subscribes to. - * @return the name of the binding target. - */ - @AliasFor(annotation=StreamListener.class, attribute="target") - String value() default ""; - - /** - * The name of the binding target (e.g. channel) that the method subscribes to. - * @return the name of the binding target. - */ - @AliasFor(annotation=StreamListener.class, attribute="target") - String target() default ""; - - /** - * A condition that must be met by all items that are dispatched to this method. - * @return a SpEL expression that must evaluate to a {@code boolean} value. - */ - @AliasFor(annotation=StreamListener.class, attribute="condition") - String condition() default ""; - -} diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerContentTypeConversionTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerContentTypeConversionTests.java index baae43ce9..fc83b9fb0 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerContentTypeConversionTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerContentTypeConversionTests.java @@ -63,6 +63,7 @@ public class StreamListenerContentTypeConversionTests { public static class TestSinkWithContentTypeConversion { List receivedArguments = new ArrayList<>(); + CountDownLatch latch = new CountDownLatch(1); @StreamListener(Sink.INPUT) diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerDuplicateMappingTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerDuplicateMappingTests.java index d482c48fe..dafa2c693 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerDuplicateMappingTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerDuplicateMappingTests.java @@ -64,8 +64,8 @@ public class StreamListenerDuplicateMappingTests { context = SpringApplication.run(TestDuplicateMappingFromAbstractMethod.class, "--server.port=0"); } catch (BeanCreationException e) { - String errorMessage = e.getCause().getMessage().startsWith("Duplicate @StreamListener mapping") ? - "Duplicate mapping exception is not expected" : "Test failed with exception"; + String errorMessage = e.getCause().getMessage().startsWith("Duplicate @StreamListener mapping") + ? "Duplicate mapping exception is not expected" : "Test failed with exception"; fail(errorMessage + ": " + e.getMessage()); } finally { @@ -75,6 +75,14 @@ public class StreamListenerDuplicateMappingTests { } } + public interface GenericSink { + void testMethod(T msg); + } + + public interface Base { + + } + @EnableBinding(Processor.class) @EnableAutoConfiguration public static class TestMultipleMappingsWithReturnValue { @@ -102,14 +110,6 @@ public class StreamListenerDuplicateMappingTests { } } - public interface GenericSink { - void testMethod(T msg); - } - - public interface Base { - - } - public class TestBase implements Base { } diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerHandlerMethodTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerHandlerMethodTests.java index 61f09a9ab..0e1f8f9ab 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerHandlerMethodTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerHandlerMethodTests.java @@ -79,7 +79,8 @@ public class StreamListenerHandlerMethodTests { @Test public void testMethodWithObjectAsMethodArgument() throws Exception { - ConfigurableApplicationContext context = SpringApplication.run(TestMethodWithObjectAsMethodArgument.class, "--server.port=0"); + ConfigurableApplicationContext context = SpringApplication.run(TestMethodWithObjectAsMethodArgument.class, + "--server.port=0"); Processor processor = context.getBean(Processor.class); String id = UUID.randomUUID().toString(); final CountDownLatch latch = new CountDownLatch(1); @@ -94,11 +95,13 @@ public class StreamListenerHandlerMethodTests { @Test public void testStreamListenerMethodWithTargetBeanFromOutside() throws Exception { - ConfigurableApplicationContext context = SpringApplication.run(TestStreamListenerMethodWithTargetBeanFromOutside.class, "--server.port=0"); + ConfigurableApplicationContext context = SpringApplication + .run(TestStreamListenerMethodWithTargetBeanFromOutside.class, "--server.port=0"); Sink sink = context.getBean(Sink.class); final String testMessageToSend = "testing"; sink.input().send(MessageBuilder.withPayload(testMessageToSend).build()); - DirectChannel directChannel = (DirectChannel) context.getBean(testMessageToSend.toUpperCase(), MessageChannel.class); + DirectChannel directChannel = (DirectChannel) context.getBean(testMessageToSend.toUpperCase(), + MessageChannel.class); MessageCollector messageCollector = context.getBean(MessageCollector.class); Message result = messageCollector.forChannel(directChannel).poll(1000, TimeUnit.MILLISECONDS); sink.input().send(MessageBuilder.withPayload(testMessageToSend).build()); @@ -159,7 +162,8 @@ public class StreamListenerHandlerMethodTests { } catch (BeanCreationException e) { assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); - assertThat(e.getCause()).hasMessageContaining(StreamListenerErrorMessages.INVALID_DECLARATIVE_METHOD_PARAMETERS); + assertThat(e.getCause()) + .hasMessageContaining(StreamListenerErrorMessages.INVALID_DECLARATIVE_METHOD_PARAMETERS); } } @@ -232,9 +236,11 @@ public class StreamListenerHandlerMethodTests { @Test public void testMethodWithMultipleInputParameters() throws Exception { - ConfigurableApplicationContext context = SpringApplication.run(TestMethodWithMultipleInputParameters.class, "--server.port=0"); + ConfigurableApplicationContext context = SpringApplication.run(TestMethodWithMultipleInputParameters.class, + "--server.port=0"); Processor processor = context.getBean(Processor.class); - StreamListenerTestUtils.FooInboundChannel1 inboundChannel2 = context.getBean(StreamListenerTestUtils.FooInboundChannel1.class); + StreamListenerTestUtils.FooInboundChannel1 inboundChannel2 = context + .getBean(StreamListenerTestUtils.FooInboundChannel1.class); String id = UUID.randomUUID().toString(); final CountDownLatch latch = new CountDownLatch(2); ((SubscribableChannel) processor.output()).subscribe(new MessageHandler() { @@ -254,10 +260,12 @@ public class StreamListenerHandlerMethodTests { @Test public void testMethodWithMultipleOutputParameters() throws Exception { - ConfigurableApplicationContext context = SpringApplication.run(TestMethodWithMultipleOutputParameters.class, "--server.port=0"); + ConfigurableApplicationContext context = SpringApplication.run(TestMethodWithMultipleOutputParameters.class, + "--server.port=0"); Processor processor = context.getBean(Processor.class); String id = UUID.randomUUID().toString(); - StreamListenerTestUtils.FooOutboundChannel1 source2 = context.getBean(StreamListenerTestUtils.FooOutboundChannel1.class); + StreamListenerTestUtils.FooOutboundChannel1 source2 = context + .getBean(StreamListenerTestUtils.FooOutboundChannel1.class); final CountDownLatch latch = new CountDownLatch(2); ((SubscribableChannel) processor.output()).subscribe(new MessageHandler() { @Override @@ -281,28 +289,31 @@ public class StreamListenerHandlerMethodTests { context.close(); } - @EnableBinding({Processor.class, StreamListenerTestUtils.FooOutboundChannel1.class}) + @EnableBinding({ Processor.class, StreamListenerTestUtils.FooOutboundChannel1.class }) @EnableAutoConfiguration public static class TestMethodWithMultipleOutputParameters { @StreamListener - public void receive(@Input(Processor.INPUT) SubscribableChannel input, @Output(Processor.OUTPUT) final MessageChannel output1, + public void receive(@Input(Processor.INPUT) SubscribableChannel input, + @Output(Processor.OUTPUT) final MessageChannel output1, @Output(StreamListenerTestUtils.FooOutboundChannel1.OUTPUT) final MessageChannel output2) { input.subscribe(new MessageHandler() { @Override public void handleMessage(Message message) throws MessagingException { if (message.getHeaders().get("output").equals("output1")) { - output1.send(org.springframework.messaging.support.MessageBuilder.withPayload(message.getPayload().toString().toUpperCase()).build()); + output1.send(org.springframework.messaging.support.MessageBuilder + .withPayload(message.getPayload().toString().toUpperCase()).build()); } else if (message.getHeaders().get("output").equals("output2")) { - output2.send(org.springframework.messaging.support.MessageBuilder.withPayload(message.getPayload().toString().toLowerCase()).build()); + output2.send(org.springframework.messaging.support.MessageBuilder + .withPayload(message.getPayload().toString().toLowerCase()).build()); } } }); } } - @EnableBinding({Sink.class}) + @EnableBinding({ Sink.class }) @EnableAutoConfiguration public static class TestMethodWithoutInput { @@ -311,7 +322,7 @@ public class StreamListenerHandlerMethodTests { } } - @EnableBinding({Processor.class}) + @EnableBinding({ Processor.class }) @EnableAutoConfiguration public static class TestMethodWithObjectAsMethodArgument { @@ -340,7 +351,7 @@ public class StreamListenerHandlerMethodTests { } } - @EnableBinding({Sink.class}) + @EnableBinding({ Sink.class }) @EnableAutoConfiguration public static class TestInvalidInputOnMethod { @@ -350,7 +361,7 @@ public class StreamListenerHandlerMethodTests { } } - @EnableBinding({Sink.class}) + @EnableBinding({ Sink.class }) @EnableAutoConfiguration public static class TestAmbiguousMethodArguments1 { @@ -359,27 +370,29 @@ public class StreamListenerHandlerMethodTests { } } - @EnableBinding({Sink.class}) + @EnableBinding({ Sink.class }) @EnableAutoConfiguration public static class TestAmbiguousMethodArguments2 { @StreamListener(Processor.INPUT) - public void receive(@Payload StreamListenerTestUtils.FooPojo fooPojo, @Payload StreamListenerTestUtils.BarPojo barPojo) { + public void receive(@Payload StreamListenerTestUtils.FooPojo fooPojo, + @Payload StreamListenerTestUtils.BarPojo barPojo) { } } - @EnableBinding({Processor.class, StreamListenerTestUtils.FooOutboundChannel1.class}) + @EnableBinding({ Processor.class, StreamListenerTestUtils.FooOutboundChannel1.class }) @EnableAutoConfiguration public static class TestReturnTypeWithMultipleOutput { @StreamListener - public String receive(@Input(Processor.INPUT) SubscribableChannel input1, @Output(Processor.OUTPUT) MessageChannel output1, + public String receive(@Input(Processor.INPUT) SubscribableChannel input1, + @Output(Processor.OUTPUT) MessageChannel output1, @Output(StreamListenerTestUtils.FooOutboundChannel1.OUTPUT) MessageChannel output2) { return "foo"; } } - @EnableBinding({Processor.class, StreamListenerTestUtils.FooOutboundChannel1.class}) + @EnableBinding({ Processor.class, StreamListenerTestUtils.FooOutboundChannel1.class }) @EnableAutoConfiguration public static class TestInvalidReturnTypeWithNoOutput { @@ -389,7 +402,7 @@ public class StreamListenerHandlerMethodTests { } } - @EnableBinding({Processor.class}) + @EnableBinding({ Processor.class }) @EnableAutoConfiguration public static class TestInvalidInputAnnotationWithNoValue { @@ -398,7 +411,7 @@ public class StreamListenerHandlerMethodTests { } } - @EnableBinding({Processor.class}) + @EnableBinding({ Processor.class }) @EnableAutoConfiguration public static class TestInvalidOutputAnnotationWithNoValue { @@ -407,7 +420,7 @@ public class StreamListenerHandlerMethodTests { } } - @EnableBinding({Sink.class}) + @EnableBinding({ Sink.class }) @EnableAutoConfiguration public static class TestMethodInvalidInboundName { @@ -416,16 +429,17 @@ public class StreamListenerHandlerMethodTests { } } - @EnableBinding({Processor.class}) + @EnableBinding({ Processor.class }) @EnableAutoConfiguration public static class TestMethodInvalidOutboundName { @StreamListener - public void receive(@Input(Processor.INPUT) SubscribableChannel input, @Output("invalid") MessageChannel output) { + public void receive(@Input(Processor.INPUT) SubscribableChannel input, + @Output("invalid") MessageChannel output) { } } - @EnableBinding({Sink.class}) + @EnableBinding({ Sink.class }) @EnableAutoConfiguration public static class TestMethodWithInputAsMethodAndParameter { @@ -434,39 +448,44 @@ public class StreamListenerHandlerMethodTests { } } - @EnableBinding({Processor.class, StreamListenerTestUtils.FooOutboundChannel1.class}) + @EnableBinding({ Processor.class, StreamListenerTestUtils.FooOutboundChannel1.class }) @EnableAutoConfiguration public static class TestMethodWithOutputAsMethodAndParameter { @StreamListener @Output(StreamListenerTestUtils.FooOutboundChannel1.OUTPUT) - public void receive(@Input(Processor.INPUT) SubscribableChannel input, @Output(Processor.OUTPUT) final MessageChannel output1) { + public void receive(@Input(Processor.INPUT) SubscribableChannel input, + @Output(Processor.OUTPUT) final MessageChannel output1) { input.subscribe(new MessageHandler() { @Override public void handleMessage(Message message) throws MessagingException { - output1.send(org.springframework.messaging.support.MessageBuilder.withPayload(message.getPayload().toString().toUpperCase()).build()); + output1.send(org.springframework.messaging.support.MessageBuilder + .withPayload(message.getPayload().toString().toUpperCase()).build()); } }); } } - @EnableBinding({Processor.class, StreamListenerTestUtils.FooInboundChannel1.class}) + @EnableBinding({ Processor.class, StreamListenerTestUtils.FooInboundChannel1.class }) @EnableAutoConfiguration public static class TestMethodWithMultipleInputParameters { @StreamListener - public void receive(@Input(Processor.INPUT) SubscribableChannel input1, @Input(StreamListenerTestUtils.FooInboundChannel1.INPUT) SubscribableChannel input2, + public void receive(@Input(Processor.INPUT) SubscribableChannel input1, + @Input(StreamListenerTestUtils.FooInboundChannel1.INPUT) SubscribableChannel input2, final @Output(Processor.OUTPUT) MessageChannel output) { input1.subscribe(new MessageHandler() { @Override public void handleMessage(Message message) throws MessagingException { - output.send(org.springframework.messaging.support.MessageBuilder.withPayload(message.getPayload().toString().toUpperCase()).build()); + output.send(org.springframework.messaging.support.MessageBuilder + .withPayload(message.getPayload().toString().toUpperCase()).build()); } }); input2.subscribe(new MessageHandler() { @Override public void handleMessage(Message message) throws MessagingException { - output.send(org.springframework.messaging.support.MessageBuilder.withPayload(message.getPayload().toString().toUpperCase()).build()); + output.send(org.springframework.messaging.support.MessageBuilder + .withPayload(message.getPayload().toString().toUpperCase()).build()); } }); } diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMessageArgumentTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMessageArgumentTests.java index 02644a768..cdf2d0e85 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMessageArgumentTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMessageArgumentTests.java @@ -56,7 +56,7 @@ public class StreamListenerMessageArgumentTests { @Parameterized.Parameters public static Collection InputConfigs() { - return Arrays.asList(new Class[] {TestPojoWithMessageArgument1.class, TestPojoWithMessageArgument2.class}); + return Arrays.asList(new Class[] { TestPojoWithMessageArgument1.class, TestPojoWithMessageArgument2.class }); } @Test diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMethodReturnWithConversionTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMethodReturnWithConversionTests.java index f16090988..b3e8ada39 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMethodReturnWithConversionTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMethodReturnWithConversionTests.java @@ -52,11 +52,12 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Ilayaperumal Gopinathan */ @RunWith(StreamListenerMethodReturnWithConversionTests.class) -@Suite.SuiteClasses({StreamListenerMethodReturnWithConversionTests.TestReturnConversion.class, - StreamListenerMethodReturnWithConversionTests.TestReturnNoConversion.class}) +@Suite.SuiteClasses({ StreamListenerMethodReturnWithConversionTests.TestReturnConversion.class, + StreamListenerMethodReturnWithConversionTests.TestReturnNoConversion.class }) public class StreamListenerMethodReturnWithConversionTests extends Suite { - public StreamListenerMethodReturnWithConversionTests(Class klass, RunnerBuilder builder) throws InitializationError { + public StreamListenerMethodReturnWithConversionTests(Class klass, RunnerBuilder builder) + throws InitializationError { super(klass, builder); } @@ -71,7 +72,7 @@ public class StreamListenerMethodReturnWithConversionTests extends Suite { @Parameterized.Parameters public static Collection InputConfigs() { - return Arrays.asList(new Class[] {TestPojoWithMimeType1.class, TestPojoWithMimeType2.class}); + return Arrays.asList(new Class[] { TestPojoWithMimeType1.class, TestPojoWithMimeType2.class }); } @Test @@ -87,10 +88,12 @@ public class StreamListenerMethodReturnWithConversionTests extends Suite { TestPojoWithMimeType testPojoWithMimeType = context.getBean(TestPojoWithMimeType.class); assertThat(testPojoWithMimeType.receivedPojos).hasSize(1); assertThat(testPojoWithMimeType.receivedPojos.get(0)).hasFieldOrPropertyWithValue("foo", "barbar" + id); - Message message = (Message) collector.forChannel(processor.output()).poll(1, TimeUnit.SECONDS); + Message message = (Message) collector.forChannel(processor.output()).poll(1, + TimeUnit.SECONDS); assertThat(message).isNotNull(); assertThat(message.getPayload()).isEqualTo("{\"bar\":\"barbar" + id + "\"}"); - assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class).includes(MimeTypeUtils.APPLICATION_JSON)); + assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class) + .includes(MimeTypeUtils.APPLICATION_JSON)); context.close(); } } @@ -106,7 +109,7 @@ public class StreamListenerMethodReturnWithConversionTests extends Suite { @Parameterized.Parameters public static Collection InputConfigs() { - return Arrays.asList(new Class[] {TestPojoWithMimeType1.class, TestPojoWithMimeType2.class}); + return Arrays.asList(new Class[] { TestPojoWithMimeType1.class, TestPojoWithMimeType2.class }); } @Test @@ -121,8 +124,9 @@ public class StreamListenerMethodReturnWithConversionTests extends Suite { TestPojoWithMimeType testPojoWithMimeType = context.getBean(TestPojoWithMimeType.class); assertThat(testPojoWithMimeType.receivedPojos).hasSize(1); assertThat(testPojoWithMimeType.receivedPojos.get(0)).hasFieldOrPropertyWithValue("foo", "barbar" + id); - Message message = (Message) collector.forChannel(processor.output()).poll(1, - TimeUnit.SECONDS); + Message message = (Message) collector + .forChannel(processor.output()).poll(1, + TimeUnit.SECONDS); assertThat(message).isNotNull(); assertThat(message.getPayload().getBar()).isEqualTo("barbar" + id); assertThat(message.getHeaders().get(MessageHeaders.CONTENT_TYPE, MimeType.class) == null); diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMethodWithReturnMessageTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMethodWithReturnMessageTests.java index e865a0d23..9d23dc99d 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMethodWithReturnMessageTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMethodWithReturnMessageTests.java @@ -56,7 +56,7 @@ public class StreamListenerMethodWithReturnMessageTests { @Parameterized.Parameters public static Collection InputConfigs() { - return Arrays.asList(new Class[]{TestPojoWithMessageReturn1.class, TestPojoWithMessageReturn2.class}); + return Arrays.asList(new Class[] { TestPojoWithMessageReturn1.class, TestPojoWithMessageReturn2.class }); } @Test diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMethodWithReturnValueTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMethodWithReturnValueTests.java index 38f688475..af819fc06 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMethodWithReturnValueTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerMethodWithReturnValueTests.java @@ -56,7 +56,7 @@ public class StreamListenerMethodWithReturnValueTests { @Parameterized.Parameters public static Collection InputConfigs() { - return Arrays.asList(new Class[]{TestStringProcessor1.class, TestStringProcessor2.class}); + return Arrays.asList(new Class[] { TestStringProcessor1.class, TestStringProcessor2.class }); } @Test diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerTestUtils.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerTestUtils.java index 45070b7ed..243d39921 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerTestUtils.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerTestUtils.java @@ -26,6 +26,24 @@ import org.springframework.messaging.SubscribableChannel; */ public class StreamListenerTestUtils { + public interface FooInboundChannel1 { + + String INPUT = "foo1-input"; + + @Input(FooInboundChannel1.INPUT) + SubscribableChannel input(); + + } + + public interface FooOutboundChannel1 { + + String OUTPUT = "foo1-output"; + + @Output(FooOutboundChannel1.OUTPUT) + MessageChannel output(); + + } + public static class FooPojo { private String foo; @@ -51,22 +69,4 @@ public class StreamListenerTestUtils { this.bar = bar; } } - - public interface FooInboundChannel1 { - - String INPUT = "foo1-input"; - - @Input(FooInboundChannel1.INPUT) - SubscribableChannel input(); - - } - - public interface FooOutboundChannel1 { - - String OUTPUT = "foo1-output"; - - @Output(FooOutboundChannel1.OUTPUT) - MessageChannel output(); - - } } diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerWithAnnotatedInputOutputArgsTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerWithAnnotatedInputOutputArgsTests.java index 1eb0e2fea..69b9e9621 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerWithAnnotatedInputOutputArgsTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerWithAnnotatedInputOutputArgsTests.java @@ -73,13 +73,15 @@ public class StreamListenerWithAnnotatedInputOutputArgsTests { } catch (BeanCreationException e) { assertThat(e.getCause()).isInstanceOf(IllegalArgumentException.class); - assertThat(e.getCause()).hasMessageContaining(StreamListenerErrorMessages.INVALID_DECLARATIVE_METHOD_PARAMETERS); + assertThat(e.getCause()) + .hasMessageContaining(StreamListenerErrorMessages.INVALID_DECLARATIVE_METHOD_PARAMETERS); } } @Test public void testInputOutputArgsWithParameterOrderChanged() throws Exception { - ConfigurableApplicationContext context = SpringApplication.run(TestInputOutputArgsWithParameterOrderChanged.class, "--server.port=0"); + ConfigurableApplicationContext context = SpringApplication + .run(TestInputOutputArgsWithParameterOrderChanged.class, "--server.port=0"); sendMessageAndValidate(context); } @@ -94,13 +96,13 @@ public class StreamListenerWithAnnotatedInputOutputArgsTests { context.close(); } - @EnableBinding(Processor.class) @EnableAutoConfiguration public static class TestInputOutputArgs { @StreamListener - public void receive(@Input(Processor.INPUT) SubscribableChannel input, @Output(Processor.OUTPUT) final MessageChannel output) { + public void receive(@Input(Processor.INPUT) SubscribableChannel input, + @Output(Processor.OUTPUT) final MessageChannel output) { input.subscribe(new MessageHandler() { @Override public void handleMessage(Message message) throws MessagingException { @@ -115,7 +117,8 @@ public class StreamListenerWithAnnotatedInputOutputArgsTests { public static class TestInputOutputArgsWithMoreParameters { @StreamListener - public void receive(@Input(Processor.INPUT) SubscribableChannel input, @Output(Processor.OUTPUT) final MessageChannel output, + public void receive(@Input(Processor.INPUT) SubscribableChannel input, + @Output(Processor.OUTPUT) final MessageChannel output, String someArg) { input.subscribe(new MessageHandler() { @Override @@ -131,7 +134,8 @@ public class StreamListenerWithAnnotatedInputOutputArgsTests { public static class TestInputOutputArgsWithInvalidBindableTarget { @StreamListener - public void receive(@Input("invalid") SubscribableChannel input, @Output(Processor.OUTPUT) final MessageChannel output) { + public void receive(@Input("invalid") SubscribableChannel input, + @Output(Processor.OUTPUT) final MessageChannel output) { input.subscribe(new MessageHandler() { @Override public void handleMessage(Message message) throws MessagingException { @@ -146,7 +150,8 @@ public class StreamListenerWithAnnotatedInputOutputArgsTests { public static class TestInputOutputArgsWithParameterOrderChanged { @StreamListener - public void receive(@Output(Processor.OUTPUT) final MessageChannel output, @Input("input") SubscribableChannel input) { + public void receive(@Output(Processor.OUTPUT) final MessageChannel output, + @Input("input") SubscribableChannel input) { input.subscribe(new MessageHandler() { @Override public void handleMessage(Message message) throws MessagingException { diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerWithConditionsTest.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerWithConditionsTest.java index 50706f8c1..73cc0a261 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerWithConditionsTest.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/StreamListenerWithConditionsTest.java @@ -75,13 +75,16 @@ public class StreamListenerWithConditionsTest { @SuppressWarnings("unchecked") public void testConditionalFailsWithReturnValue() throws Exception { try { - ConfigurableApplicationContext context = SpringApplication.run(TestConditionalOnMethodWithReturnValueFails.class, + ConfigurableApplicationContext context = SpringApplication.run( + TestConditionalOnMethodWithReturnValueFails.class, "--server.port=0"); context.close(); fail("Context creation failure expected"); - } catch (BeanCreationException e) { + } + catch (BeanCreationException e) { assertThat(e).hasRootCauseInstanceOf(IllegalArgumentException.class); - assertThat(e.getCause()).hasMessageContaining(StreamListenerErrorMessages.CONDITION_ON_METHOD_RETURNING_VALUE); + assertThat(e.getCause()) + .hasMessageContaining(StreamListenerErrorMessages.CONDITION_ON_METHOD_RETURNING_VALUE); } } @@ -89,11 +92,13 @@ public class StreamListenerWithConditionsTest { @SuppressWarnings("unchecked") public void testConditionalFailsWithDeclarativeMethod() throws Exception { try { - ConfigurableApplicationContext context = SpringApplication.run(TestConditionalOnDeclarativeMethodFails.class, + ConfigurableApplicationContext context = SpringApplication.run( + TestConditionalOnDeclarativeMethodFails.class, "--server.port=0"); context.close(); fail("Context creation failure expected"); - } catch (BeanCreationException e) { + } + catch (BeanCreationException e) { assertThat(e).hasRootCauseInstanceOf(IllegalArgumentException.class); assertThat(e.getCause()).hasMessageContaining(StreamListenerErrorMessages.CONDITION_ON_DECLARATIVE_METHOD); } diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/TextPlainConversionTest.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/TextPlainConversionTest.java index 84f22018f..1c4f71d9f 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/TextPlainConversionTest.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/TextPlainConversionTest.java @@ -43,8 +43,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @since 1.2 */ @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = TextPlainConversionTest.FooProcessor.class, - webEnvironment = SpringBootTest.WebEnvironment.NONE) +@SpringBootTest(classes = TextPlainConversionTest.FooProcessor.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) public class TextPlainConversionTest { @Autowired @@ -83,7 +82,6 @@ public class TextPlainConversionTest { assertThat(received.getPayload()).isEqualTo("Foo{name='Foo{name='Bar'}'}"); } - @EnableBinding(Processor.class) @EnableAutoConfiguration @PropertySource("classpath:/org/springframework/cloud/stream/config/textplain/text-plain.properties") diff --git a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/aggregate/AggregateApplicationTests.java b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/aggregate/AggregateApplicationTests.java index f36d91679..79ba8ef00 100644 --- a/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/aggregate/AggregateApplicationTests.java +++ b/spring-cloud-stream-integration-tests/src/test/java/org/springframework/cloud/stream/config/aggregate/AggregateApplicationTests.java @@ -44,10 +44,13 @@ public class AggregateApplicationTests { @Test @SuppressWarnings("unchecked") public void testAggregateApplication() throws Exception { - ConfigurableApplicationContext context = new AggregateApplicationBuilder(TestSupportBinderAutoConfiguration.class).from(TestSource.class).to(TestProcessor.class).run(); - TestSupportBinder testSupportBinder = (TestSupportBinder) context.getBean(BinderFactory.class).getBinder(null, MessageChannel.class); + ConfigurableApplicationContext context = new AggregateApplicationBuilder( + TestSupportBinderAutoConfiguration.class).from(TestSource.class).to(TestProcessor.class).run(); + TestSupportBinder testSupportBinder = (TestSupportBinder) context.getBean(BinderFactory.class).getBinder(null, + MessageChannel.class); MessageChannel processorOutput = testSupportBinder.getChannelForName("output"); - Message received = (Message) (testSupportBinder.messageCollector().forChannel(processorOutput).poll(5, TimeUnit.SECONDS)); + Message received = (Message) (testSupportBinder.messageCollector().forChannel(processorOutput) + .poll(5, TimeUnit.SECONDS)); Assert.assertThat(received, notNullValue()); Assert.assertTrue(received.getPayload().endsWith("processed")); } diff --git a/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/ApplicationMetrics.java b/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/ApplicationMetrics.java index 43936669a..ee9d045fe 100644 --- a/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/ApplicationMetrics.java +++ b/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/ApplicationMetrics.java @@ -35,7 +35,7 @@ public class ApplicationMetrics { private final Date createdTime; private String name; - + private Collection> metrics; private Map properties; diff --git a/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/ApplicationMetricsProperties.java b/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/ApplicationMetricsProperties.java index a95ab64d3..875f0bcc4 100644 --- a/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/ApplicationMetricsProperties.java +++ b/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/ApplicationMetricsProperties.java @@ -44,6 +44,8 @@ import org.springframework.util.PatternMatchUtils; public class ApplicationMetricsProperties implements ApplicationListener { + private final MetricExportProperties metricExportProperties; + private String prefix = ""; @Value("${spring.application.name:${vcap.application.name:${spring.config.name:application}}}") @@ -53,17 +55,23 @@ public class ApplicationMetricsProperties private String[] properties; - private final MetricExportProperties metricExportProperties; - - public TriggerProperties getTrigger() { - return metricExportProperties.findTrigger(BinderMetricsAutoConfiguration.APPLICATION_METRICS_EXPORTER_TRIGGER_NAME); - } + /** + * List of properties that are going to be appended to each message. This gets + * populate by onApplicationEvent, once the context refreshes to avoid overhead of + * doing per message basis. + */ + private Map exportProperties = new HashMap<>(); public ApplicationMetricsProperties(MetricExportProperties metricExportProperties) { Assert.notNull(metricExportProperties, "'metricsExportProperties' cannot be null"); this.metricExportProperties = metricExportProperties; } + public TriggerProperties getTrigger() { + return metricExportProperties + .findTrigger(BinderMetricsAutoConfiguration.APPLICATION_METRICS_EXPORTER_TRIGGER_NAME); + } + public String getPrefix() { return prefix; } @@ -91,13 +99,6 @@ public class ApplicationMetricsProperties this.properties = properties; } - /** - * List of properties that are going to be appended to each message. This gets - * populate by onApplicationEvent, once the context refreshes to avoid overhead of - * doing per message basis. - */ - private Map exportProperties = new HashMap<>(); - public Map getExportProperties() { return exportProperties; } @@ -137,7 +138,7 @@ public class ApplicationMetricsProperties relaxedLoop: for (String relaxedPropertyName : relaxedNames) { if (isMatch(relaxedPropertyName, this.properties, null)) { Object value = source.getProperty(propertyName); - String stringValue = ObjectUtils.nullSafeToString(value); + String stringValue = ObjectUtils.nullSafeToString(value); Object exportedValue = null; if (value != null) { exportedValue = stringValue.startsWith("#{") diff --git a/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/config/BinderMetricsAutoConfiguration.java b/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/config/BinderMetricsAutoConfiguration.java index 4124bf254..bb2b47792 100644 --- a/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/config/BinderMetricsAutoConfiguration.java +++ b/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/config/BinderMetricsAutoConfiguration.java @@ -40,8 +40,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; /** - * Autoconfiguration registering an {@link Exporter} that publishes application metrics over - * the {@link Emitter#applicationMetrics()} channel. + * Autoconfiguration registering an {@link Exporter} that publishes application metrics + * over the {@link Emitter#applicationMetrics()} channel. * * @author Vinicius Carvalho * @author Marius Bogoevici @@ -56,19 +56,15 @@ import org.springframework.context.annotation.Lazy; + ".destination") public class BinderMetricsAutoConfiguration { - public static Log log = LogFactory.getLog(BinderMetricsAutoConfiguration.class); - public static final String APPLICATION_METRICS_EXPORTER_TRIGGER_NAME = "application"; - @Bean - public MetricJsonSerializer metricJsonSerializer() { - return new MetricJsonSerializer(); - } + public static Log log = LogFactory.getLog(BinderMetricsAutoConfiguration.class); /** - * Postprocessor for installing the {@link ApplicationMetricsExporter} as an - * exporter under the name {@code application}. - * @param endpoint the metrics endpoint (lazy reference to prevent early initialization) + * Postprocessor for installing the {@link ApplicationMetricsExporter} as an exporter + * under the name {@code application}. + * @param endpoint the metrics endpoint (lazy reference to prevent early + * initialization) * @param emitter the emitter bound interface * @param properties application metrics properties * @return @@ -101,4 +97,9 @@ public class BinderMetricsAutoConfiguration { }; } + @Bean + public MetricJsonSerializer metricJsonSerializer() { + return new MetricJsonSerializer(); + } + } diff --git a/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/config/MetricJsonSerializer.java b/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/config/MetricJsonSerializer.java index 18c5fdb5b..00e80584d 100644 --- a/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/config/MetricJsonSerializer.java +++ b/spring-cloud-stream-metrics/src/main/java/org/springframework/cloud/stream/metrics/config/MetricJsonSerializer.java @@ -46,6 +46,12 @@ public class MetricJsonSerializer { private static final BlockingQueue formatters = new LinkedBlockingQueue(); + private static DateFormat defaultDateFormat() { + DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); + df.setTimeZone(TimeZone.getTimeZone("GMT")); + return df; + } + public static class Serializer extends JsonSerializer> { @Override @@ -95,10 +101,4 @@ public class MetricJsonSerializer { } } - - private static DateFormat defaultDateFormat() { - DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX"); - df.setTimeZone(TimeZone.getTimeZone("GMT")); - return df; - } } diff --git a/spring-cloud-stream-metrics/src/test/java/org/springframework/cloud/stream/metrics/ApplicationMetricsExporterTests.java b/spring-cloud-stream-metrics/src/test/java/org/springframework/cloud/stream/metrics/ApplicationMetricsExporterTests.java index ea759e786..bd11db3dd 100644 --- a/spring-cloud-stream-metrics/src/test/java/org/springframework/cloud/stream/metrics/ApplicationMetricsExporterTests.java +++ b/spring-cloud-stream-metrics/src/test/java/org/springframework/cloud/stream/metrics/ApplicationMetricsExporterTests.java @@ -101,7 +101,8 @@ public class ApplicationMetricsExporterTests { .poll(10, TimeUnit.SECONDS); Assert.assertNotNull(message); ObjectMapper mapper = applicationContext.getBean(ObjectMapper.class); - ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), ApplicationMetrics.class); + ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), + ApplicationMetrics.class); Assert.assertTrue(contains("integration.channel.errorChannel.errorRate.mean", applicationMetrics.getMetrics())); Assert.assertTrue(contains("mem", applicationMetrics.getMetrics())); @@ -171,7 +172,8 @@ public class ApplicationMetricsExporterTests { .poll(10, TimeUnit.SECONDS); Assert.assertNotNull(message); ObjectMapper mapper = applicationContext.getBean(ObjectMapper.class); - ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), ApplicationMetrics.class); + ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), + ApplicationMetrics.class); Assert.assertFalse(contains("integration.channel.errorChannel.errorRate.mean", applicationMetrics.getMetrics())); Assert.assertTrue(contains("mem", applicationMetrics.getMetrics())); @@ -193,7 +195,8 @@ public class ApplicationMetricsExporterTests { .poll(10, TimeUnit.SECONDS); Assert.assertNotNull(message); ObjectMapper mapper = applicationContext.getBean(ObjectMapper.class); - ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), ApplicationMetrics.class); + ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), + ApplicationMetrics.class); Assert.assertFalse(contains("mem", applicationMetrics.getMetrics())); Assert.assertTrue(contains("integration.channel.errorChannel.errorRate.mean", applicationMetrics.getMetrics())); @@ -225,7 +228,8 @@ public class ApplicationMetricsExporterTests { .poll(10, TimeUnit.SECONDS); Assert.assertNotNull(message); ObjectMapper mapper = applicationContext.getBean(ObjectMapper.class); - ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), ApplicationMetrics.class); + ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), + ApplicationMetrics.class); Assert.assertTrue(contains("integration.channel.errorChannel.errorRate.mean", applicationMetrics.getMetrics())); Assertions.assertThat(applicationMetrics.getProperties().get("spring.cloud.application.guid")) @@ -260,13 +264,15 @@ public class ApplicationMetricsExporterTests { .poll(10, TimeUnit.SECONDS); Assert.assertNotNull(message); ObjectMapper mapper = applicationContext.getBean(ObjectMapper.class); - ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), ApplicationMetrics.class); + ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), + ApplicationMetrics.class); Assert.assertTrue(contains("integration.channel.errorChannel.errorRate.mean", applicationMetrics.getMetrics())); Assertions.assertThat(applicationMetrics.getProperties().get("spring.cloud.application.guid.test.metrics")) .isEqualTo("highPriority"); applicationContext.close(); - } finally { + } + finally { System.clearProperty("spring.cloud.application.guid.test.metrics"); } } @@ -285,7 +291,8 @@ public class ApplicationMetricsExporterTests { .poll(10, TimeUnit.SECONDS); Assert.assertNotNull(message); ObjectMapper mapper = applicationContext.getBean(ObjectMapper.class); - ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), ApplicationMetrics.class); + ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), + ApplicationMetrics.class); Assert.assertTrue(contains("integration.channel.errorChannel.errorRate.mean", applicationMetrics.getMetrics())); Assert.assertTrue(contains("mem", applicationMetrics.getMetrics())); diff --git a/spring-cloud-stream-metrics/src/test/java/org/springframework/cloud/stream/metrics/RelaxedPropertiesUtilsTests.java b/spring-cloud-stream-metrics/src/test/java/org/springframework/cloud/stream/metrics/RelaxedPropertiesUtilsTests.java index ea6bf52e0..306666ef2 100644 --- a/spring-cloud-stream-metrics/src/test/java/org/springframework/cloud/stream/metrics/RelaxedPropertiesUtilsTests.java +++ b/spring-cloud-stream-metrics/src/test/java/org/springframework/cloud/stream/metrics/RelaxedPropertiesUtilsTests.java @@ -33,8 +33,10 @@ public class RelaxedPropertiesUtilsTests { RelaxedNames springEnv = new RelaxedNames("SPRING_APPLICATION_NAME"); RelaxedNames springDot = new RelaxedNames("spring.application.name"); RelaxedNames springCamel = new RelaxedNames("springApplicationName"); - RelaxedNames contentType = new RelaxedNames("spring.cloud.stream.bindings.applicationMetricsChannel.contentType"); - RelaxedNames contentTypeEnv = new RelaxedNames("SPRING_CLOUD_STREAM_BINDINGS_APPLICATION-METRICS-CHANNEL_CONTENT-TYPE"); + RelaxedNames contentType = new RelaxedNames( + "spring.cloud.stream.bindings.applicationMetricsChannel.contentType"); + RelaxedNames contentTypeEnv = new RelaxedNames( + "SPRING_CLOUD_STREAM_BINDINGS_APPLICATION-METRICS-CHANNEL_CONTENT-TYPE"); RelaxedNames xyz = new RelaxedNames("My.X.Is"); RelaxedNames springMetrics = new RelaxedNames("spring.cloud.stream.applicationMetricsChannel"); RelaxedNames springMetricsEnv = new RelaxedNames("spring.cloud.stream.application-metrics-channel"); diff --git a/spring-cloud-stream-metrics/src/test/java/org/springframework/cloud/stream/metrics/config/MetricJsonSerializerTests.java b/spring-cloud-stream-metrics/src/test/java/org/springframework/cloud/stream/metrics/config/MetricJsonSerializerTests.java index ef265db87..ea4d85c45 100644 --- a/spring-cloud-stream-metrics/src/test/java/org/springframework/cloud/stream/metrics/config/MetricJsonSerializerTests.java +++ b/spring-cloud-stream-metrics/src/test/java/org/springframework/cloud/stream/metrics/config/MetricJsonSerializerTests.java @@ -21,7 +21,6 @@ import java.util.Date; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; - import org.json.JSONObject; import org.junit.Test; @@ -36,17 +35,17 @@ import static org.junit.Assert.assertEquals; public class MetricJsonSerializerTests { @Test - public void validateAlwaysGMTDateAndFormat() throws Exception { + public void validateAlwaysGMTDateAndFormat() throws Exception { Date date = new Date(1493060197188L); // Mon Apr 24 14:56:37 EDT 2017 - Metric metric = new Metric("Hello", 123, date); - + Metric metric = new Metric("Hello", 123, date); + JsonFactory factory = new JsonFactory(); - StringWriter writer = new StringWriter(); + StringWriter writer = new StringWriter(); JsonGenerator jsonGenerator = factory.createGenerator(writer); - Serializer ser = new Serializer(); + Serializer ser = new Serializer(); ser.serialize(metric, jsonGenerator, null); jsonGenerator.flush(); - + JSONObject json = new JSONObject(writer.toString()); String serializedTimestamp = json.getString("timestamp"); assertEquals("2017-04-24T18:56:37.188Z", serializedTimestamp); diff --git a/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/FluxToMessageChannelResultAdapter.java b/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/FluxToMessageChannelResultAdapter.java index 2264bfbd9..61d1652d9 100644 --- a/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/FluxToMessageChannelResultAdapter.java +++ b/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/FluxToMessageChannelResultAdapter.java @@ -26,8 +26,8 @@ import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; /** - * A {@link org.springframework.cloud.stream.binding.StreamListenerResultAdapter} from a {@link Flux} - * return type to a bound {@link MessageChannel}. + * A {@link org.springframework.cloud.stream.binding.StreamListenerResultAdapter} from a + * {@link Flux} return type to a bound {@link MessageChannel}. * @author Marius Bogoevici */ public class FluxToMessageChannelResultAdapter diff --git a/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/MessageChannelToFluxSenderParameterAdapter.java b/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/MessageChannelToFluxSenderParameterAdapter.java index 76a919ad1..9467cddf7 100644 --- a/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/MessageChannelToFluxSenderParameterAdapter.java +++ b/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/MessageChannelToFluxSenderParameterAdapter.java @@ -53,8 +53,9 @@ public class MessageChannelToFluxSenderParameterAdapter .doOnError(e -> this.log.error("Error during processing: ", e)) .retry() .subscribe( - result -> bindingTarget.send(result instanceof Message ? (Message) result : - MessageBuilder.withPayload(result).build()), e -> sendResult.onError(e), + result -> bindingTarget.send(result instanceof Message ? (Message) result + : MessageBuilder.withPayload(result).build()), + e -> sendResult.onError(e), () -> sendResult.onComplete()); return sendResult; }; diff --git a/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/MessageChannelToObservableSenderParameterAdapter.java b/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/MessageChannelToObservableSenderParameterAdapter.java index ee0ee0ff7..95606e54f 100644 --- a/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/MessageChannelToObservableSenderParameterAdapter.java +++ b/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/MessageChannelToObservableSenderParameterAdapter.java @@ -55,8 +55,7 @@ public class MessageChannelToObservableSenderParameterAdapter implements public ObservableSender adapt(MessageChannel bindingTarget, MethodParameter parameter) { return new ObservableSender() { - private FluxSender fluxSender = MessageChannelToObservableSenderParameterAdapter.this - .messageChannelToFluxSenderArgumentAdapter + private FluxSender fluxSender = MessageChannelToObservableSenderParameterAdapter.this.messageChannelToFluxSenderArgumentAdapter .adapt(bindingTarget, parameter); @Override diff --git a/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ObservableToMessageChannelResultAdapter.java b/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ObservableToMessageChannelResultAdapter.java index 1157bb71d..85dde03af 100644 --- a/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ObservableToMessageChannelResultAdapter.java +++ b/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ObservableToMessageChannelResultAdapter.java @@ -26,8 +26,8 @@ import org.springframework.messaging.MessageChannel; import org.springframework.util.Assert; /** - * A {@link StreamListenerResultAdapter} from an {@link Observable} - * return type to a bound {@link MessageChannel}. + * A {@link StreamListenerResultAdapter} from an {@link Observable} return type to a bound + * {@link MessageChannel}. * * @author Marius Bogoevici */ diff --git a/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ReactiveSupportAutoConfiguration.java b/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ReactiveSupportAutoConfiguration.java index f13b504e9..89f748dd5 100644 --- a/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ReactiveSupportAutoConfiguration.java +++ b/spring-cloud-stream-reactive/src/main/java/org/springframework/cloud/stream/reactive/ReactiveSupportAutoConfiguration.java @@ -71,8 +71,7 @@ public class ReactiveSupportAutoConfiguration { @Bean @ConditionalOnMissingBean(ObservableToMessageChannelResultAdapter.class) - public ObservableToMessageChannelResultAdapter - observableToMessageChannelResultAdapter( + public ObservableToMessageChannelResultAdapter observableToMessageChannelResultAdapter( FluxToMessageChannelResultAdapter fluxToMessageChannelResultAdapter) { return new ObservableToMessageChannelResultAdapter(fluxToMessageChannelResultAdapter); } diff --git a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerGenericFluxInputOutputArgsWithMessageTests.java b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerGenericFluxInputOutputArgsWithMessageTests.java index 895010706..d8c8e9aa4 100644 --- a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerGenericFluxInputOutputArgsWithMessageTests.java +++ b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerGenericFluxInputOutputArgsWithMessageTests.java @@ -44,9 +44,21 @@ import static org.springframework.cloud.stream.binding.StreamListenerErrorMessag @SuppressWarnings("unchecked") public class StreamListenerGenericFluxInputOutputArgsWithMessageTests { + @SuppressWarnings("unchecked") + private static void sendMessageAndValidate(ConfigurableApplicationContext context) throws InterruptedException { + Processor processor = context.getBean(Processor.class); + String sentPayload = "hello " + UUID.randomUUID().toString(); + processor.input().send(MessageBuilder.withPayload(sentPayload).setHeader("contentType", "text/plain").build()); + MessageCollector messageCollector = context.getBean(MessageCollector.class); + Message result = messageCollector.forChannel(processor.output()).poll(1000, TimeUnit.MILLISECONDS); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(sentPayload.toUpperCase()); + } + @Test public void testGenericFluxInputOutputArgsWithMessage() throws Exception { - ConfigurableApplicationContext context = SpringApplication.run(TestGenericStringFluxInputOutputArgsWithMessageImpl1.class, "--server.port=0"); + ConfigurableApplicationContext context = SpringApplication + .run(TestGenericStringFluxInputOutputArgsWithMessageImpl1.class, "--server.port=0"); sendMessageAndValidate(context); context.close(); } @@ -62,21 +74,12 @@ public class StreamListenerGenericFluxInputOutputArgsWithMessageTests { } } - @SuppressWarnings("unchecked") - private static void sendMessageAndValidate(ConfigurableApplicationContext context) throws InterruptedException { - Processor processor = context.getBean(Processor.class); - String sentPayload = "hello " + UUID.randomUUID().toString(); - processor.input().send(MessageBuilder.withPayload(sentPayload).setHeader("contentType", "text/plain").build()); - MessageCollector messageCollector = context.getBean(MessageCollector.class); - Message result = messageCollector.forChannel(processor.output()).poll(1000, TimeUnit.MILLISECONDS); - assertThat(result).isNotNull(); - assertThat(result.getPayload()).isEqualTo(sentPayload.toUpperCase()); + public static class TestGenericStringFluxInputOutputArgsWithMessageImpl1 + extends TestGenericFluxInputOutputArgsWithMessage1 { } - public static class TestGenericStringFluxInputOutputArgsWithMessageImpl1 extends TestGenericFluxInputOutputArgsWithMessage1 { - } - - public static class TestGenericStringFluxInputOutputArgsWithMessageImpl2 extends TestGenericFluxInputOutputArgsWithMessage2 { + public static class TestGenericStringFluxInputOutputArgsWithMessageImpl2 + extends TestGenericFluxInputOutputArgsWithMessage2 { } @EnableBinding(Processor.class) diff --git a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerInterruptionTests.java b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerInterruptionTests.java index 1a8aa6a50..57d782e72 100644 --- a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerInterruptionTests.java +++ b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerInterruptionTests.java @@ -35,8 +35,8 @@ import org.springframework.messaging.support.MessageBuilder; import static org.assertj.core.api.Assertions.assertThat; /** - * Test validating that a fix for - * is present. + * Test validating that a fix for + * is present. * * @author Marius Bogoevici */ diff --git a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsTests.java b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsTests.java index 8b2e4bd44..7ff1702ca 100644 --- a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsTests.java +++ b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsTests.java @@ -56,14 +56,7 @@ public class StreamListenerReactiveInputOutputArgsTests { @Parameterized.Parameters public static Collection InputConfigs() { - return Arrays.asList(new Class[]{ReactorTestInputOutputArgs.class, RxJava1TestInputOutputArgs.class}); - } - - @Test - public void testInputOutputArgs() throws Exception { - ConfigurableApplicationContext context = SpringApplication.run(this.configClass, "--server.port=0"); - sendMessageAndValidate(context); - context.close(); + return Arrays.asList(new Class[] { ReactorTestInputOutputArgs.class, RxJava1TestInputOutputArgs.class }); } private static void sendMessageAndValidate(ConfigurableApplicationContext context) throws InterruptedException { @@ -77,6 +70,13 @@ public class StreamListenerReactiveInputOutputArgsTests { assertThat(result.getPayload()).isEqualTo(sentPayload.toUpperCase()); } + @Test + public void testInputOutputArgs() throws Exception { + ConfigurableApplicationContext context = SpringApplication.run(this.configClass, "--server.port=0"); + sendMessageAndValidate(context); + context.close(); + } + @EnableBinding(Processor.class) @EnableAutoConfiguration public static class ReactorTestInputOutputArgs { @@ -92,7 +92,8 @@ public class StreamListenerReactiveInputOutputArgsTests { public static class RxJava1TestInputOutputArgs { @StreamListener - public void receive(@Input(Processor.INPUT) Observable input, @Output(Processor.OUTPUT) ObservableSender output) { + public void receive(@Input(Processor.INPUT) Observable input, + @Output(Processor.OUTPUT) ObservableSender output) { output.send(input.map(m -> m.toUpperCase())); } } diff --git a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsWithMessageTests.java b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsWithMessageTests.java index 037e8ca4e..5e81d664d 100644 --- a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsWithMessageTests.java +++ b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsWithMessageTests.java @@ -56,14 +56,8 @@ public class StreamListenerReactiveInputOutputArgsWithMessageTests { @Parameterized.Parameters public static Collection InputConfigs() { - return Arrays.asList(new Class[]{ReactorTestInputOutputArgsWithMessage.class, RxJava1TestInputOutputArgsWithMessage.class}); - } - - @Test - public void testInputOutputArgs() throws Exception { - ConfigurableApplicationContext context = SpringApplication.run(this.configClass, "--server.port=0"); - sendMessageAndValidate(context); - context.close(); + return Arrays.asList(new Class[] { ReactorTestInputOutputArgsWithMessage.class, + RxJava1TestInputOutputArgsWithMessage.class }); } private static void sendMessageAndValidate(ConfigurableApplicationContext context) throws InterruptedException { @@ -77,6 +71,13 @@ public class StreamListenerReactiveInputOutputArgsWithMessageTests { assertThat(result.getPayload()).isEqualTo(sentPayload.toUpperCase()); } + @Test + public void testInputOutputArgs() throws Exception { + ConfigurableApplicationContext context = SpringApplication.run(this.configClass, "--server.port=0"); + sendMessageAndValidate(context); + context.close(); + } + @EnableBinding(Processor.class) @EnableAutoConfiguration public static class ReactorTestInputOutputArgsWithMessage { diff --git a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsWithSenderAndFailureTests.java b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsWithSenderAndFailureTests.java index 9b35722ab..ac4c94a62 100644 --- a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsWithSenderAndFailureTests.java +++ b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsWithSenderAndFailureTests.java @@ -56,19 +56,10 @@ public class StreamListenerReactiveInputOutputArgsWithSenderAndFailureTests { @Parameterized.Parameters public static Collection InputConfigs() { - return Arrays.asList(new Class[]{TestInputOutputArgsWithFluxSenderAndFailure.class, TestInputOutputArgsWithObservableSenderAndFailure.class}); + return Arrays.asList(new Class[] { TestInputOutputArgsWithFluxSenderAndFailure.class, + TestInputOutputArgsWithObservableSenderAndFailure.class }); } - @Test - public void testInputOutputArgsWithFluxSenderAndFailure() throws Exception { - ConfigurableApplicationContext context = SpringApplication.run(this.configClass, "--server.port=0"); - sendMessageAndValidate(context); - sendFailingMessage(context); - sendMessageAndValidate(context); - context.close(); - } - - private static void sendMessageAndValidate(ConfigurableApplicationContext context) throws InterruptedException { @SuppressWarnings("unchecked") Processor processor = context.getBean(Processor.class); @@ -86,11 +77,21 @@ public class StreamListenerReactiveInputOutputArgsWithSenderAndFailureTests { processor.input().send(MessageBuilder.withPayload("fail").setHeader("contentType", "text/plain").build()); } + @Test + public void testInputOutputArgsWithFluxSenderAndFailure() throws Exception { + ConfigurableApplicationContext context = SpringApplication.run(this.configClass, "--server.port=0"); + sendMessageAndValidate(context); + sendFailingMessage(context); + sendMessageAndValidate(context); + context.close(); + } + @EnableBinding(Processor.class) @EnableAutoConfiguration public static class TestInputOutputArgsWithFluxSenderAndFailure { @StreamListener - public void receive(@Input(Processor.INPUT) Flux> input, @Output(Processor.OUTPUT) FluxSender output) { + public void receive(@Input(Processor.INPUT) Flux> input, + @Output(Processor.OUTPUT) FluxSender output) { output.send(input .map(m -> m.getPayload().toString()) .map(m -> { @@ -109,7 +110,8 @@ public class StreamListenerReactiveInputOutputArgsWithSenderAndFailureTests { @EnableAutoConfiguration public static class TestInputOutputArgsWithObservableSenderAndFailure { @StreamListener - public void receive(@Input(Processor.INPUT) Observable> input, @Output(Processor.OUTPUT) ObservableSender output) { + public void receive(@Input(Processor.INPUT) Observable> input, + @Output(Processor.OUTPUT) ObservableSender output) { output.send(input .map(m -> m.getPayload().toString()) .map(m -> { diff --git a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsWithSenderTests.java b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsWithSenderTests.java index 4a94d3090..ed2500d47 100644 --- a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsWithSenderTests.java +++ b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveInputOutputArgsWithSenderTests.java @@ -56,7 +56,19 @@ public class StreamListenerReactiveInputOutputArgsWithSenderTests { @Parameterized.Parameters public static Collection InputConfigs() { - return Arrays.asList(new Class[]{ReactorTestInputOutputArgsWithFluxSender.class, RxJava1TestInputOutputArgsWithObservableSender.class}); + return Arrays.asList(new Class[] { ReactorTestInputOutputArgsWithFluxSender.class, + RxJava1TestInputOutputArgsWithObservableSender.class }); + } + + private static void sendMessageAndValidate(ConfigurableApplicationContext context) throws InterruptedException { + @SuppressWarnings("unchecked") + Processor processor = context.getBean(Processor.class); + String sentPayload = "hello " + UUID.randomUUID().toString(); + processor.input().send(MessageBuilder.withPayload(sentPayload).setHeader("contentType", "text/plain").build()); + MessageCollector messageCollector = context.getBean(MessageCollector.class); + Message result = messageCollector.forChannel(processor.output()).poll(1000, TimeUnit.MILLISECONDS); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(sentPayload.toUpperCase()); } @Test @@ -70,23 +82,12 @@ public class StreamListenerReactiveInputOutputArgsWithSenderTests { context.close(); } - - private static void sendMessageAndValidate(ConfigurableApplicationContext context) throws InterruptedException { - @SuppressWarnings("unchecked") - Processor processor = context.getBean(Processor.class); - String sentPayload = "hello " + UUID.randomUUID().toString(); - processor.input().send(MessageBuilder.withPayload(sentPayload).setHeader("contentType", "text/plain").build()); - MessageCollector messageCollector = context.getBean(MessageCollector.class); - Message result = messageCollector.forChannel(processor.output()).poll(1000, TimeUnit.MILLISECONDS); - assertThat(result).isNotNull(); - assertThat(result.getPayload()).isEqualTo(sentPayload.toUpperCase()); - } - @EnableBinding(Processor.class) @EnableAutoConfiguration public static class ReactorTestInputOutputArgsWithFluxSender { @StreamListener - public void receive(@Input(Processor.INPUT) Flux> input, @Output(Processor.OUTPUT) FluxSender output) { + public void receive(@Input(Processor.INPUT) Flux> input, + @Output(Processor.OUTPUT) FluxSender output) { output.send(input .map(m -> m.getPayload().toString().toUpperCase()) .map(o -> MessageBuilder.withPayload(o).build())); @@ -97,8 +98,8 @@ public class StreamListenerReactiveInputOutputArgsWithSenderTests { @EnableAutoConfiguration public static class RxJava1TestInputOutputArgsWithObservableSender { @StreamListener - public void receive(@Input(Processor.INPUT) Observable> input, @Output(Processor.OUTPUT) - ObservableSender output) { + public void receive(@Input(Processor.INPUT) Observable> input, + @Output(Processor.OUTPUT) ObservableSender output) { output.send(input .map(m -> m.getPayload().toString().toUpperCase()) .map(o -> MessageBuilder.withPayload(o).build())); diff --git a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveMethodTests.java b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveMethodTests.java index 0ddbd4e6c..b22ceeb02 100644 --- a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveMethodTests.java +++ b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveMethodTests.java @@ -49,16 +49,6 @@ public class StreamListenerReactiveMethodTests { } } - @EnableBinding(Processor.class) - @EnableAutoConfiguration - public static class ReactorTestInputOutputArgs { - - @StreamListener(Processor.INPUT) - public void receive(Flux input, @Output(Processor.OUTPUT) FluxSender output) { - output.send(input.map(m -> m.toUpperCase())); - } - } - @Test public void testRxJava1InvalidInputValueWithOutputMethodParameters() { try { @@ -70,16 +60,6 @@ public class StreamListenerReactiveMethodTests { } } - @EnableBinding(Processor.class) - @EnableAutoConfiguration - public static class RxJava1TestInputOutputArgs { - - @StreamListener(Processor.INPUT) - public void receive(Observable input, @Output(Processor.OUTPUT) ObservableSender output) { - output.send(input.map(m -> m.toUpperCase())); - } - } - @Test public void testMethodReturnTypeWithNoOutboundSpecified() { try { @@ -91,6 +71,26 @@ public class StreamListenerReactiveMethodTests { } } + @EnableBinding(Processor.class) + @EnableAutoConfiguration + public static class ReactorTestInputOutputArgs { + + @StreamListener(Processor.INPUT) + public void receive(Flux input, @Output(Processor.OUTPUT) FluxSender output) { + output.send(input.map(m -> m.toUpperCase())); + } + } + + @EnableBinding(Processor.class) + @EnableAutoConfiguration + public static class RxJava1TestInputOutputArgs { + + @StreamListener(Processor.INPUT) + public void receive(Observable input, @Output(Processor.OUTPUT) ObservableSender output) { + output.send(input.map(m -> m.toUpperCase())); + } + } + @EnableBinding(Processor.class) @EnableAutoConfiguration public static class ReactorTestReturn5 { diff --git a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveMethodWithReturnTypeTests.java b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveMethodWithReturnTypeTests.java index 66cc5382a..1cd496f2d 100644 --- a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveMethodWithReturnTypeTests.java +++ b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveMethodWithReturnTypeTests.java @@ -57,17 +57,10 @@ public class StreamListenerReactiveMethodWithReturnTypeTests { @Parameterized.Parameters public static Collection InputConfigs() { - return Arrays.asList(new Class[]{ReactorTestReturn1.class, ReactorTestReturn2.class, ReactorTestReturn3.class, ReactorTestReturn4.class, - RxJava1TestReturn1.class, RxJava1TestReturn2.class, RxJava1TestReturn3.class, RxJava1TestReturn4.class}); - } - - @Test - public void testReturn() throws Exception { - ConfigurableApplicationContext context = SpringApplication.run(this.configClass, "--server.port=0"); - sendMessageAndValidate(context); - sendMessageAndValidate(context); - sendMessageAndValidate(context); - context.close(); + return Arrays.asList(new Class[] { ReactorTestReturn1.class, ReactorTestReturn2.class, ReactorTestReturn3.class, + ReactorTestReturn4.class, + RxJava1TestReturn1.class, RxJava1TestReturn2.class, RxJava1TestReturn3.class, + RxJava1TestReturn4.class }); } private static void sendMessageAndValidate(ConfigurableApplicationContext context) throws InterruptedException { @@ -81,14 +74,21 @@ public class StreamListenerReactiveMethodWithReturnTypeTests { assertThat(result.getPayload()).isEqualTo(sentPayload.toUpperCase()); } + @Test + public void testReturn() throws Exception { + ConfigurableApplicationContext context = SpringApplication.run(this.configClass, "--server.port=0"); + sendMessageAndValidate(context); + sendMessageAndValidate(context); + sendMessageAndValidate(context); + context.close(); + } + @EnableBinding(Processor.class) @EnableAutoConfiguration public static class ReactorTestReturn1 { @StreamListener - public - @Output(Processor.OUTPUT) - Flux receive(@Input(Processor.INPUT) Flux input) { + public @Output(Processor.OUTPUT) Flux receive(@Input(Processor.INPUT) Flux input) { return input.map(m -> m.toUpperCase()); } } @@ -131,9 +131,7 @@ public class StreamListenerReactiveMethodWithReturnTypeTests { public static class RxJava1TestReturn1 { @StreamListener - public - @Output(Processor.OUTPUT) - Observable receive(@Input(Processor.INPUT) Observable input) { + public @Output(Processor.OUTPUT) Observable receive(@Input(Processor.INPUT) Observable input) { return input.map(m -> m.toUpperCase()); } } @@ -143,9 +141,7 @@ public class StreamListenerReactiveMethodWithReturnTypeTests { public static class RxJava1TestReturn2 { @StreamListener(Processor.INPUT) - public - @Output(Processor.OUTPUT) - Observable receive(Observable input) { + public @Output(Processor.OUTPUT) Observable receive(Observable input) { return input.map(m -> m.toUpperCase()); } } @@ -155,9 +151,7 @@ public class StreamListenerReactiveMethodWithReturnTypeTests { public static class RxJava1TestReturn3 { @StreamListener(Processor.INPUT) - public - @SendTo(Processor.OUTPUT) - Observable receive(Observable input) { + public @SendTo(Processor.OUTPUT) Observable receive(Observable input) { return input.map(m -> m.toUpperCase()); } } @@ -167,9 +161,7 @@ public class StreamListenerReactiveMethodWithReturnTypeTests { public static class RxJava1TestReturn4 { @StreamListener - public - @SendTo(Processor.OUTPUT) - Observable receive(@Input(Processor.INPUT) Observable input) { + public @SendTo(Processor.OUTPUT) Observable receive(@Input(Processor.INPUT) Observable input) { return input.map(m -> m.toUpperCase()); } } diff --git a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveReturnWithFailureTests.java b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveReturnWithFailureTests.java index e901065c4..211bd6c05 100644 --- a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveReturnWithFailureTests.java +++ b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveReturnWithFailureTests.java @@ -57,20 +57,11 @@ public class StreamListenerReactiveReturnWithFailureTests { @Parameterized.Parameters public static Collection InputConfigs() { - return Arrays.asList(new Class[] {ReactorTestReturnWithFailure1.class, ReactorTestReturnWithFailure2.class, - ReactorTestReturnWithFailure3.class, ReactorTestReturnWithFailure4.class, RxJava1TestReturnWithFailure1.class, - RxJava1TestReturnWithFailure2.class, RxJava1TestReturnWithFailure3.class, RxJava1TestReturnWithFailure4.class}); - } - - @Test - public void testReturnWithFailure() throws Exception { - ConfigurableApplicationContext context = SpringApplication.run(this.configClass, "--server.port=0"); - sendMessageAndValidate(context); - sendFailingMessage(context); - sendMessageAndValidate(context); - sendFailingMessage(context); - sendMessageAndValidate(context); - context.close(); + return Arrays.asList(new Class[] { ReactorTestReturnWithFailure1.class, ReactorTestReturnWithFailure2.class, + ReactorTestReturnWithFailure3.class, ReactorTestReturnWithFailure4.class, + RxJava1TestReturnWithFailure1.class, + RxJava1TestReturnWithFailure2.class, RxJava1TestReturnWithFailure3.class, + RxJava1TestReturnWithFailure4.class }); } private static void sendMessageAndValidate(ConfigurableApplicationContext context) throws InterruptedException { @@ -90,14 +81,23 @@ public class StreamListenerReactiveReturnWithFailureTests { processor.input().send(MessageBuilder.withPayload("fail").setHeader("contentType", "text/plain").build()); } + @Test + public void testReturnWithFailure() throws Exception { + ConfigurableApplicationContext context = SpringApplication.run(this.configClass, "--server.port=0"); + sendMessageAndValidate(context); + sendFailingMessage(context); + sendMessageAndValidate(context); + sendFailingMessage(context); + sendMessageAndValidate(context); + context.close(); + } + @EnableBinding(Processor.class) @EnableAutoConfiguration public static class ReactorTestReturnWithFailure1 { @StreamListener - public - @Output(Processor.OUTPUT) - Flux receive(@Input(Processor.INPUT) Flux input) { + public @Output(Processor.OUTPUT) Flux receive(@Input(Processor.INPUT) Flux input) { return input.map(m -> { if (!m.equals("fail")) { return m.toUpperCase(); @@ -114,9 +114,7 @@ public class StreamListenerReactiveReturnWithFailureTests { public static class ReactorTestReturnWithFailure2 { @StreamListener(Processor.INPUT) - public - @Output(Processor.OUTPUT) - Flux receive(Flux input) { + public @Output(Processor.OUTPUT) Flux receive(Flux input) { return input.map(m -> { if (!m.equals("fail")) { return m.toUpperCase(); @@ -133,9 +131,7 @@ public class StreamListenerReactiveReturnWithFailureTests { public static class ReactorTestReturnWithFailure3 { @StreamListener(Processor.INPUT) - public - @SendTo(Processor.OUTPUT) - Flux receive(Flux input) { + public @SendTo(Processor.OUTPUT) Flux receive(Flux input) { return input.map(m -> { if (!m.equals("fail")) { return m.toUpperCase(); @@ -152,9 +148,7 @@ public class StreamListenerReactiveReturnWithFailureTests { public static class ReactorTestReturnWithFailure4 { @StreamListener - public - @SendTo(Processor.OUTPUT) - Flux receive(@Input(Processor.INPUT) Flux input) { + public @SendTo(Processor.OUTPUT) Flux receive(@Input(Processor.INPUT) Flux input) { return input.map(m -> { if (!m.equals("fail")) { return m.toUpperCase(); @@ -171,9 +165,7 @@ public class StreamListenerReactiveReturnWithFailureTests { public static class RxJava1TestReturnWithFailure1 { @StreamListener - public - @Output(Processor.OUTPUT) - Observable receive(@Input(Processor.INPUT) Observable input) { + public @Output(Processor.OUTPUT) Observable receive(@Input(Processor.INPUT) Observable input) { return input.map(m -> { if (!m.equals("fail")) { return m.toUpperCase(); @@ -190,9 +182,7 @@ public class StreamListenerReactiveReturnWithFailureTests { public static class RxJava1TestReturnWithFailure2 { @StreamListener - public - @SendTo(Processor.OUTPUT) - Observable receive(@Input(Processor.INPUT) Observable input) { + public @SendTo(Processor.OUTPUT) Observable receive(@Input(Processor.INPUT) Observable input) { return input.map(m -> { if (!m.equals("fail")) { return m.toUpperCase(); @@ -209,9 +199,7 @@ public class StreamListenerReactiveReturnWithFailureTests { public static class RxJava1TestReturnWithFailure3 { @StreamListener(Processor.INPUT) - public - @SendTo(Processor.OUTPUT) - Observable receive(Observable input) { + public @SendTo(Processor.OUTPUT) Observable receive(Observable input) { return input.map(m -> { if (!m.equals("fail")) { return m.toUpperCase(); @@ -228,9 +216,7 @@ public class StreamListenerReactiveReturnWithFailureTests { public static class RxJava1TestReturnWithFailure4 { @StreamListener(Processor.INPUT) - public - @Output(Processor.OUTPUT) - Observable receive(Observable input) { + public @Output(Processor.OUTPUT) Observable receive(Observable input) { return input.map(m -> { if (!m.equals("fail")) { return m.toUpperCase(); diff --git a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveReturnWithMessageTests.java b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveReturnWithMessageTests.java index 714da085a..3e0820652 100644 --- a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveReturnWithMessageTests.java +++ b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveReturnWithMessageTests.java @@ -57,16 +57,11 @@ public class StreamListenerReactiveReturnWithMessageTests { @Parameterized.Parameters public static Collection InputConfigs() { - return Arrays.asList(new Class[] {ReactorTestReturnWithMessage1.class, ReactorTestReturnWithMessage2.class, - ReactorTestReturnWithMessage3.class, ReactorTestReturnWithMessage4.class, RxJava1TestReturnWithMessage1.class, - RxJava1TestReturnWithMessage2.class, RxJava1TestReturnWithMessage3.class, RxJava1TestReturnWithMessage4.class}); - } - - @Test - public void testReturnWithMessage() throws Exception { - ConfigurableApplicationContext context = SpringApplication.run(this.configClass, "--server.port=0"); - sendMessageAndValidate(context); - context.close(); + return Arrays.asList(new Class[] { ReactorTestReturnWithMessage1.class, ReactorTestReturnWithMessage2.class, + ReactorTestReturnWithMessage3.class, ReactorTestReturnWithMessage4.class, + RxJava1TestReturnWithMessage1.class, + RxJava1TestReturnWithMessage2.class, RxJava1TestReturnWithMessage3.class, + RxJava1TestReturnWithMessage4.class }); } private static void sendMessageAndValidate(ConfigurableApplicationContext context) throws InterruptedException { @@ -80,14 +75,19 @@ public class StreamListenerReactiveReturnWithMessageTests { assertThat(result.getPayload()).isEqualTo(sentPayload.toUpperCase()); } + @Test + public void testReturnWithMessage() throws Exception { + ConfigurableApplicationContext context = SpringApplication.run(this.configClass, "--server.port=0"); + sendMessageAndValidate(context); + context.close(); + } + @EnableBinding(Processor.class) @EnableAutoConfiguration public static class ReactorTestReturnWithMessage1 { @StreamListener - public - @Output(Processor.OUTPUT) - Flux receive(@Input(Processor.INPUT) Flux> input) { + public @Output(Processor.OUTPUT) Flux receive(@Input(Processor.INPUT) Flux> input) { return input.map(m -> m.getPayload().toUpperCase()); } } @@ -97,9 +97,7 @@ public class StreamListenerReactiveReturnWithMessageTests { public static class ReactorTestReturnWithMessage2 { @StreamListener(Processor.INPUT) - public - @Output(Processor.OUTPUT) - Flux receive(Flux> input) { + public @Output(Processor.OUTPUT) Flux receive(Flux> input) { return input.map(m -> m.getPayload().toUpperCase()); } } @@ -109,22 +107,17 @@ public class StreamListenerReactiveReturnWithMessageTests { public static class ReactorTestReturnWithMessage3 { @StreamListener(Processor.INPUT) - public - @SendTo(Processor.OUTPUT) - Flux receive(Flux> input) { + public @SendTo(Processor.OUTPUT) Flux receive(Flux> input) { return input.map(m -> m.getPayload().toUpperCase()); } } - @EnableBinding(Processor.class) @EnableAutoConfiguration public static class ReactorTestReturnWithMessage4 { @StreamListener - public - @SendTo(Processor.OUTPUT) - Flux receive(@Input(Processor.INPUT) Flux> input) { + public @SendTo(Processor.OUTPUT) Flux receive(@Input(Processor.INPUT) Flux> input) { return input.map(m -> m.getPayload().toUpperCase()); } } @@ -134,9 +127,8 @@ public class StreamListenerReactiveReturnWithMessageTests { public static class RxJava1TestReturnWithMessage1 { @StreamListener - public - @Output(Processor.OUTPUT) - Observable receive(@Input(Processor.INPUT) Observable> input) { + public @Output(Processor.OUTPUT) Observable receive( + @Input(Processor.INPUT) Observable> input) { return input.map(m -> m.getPayload().toUpperCase()); } } @@ -146,9 +138,8 @@ public class StreamListenerReactiveReturnWithMessageTests { public static class RxJava1TestReturnWithMessage2 { @StreamListener - public - @SendTo(Processor.OUTPUT) - Observable receive(@Input(Processor.INPUT) Observable> input) { + public @SendTo(Processor.OUTPUT) Observable receive( + @Input(Processor.INPUT) Observable> input) { return input.map(m -> m.getPayload().toUpperCase()); } } @@ -158,9 +149,7 @@ public class StreamListenerReactiveReturnWithMessageTests { public static class RxJava1TestReturnWithMessage3 { @StreamListener(Processor.INPUT) - public - @Output(Processor.OUTPUT) - Observable receive(Observable> input) { + public @Output(Processor.OUTPUT) Observable receive(Observable> input) { return input.map(m -> m.getPayload().toUpperCase()); } } @@ -170,9 +159,7 @@ public class StreamListenerReactiveReturnWithMessageTests { public static class RxJava1TestReturnWithMessage4 { @StreamListener(Processor.INPUT) - public - @SendTo(Processor.OUTPUT) - Observable receive(Observable> input) { + public @SendTo(Processor.OUTPUT) Observable receive(Observable> input) { return input.map(m -> m.getPayload().toUpperCase()); } } diff --git a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveReturnWithPojoTests.java b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveReturnWithPojoTests.java index 70a874172..f56c141a7 100644 --- a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveReturnWithPojoTests.java +++ b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerReactiveReturnWithPojoTests.java @@ -56,9 +56,9 @@ public class StreamListenerReactiveReturnWithPojoTests { @Parameterized.Parameters public static Collection InputConfigs() { - return Arrays.asList(new Class[] {ReactorTestReturnWithPojo1.class, ReactorTestReturnWithPojo2.class, + return Arrays.asList(new Class[] { ReactorTestReturnWithPojo1.class, ReactorTestReturnWithPojo2.class, ReactorTestReturnWithPojo3.class, ReactorTestReturnWithPojo4.class, RxJava1TestReturnWithPojo1.class, - RxJava1TestReturnWithPojo2.class, RxJava1TestReturnWithPojo3.class, RxJava1TestReturnWithPojo4.class}); + RxJava1TestReturnWithPojo2.class, RxJava1TestReturnWithPojo3.class, RxJava1TestReturnWithPojo4.class }); } @Test @@ -81,9 +81,7 @@ public class StreamListenerReactiveReturnWithPojoTests { public static class ReactorTestReturnWithPojo1 { @StreamListener - public - @Output(Processor.OUTPUT) - Flux receive(@Input(Processor.INPUT) Flux input) { + public @Output(Processor.OUTPUT) Flux receive(@Input(Processor.INPUT) Flux input) { return input.map(m -> new BarPojo(m.getMessage())); } } @@ -93,9 +91,7 @@ public class StreamListenerReactiveReturnWithPojoTests { public static class ReactorTestReturnWithPojo2 { @StreamListener(Processor.INPUT) - public - @Output(Processor.OUTPUT) - Flux receive(Flux input) { + public @Output(Processor.OUTPUT) Flux receive(Flux input) { return input.map(m -> new BarPojo(m.getMessage())); } } @@ -105,9 +101,7 @@ public class StreamListenerReactiveReturnWithPojoTests { public static class ReactorTestReturnWithPojo3 { @StreamListener(Processor.INPUT) - public - @SendTo(Processor.OUTPUT) - Flux receive(Flux input) { + public @SendTo(Processor.OUTPUT) Flux receive(Flux input) { return input.map(m -> new BarPojo(m.getMessage())); } } @@ -117,9 +111,7 @@ public class StreamListenerReactiveReturnWithPojoTests { public static class ReactorTestReturnWithPojo4 { @StreamListener - public - @SendTo(Processor.OUTPUT) - Flux receive(@Input(Processor.INPUT) Flux input) { + public @SendTo(Processor.OUTPUT) Flux receive(@Input(Processor.INPUT) Flux input) { return input.map(m -> new BarPojo(m.getMessage())); } } @@ -129,9 +121,8 @@ public class StreamListenerReactiveReturnWithPojoTests { public static class RxJava1TestReturnWithPojo1 { @StreamListener - public - @Output(Processor.OUTPUT) - Observable receive(@Input(Processor.INPUT) Observable input) { + public @Output(Processor.OUTPUT) Observable receive( + @Input(Processor.INPUT) Observable input) { return input.map(m -> new BarPojo(m.getMessage())); } } @@ -141,9 +132,8 @@ public class StreamListenerReactiveReturnWithPojoTests { public static class RxJava1TestReturnWithPojo2 { @StreamListener - public - @SendTo(Processor.OUTPUT) - Observable receive(@Input(Processor.INPUT) Observable input) { + public @SendTo(Processor.OUTPUT) Observable receive( + @Input(Processor.INPUT) Observable input) { return input.map(m -> new BarPojo(m.getMessage())); } } @@ -153,9 +143,7 @@ public class StreamListenerReactiveReturnWithPojoTests { public static class RxJava1TestReturnWithPojo3 { @StreamListener(Processor.INPUT) - public - @Output(Processor.OUTPUT) - Observable receive(Observable input) { + public @Output(Processor.OUTPUT) Observable receive(Observable input) { return input.map(m -> new BarPojo(m.getMessage())); } } @@ -165,9 +153,7 @@ public class StreamListenerReactiveReturnWithPojoTests { public static class RxJava1TestReturnWithPojo4 { @StreamListener(Processor.INPUT) - public - @SendTo(Processor.OUTPUT) - Observable receive(Observable input) { + public @SendTo(Processor.OUTPUT) Observable receive(Observable input) { return input.map(m -> new BarPojo(m.getMessage())); } } diff --git a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerWildCardFluxInputOutputArgsWithMessageTests.java b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerWildCardFluxInputOutputArgsWithMessageTests.java index 83818998f..0d6d304ca 100644 --- a/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerWildCardFluxInputOutputArgsWithMessageTests.java +++ b/spring-cloud-stream-reactive/src/test/java/org/springframework/cloud/stream/reactive/StreamListenerWildCardFluxInputOutputArgsWithMessageTests.java @@ -45,9 +45,21 @@ import static org.springframework.cloud.stream.binding.StreamListenerErrorMessag */ public class StreamListenerWildCardFluxInputOutputArgsWithMessageTests { + private static void sendMessageAndValidate(ConfigurableApplicationContext context) throws InterruptedException { + @SuppressWarnings("unchecked") + Processor processor = context.getBean(Processor.class); + String sentPayload = "hello " + UUID.randomUUID().toString(); + processor.input().send(MessageBuilder.withPayload(sentPayload).setHeader("contentType", "text/plain").build()); + MessageCollector messageCollector = context.getBean(MessageCollector.class); + Message result = messageCollector.forChannel(processor.output()).poll(1000, TimeUnit.MILLISECONDS); + assertThat(result).isNotNull(); + assertThat(result.getPayload()).isEqualTo(sentPayload.toUpperCase()); + } + @Test public void testWildCardFluxInputOutputArgsWithMessage() throws Exception { - ConfigurableApplicationContext context = SpringApplication.run(TestWildCardFluxInputOutputArgsWithMessage1.class, "--server.port=0"); + ConfigurableApplicationContext context = SpringApplication + .run(TestWildCardFluxInputOutputArgsWithMessage1.class, "--server.port=0"); sendMessageAndValidate(context); context.close(); } @@ -74,17 +86,6 @@ public class StreamListenerWildCardFluxInputOutputArgsWithMessageTests { } } - private static void sendMessageAndValidate(ConfigurableApplicationContext context) throws InterruptedException { - @SuppressWarnings("unchecked") - Processor processor = context.getBean(Processor.class); - String sentPayload = "hello " + UUID.randomUUID().toString(); - processor.input().send(MessageBuilder.withPayload(sentPayload).setHeader("contentType", "text/plain").build()); - MessageCollector messageCollector = context.getBean(MessageCollector.class); - Message result = messageCollector.forChannel(processor.output()).poll(1000, TimeUnit.MILLISECONDS); - assertThat(result).isNotNull(); - assertThat(result.getPayload()).isEqualTo(sentPayload.toUpperCase()); - } - @EnableBinding(Processor.class) @EnableAutoConfiguration public static class TestWildCardFluxInputOutputArgsWithMessage1 { diff --git a/spring-cloud-stream-rxjava/src/main/java/org/springframework/cloud/stream/annotation/rxjava/EnableRxJavaProcessor.java b/spring-cloud-stream-rxjava/src/main/java/org/springframework/cloud/stream/annotation/rxjava/EnableRxJavaProcessor.java index e53ec0292..a42edcf48 100644 --- a/spring-cloud-stream-rxjava/src/main/java/org/springframework/cloud/stream/annotation/rxjava/EnableRxJavaProcessor.java +++ b/spring-cloud-stream-rxjava/src/main/java/org/springframework/cloud/stream/annotation/rxjava/EnableRxJavaProcessor.java @@ -28,11 +28,13 @@ import org.springframework.cloud.stream.messaging.Processor; import org.springframework.context.annotation.Import; /** - * Annotation that identifies the class as RxJava processor module. The class that has {@link EnableRxJavaProcessor} - * annotated is expected to provide a bean that implements {@link RxJavaProcessor}. + * Annotation that identifies the class as RxJava processor module. The class that has + * {@link EnableRxJavaProcessor} annotated is expected to provide a bean that implements + * {@link RxJavaProcessor}. * * @author Ilayaperumal Gopinathan - * @deprecated in favor of {@link org.springframework.cloud.stream.annotation.StreamListener} with reactive types + * @deprecated in favor of + * {@link org.springframework.cloud.stream.annotation.StreamListener} with reactive types */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) diff --git a/spring-cloud-stream-rxjava/src/main/java/org/springframework/cloud/stream/annotation/rxjava/RxJavaProcessor.java b/spring-cloud-stream-rxjava/src/main/java/org/springframework/cloud/stream/annotation/rxjava/RxJavaProcessor.java index d8cd919d7..bf7639ac4 100644 --- a/spring-cloud-stream-rxjava/src/main/java/org/springframework/cloud/stream/annotation/rxjava/RxJavaProcessor.java +++ b/spring-cloud-stream-rxjava/src/main/java/org/springframework/cloud/stream/annotation/rxjava/RxJavaProcessor.java @@ -23,7 +23,8 @@ import rx.Observable; * * @author Mark Pollack * @author Ilayaperumal Gopinathan - * @deprecated in favor of {@link org.springframework.cloud.stream.annotation.StreamListener} with reactive types + * @deprecated in favor of + * {@link org.springframework.cloud.stream.annotation.StreamListener} with reactive types */ @Deprecated public interface RxJavaProcessor { diff --git a/spring-cloud-stream-rxjava/src/main/java/org/springframework/cloud/stream/annotation/rxjava/SubjectMessageHandler.java b/spring-cloud-stream-rxjava/src/main/java/org/springframework/cloud/stream/annotation/rxjava/SubjectMessageHandler.java index ea81df0a7..0c4d44a67 100644 --- a/spring-cloud-stream-rxjava/src/main/java/org/springframework/cloud/stream/annotation/rxjava/SubjectMessageHandler.java +++ b/spring-cloud-stream-rxjava/src/main/java/org/springframework/cloud/stream/annotation/rxjava/SubjectMessageHandler.java @@ -34,34 +34,39 @@ import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** - * Adapts the item at a time delivery of a {@link org.springframework.messaging.MessageHandler} - * by delegating processing to a {@link Observable}. + * Adapts the item at a time delivery of a + * {@link org.springframework.messaging.MessageHandler} by delegating processing to a + * {@link Observable}. *

- * The outputStream of the processor is used to create a message and send it to the output channel. If the - * input channel and output channel are connected to the {@link org.springframework.cloud.stream.binder.Binder}, - * then data delivered to the input stream via a call to onNext is invoked on the dispatcher thread of the binder - * and sending a message to the output channel will involve IO operations on the binder. + * The outputStream of the processor is used to create a message and send it to the output + * channel. If the input channel and output channel are connected to the + * {@link org.springframework.cloud.stream.binder.Binder}, then data delivered to the + * input stream via a call to onNext is invoked on the dispatcher thread of the binder and + * sending a message to the output channel will involve IO operations on the binder. *

- * The implementation uses a SerializedSubject. This has the advantage that the state of the Observabale - * can be shared across all the incoming dispatcher threads that are invoking onNext. It has the disadvantage - * that processing and sending to the output channel will execute serially on one of the dispatcher threads. + * The implementation uses a SerializedSubject. This has the advantage that the state of + * the Observabale can be shared across all the incoming dispatcher threads that are + * invoking onNext. It has the disadvantage that processing and sending to the output + * channel will execute serially on one of the dispatcher threads. *

- * The use of this handler makes for a very natural first experience when processing data. For example given - * the stream http | rxjava-processor | log where the rxjava-processor does a - * buffer(5) and then produces a single value. Sending 10 messages to the http source will - * result in 2 messages in the log, no matter how many dispatcher threads are used. + * The use of this handler makes for a very natural first experience when processing data. + * For example given the stream http | rxjava-processor | log where + * the rxjava-processor does a buffer(5) and then produces a + * single value. Sending 10 messages to the http source will result in 2 messages in the + * log, no matter how many dispatcher threads are used. *

- * You can modify what thread the outputStream subscriber, which does the send to the output channel, - * will use by explicitly calling observeOn before returning the outputStream from your processor. + * You can modify what thread the outputStream subscriber, which does the send to the + * output channel, will use by explicitly calling observeOn before returning + * the outputStream from your processor. *

- + * * All error handling is the responsibility of the processor implementation. * * @author Mark Pollack * @author Ilayaperumal Gopinathan * @author Marius Bogoevici */ -@SuppressWarnings({"unchecked", "rawtypes"}) +@SuppressWarnings({ "unchecked", "rawtypes" }) @Deprecated public class SubjectMessageHandler extends AbstractMessageProducingHandler implements SmartLifecycle { @@ -76,7 +81,7 @@ public class SubjectMessageHandler extends AbstractMessageProducingHandler imple private volatile boolean running; - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) public SubjectMessageHandler(RxJavaProcessor processor) { Assert.notNull(processor, "RxJava processor must not be null."); this.processor = processor; diff --git a/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/config/SchemaServerConfiguration.java b/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/config/SchemaServerConfiguration.java index 2528cea85..48f9c545e 100644 --- a/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/config/SchemaServerConfiguration.java +++ b/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/config/SchemaServerConfiguration.java @@ -48,17 +48,18 @@ public class SchemaServerConfiguration { return new BeanFactoryPostProcessor() { @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws - BeansException { + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { if (beanFactory instanceof BeanDefinitionRegistry) { - EntityScanPackages.register((BeanDefinitionRegistry) beanFactory, Collections.singletonList(Schema.class.getPackage().getName())); + EntityScanPackages.register((BeanDefinitionRegistry) beanFactory, + Collections.singletonList(Schema.class.getPackage().getName())); } } }; } @Bean - public ServerController serverController(SchemaRepository repository, SchemaServerProperties schemeServerProperties) { + public ServerController serverController(SchemaRepository repository, + SchemaServerProperties schemeServerProperties) { return new ServerController(repository, schemaValidators(), schemeServerProperties); } diff --git a/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/config/SchemaServerProperties.java b/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/config/SchemaServerProperties.java index c81aa9c19..8b60b885b 100644 --- a/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/config/SchemaServerProperties.java +++ b/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/config/SchemaServerProperties.java @@ -14,7 +14,6 @@ * limitations under the License. */ - package org.springframework.cloud.stream.schema.server.config; import org.springframework.boot.context.properties.ConfigurationProperties; diff --git a/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/controllers/ServerController.java b/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/controllers/ServerController.java index cbe8d51af..c9d92f51f 100644 --- a/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/controllers/ServerController.java +++ b/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/controllers/ServerController.java @@ -14,7 +14,6 @@ * limitations under the License. */ - package org.springframework.cloud.stream.schema.server.controllers; import java.util.List; @@ -134,10 +133,12 @@ public class ServerController { } @RequestMapping(method = RequestMethod.GET, produces = "application/json", path = "/{subject}/{format}") - public ResponseEntity> findBySubjectAndVersion(@PathVariable("subject") String subject, @PathVariable("format") String format) { + public ResponseEntity> findBySubjectAndVersion(@PathVariable("subject") String subject, + @PathVariable("format") String format) { List schemas = repository.findBySubjectAndFormatOrderByVersion(subject, format); if (schemas == null || schemas.size() == 0) { - throw new SchemaNotFoundException(String.format("No schemas found for subject %s and format %s", subject, format)); + throw new SchemaNotFoundException( + String.format("No schemas found for subject %s and format %s", subject, format)); } return new ResponseEntity>(schemas, HttpStatus.OK); } diff --git a/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/model/Compatibility.java b/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/model/Compatibility.java index 3a3bb9fe2..29fec1fd4 100644 --- a/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/model/Compatibility.java +++ b/spring-cloud-stream-schema-server/src/main/java/org/springframework/cloud/stream/schema/server/model/Compatibility.java @@ -14,12 +14,14 @@ * limitations under the License. */ - package org.springframework.cloud.stream.schema.server.model; /** * @author Vinicius Carvalho */ public enum Compatibility { - BACKWARD, FORWARD, FULL, INCOMPATIBLE; + BACKWARD, + FORWARD, + FULL, + INCOMPATIBLE; } diff --git a/spring-cloud-stream-schema-server/src/test/java/org/springframework/cloud/stream/schema/server/SchemaRegistryServerAvroTests.java b/spring-cloud-stream-schema-server/src/test/java/org/springframework/cloud/stream/schema/server/SchemaRegistryServerAvroTests.java index 754eac83a..c91826c53 100644 --- a/spring-cloud-stream-schema-server/src/test/java/org/springframework/cloud/stream/schema/server/SchemaRegistryServerAvroTests.java +++ b/spring-cloud-stream-schema-server/src/test/java/org/springframework/cloud/stream/schema/server/SchemaRegistryServerAvroTests.java @@ -207,7 +207,8 @@ public class SchemaRegistryServerAvroTests { ResponseEntity response1 = client.postForEntity("http://localhost:8990/", schema1, Schema.class); Assert.assertTrue(response1.getStatusCode().is2xxSuccessful()); - Assert.assertEquals(HttpStatus.OK, client.getForEntity("http://localhost:8990/test/avro/v1", Schema.class).getStatusCode()); + Assert.assertEquals(HttpStatus.OK, + client.getForEntity("http://localhost:8990/test/avro/v1", Schema.class).getStatusCode()); client.getForEntity("http://localhost:8990/test/avro/1", Schema.class); Schema schema2 = new Schema(); schema2.setFormat("avro"); @@ -216,7 +217,8 @@ public class SchemaRegistryServerAvroTests { ResponseEntity response2 = client.postForEntity("http://localhost:8990/", schema2, Schema.class); Assert.assertTrue(response2.getStatusCode().is2xxSuccessful()); - Assert.assertEquals(HttpStatus.OK, client.getForEntity("http://localhost:8990/test/avro/v2", Schema.class).getStatusCode()); + Assert.assertEquals(HttpStatus.OK, + client.getForEntity("http://localhost:8990/test/avro/v2", Schema.class).getStatusCode()); schemaServerProperties.setAllowSchemaDeletion(true); client.delete("http://localhost:8990/test"); ResponseEntity response4 = client @@ -236,7 +238,8 @@ public class SchemaRegistryServerAvroTests { ResponseEntity response1 = client.postForEntity("http://localhost:8990/", schema, Schema.class); Assert.assertTrue(response1.getStatusCode().is2xxSuccessful()); - ResponseEntity deleteBySubjectFormatVersion = client.exchange("http://localhost:8990/test/avro/v1", HttpMethod.DELETE, + ResponseEntity deleteBySubjectFormatVersion = client.exchange("http://localhost:8990/test/avro/v1", + HttpMethod.DELETE, null, Object.class); assertThat(deleteBySubjectFormatVersion.getStatusCode()).isEqualTo(HttpStatus.METHOD_NOT_ALLOWED); ResponseEntity deleteBySubject = client.exchange("http://localhost:8990/test", HttpMethod.DELETE, @@ -266,8 +269,9 @@ public class SchemaRegistryServerAvroTests { v2, Schema.class); Assert.assertTrue(response2.getStatusCode().is2xxSuccessful()); - ResponseEntity> schemaResponse = client.exchange("http://localhost:8990/test/avro", HttpMethod.GET, null, new ParameterizedTypeReference>() { - }); + ResponseEntity> schemaResponse = client.exchange("http://localhost:8990/test/avro", HttpMethod.GET, + null, new ParameterizedTypeReference>() { + }); Assert.assertTrue(schemaResponse.getStatusCode().is2xxSuccessful()); Assert.assertEquals(2, schemaResponse.getBody().size()); diff --git a/spring-cloud-stream-schema-server/src/test/java/org/springframework/cloud/stream/schema/server/entityScanning/EntityScanningTests.java b/spring-cloud-stream-schema-server/src/test/java/org/springframework/cloud/stream/schema/server/entityScanning/EntityScanningTests.java index dba2b38ac..350d49a4b 100644 --- a/spring-cloud-stream-schema-server/src/test/java/org/springframework/cloud/stream/schema/server/entityScanning/EntityScanningTests.java +++ b/spring-cloud-stream-schema-server/src/test/java/org/springframework/cloud/stream/schema/server/entityScanning/EntityScanningTests.java @@ -30,7 +30,8 @@ public class EntityScanningTests { @Test public void testApplicationWithEmbeddedSchemaRegistryServerOutsideOfRootPackage() throws Exception { - final ConfigurableApplicationContext context = SpringApplication.run(CustomApplicationEmbeddingSchemaServer.class, "--server.port=0"); + final ConfigurableApplicationContext context = SpringApplication + .run(CustomApplicationEmbeddingSchemaServer.class, "--server.port=0"); context.close(); } diff --git a/spring-cloud-stream-schema-server/src/test/java/org/springframework/cloud/stream/schema/server/entityScanning/EntityScanningTestsWithEntityScan.java b/spring-cloud-stream-schema-server/src/test/java/org/springframework/cloud/stream/schema/server/entityScanning/EntityScanningTestsWithEntityScan.java index 69264024f..0da787ecb 100644 --- a/spring-cloud-stream-schema-server/src/test/java/org/springframework/cloud/stream/schema/server/entityScanning/EntityScanningTestsWithEntityScan.java +++ b/spring-cloud-stream-schema-server/src/test/java/org/springframework/cloud/stream/schema/server/entityScanning/EntityScanningTestsWithEntityScan.java @@ -31,7 +31,8 @@ public class EntityScanningTestsWithEntityScan { @Test public void testApplicationWithEmbeddedSchemaRegistryServerOutsideOfRootPackage() throws Exception { - final ConfigurableApplicationContext context = SpringApplication.run(CustomApplicationEmbeddingSchemaServer.class, "--server.port=0"); + final ConfigurableApplicationContext context = SpringApplication + .run(CustomApplicationEmbeddingSchemaServer.class, "--server.port=0"); context.close(); } diff --git a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/ParsedSchema.java b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/ParsedSchema.java index 82a5513ff..6923479df 100644 --- a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/ParsedSchema.java +++ b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/ParsedSchema.java @@ -21,13 +21,14 @@ import org.apache.avro.Schema; /** * Stores a {@link Schema} together with its String representation. * - * Helps to avoid unnecessary parsing of schema textual representation, - * as well as calls to {@link org.apache.avro.Schema} toString method which is very - * expensive due the utilization of {@link com.fasterxml.jackson.databind.ObjectMapper} - * to output a JSON representation of the schema. + * Helps to avoid unnecessary parsing of schema textual representation, as well as calls + * to {@link org.apache.avro.Schema} toString method which is very expensive due the + * utilization of {@link com.fasterxml.jackson.databind.ObjectMapper} to output a JSON + * representation of the schema. * - * Once a schema is found for any Class, be it a POJO or a {@link org.apache.avro.generic.GenericContainer}, - * both textual representation as well as the {@link org.apache.avro.Schema} will be stored within this class. + * Once a schema is found for any Class, be it a POJO or a + * {@link org.apache.avro.generic.GenericContainer}, both textual representation as well + * as the {@link org.apache.avro.Schema} will be stored within this class. * * @author Vinicius Carvalho * @@ -40,7 +41,7 @@ public class ParsedSchema { private SchemaRegistrationResponse registration; - public ParsedSchema(Schema schema){ + public ParsedSchema(Schema schema) { this.schema = schema; this.representation = schema.toString(); } diff --git a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AbstractAvroMessageConverter.java b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AbstractAvroMessageConverter.java index 7199c6c46..a1480b3c8 100644 --- a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AbstractAvroMessageConverter.java +++ b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AbstractAvroMessageConverter.java @@ -45,12 +45,12 @@ import org.springframework.messaging.converter.MessageConversionException; import org.springframework.util.MimeType; /** - * Base class for Apache Avro {@link org.springframework.messaging.converter.MessageConverter} implementations. + * Base class for Apache Avro + * {@link org.springframework.messaging.converter.MessageConverter} implementations. * @author Marius Bogoevici */ public abstract class AbstractAvroMessageConverter extends AbstractMessageConverter { - protected AbstractAvroMessageConverter(MimeType supportedMimeType) { super(supportedMimeType); } diff --git a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AvroMessageConverterAutoConfiguration.java b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AvroMessageConverterAutoConfiguration.java index b4436fcb5..947323270 100644 --- a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AvroMessageConverterAutoConfiguration.java +++ b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AvroMessageConverterAutoConfiguration.java @@ -38,19 +38,17 @@ import org.springframework.util.ObjectUtils; @ConditionalOnClass(name = "org.apache.avro.Schema") @ConditionalOnProperty(value = "spring.cloud.stream.schemaRegistryClient.enabled", matchIfMissing = true) @ConditionalOnBean(type = "org.springframework.cloud.stream.schema.client.SchemaRegistryClient") -@EnableConfigurationProperties({AvroMessageConverterProperties.class}) +@EnableConfigurationProperties({ AvroMessageConverterProperties.class }) public class AvroMessageConverterAutoConfiguration { @Autowired private AvroMessageConverterProperties avroMessageConverterProperties; - @Bean @ConditionalOnMissingBean(AvroSchemaRegistryClientMessageConverter.class) public AvroSchemaRegistryClientMessageConverter avroSchemaMessageConverter( SchemaRegistryClient schemaRegistryClient) { - AvroSchemaRegistryClientMessageConverter - avroSchemaRegistryClientMessageConverter = new AvroSchemaRegistryClientMessageConverter( + AvroSchemaRegistryClientMessageConverter avroSchemaRegistryClientMessageConverter = new AvroSchemaRegistryClientMessageConverter( schemaRegistryClient); avroSchemaRegistryClientMessageConverter.setDynamicSchemaGenerationEnabled( this.avroMessageConverterProperties.isDynamicSchemaGenerationEnabled()); @@ -70,7 +68,7 @@ public class AvroMessageConverterAutoConfiguration { @Bean @ConditionalOnMissingBean - public CacheManager cacheManager(){ + public CacheManager cacheManager() { return new ConcurrentMapCacheManager(); } } diff --git a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AvroSchemaMessageConverter.java b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AvroSchemaMessageConverter.java index 779f7ae49..a7cc4290a 100644 --- a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AvroSchemaMessageConverter.java +++ b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AvroSchemaMessageConverter.java @@ -27,14 +27,11 @@ import org.springframework.util.Assert; import org.springframework.util.MimeType; /** - * A {@link org.springframework.messaging.converter.MessageConverter} - * using Apache Avro. - * The schema for serializing and deserializing will be automatically inferred - * from the class for {@link org.apache.avro.specific.SpecificRecord} and regular - * classes, unless a specific schema is set, case in which that schema will be used - * instead. - * For converting to {@link org.apache.avro.generic.GenericRecord} targets, - * a schema must be set.s + * A {@link org.springframework.messaging.converter.MessageConverter} using Apache Avro. + * The schema for serializing and deserializing will be automatically inferred from the + * class for {@link org.apache.avro.specific.SpecificRecord} and regular classes, unless a + * specific schema is set, case in which that schema will be used instead. For converting + * to {@link org.apache.avro.generic.GenericRecord} targets, a schema must be set.s * @author Marius Bogoevici */ @@ -43,24 +40,24 @@ public class AvroSchemaMessageConverter extends AbstractAvroMessageConverter { private Schema schema; /** - * Create a {@link AvroSchemaMessageConverter}. - * Uses the default {@link MimeType} of {@code "application/avro"}. + * Create a {@link AvroSchemaMessageConverter}. Uses the default {@link MimeType} of + * {@code "application/avro"}. */ public AvroSchemaMessageConverter() { super(new MimeType("application", "avro")); } /** - * Create a {@link AvroSchemaMessageConverter}. - * The converter will be used for the provided {@link MimeType}. + * Create a {@link AvroSchemaMessageConverter}. The converter will be used for the + * provided {@link MimeType}. */ public AvroSchemaMessageConverter(MimeType supportedMimeType) { super(supportedMimeType); } /** - * Create a {@link AvroSchemaMessageConverter}. - * The converter will be used for the provided {@link MimeType}s. + * Create a {@link AvroSchemaMessageConverter}. The converter will be used for the + * provided {@link MimeType}s. * @param supportedMimeTypes the mime types supported by this converter */ public AvroSchemaMessageConverter(Collection supportedMimeTypes) { diff --git a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AvroSchemaRegistryClientMessageConverter.java b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AvroSchemaRegistryClientMessageConverter.java index ba8a7d062..d8efadf25 100644 --- a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AvroSchemaRegistryClientMessageConverter.java +++ b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/avro/AvroSchemaRegistryClientMessageConverter.java @@ -110,13 +110,15 @@ public class AvroSchemaRegistryClientMessageConverter extends AbstractAvroMessag } /** - * Creates a new instance, configuring it with {@link SchemaRegistryClient} and {@link CacheManager}. + * Creates a new instance, configuring it with {@link SchemaRegistryClient} and + * {@link CacheManager}. * @param schemaRegistryClient the {@link SchemaRegistryClient} used to interact with * the schema registry server. - * @param cacheManager instance of {@link CacheManager} to cache parsed schemas. If caching - * is not required use {@link NoOpCacheManager} + * @param cacheManager instance of {@link CacheManager} to cache parsed schemas. If + * caching is not required use {@link NoOpCacheManager} */ - public AvroSchemaRegistryClientMessageConverter(SchemaRegistryClient schemaRegistryClient, CacheManager cacheManager) { + public AvroSchemaRegistryClientMessageConverter(SchemaRegistryClient schemaRegistryClient, + CacheManager cacheManager) { super(Arrays.asList(new MimeType("application", "*+avro"))); Assert.notNull(schemaRegistryClient, "cannot be null"); Assert.notNull(cacheManager, "'cacheManager' cannot be null"); @@ -194,7 +196,7 @@ public class AvroSchemaRegistryClientMessageConverter extends AbstractAvroMessag } } } - if (this.cacheManager instanceof NoOpCacheManager){ + if (this.cacheManager instanceof NoOpCacheManager) { logger.warn("Schema caching is effectively disabled " + "since configured cache manager is a NoOpCacheManager. If this was not " + "the intention, please provide the appropriate instance of CacheManager " @@ -337,7 +339,6 @@ public class AvroSchemaRegistryClientMessageConverter extends AbstractAvroMessag return schema; } - /** * @deprecated as of release 1.0.4. Please use the constructor to inject CacheManager */ diff --git a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/CachingRegistryClient.java b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/CachingRegistryClient.java index 3ba9f9a9b..e661b3f17 100644 --- a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/CachingRegistryClient.java +++ b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/CachingRegistryClient.java @@ -46,9 +46,9 @@ public class CachingRegistryClient implements SchemaRegistryClient { @Override public SchemaRegistrationResponse register(String subject, String format, String schema) { - SchemaRegistrationResponse response = delegate.register(subject,format,schema); - cacheManager.getCache(ID_CACHE).put(response.getSchemaReference(),schema); - cacheManager.getCache(REF_CACHE).put(response.getId(),schema); + SchemaRegistrationResponse response = delegate.register(subject, format, schema); + cacheManager.getCache(ID_CACHE).put(response.getSchemaReference(), schema); + cacheManager.getCache(REF_CACHE).put(response.getId(), schema); return response; } diff --git a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/DefaultSchemaRegistryClient.java b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/DefaultSchemaRegistryClient.java index 92d82eb0b..d1ca29c1a 100644 --- a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/DefaultSchemaRegistryClient.java +++ b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/DefaultSchemaRegistryClient.java @@ -31,7 +31,6 @@ import org.springframework.web.client.RestTemplate; */ public class DefaultSchemaRegistryClient implements SchemaRegistryClient { - private RestTemplate template; private String endpoint = "http://localhost:8990"; @@ -69,7 +68,8 @@ public class DefaultSchemaRegistryClient implements SchemaRegistryClient { ResponseEntity responseEntity = this.template.getForEntity( this.endpoint + "/" + schemaReference.getSubject() + "/" + schemaReference .getFormat() + "/v" + schemaReference - .getVersion(), Map.class); + .getVersion(), + Map.class); if (!responseEntity.getStatusCode().is2xxSuccessful()) { throw new RuntimeException("Failed to fetch schema: " + responseEntity.toString()); } diff --git a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/EnableSchemaRegistryClient.java b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/EnableSchemaRegistryClient.java index f7767cd64..7eeb20cd9 100644 --- a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/EnableSchemaRegistryClient.java +++ b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/EnableSchemaRegistryClient.java @@ -30,7 +30,7 @@ import org.springframework.context.annotation.Import; /** * @author Marius Bogoevici */ -@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE}) +@Target({ ElementType.TYPE, ElementType.ANNOTATION_TYPE }) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited diff --git a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/SchemaRegistryClient.java b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/SchemaRegistryClient.java index 3d0d136f9..e67d3c6ba 100644 --- a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/SchemaRegistryClient.java +++ b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/SchemaRegistryClient.java @@ -26,16 +26,19 @@ import org.springframework.cloud.stream.schema.SchemaRegistrationResponse; public interface SchemaRegistryClient { /** - * Registers a schema with the remote repository returning the unique identifier associated with this schema. + * Registers a schema with the remote repository returning the unique identifier + * associated with this schema. * @param subject the full name of the schema * @param schema - * @return a {@link SchemaRegistrationResponse} representing the result of the operation + * @return a {@link SchemaRegistrationResponse} representing the result of the + * operation */ SchemaRegistrationResponse register(String subject, String format, String schema); /** * Retrieves a schema by its reference (subject and version). - * @param schemaReference a {@link SchemaReference} used to identify the target schema. + * @param schemaReference a {@link SchemaReference} used to identify the target + * schema. * @return */ String fetch(SchemaReference schemaReference); diff --git a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/config/SchemaRegistryClientConfiguration.java b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/config/SchemaRegistryClientConfiguration.java index fc30ef4be..e92606b30 100644 --- a/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/config/SchemaRegistryClientConfiguration.java +++ b/spring-cloud-stream-schema/src/main/java/org/springframework/cloud/stream/schema/client/config/SchemaRegistryClientConfiguration.java @@ -44,7 +44,8 @@ public class SchemaRegistryClientConfiguration { defaultSchemaRegistryClient.setEndpoint(schemaRegistryClientProperties.getEndpoint()); } - SchemaRegistryClient client = (schemaRegistryClientProperties.isCached()) ? new CachingRegistryClient(defaultSchemaRegistryClient) : defaultSchemaRegistryClient; + SchemaRegistryClient client = (schemaRegistryClientProperties.isCached()) + ? new CachingRegistryClient(defaultSchemaRegistryClient) : defaultSchemaRegistryClient; return client; } diff --git a/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroMessageConverterSerializationTests.java b/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroMessageConverterSerializationTests.java index bf542a154..9c921b896 100644 --- a/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroMessageConverterSerializationTests.java +++ b/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroMessageConverterSerializationTests.java @@ -53,12 +53,12 @@ public class AvroMessageConverterSerializationTests { Pattern versionedSchema = Pattern.compile( "application/" + "vnd" + "\\.([\\p{Alnum}\\$\\.]+)\\.v(\\p{Digit}+)\\+avro"); - private ConfigurableApplicationContext schemaRegistryServerContext; Log logger = LogFactory.getLog(getClass()); + private ConfigurableApplicationContext schemaRegistryServerContext; @Before - public void setup(){ + public void setup() { schemaRegistryServerContext = SpringApplication.run( SchemaRegistryServerApplication.class); } @@ -72,9 +72,10 @@ public class AvroMessageConverterSerializationTests { public void sourceWriteSameVersion() throws Exception { User specificRecord = new User(); specificRecord.setName("joe"); - Schema v1 = new Schema.Parser().parse(AvroMessageConverterSerializationTests.class.getClassLoader().getResourceAsStream("schemas/user.avsc")); + Schema v1 = new Schema.Parser().parse( + AvroMessageConverterSerializationTests.class.getClassLoader().getResourceAsStream("schemas/user.avsc")); GenericRecord genericRecord = new GenericData.Record(v1); - genericRecord.put("name","joe"); + genericRecord.put("name", "joe"); SchemaRegistryClient client = new DefaultSchemaRegistryClient(); AvroSchemaRegistryClientMessageConverter converter = new AvroSchemaRegistryClientMessageConverter(client); converter.setDynamicSchemaGenerationEnabled(false); @@ -82,13 +83,19 @@ public class AvroMessageConverterSerializationTests { converter.setCacheManager(new ConcurrentMapCacheManager()); converter.afterPropertiesSet(); - Message specificMessage = converter.toMessage(specificRecord,new MutableMessageHeaders(Collections.emptyMap()), MimeTypeUtils.parseMimeType("application/*+avro")); - SchemaReference specificRef = extractSchemaReference( MimeTypeUtils.parseMimeType(specificMessage.getHeaders().get("contentType").toString())); + Message specificMessage = converter.toMessage(specificRecord, + new MutableMessageHeaders(Collections.emptyMap()), + MimeTypeUtils.parseMimeType("application/*+avro")); + SchemaReference specificRef = extractSchemaReference( + MimeTypeUtils.parseMimeType(specificMessage.getHeaders().get("contentType").toString())); - Message genericMessage = converter.toMessage(genericRecord,new MutableMessageHeaders(Collections.emptyMap()), MimeTypeUtils.parseMimeType("application/*+avro")); - SchemaReference genericRef = extractSchemaReference( MimeTypeUtils.parseMimeType(genericMessage.getHeaders().get("contentType").toString())); + Message genericMessage = converter.toMessage(genericRecord, + new MutableMessageHeaders(Collections.emptyMap()), + MimeTypeUtils.parseMimeType("application/*+avro")); + SchemaReference genericRef = extractSchemaReference( + MimeTypeUtils.parseMimeType(genericMessage.getHeaders().get("contentType").toString())); - Assert.assertEquals(genericRef,specificRef); + Assert.assertEquals(genericRef, specificRef); Assert.assertEquals(1, genericRef.getVersion()); } @@ -98,7 +105,8 @@ public class AvroMessageConverterSerializationTests { if (schemaMatcher.find()) { String subject = schemaMatcher.group(1); Integer version = Integer.parseInt(schemaMatcher.group(2)); - schemaReference = new SchemaReference(subject, version, AvroSchemaRegistryClientMessageConverter.AVRO_FORMAT); + schemaReference = new SchemaReference(subject, version, + AvroSchemaRegistryClientMessageConverter.AVRO_FORMAT); } return schemaReference; } diff --git a/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroSchemaMessageConverterTests.java b/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroSchemaMessageConverterTests.java index fae1f8d6f..5ef37d995 100644 --- a/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroSchemaMessageConverterTests.java +++ b/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroSchemaMessageConverterTests.java @@ -68,7 +68,6 @@ public class AvroSchemaMessageConverterTests { Message outboundMessage = sourceMessageCollector.forChannel(source.output()).poll(1000, TimeUnit.MILLISECONDS); - ConfigurableApplicationContext barSourceContext = SpringApplication.run(AvroSourceApplication.class, "--server.port=0", "--spring.jmx.enabled=false", @@ -87,7 +86,6 @@ public class AvroSchemaMessageConverterTests { assertThat(barOutboundMessage).isNotNull(); - User2 secondUser2OutboundPojo = new User2(); secondUser2OutboundPojo.setFavoriteColor("foo" + UUID.randomUUID().toString()); secondUser2OutboundPojo.setFavoritePlace("foo" + UUID.randomUUID().toString()); @@ -96,7 +94,6 @@ public class AvroSchemaMessageConverterTests { Message secondBarOutboundMessage = sourceMessageCollector.forChannel(source.output()).poll(1000, TimeUnit.MILLISECONDS); - ConfigurableApplicationContext sinkContext = SpringApplication.run(AvroSinkApplication.class, "--server.port=0", "--spring.jmx.enabled=false", @@ -139,7 +136,6 @@ public class AvroSchemaMessageConverterTests { Message outboundMessage = sourceMessageCollector.forChannel(source.output()).poll(1000, TimeUnit.MILLISECONDS); - ConfigurableApplicationContext barSourceContext = SpringApplication.run(AvroSourceApplication.class, "--server.port=0", "--spring.jmx.enabled=false", @@ -157,7 +153,6 @@ public class AvroSchemaMessageConverterTests { assertThat(barOutboundMessage).isNotNull(); - User2 secondUser2OutboundPojo = new User2(); secondUser2OutboundPojo.setFavoriteColor("foo" + UUID.randomUUID().toString()); secondUser2OutboundPojo.setFavoritePlace("foo" + UUID.randomUUID().toString()); @@ -166,7 +161,6 @@ public class AvroSchemaMessageConverterTests { Message secondBarOutboundMessage = sourceMessageCollector.forChannel(source.output()).poll(1000, TimeUnit.MILLISECONDS); - ConfigurableApplicationContext sinkContext = SpringApplication.run(AvroSinkApplication.class, "--server.port=0", "--spring.jmx.enabled=false", @@ -192,19 +186,18 @@ public class AvroSchemaMessageConverterTests { sourceContext.close(); } - @EnableBinding(Source.class) @EnableAutoConfiguration @ConfigurationProperties public static class AvroSourceApplication { + private Resource schemaLocation; + @Bean public SchemaRegistryClient schemaRegistryClient() { return stubSchemaRegistryClient; } - private Resource schemaLocation; - public void setSchemaLocation(Resource schemaLocation) { this.schemaLocation = schemaLocation; } @@ -227,13 +220,13 @@ public class AvroSchemaMessageConverterTests { public List receivedUsers = new ArrayList<>(); + private Resource schemaLocation; + @StreamListener(Sink.INPUT) public void listen(User1 user) { receivedUsers.add(user); } - private Resource schemaLocation; - public void setSchemaLocation(Resource schemaLocation) { this.schemaLocation = schemaLocation; } diff --git a/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroSchemaRegistryClientMessageConverterTests.java b/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroSchemaRegistryClientMessageConverterTests.java index 634cd210a..92aba20e9 100644 --- a/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroSchemaRegistryClientMessageConverterTests.java +++ b/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroSchemaRegistryClientMessageConverterTests.java @@ -44,6 +44,7 @@ import org.springframework.messaging.Message; import org.springframework.messaging.support.MessageBuilder; import static org.assertj.core.api.Assertions.assertThat; + /** * @author Marius Bogoevici * @author Oleg Zhurakousky @@ -72,7 +73,6 @@ public class AvroSchemaRegistryClientMessageConverterTests { Message outboundMessage = sourceMessageCollector.forChannel(source.output()).poll(1000, TimeUnit.MILLISECONDS); - ConfigurableApplicationContext barSourceContext = SpringApplication.run(AvroSourceApplication.class, "--server.port=0", "--spring.jmx.enabled=false", @@ -89,7 +89,6 @@ public class AvroSchemaRegistryClientMessageConverterTests { assertThat(barOutboundMessage).isNotNull(); - User2 secondBarOutboundPojo = new User2(); secondBarOutboundPojo.setFavoriteColor("foo" + UUID.randomUUID().toString()); secondBarOutboundPojo.setName("foo" + UUID.randomUUID().toString()); @@ -97,7 +96,6 @@ public class AvroSchemaRegistryClientMessageConverterTests { Message secondBarOutboundMessage = sourceMessageCollector.forChannel(source.output()).poll(1000, TimeUnit.MILLISECONDS); - ConfigurableApplicationContext sinkContext = SpringApplication.run(AvroSinkApplication.class, "--server.port=0", "--spring.jmx.enabled=false"); Sink sink = sinkContext.getBean(Sink.class); @@ -116,7 +114,6 @@ public class AvroSchemaRegistryClientMessageConverterTests { assertThat(receivedPojos.get(1).getName()).isEqualTo(firstOutboundUser2.getName()); assertThat(receivedPojos.get(1).getFavoritePlace()).isEqualTo("Boston"); - assertThat(receivedPojos.get(2)).isNotSameAs(secondBarOutboundPojo); assertThat(receivedPojos.get(2).getFavoriteColor()).isEqualTo(secondBarOutboundPojo.getFavoriteColor()); assertThat(receivedPojos.get(2).getName()).isEqualTo(secondBarOutboundPojo.getName()); @@ -128,6 +125,16 @@ public class AvroSchemaRegistryClientMessageConverterTests { schemaRegistryServerContext.close(); } + @Test + public void testNoCacheConfiguration() { + ConfigurableApplicationContext sourceContext = SpringApplication.run(NoCacheConfiguration.class, + "--spring.main.web-environment=false"); + AvroSchemaRegistryClientMessageConverter converter = sourceContext + .getBean(AvroSchemaRegistryClientMessageConverter.class); + DirectFieldAccessor accessor = new DirectFieldAccessor(converter); + assertThat(accessor.getPropertyValue("cacheManager")).isInstanceOf(NoOpCacheManager.class); + } + @EnableBinding(Source.class) @EnableAutoConfiguration @EnableSchemaRegistryClient @@ -149,14 +156,6 @@ public class AvroSchemaRegistryClientMessageConverterTests { } - @Test - public void testNoCacheConfiguration (){ - ConfigurableApplicationContext sourceContext = SpringApplication.run(NoCacheConfiguration.class, "--spring.main.web-environment=false"); - AvroSchemaRegistryClientMessageConverter converter = sourceContext.getBean(AvroSchemaRegistryClientMessageConverter.class); - DirectFieldAccessor accessor = new DirectFieldAccessor(converter); - assertThat(accessor.getPropertyValue("cacheManager")).isInstanceOf(NoOpCacheManager.class); - } - @Configuration public static class NoCacheConfiguration { @SuppressWarnings("deprecation") diff --git a/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroStubSchemaRegistryClientMessageConverterTests.java b/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroStubSchemaRegistryClientMessageConverterTests.java index 5427e7f38..ee809a5ff 100644 --- a/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroStubSchemaRegistryClientMessageConverterTests.java +++ b/spring-cloud-stream-schema/src/test/java/org/springframework/cloud/schema/avro/AvroStubSchemaRegistryClientMessageConverterTests.java @@ -62,7 +62,6 @@ public class AvroStubSchemaRegistryClientMessageConverterTests { Message outboundMessage = sourceMessageCollector.forChannel(source.output()).poll(1000, TimeUnit.MILLISECONDS); - ConfigurableApplicationContext barSourceContext = SpringApplication.run(AvroSourceApplication.class, "--server.port=0", "--spring.jmx.enabled=false", @@ -79,7 +78,6 @@ public class AvroStubSchemaRegistryClientMessageConverterTests { assertThat(barOutboundMessage).isNotNull(); - User2 secondBarOutboundPojo = new User2(); secondBarOutboundPojo.setFavoriteColor("foo" + UUID.randomUUID().toString()); secondBarOutboundPojo.setName("foo" + UUID.randomUUID().toString()); @@ -87,7 +85,6 @@ public class AvroStubSchemaRegistryClientMessageConverterTests { Message secondBarOutboundMessage = sourceMessageCollector.forChannel(source.output()).poll(1000, TimeUnit.MILLISECONDS); - ConfigurableApplicationContext sinkContext = SpringApplication.run(AvroSinkApplication.class, "--server.port=0", "--spring.jmx.enabled=false"); Sink sink = sinkContext.getBean(Sink.class); @@ -106,7 +103,6 @@ public class AvroStubSchemaRegistryClientMessageConverterTests { assertThat(receivedPojos.get(1).getName()).isEqualTo(firstOutboundUser2.getName()); assertThat(receivedPojos.get(1).getFavoritePlace()).isEqualTo("Boston"); - assertThat(receivedPojos.get(2)).isNotSameAs(secondBarOutboundPojo); assertThat(receivedPojos.get(2).getFavoriteColor()).isEqualTo(secondBarOutboundPojo.getFavoriteColor()); assertThat(receivedPojos.get(2).getName()).isEqualTo(secondBarOutboundPojo.getName()); diff --git a/spring-cloud-stream-test-support-internal/src/main/java/org/springframework/cloud/stream/test/junit/AbstractExternalResourceTestSupport.java b/spring-cloud-stream-test-support-internal/src/main/java/org/springframework/cloud/stream/test/junit/AbstractExternalResourceTestSupport.java index a14025d02..db462a801 100644 --- a/spring-cloud-stream-test-support-internal/src/main/java/org/springframework/cloud/stream/test/junit/AbstractExternalResourceTestSupport.java +++ b/spring-cloud-stream-test-support-internal/src/main/java/org/springframework/cloud/stream/test/junit/AbstractExternalResourceTestSupport.java @@ -42,12 +42,12 @@ public abstract class AbstractExternalResourceTestSupport implements TestRule public static final String SCS_EXTERNAL_SERVERS_REQUIRED = "SCS_EXTERNAL_SERVERS_REQUIRED"; + protected final Log logger = LogFactory.getLog(getClass()); + protected R resource; private String resourceDescription; - protected final Log logger = LogFactory.getLog(getClass()); - protected AbstractExternalResourceTestSupport(String resourceDescription) { Assert.hasText(resourceDescription, "resourceDescription is required"); this.resourceDescription = resourceDescription; diff --git a/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/binder/MessageCollector.java b/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/binder/MessageCollector.java index 2c406cc82..41a9a19bc 100644 --- a/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/binder/MessageCollector.java +++ b/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/binder/MessageCollector.java @@ -22,8 +22,8 @@ import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; /** - * Maintains a map between (output) channels and messages received (in FIFO order). To be injected in tests that - * can then run assertions on the enqueued messages. + * Maintains a map between (output) channels and messages received (in FIFO order). To be + * injected in tests that can then run assertions on the enqueued messages. * * @author Eric Bottard */ diff --git a/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/binder/TestBinderEnvironmentPostProcessor.java b/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/binder/TestBinderEnvironmentPostProcessor.java index 1879617c6..b8fca8ff4 100644 --- a/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/binder/TestBinderEnvironmentPostProcessor.java +++ b/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/binder/TestBinderEnvironmentPostProcessor.java @@ -25,7 +25,8 @@ import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; /** - * An {@link EnvironmentPostProcessor} that sets some configuration properties for {@link TestSupportBinder}. + * An {@link EnvironmentPostProcessor} that sets some configuration properties for + * {@link TestSupportBinder}. * * @author Ilayaperumal Gopinathan */ diff --git a/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/binder/TestSupportBinder.java b/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/binder/TestSupportBinder.java index f941cbcea..c52e1fc41 100644 --- a/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/binder/TestSupportBinder.java +++ b/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/binder/TestSupportBinder.java @@ -36,9 +36,12 @@ import org.springframework.messaging.SubscribableChannel; import org.springframework.util.Assert; /** - * A minimal binder that
    - *
  • does nothing about binding consumers, leaving the channel as-is, so that a test author can interact with it directly,
  • - *
  • registers a queue channel on the producer side, so that it is easy to assert what is received.
  • + * A minimal binder that + *
      + *
    • does nothing about binding consumers, leaving the channel as-is, so that a test + * author can interact with it directly,
    • + *
    • registers a queue channel on the producer side, so that it is easy to assert what + * is received.
    • *
    * * @author Eric Bottard @@ -53,12 +56,14 @@ public class TestSupportBinder implements Binder messageChannels = new ConcurrentHashMap<>(); @Override - public Binding bindConsumer(String name, String group, MessageChannel inboundBindTarget, ConsumerProperties properties) { + public Binding bindConsumer(String name, String group, MessageChannel inboundBindTarget, + ConsumerProperties properties) { return new TestBinding(inboundBindTarget, null); } /** - * Registers a single subscriber to the channel, that enqueues messages for later retrieval and assertion in tests. + * Registers a single subscriber to the channel, that enqueues messages for later + * retrieval and assertion in tests. */ @Override public Binding bindProducer(String name, MessageChannel outboundBindTarget, @@ -99,7 +104,8 @@ public class TestSupportBinder implements Binder Binder getBinder(String configurationName, Class bindableType) { + public Binder getBinder( + String configurationName, Class bindableType) { return (Binder) messageChannelBinder; } }; diff --git a/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/matcher/MessageQueueMatcher.java b/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/matcher/MessageQueueMatcher.java index 3069a1b1e..abc714c40 100644 --- a/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/matcher/MessageQueueMatcher.java +++ b/spring-cloud-stream-test-support/src/main/java/org/springframework/cloud/stream/test/matcher/MessageQueueMatcher.java @@ -33,7 +33,9 @@ import org.springframework.messaging.Message; /** * A Hamcrest Matcher meant to be used in conjunction with {@link TestSupportBinder}. * - *

    Expected usage is of the form (with appropriate static imports): + *

    + * Expected usage is of the form (with appropriate static imports): + * *

      * public class TransformProcessorApplicationTests {
      *
    @@ -51,7 +53,8 @@ import org.springframework.messaging.Message;
      *        assertThat(messageCollector.forChannel(processor.output()), receivesPayloadThat(is("hellofoo")).within(10));
      *    }
      *
    - * }
    + * } + * *

    * * @author Eric Bottard @@ -62,12 +65,12 @@ public class MessageQueueMatcher extends BaseMatcher private final long timeout; + private final TimeUnit unit; + private Extractor, T> extractor; private Map>, T> actuallyReceived = new HashMap<>(); - private final TimeUnit unit; - public MessageQueueMatcher(Matcher delegate, long timeout, TimeUnit unit, Extractor, T> extractor) { this.delegate = delegate; this.timeout = timeout; @@ -75,6 +78,28 @@ public class MessageQueueMatcher extends BaseMatcher this.extractor = extractor; } + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static

    MessageQueueMatcher

    receivesMessageThat(Matcher> messageMatcher) { + return new MessageQueueMatcher(messageMatcher, 5, TimeUnit.SECONDS, + new Extractor, Message

    >("a message that ") { + @Override + public Message

    apply(Message

    m) { + return m; + } + }); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + public static

    MessageQueueMatcher

    receivesPayloadThat(Matcher

    payloadMatcher) { + return new MessageQueueMatcher(payloadMatcher, 5, TimeUnit.SECONDS, + new Extractor, P>("a message whose payload ") { + @Override + public P apply(Message

    m) { + return m.getPayload(); + } + }); + } + @Override public boolean matches(Object item) { @SuppressWarnings("unchecked") @@ -129,28 +154,9 @@ public class MessageQueueMatcher extends BaseMatcher description.appendText("Channel to receive ").appendDescriptionOf(extractor).appendDescriptionOf(delegate); } - @SuppressWarnings({"unchecked", "rawtypes"}) - public static

    MessageQueueMatcher

    receivesMessageThat(Matcher> messageMatcher) { - return new MessageQueueMatcher(messageMatcher, 5, TimeUnit.SECONDS, new Extractor, Message

    >("a message that ") { - @Override - public Message

    apply(Message

    m) { - return m; - } - }); - } - - @SuppressWarnings({"unchecked", "rawtypes"}) - public static

    MessageQueueMatcher

    receivesPayloadThat(Matcher

    payloadMatcher) { - return new MessageQueueMatcher(payloadMatcher, 5, TimeUnit.SECONDS, new Extractor, P>("a message whose payload ") { - @Override - public P apply(Message

    m) { - return m.getPayload(); - } - }); - } - /** - * A transformation to be applied to a received message before asserting, e.g. to only inspect the payload. + * A transformation to be applied to a received message before asserting, e.g. + * to only inspect the payload. */ public static abstract class Extractor implements Function, SelfDescribing { @@ -166,6 +172,4 @@ public class MessageQueueMatcher extends BaseMatcher } } - - } diff --git a/spring-cloud-stream-test-support/src/test/java/org/springframework/cloud/stream/test/aggregate/AggregateWithBeanTest.java b/spring-cloud-stream-test-support/src/test/java/org/springframework/cloud/stream/test/aggregate/AggregateWithBeanTest.java index 5597613b5..df1add7e0 100644 --- a/spring-cloud-stream-test-support/src/test/java/org/springframework/cloud/stream/test/aggregate/AggregateWithBeanTest.java +++ b/spring-cloud-stream-test-support/src/test/java/org/springframework/cloud/stream/test/aggregate/AggregateWithBeanTest.java @@ -42,7 +42,7 @@ import static org.assertj.core.api.Assertions.assertThat; * @author Marius Bogoevici */ @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = AggregateWithBeanTest.ChainedProcessors.class, properties = {"server.port=-1"}) +@SpringBootTest(classes = AggregateWithBeanTest.ChainedProcessors.class, properties = { "server.port=-1" }) public class AggregateWithBeanTest { @Autowired diff --git a/spring-cloud-stream-test-support/src/test/java/org/springframework/cloud/stream/test/aggregate/AggregateWithMainTest.java b/spring-cloud-stream-test-support/src/test/java/org/springframework/cloud/stream/test/aggregate/AggregateWithMainTest.java index efe8e5d9a..b00cc88cb 100644 --- a/spring-cloud-stream-test-support/src/test/java/org/springframework/cloud/stream/test/aggregate/AggregateWithMainTest.java +++ b/spring-cloud-stream-test-support/src/test/java/org/springframework/cloud/stream/test/aggregate/AggregateWithMainTest.java @@ -43,8 +43,9 @@ public class AggregateWithMainTest { @Test public void testAggregateApplication() throws InterruptedException { // emulate a main method - ConfigurableApplicationContext context = new AggregateApplicationBuilder(TestSupportBinderAutoConfiguration.class).from(UppercaseProcessor.class) - .namespace("upper").to(SuffixProcessor.class).namespace("suffix").run(); + ConfigurableApplicationContext context = new AggregateApplicationBuilder( + TestSupportBinderAutoConfiguration.class).from(UppercaseProcessor.class) + .namespace("upper").to(SuffixProcessor.class).namespace("suffix").run(); AggregateApplication aggregateAccessor = context.getBean(AggregateApplication.class); MessageCollector messageCollector = context.getBean(MessageCollector.class); @@ -61,7 +62,6 @@ public class AggregateWithMainTest { @EnableBinding(Processor.class) public static class UppercaseProcessor { - @Autowired Processor processor; diff --git a/spring-cloud-stream-test-support/src/test/java/org/springframework/cloud/stream/test/example/ExampleTest.java b/spring-cloud-stream-test-support/src/test/java/org/springframework/cloud/stream/test/example/ExampleTest.java index e6fbfcea4..70f8c92d7 100644 --- a/spring-cloud-stream-test-support/src/test/java/org/springframework/cloud/stream/test/example/ExampleTest.java +++ b/spring-cloud-stream-test-support/src/test/java/org/springframework/cloud/stream/test/example/ExampleTest.java @@ -36,11 +36,12 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.assertj.core.api.Assertions.assertThat; /** - * Integration test that validates that {@link org.springframework.cloud.stream.test.binder.TestSupportBinder} applies + * Integration test that validates that + * {@link org.springframework.cloud.stream.test.binder.TestSupportBinder} applies * correctly. */ @RunWith(SpringJUnit4ClassRunner.class) -@SpringBootTest(classes = ExampleTest.MyProcessor.class, properties = {"server.port=-1"}) +@SpringBootTest(classes = ExampleTest.MyProcessor.class, properties = { "server.port=-1" }) @DirtiesContext public class ExampleTest { @@ -63,7 +64,6 @@ public class ExampleTest { assertThat(received.getPayload()).isEqualTo("hello world"); } - @SpringBootApplication @EnableBinding(Processor.class) public static class MyProcessor { diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/aggregate/AggregateApplication.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/aggregate/AggregateApplication.java index cf9633cc9..16efe4926 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/aggregate/AggregateApplication.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/aggregate/AggregateApplication.java @@ -17,15 +17,16 @@ package org.springframework.cloud.stream.aggregate; /** - * Handle to an aggregate application, providing access to the underlying - * components of the aggregate (e.g. bindable instances). + * Handle to an aggregate application, providing access to the underlying components of + * the aggregate (e.g. bindable instances). * * @author Marius Bogoevici */ public interface AggregateApplication { /** - * Retrieves the bindable proxy instance (e.g. {@link org.springframework.cloud.stream.messaging.Processor}, + * Retrieves the bindable proxy instance (e.g. + * {@link org.springframework.cloud.stream.messaging.Processor}, * {@link org.springframework.cloud.stream.messaging.Source}, * {@link org.springframework.cloud.stream.messaging.Sink} or custom interface) from * the given namespace. diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/aggregate/AggregateApplicationBuilder.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/aggregate/AggregateApplicationBuilder.java index a5c3cffa7..bce346eec 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/aggregate/AggregateApplicationBuilder.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/aggregate/AggregateApplicationBuilder.java @@ -61,7 +61,7 @@ import org.springframework.util.StringUtils; */ @EnableBinding public class AggregateApplicationBuilder implements AggregateApplication, ApplicationContextAware, - SmartInitializingSingleton { + SmartInitializingSingleton { private static final String CHILD_CONTEXT_SUFFIX = ".spring.cloud.stream.context"; @@ -84,11 +84,11 @@ public class AggregateApplicationBuilder implements AggregateApplication, Applic private boolean webEnvironment = true; public AggregateApplicationBuilder(String... args) { - this(new Object[]{ParentConfiguration.class}, args); + this(new Object[] { ParentConfiguration.class }, args); } public AggregateApplicationBuilder(Object source, String... args) { - this(new Object[]{source}, args); + this(new Object[] { source }, args); } public AggregateApplicationBuilder(Object[] sources, String[] args) { @@ -108,7 +108,7 @@ public class AggregateApplicationBuilder implements AggregateApplication, Applic } public AggregateApplicationBuilder parent(Object source, String... args) { - return parent(new Object[]{source}, args); + return parent(new Object[] { source }, args); } public AggregateApplicationBuilder parent(Object[] sources, String[] args) { @@ -194,16 +194,18 @@ public class AggregateApplicationBuilder implements AggregateApplication, Applic Class appToEmbed = appConfigurer.getApp(); // Always update namespace before preparing SharedChannelRegistry if (appConfigurer.namespace == null) { - appConfigurer.namespace = AggregateApplicationUtils.getDefaultNamespace(appConfigurer.getApp().getName(), i); + appConfigurer.namespace = AggregateApplicationUtils + .getDefaultNamespace(appConfigurer.getApp().getName(), i); } appsToEmbed.put(appToEmbed, appConfigurer.namespace); appConfigurers.put(appConfigurer, appConfigurer.namespace); } if (this.parentContext == null) { if (Boolean.TRUE.equals(this.webEnvironment)) { - this.addParentSources(new Object[]{EmbeddedServletContainerAutoConfiguration.class}); + this.addParentSources(new Object[] { EmbeddedServletContainerAutoConfiguration.class }); } - this.parentContext = AggregateApplicationUtils.createParentContext(this.parentSources.toArray(new Object[0]), + this.parentContext = AggregateApplicationUtils.createParentContext( + this.parentSources.toArray(new Object[0]), this.parentArgs.toArray(new String[0]), selfContained(), this.webEnvironment, this.headless); } else { @@ -216,7 +218,8 @@ public class AggregateApplicationBuilder implements AggregateApplication, Applic new SharedChannelRegistry(sharedBindingTargetRegistry)); } } - SharedBindingTargetRegistry sharedBindingTargetRegistry = this.parentContext.getBean(SharedBindingTargetRegistry.class); + SharedBindingTargetRegistry sharedBindingTargetRegistry = this.parentContext + .getBean(SharedBindingTargetRegistry.class); AggregateApplicationUtils.prepareSharedBindingTargetRegistry(sharedBindingTargetRegistry, appsToEmbed); PropertySources propertySources = this.parentContext.getEnvironment() .getPropertySources(); @@ -291,6 +294,36 @@ public class AggregateApplicationBuilder implements AggregateApplication, Applic return new ChildContextBuilder(AggregateApplicationUtils.embedApp(parentContext, namespace, app)); } + private static class ChildContextHolder { + + private final ConfigurableApplicationContext childContext; + + ChildContextHolder(ConfigurableApplicationContext childContext) { + Assert.notNull(childContext, "cannot be null"); + this.childContext = childContext; + } + + public ConfigurableApplicationContext getChildContext() { + return childContext; + } + } + + @ImportAutoConfiguration({ ChannelBindingAutoConfiguration.class, EndpointAutoConfiguration.class }) + @EnableBinding + public static class ParentConfiguration { + @Bean + @ConditionalOnMissingBean(SharedBindingTargetRegistry.class) + public SharedBindingTargetRegistry sharedBindingTargetRegistry() { + return new SharedBindingTargetRegistry(); + } + + @Bean + @ConditionalOnMissingBean(SharedChannelRegistry.class) + public SharedChannelRegistry sharedChannelRegistry(SharedBindingTargetRegistry sharedBindingTargetRegistry) { + return new SharedChannelRegistry(sharedBindingTargetRegistry); + } + } + public class SourceConfigurer extends AppConfigurer { public SourceConfigurer(Class app) { @@ -382,7 +415,7 @@ public class AggregateApplicationBuilder implements AggregateApplication, Applic void embed() { final ConfigurableApplicationContext childContext = childContext(this.app, AggregateApplicationBuilder.this.parentContext, this.namespace).args(this.args).config(this.names) - .profiles(this.profiles).run(); + .profiles(this.profiles).run(); // Register bindable proxies as beans so they can be queried for later Map bindableProxies = BeanFactoryUtils .beansOfTypeIncludingAncestors(childContext.getBeanFactory(), BindableProxyFactory.class); @@ -402,7 +435,8 @@ public class AggregateApplicationBuilder implements AggregateApplication, Applic if (BeanFactoryUtils.beansOfTypeIncludingAncestors(AggregateApplicationBuilder.this.parentContext, IntegrationMBeanExporter.class).size() > 0) { BeanFactoryUtils - .beanOfTypeIncludingAncestors(AggregateApplicationBuilder.this.parentContext, MetricsEndpoint.class) + .beanOfTypeIncludingAncestors(AggregateApplicationBuilder.this.parentContext, + MetricsEndpoint.class) .registerPublicMetrics( new MetricReaderPublicMetrics(new NamespaceAwareSpringIntegrationMetricReader( this.namespace, childContext.getBean(IntegrationMBeanExporter.class)))); @@ -413,7 +447,6 @@ public class AggregateApplicationBuilder implements AggregateApplication, Applic return applicationBuilder; } - public String[] getArgs() { return this.args; } @@ -467,34 +500,4 @@ public class AggregateApplicationBuilder implements AggregateApplication, Applic } - private static class ChildContextHolder { - - private final ConfigurableApplicationContext childContext; - - ChildContextHolder(ConfigurableApplicationContext childContext) { - Assert.notNull(childContext, "cannot be null"); - this.childContext = childContext; - } - - public ConfigurableApplicationContext getChildContext() { - return childContext; - } - } - - @ImportAutoConfiguration({ChannelBindingAutoConfiguration.class, EndpointAutoConfiguration.class}) - @EnableBinding - public static class ParentConfiguration { - @Bean - @ConditionalOnMissingBean(SharedBindingTargetRegistry.class) - public SharedBindingTargetRegistry sharedBindingTargetRegistry() { - return new SharedBindingTargetRegistry(); - } - - @Bean - @ConditionalOnMissingBean(SharedChannelRegistry.class) - public SharedChannelRegistry sharedChannelRegistry(SharedBindingTargetRegistry sharedBindingTargetRegistry) { - return new SharedChannelRegistry(sharedBindingTargetRegistry); - } - } - } diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/aggregate/NamespaceAwareSpringIntegrationMetricReader.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/aggregate/NamespaceAwareSpringIntegrationMetricReader.java index 2982c3b9f..6cdc70fd1 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/aggregate/NamespaceAwareSpringIntegrationMetricReader.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/aggregate/NamespaceAwareSpringIntegrationMetricReader.java @@ -27,11 +27,13 @@ import org.springframework.integration.support.management.Statistics; import org.springframework.util.Assert; /** - * A customized version of {@link org.springframework.boot.actuate.metrics.integration.SpringIntegrationMetricReader} that - * provides support for customizing channels with a namespace prefix. + * A customized version of + * {@link org.springframework.boot.actuate.metrics.integration.SpringIntegrationMetricReader} + * that provides support for customizing channels with a namespace prefix. * * @author Marius Bogoevici - * @see org.springframework.boot.actuate.metrics.integration.SpringIntegrationMetricReader for original implementation + * @see org.springframework.boot.actuate.metrics.integration.SpringIntegrationMetricReader + * for original implementation */ public class NamespaceAwareSpringIntegrationMetricReader implements MetricReader { @@ -101,4 +103,3 @@ public class NamespaceAwareSpringIntegrationMetricReader implements MetricReader } } - diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/annotation/Bindings.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/annotation/Bindings.java index 30c89f0a1..3c584a77b 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/annotation/Bindings.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/annotation/Bindings.java @@ -26,13 +26,13 @@ import java.lang.annotation.Target; import org.springframework.beans.factory.annotation.Qualifier; /** - * Indicates an instance of an interface containing methods returning bound - * inputs and outputs. + * Indicates an instance of an interface containing methods returning bound inputs and + * outputs. * * @author Dave Syer * @author Marius Bogoevici - * @deprecated As of 1.1 for being redundant (beans qualified by it are already - * uniquely identified by their type) + * @deprecated As of 1.1 for being redundant (beans qualified by it are already uniquely + * identified by their type) */ @Qualifier diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/annotation/Input.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/annotation/Input.java index 7dd88c120..35c4767b7 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/annotation/Input.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/annotation/Input.java @@ -34,7 +34,7 @@ import org.springframework.beans.factory.annotation.Qualifier; @Qualifier @Target({ ElementType.FIELD, ElementType.METHOD, - ElementType.ANNOTATION_TYPE, ElementType.PARAMETER }) + ElementType.ANNOTATION_TYPE, ElementType.PARAMETER }) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/annotation/StreamListener.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/annotation/StreamListener.java index 15834c082..172396f43 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/annotation/StreamListener.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/annotation/StreamListener.java @@ -141,7 +141,7 @@ public @interface StreamListener { * @return the name of the binding target. */ @AliasFor("value") - String target() default ""; + String target() default ""; /** * A condition that must be met by all items that are dispatched to this method. diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractBinder.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractBinder.java index 418eac37e..5772c1049 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractBinder.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/AbstractBinder.java @@ -68,12 +68,12 @@ public abstract class AbstractBinder> payloadTypeCache = new ConcurrentHashMap<>(); @@ -82,7 +82,7 @@ public abstract class AbstractBinder - *

  • {@link #createProducerMessageHandler(ProducerDestination, ProducerProperties)}
  • - *
  • {@link #createConsumerEndpoint(ConsumerDestination, String, ConsumerProperties)}
  • + *
  • {@link #createProducerMessageHandler(ProducerDestination, ProducerProperties)}
  • + *
  • {@link #createConsumerEndpoint(ConsumerDestination, String, ConsumerProperties)} + *
  • *
* - * @param the consumer properties type - * @param

the producer properties type + * @param the consumer properties type + * @param

the producer properties type * @author Marius Bogoevici * @author Ilayaperumal Gopinathan * @author Soby Chacko @@ -59,9 +60,13 @@ public abstract class AbstractMessageChannelBinder(destination, null, outputChannel, producerMessageHandler instanceof Lifecycle ? (Lifecycle) producerMessageHandler : null) { @@ -139,8 +142,10 @@ public abstract class AbstractMessageChannelBinder - * In order to be fully compliant, the {@link MessageHandler} of the binder - * must observe the following headers: + * In order to be fully compliant, the {@link MessageHandler} of the binder must + * observe the following headers: *

    - *
  • {@link BinderHeaders#PARTITION_HEADER} - indicates the target - * partition where the message must be sent
  • + *
  • {@link BinderHeaders#PARTITION_HEADER} - indicates the target partition where + * the message must be sent
  • *
*

* - * @param destination the name of the target destination + * @param destination the name of the target destination * @param producerProperties the producer properties * @return the message handler for sending data to the target middleware * @throws Exception */ - protected abstract MessageHandler createProducerMessageHandler(ProducerDestination destination, P producerProperties) + protected abstract MessageHandler createProducerMessageHandler(ProducerDestination destination, + P producerProperties) throws Exception; /** * Invoked after the unbinding of a producer. Subclasses may override this to provide * their own logic for dealing with unbinding. * - * @param destination the bound destination + * @param destination the bound destination * @param producerProperties the producer properties */ protected void afterUnbindProducer(ProducerDestination destination, P producerProperties) { @@ -181,16 +187,17 @@ public abstract class AbstractMessageChannelBinder message) throws Exception { - Message messageToSend = (this.useNativeEncoding) ? - message : serializeAndEmbedHeadersIfApplicable(message); + Message messageToSend = (this.useNativeEncoding) ? message + : serializeAndEmbedHeadersIfApplicable(message); this.delegate.handleMessage(messageToSend); } @@ -348,7 +357,8 @@ public abstract class AbstractMessageChannelBinder { /** - * Unbinds the target component represented by this instance and stops any active components. - * Implementations must be idempotent. After this method is invoked, the target is not expected - * to receive any messages; this instance should be discarded, and a new Binding should be - * created instead. + * Unbinds the target component represented by this instance and stops any active + * components. Implementations must be idempotent. After this method is invoked, the + * target is not expected to receive any messages; this instance should be discarded, + * and a new Binding should be created instead. */ void unbind(); } diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/BindingCleaner.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/BindingCleaner.java index 09933768e..0477165a6 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/BindingCleaner.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/BindingCleaner.java @@ -19,7 +19,6 @@ package org.springframework.cloud.stream.binder; import java.util.List; import java.util.Map; - /** * Interface for implementations that perform cleanup for binders. * @@ -30,8 +29,9 @@ public interface BindingCleaner { /** * Clean up all resources for the supplied stream/job. - * @param entity the stream or job; may be terminated with a simple wild card '*', in which - * case all streams with names starting with the characters before the '*' will be cleaned. + * @param entity the stream or job; may be terminated with a simple wild card '*', in + * which case all streams with names starting with the characters before the '*' will + * be cleaned. * @param isJob true if the entity is a job. * @return a map of lists of resources removed. */ diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ConsumerProperties.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ConsumerProperties.java index cd80cd07f..e94cfe1c4 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ConsumerProperties.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ConsumerProperties.java @@ -82,17 +82,13 @@ public class ConsumerProperties { this.instanceIndex = instanceIndex; } - public void setMaxAttempts(int maxAttempts) { - this.maxAttempts = maxAttempts; - } - @Min(value = 1, message = "Max attempts should be greater than zero.") public int getMaxAttempts() { return maxAttempts; } - public void setBackOffInitialInterval(int backOffInitialInterval) { - this.backOffInitialInterval = backOffInitialInterval; + public void setMaxAttempts(int maxAttempts) { + this.maxAttempts = maxAttempts; } @Min(value = 1, message = "Backoff initial interval should be greater than zero.") @@ -100,8 +96,8 @@ public class ConsumerProperties { return backOffInitialInterval; } - public void setBackOffMaxInterval(int backOffMaxInterval) { - this.backOffMaxInterval = backOffMaxInterval; + public void setBackOffInitialInterval(int backOffInitialInterval) { + this.backOffInitialInterval = backOffInitialInterval; } @Min(value = 1, message = "Backoff max interval should be greater than zero.") @@ -109,8 +105,8 @@ public class ConsumerProperties { return backOffMaxInterval; } - public void setBackOffMultiplier(double backOffMultiplier) { - this.backOffMultiplier = backOffMultiplier; + public void setBackOffMaxInterval(int backOffMaxInterval) { + this.backOffMaxInterval = backOffMaxInterval; } @Min(value = 1, message = "Backoff multiplier should be greater than zero.") @@ -118,6 +114,10 @@ public class ConsumerProperties { return backOffMultiplier; } + public void setBackOffMultiplier(double backOffMultiplier) { + this.backOffMultiplier = backOffMultiplier; + } + public HeaderMode getHeaderMode() { return this.headerMode; } @@ -126,4 +126,3 @@ public class ConsumerProperties { this.headerMode = headerMode; } } - diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/DefaultBinderFactory.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/DefaultBinderFactory.java index ffd34065f..eb692949d 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/DefaultBinderFactory.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/DefaultBinderFactory.java @@ -218,6 +218,25 @@ public class DefaultBinderFactory implements BinderFactory, DisposableBean, Appl return (Binder) this.binderInstanceCache.get(configurationName).getBinderInstance(); } + /** + * A listener that can be registered with the {@link DefaultBinderFactory} that allows + * the registration of additional configuration. + * + * @author Ilayaperumal Gopinathan + */ + public interface Listener { + + /** + * Applying additional capabilities to the binder after the binder context has + * been initialized. + * + * @param configurationName the binder configuration name + * @param binderContext the application context of the binder + */ + void afterBinderContextInitialized(String configurationName, + ConfigurableApplicationContext binderContext); + } + /** * Utility class for storing {@link Binder} instances, along with their associated * contexts. @@ -241,23 +260,4 @@ public class DefaultBinderFactory implements BinderFactory, DisposableBean, Appl return this.binderContext; } } - - /** - * A listener that can be registered with the {@link DefaultBinderFactory} that - * allows the registration of additional configuration. - * - * @author Ilayaperumal Gopinathan - */ - public interface Listener { - - /** - * Applying additional capabilities to the binder after the binder context - * has been initialized. - * - * @param configurationName the binder configuration name - * @param binderContext the application context of the binder - */ - void afterBinderContextInitialized(String configurationName, - ConfigurableApplicationContext binderContext); - } } diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/DefaultBinding.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/DefaultBinding.java index 1d18f70e9..bab7864aa 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/DefaultBinding.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/DefaultBinding.java @@ -46,8 +46,8 @@ public class DefaultBinding implements Binding { * @param name the name of the binding target * @param group the group (only for input targets) * @param target the binding target - * @param lifecycle {@link Lifecycle} that runs while the - * binding is active and will be stopped during unbinding + * @param lifecycle {@link Lifecycle} that runs while the binding is active and will + * be stopped during unbinding */ public DefaultBinding(String name, String group, T target, Lifecycle lifecycle) { Assert.notNull(target, "target must not be null"); diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ExtendedBindingProperties.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ExtendedBindingProperties.java index afb24d332..d50aa7a09 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ExtendedBindingProperties.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ExtendedBindingProperties.java @@ -17,7 +17,8 @@ package org.springframework.cloud.stream.binder; /** - * Properties that extend the common binding properties for a particular binder implementation. + * Properties that extend the common binding properties for a particular binder + * implementation. * * @author Marius Bogoevici * @author Mark Fisher diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ExtendedConsumerProperties.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ExtendedConsumerProperties.java index a203f4038..afa168306 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ExtendedConsumerProperties.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ExtendedConsumerProperties.java @@ -17,7 +17,8 @@ package org.springframework.cloud.stream.binder; /** - * Extension of {@link ConsumerProperties} to be used with an {@link ExtendedPropertiesBinder}. + * Extension of {@link ConsumerProperties} to be used with an + * {@link ExtendedPropertiesBinder}. * * @author Marius Bogoevici */ diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ExtendedPropertiesBinder.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ExtendedPropertiesBinder.java index 7c9d2835c..453d2805a 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ExtendedPropertiesBinder.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/ExtendedPropertiesBinder.java @@ -17,13 +17,15 @@ package org.springframework.cloud.stream.binder; /** - * Extension of {@link Binder} that takes {@link ExtendedConsumerProperties} and {@link ExtendedProducerProperties} - * as arguments. In addition to supporting binding operations, it allows the binder to provide values for the - * additional properties it expects on the bindings. + * Extension of {@link Binder} that takes {@link ExtendedConsumerProperties} and + * {@link ExtendedProducerProperties} as arguments. In addition to supporting binding + * operations, it allows the binder to provide values for the additional properties it + * expects on the bindings. * * @author Marius Bogoevici */ public interface ExtendedPropertiesBinder - extends Binder, ExtendedProducerProperties

>, ExtendedBindingProperties { + extends Binder, ExtendedProducerProperties

>, + ExtendedBindingProperties { } diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/MessageValues.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/MessageValues.java index 5ac76634d..ef6e93e3d 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/MessageValues.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/MessageValues.java @@ -27,8 +27,8 @@ import org.springframework.messaging.Message; import org.springframework.util.Assert; /** - * A mutable type for allowing {@link Binder} implementations to transform and enrich message content more - * efficiently. + * A mutable type for allowing {@link Binder} implementations to transform and enrich + * message content more efficiently. * @author David Turanski * @author Marius Bogoevici */ @@ -61,28 +61,6 @@ public class MessageValues implements Map { return payload; } - public Map getHeaders() { - return headers; - } - - /** - * Convert to a {@link Message} using a {@link org.springframework.integration.support.MessageBuilderFactory}. - * @param messageBuilderFactory the MessageBuilderFactory - * @return the Message - */ - public Message toMessage(MessageBuilderFactory messageBuilderFactory) { - return messageBuilderFactory.withPayload(this.payload).copyHeaders(this.headers).build(); - } - - - /** - * Convert to a {@link Message} using a the default {@link org.springframework.integration.support.MessageBuilder}. - * @return the Message - */ - public Message toMessage() { - return MessageBuilder.withPayload(this.payload).copyHeaders(this.headers).build(); - } - /** * Set the payload * @param payload any non null object. @@ -92,6 +70,29 @@ public class MessageValues implements Map { this.payload = payload; } + public Map getHeaders() { + return headers; + } + + /** + * Convert to a {@link Message} using a + * {@link org.springframework.integration.support.MessageBuilderFactory}. + * @param messageBuilderFactory the MessageBuilderFactory + * @return the Message + */ + public Message toMessage(MessageBuilderFactory messageBuilderFactory) { + return messageBuilderFactory.withPayload(this.payload).copyHeaders(this.headers).build(); + } + + /** + * Convert to a {@link Message} using a the default + * {@link org.springframework.integration.support.MessageBuilder}. + * @return the Message + */ + public Message toMessage() { + return MessageBuilder.withPayload(this.payload).copyHeaders(this.headers).build(); + } + @Override public int size() { return headers.size(); diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/PartitionHandler.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/PartitionHandler.java index 49b7d25d5..7deb85575 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/PartitionHandler.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/PartitionHandler.java @@ -21,9 +21,9 @@ import org.springframework.messaging.Message; import org.springframework.util.Assert; /** - * Utility class to determine if a binding is configured for partitioning - * (based on the binder properties provided in the constructor) and - * what partition a message should be delivered to. + * Utility class to determine if a binding is configured for partitioning (based on the + * binder properties provided in the constructor) and what partition a message should be + * delivered to. * * @author Patrick Peralta * @author David Turanski @@ -45,10 +45,10 @@ public class PartitionHandler { /** * Construct a {@code PartitionHandler}. * - * @param evaluationContext evaluation context for binder - * @param properties binder properties + * @param evaluationContext evaluation context for binder + * @param properties binder properties * @param partitionKeyExtractorStrategy PartitionKeyExtractor strategy - * @param partitionSelectorStrategy PartitionSelector strategy + * @param partitionSelectorStrategy PartitionSelector strategy */ public PartitionHandler(EvaluationContext evaluationContext, ProducerProperties properties, @@ -63,17 +63,16 @@ public class PartitionHandler { /** * Determine the partition to which to send this message. *

- * If a partition key extractor class is provided, it is invoked to determine - * the key. Otherwise, the partition key expression is evaluated to obtain the - * key value. + * If a partition key extractor class is provided, it is invoked to determine the key. + * Otherwise, the partition key expression is evaluated to obtain the key value. *

* If a partition selector class is provided, it will be invoked to determine the * partition. Otherwise, if the partition expression is not null, it is evaluated - * against the key and is expected to return an integer to which the modulo - * function will be applied, using the {@code partitionCount} as the divisor. If no - * partition expression is provided, the key will be passed to the binder - * partition strategy along with the {@code partitionCount}. The default partition - * strategy uses {@code key.hashCode()}, and the result will be the mod of that value. + * against the key and is expected to return an integer to which the modulo function + * will be applied, using the {@code partitionCount} as the divisor. If no partition + * expression is provided, the key will be passed to the binder partition strategy + * along with the {@code partitionCount}. The default partition strategy uses + * {@code key.hashCode()}, and the result will be the mod of that value. * * @param message the message. * @return the partition diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/PartitionSelectorStrategy.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/PartitionSelectorStrategy.java index 3bfdf1424..79eb0cd44 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/PartitionSelectorStrategy.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binder/PartitionSelectorStrategy.java @@ -16,7 +16,6 @@ package org.springframework.cloud.stream.binder; - /** * Strategy for determining the partition to which a message should be sent. * @@ -25,11 +24,11 @@ package org.springframework.cloud.stream.binder; public interface PartitionSelectorStrategy { /** - * Determine the partition based on a key. The partitionCount is 1 greater - * than the maximum value of a valid partition. Typical implementations - * will return {@code someValue % partitionCount}. The caller will apply - * that same modulo operation (as well as enforcing absolute value) if the - * value exceeds partitionCount - 1. + * Determine the partition based on a key. The partitionCount is 1 greater than the + * maximum value of a valid partition. Typical implementations will return + * {@code someValue % partitionCount}. The caller will apply that same modulo + * operation (as well as enforcing absolute value) if the value exceeds partitionCount + * - 1. * * @param key the key * @param partitionCount the number of partitions diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/BindableAdapter.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/BindableAdapter.java index 35cbc6c0d..3ed30dc27 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/BindableAdapter.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/BindableAdapter.java @@ -26,7 +26,6 @@ import java.util.Set; */ public class BindableAdapter implements Bindable { - @Override public void bindInputs(BindingService adapter) { } diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/BindableProxyFactory.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/BindableProxyFactory.java index acf6167db..6e58cdf89 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/BindableProxyFactory.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/BindableProxyFactory.java @@ -57,6 +57,8 @@ public class BindableProxyFactory implements MethodInterceptor, FactoryBean targetCache = new HashMap<>(2); + @Value("${" + InternalPropertyNames.NAMESPACE_PROPERTY_NAME + ":}") private String namespace; @@ -74,8 +76,6 @@ public class BindableProxyFactory implements MethodInterceptor, FactoryBean outputHolders = new HashMap<>(); - private final Map targetCache = new HashMap<>(2); - public BindableProxyFactory(Class type) { this.type = type; } @@ -93,7 +93,7 @@ public class BindableProxyFactory implements MethodInterceptor, FactoryBean> producerBindings = new HashMap<>(); private final Map>> consumerBindings = new HashMap<>(); + private BinderFactory binderFactory; + public BindingService( BindingServiceProperties bindingServiceProperties, BinderFactory binderFactory) { diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/ContextStartAfterRefreshListener.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/ContextStartAfterRefreshListener.java index 37012c2b1..752915f5b 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/ContextStartAfterRefreshListener.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/ContextStartAfterRefreshListener.java @@ -28,7 +28,8 @@ import org.springframework.context.event.ContextRefreshedEvent; * * @author Marius Bogoevici */ -public class ContextStartAfterRefreshListener implements ApplicationListener, ApplicationContextAware { +public class ContextStartAfterRefreshListener + implements ApplicationListener, ApplicationContextAware { private ApplicationContext applicationContext; diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/DispatchingStreamListenerMessageHandler.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/DispatchingStreamListenerMessageHandler.java index 131ceb2e7..563c83f45 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/DispatchingStreamListenerMessageHandler.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/DispatchingStreamListenerMessageHandler.java @@ -28,9 +28,9 @@ import org.springframework.messaging.MessagingException; import org.springframework.util.Assert; /** - * An {@link AbstractReplyProducingMessageHandler} that delegates to a - * collection of internal {@link ConditionalStreamListenerHandler} instances, - * executing the ones that match the given expression. + * An {@link AbstractReplyProducingMessageHandler} that delegates to a collection of + * internal {@link ConditionalStreamListenerHandler} instances, executing the ones that + * match the given expression. * * @author Marius Bogoevici * @since 1.2 diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/DynamicDestinationsBindable.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/DynamicDestinationsBindable.java index f6fc05ab9..cc1abc54d 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/DynamicDestinationsBindable.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/DynamicDestinationsBindable.java @@ -24,7 +24,8 @@ import java.util.Set; import org.springframework.cloud.stream.binder.Binding; /** - * A {@link BindableAdapter} that stores the dynamic destination names and handles their unbinding. + * A {@link BindableAdapter} that stores the dynamic destination names and handles their + * unbinding. * * This class is not thread-safe. * @@ -48,7 +49,7 @@ public final class DynamicDestinationsBindable extends BindableAdapter { @Override public void unbindOutputs(BindingService adapter) { - for (Map.Entry entry: outputBindings.entrySet()) { + for (Map.Entry entry : outputBindings.entrySet()) { entry.getValue().unbind(); } outputBindings.clear(); diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/MessageChannelConfigurer.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/MessageChannelConfigurer.java index 936c6c106..ffd6d40fa 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/MessageChannelConfigurer.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/MessageChannelConfigurer.java @@ -19,7 +19,8 @@ package org.springframework.cloud.stream.binding; import org.springframework.messaging.MessageChannel; /** - * Interface to be implemented by the classes that configure the {@link Bindable} message channels. + * Interface to be implemented by the classes that configure the {@link Bindable} message + * channels. * @author Ilayaperumal Gopinathan */ public interface MessageChannelConfigurer { @@ -27,14 +28,14 @@ public interface MessageChannelConfigurer { /** * Configure the given input message channel. * @param messageChannel the message channel - * @param channelName name of the message channel + * @param channelName name of the message channel */ void configureInputChannel(MessageChannel messageChannel, String channelName); /** * Configure the given output message channel. * @param messageChannel the message channel - * @param channelName name of the message channel + * @param channelName name of the message channel */ void configureOutputChannel(MessageChannel messageChannel, String channelName); } diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/MessageChannelStreamListenerResultAdapter.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/MessageChannelStreamListenerResultAdapter.java index 337c3d007..e6d6bb629 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/MessageChannelStreamListenerResultAdapter.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/MessageChannelStreamListenerResultAdapter.java @@ -21,8 +21,9 @@ import org.springframework.messaging.MessageChannel; import org.springframework.messaging.SubscribableChannel; /** - * A {@link StreamListenerResultAdapter} used for bridging an {@link org.springframework.cloud.stream.annotation.Output} - * {@link MessageChannel} to a bound {@link MessageChannel}. + * A {@link StreamListenerResultAdapter} used for bridging an + * {@link org.springframework.cloud.stream.annotation.Output} {@link MessageChannel} to a + * bound {@link MessageChannel}. * @author Marius Bogoevici */ public class MessageChannelStreamListenerResultAdapter diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/MessageConverterConfigurer.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/MessageConverterConfigurer.java index 6d1f724a1..88336823c 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/MessageConverterConfigurer.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/MessageConverterConfigurer.java @@ -16,7 +16,6 @@ package org.springframework.cloud.stream.binding; - import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; @@ -51,11 +50,11 @@ import org.springframework.util.MimeType; import org.springframework.util.StringUtils; /** - * A {@link MessageChannelConfigurer} that sets data types and message converters based on {@link - * org.springframework.cloud.stream.config.BindingProperties#contentType}. Also adds a - * {@link org.springframework.messaging.support.ChannelInterceptor} to - * the message channel to set the `ContentType` header for the message (if not already set) based on the `ContentType` - * binding property of the channel. + * A {@link MessageChannelConfigurer} that sets data types and message converters based on + * {@link org.springframework.cloud.stream.config.BindingProperties#contentType}. Also + * adds a {@link org.springframework.messaging.support.ChannelInterceptor} to the message + * channel to set the `ContentType` header for the message (if not already set) based on + * the `ContentType` binding property of the channel. * * @author Ilayaperumal Gopinathan * @author Marius Bogoevici @@ -66,12 +65,12 @@ public class MessageConverterConfigurer implements MessageChannelConfigurer, Bea private final MessageBuilderFactory messageBuilderFactory = new MutableMessageBuilderFactory(); - private ConfigurableListableBeanFactory beanFactory; - private final CompositeMessageConverterFactory compositeMessageConverterFactory; private final BindingServiceProperties bindingServiceProperties; + private ConfigurableListableBeanFactory beanFactory; + public MessageConverterConfigurer(BindingServiceProperties bindingServiceProperties, CompositeMessageConverterFactory compositeMessageConverterFactory) { Assert.notNull(compositeMessageConverterFactory, "The message converter factory cannot be null"); @@ -102,7 +101,7 @@ public class MessageConverterConfigurer implements MessageChannelConfigurer, Bea /** * Setup data-type and message converters for the given message channel. * - * @param channel message channel to set the data-type and message converters + * @param channel message channel to set the data-type and message converters * @param channelName the channel name */ private void configureMessageChannel(MessageChannel channel, String channelName, boolean input) { @@ -114,7 +113,8 @@ public class MessageConverterConfigurer implements MessageChannelConfigurer, Bea ProducerProperties producerProperties = bindingProperties.getProducer(); if (!input && producerProperties != null && producerProperties.isPartitioned()) { messageChannel.addInterceptor(new PartitioningInterceptor(bindingProperties, - getPartitionKeyExtractorStrategy(producerProperties), getPartitionSelectorStrategy(producerProperties))); + getPartitionKeyExtractorStrategy(producerProperties), + getPartitionSelectorStrategy(producerProperties))); } if (StringUtils.hasText(contentType)) { messageChannel.addInterceptor(new ContentTypeConvertingInterceptor(contentType, input)); @@ -168,6 +168,23 @@ public class MessageConverterConfigurer implements MessageChannelConfigurer, Bea } } + /** + * Default partition strategy; only works on keys with "real" hash codes, such as + * String. Caller now always applies modulo so no need to do so here. + */ + private static class DefaultPartitionSelector implements PartitionSelectorStrategy { + + @Override + public int selectPartition(Object key, int partitionCount) { + int hashCode = key.hashCode(); + if (hashCode == Integer.MIN_VALUE) { + hashCode = 0; + } + return Math.abs(hashCode); + } + + } + private final class ContentTypeConvertingInterceptor extends ChannelInterceptorAdapter { private final String contentType; @@ -187,9 +204,8 @@ public class MessageConverterConfigurer implements MessageChannelConfigurer, Bea this.mimeType = MessageConverterUtils.getMimeType(contentType); this.input = input; if (MessageConverterUtils.X_JAVA_OBJECT.includes(this.mimeType)) { - this.klazz = - MessageConverterUtils - .getJavaTypeForJavaObjectContentType(this.mimeType); + this.klazz = MessageConverterUtils + .getJavaTypeForJavaObjectContentType(this.mimeType); } else if (this.mimeType.equals(MessageConverterUtils.X_SPRING_TUPLE)) { this.klazz = Tuple.class; @@ -201,9 +217,8 @@ public class MessageConverterConfigurer implements MessageChannelConfigurer, Bea else { this.klazz = byte[].class; } - this.messageConverter = - MessageConverterConfigurer.this.compositeMessageConverterFactory - .getMessageConverterForType(this.mimeType); + this.messageConverter = MessageConverterConfigurer.this.compositeMessageConverterFactory + .getMessageConverterForType(this.mimeType); this.provideHint = this.messageConverter instanceof AbstractMessageConverter; } @@ -250,7 +265,8 @@ public class MessageConverterConfigurer implements MessageChannelConfigurer, Bea sentMessage = MessageConverterConfigurer.this.messageBuilderFactory.withPayload(converted) .copyHeaders(message.getHeaders()).setHeaderIfAbsent(MessageHeaders.CONTENT_TYPE, - this.mimeType).build(); + this.mimeType) + .build(); } } if (sentMessage == null) { @@ -270,7 +286,8 @@ public class MessageConverterConfigurer implements MessageChannelConfigurer, Bea PartitionKeyExtractorStrategy partitionKeyExtractorStrategy, PartitionSelectorStrategy partitionSelectorStrategy) { this.bindingProperties = bindingProperties; - this.partitionHandler = new PartitionHandler(ExpressionUtils.createStandardEvaluationContext(MessageConverterConfigurer.this.beanFactory), + this.partitionHandler = new PartitionHandler( + ExpressionUtils.createStandardEvaluationContext(MessageConverterConfigurer.this.beanFactory), this.bindingProperties.getProducer(), partitionKeyExtractorStrategy, partitionSelectorStrategy); } @@ -294,21 +311,4 @@ public class MessageConverterConfigurer implements MessageChannelConfigurer, Bea } } - /** - * Default partition strategy; only works on keys with "real" hash codes, - * such as String. Caller now always applies modulo so no need to do so here. - */ - private static class DefaultPartitionSelector implements PartitionSelectorStrategy { - - @Override - public int selectPartition(Object key, int partitionCount) { - int hashCode = key.hashCode(); - if (hashCode == Integer.MIN_VALUE) { - hashCode = 0; - } - return Math.abs(hashCode); - } - - } - } diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/StreamListenerAnnotationBeanPostProcessor.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/StreamListenerAnnotationBeanPostProcessor.java index 33c297c6b..660ca6ca0 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/StreamListenerAnnotationBeanPostProcessor.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/StreamListenerAnnotationBeanPostProcessor.java @@ -76,6 +76,12 @@ public class StreamListenerAnnotationBeanPostProcessor private static final SpelExpressionParser SPEL_EXPRESSION_PARSER = new SpelExpressionParser(); + private final MultiValueMap mappedListenerMethods = new LinkedMultiValueMap<>(); + + private final List> streamListenerParameterAdapters = new ArrayList<>(); + + private final List> streamListenerResultAdapters = new ArrayList<>(); + @Autowired @Lazy private DestinationResolver binderAwareChannelResolver; @@ -84,14 +90,8 @@ public class StreamListenerAnnotationBeanPostProcessor @Lazy private MessageHandlerMethodFactory messageHandlerMethodFactory; - private final MultiValueMap mappedListenerMethods = new LinkedMultiValueMap<>(); - private ConfigurableApplicationContext applicationContext; - private final List> streamListenerParameterAdapters = new ArrayList<>(); - - private final List> streamListenerResultAdapters = new ArrayList<>(); - private EvaluationContext evaluationContext; private BeanFactory beanFactory; @@ -101,7 +101,7 @@ public class StreamListenerAnnotationBeanPostProcessor private BeanExpressionContext expressionContext; @Override - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) public final void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = (ConfigurableApplicationContext) applicationContext; } @@ -141,7 +141,8 @@ public class StreamListenerAnnotationBeanPostProcessor ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() { @Override public void doWith(final Method method) throws IllegalArgumentException, IllegalAccessException { - StreamListener streamListener = AnnotatedElementUtils.findMergedAnnotation(method, StreamListener.class); + StreamListener streamListener = AnnotatedElementUtils.findMergedAnnotation(method, + StreamListener.class); if (streamListener != null && !method.isBridge()) { streamListener = postProcessAnnotation(streamListener, method); Assert.isTrue(method.getAnnotation(Input.class) == null, @@ -179,11 +180,11 @@ public class StreamListenerAnnotationBeanPostProcessor } /** - * Extension point, allowing subclasses to customize the {@link StreamListener} annotation detected by - * the postprocessor. + * Extension point, allowing subclasses to customize the {@link StreamListener} + * annotation detected by the postprocessor. * * @param originalAnnotation the original annotation - * @param annotatedMethod the method on which the annotation has been found + * @param annotatedMethod the method on which the annotation has been found * @return the postprocessed {@link StreamListener} annotation */ protected StreamListener postProcessAnnotation(StreamListener originalAnnotation, Method annotatedMethod) { @@ -228,7 +229,7 @@ public class StreamListenerAnnotationBeanPostProcessor Class targetBeanClass = this.applicationContext.getType(targetBeanName); if (!methodParameter.getParameterType().equals(Object.class) && (targetBeanClass.isAssignableFrom(methodParameter.getParameterType()) || - methodParameter.getParameterType().isAssignableFrom(targetBeanClass))) { + methodParameter.getParameterType().isAssignableFrom(targetBeanClass))) { return true; } } @@ -251,7 +252,7 @@ public class StreamListenerAnnotationBeanPostProcessor return false; } - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) private void invokeSetupMethodOnListenedChannel(Method method, Object bean, String inboundName, String outboundName) { Object[] arguments = new Object[method.getParameterTypes().length]; @@ -317,7 +318,8 @@ public class StreamListenerAnnotationBeanPostProcessor } } - protected final void registerHandlerMethodOnListenedChannel(Method method, StreamListener streamListener, Object bean) { + protected final void registerHandlerMethodOnListenedChannel(Method method, StreamListener streamListener, + Object bean) { Assert.hasText(streamListener.value(), "The binding name cannot be null"); if (!StringUtils.hasText(streamListener.value())) { throw new BeanInitializationException("A bound component name must be specified"); diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/StreamListenerErrorMessages.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/StreamListenerErrorMessages.java index 5f8c927a7..09b670247 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/StreamListenerErrorMessages.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/StreamListenerErrorMessages.java @@ -21,18 +21,6 @@ package org.springframework.cloud.stream.binding; */ public abstract class StreamListenerErrorMessages { - private static final String PREFIX = "A method annotated with @StreamListener "; - - public static final String INPUT_AT_STREAM_LISTENER = PREFIX - + "may never be annotated with @Input. " - + "If it should listen to a specific input, use the value of @StreamListener instead"; - - public static final String RETURN_TYPE_NO_OUTBOUND_SPECIFIED = PREFIX - + "having a return type should also have an outbound target specified"; - - public static final String RETURN_TYPE_MULTIPLE_OUTBOUND_SPECIFIED = PREFIX - + "having a return type should have only one outbound target specified"; - public static final String INVALID_INBOUND_NAME = "The @Input annotation must have the name of an input as value"; public static final String INVALID_OUTBOUND_NAME = "The @Output annotation must have the name of an input as value"; @@ -48,9 +36,6 @@ public abstract class StreamListenerErrorMessages { public static final String NO_INPUT_DESTINATION = "No input destination is configured. Use either the @StreamListener value or @Input"; - public static final String INVALID_DECLARATIVE_METHOD_PARAMETERS = PREFIX - + "may use @Input or @Output annotations only in declarative mode and for parameters that are binding targets or convertible from binding targets."; - public static final String AMBIGUOUS_MESSAGE_HANDLER_METHOD_ARGUMENTS = "Ambiguous method arguments for the StreamListener method"; public static final String INVALID_INPUT_VALUES = "Cannot set both @StreamListener value and @Input annotation as method parameter"; @@ -66,4 +51,19 @@ public abstract class StreamListenerErrorMessages { public static final String CONDITION_ON_METHOD_RETURNING_VALUE = "Cannot set a condition for methods that return a value"; public static final String MULTIPLE_VALUE_RETURNING_METHODS = "If multiple @StreamListener methods are listening to the same binding target, none of them may return a value"; + + private static final String PREFIX = "A method annotated with @StreamListener "; + + public static final String INPUT_AT_STREAM_LISTENER = PREFIX + + "may never be annotated with @Input. " + + "If it should listen to a specific input, use the value of @StreamListener instead"; + + public static final String RETURN_TYPE_NO_OUTBOUND_SPECIFIED = PREFIX + + "having a return type should also have an outbound target specified"; + + public static final String RETURN_TYPE_MULTIPLE_OUTBOUND_SPECIFIED = PREFIX + + "having a return type should have only one outbound target specified"; + + public static final String INVALID_DECLARATIVE_METHOD_PARAMETERS = PREFIX + + "may use @Input or @Output annotations only in declarative mode and for parameters that are binding targets or convertible from binding targets."; } diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/SubscribableChannelBindingTargetFactory.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/SubscribableChannelBindingTargetFactory.java index 5adfadb24..e01aec339 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/SubscribableChannelBindingTargetFactory.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/binding/SubscribableChannelBindingTargetFactory.java @@ -20,7 +20,8 @@ import org.springframework.integration.channel.DirectChannel; import org.springframework.messaging.SubscribableChannel; /** - * An implementation of {@link BindingTargetFactory} for creating {@link SubscribableChannel}s. + * An implementation of {@link BindingTargetFactory} for creating + * {@link SubscribableChannel}s. * * @author Marius Bogoevici * @author David Syer diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BinderFactoryConfiguration.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BinderFactoryConfiguration.java index 8674b8c97..b688d9378 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BinderFactoryConfiguration.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BinderFactoryConfiguration.java @@ -56,7 +56,8 @@ public class BinderFactoryConfiguration { private static final String SPRING_CLOUD_STREAM_INTERNAL_PREFIX = "spring.cloud.stream.internal"; - private static final String SELF_CONTAINED_APP_PROPERTY_NAME = SPRING_CLOUD_STREAM_INTERNAL_PREFIX + ".selfContained"; + private static final String SELF_CONTAINED_APP_PROPERTY_NAME = SPRING_CLOUD_STREAM_INTERNAL_PREFIX + + ".selfContained"; private static final String BINDER_CONFIGURATIONS_BEAN_NAME = "spring.cloud.stream.binderConfigruations"; @@ -72,6 +73,24 @@ public class BinderFactoryConfiguration { @Autowired(required = false) private Collection binderFactoryListeners; + static Collection parseBinderConfigurations(ClassLoader classLoader, Resource resource) + throws IOException, ClassNotFoundException { + Properties properties = PropertiesLoaderUtils.loadProperties(resource); + Collection parsedBinderConfigurations = new ArrayList<>(); + for (Map.Entry entry : properties.entrySet()) { + String binderType = (String) entry.getKey(); + String[] binderConfigurationClassNames = StringUtils + .commaDelimitedListToStringArray((String) entry.getValue()); + Class[] binderConfigurationClasses = new Class[binderConfigurationClassNames.length]; + int i = 0; + for (String binderConfigurationClassName : binderConfigurationClassNames) { + binderConfigurationClasses[i++] = ClassUtils.forName(binderConfigurationClassName, classLoader); + } + parsedBinderConfigurations.add(new BinderType(binderType, binderConfigurationClasses)); + } + return parsedBinderConfigurations; + } + @Bean @ConditionalOnMissingBean(BinderFactory.class) public DefaultBinderFactory binderFactory() { @@ -153,22 +172,4 @@ public class BinderFactoryConfiguration { } return new DefaultBinderTypeRegistry(binderTypes); } - - static Collection parseBinderConfigurations(ClassLoader classLoader, Resource resource) - throws IOException, ClassNotFoundException { - Properties properties = PropertiesLoaderUtils.loadProperties(resource); - Collection parsedBinderConfigurations = new ArrayList<>(); - for (Map.Entry entry : properties.entrySet()) { - String binderType = (String) entry.getKey(); - String[] binderConfigurationClassNames = StringUtils - .commaDelimitedListToStringArray((String) entry.getValue()); - Class[] binderConfigurationClasses = new Class[binderConfigurationClassNames.length]; - int i = 0; - for (String binderConfigurationClassName : binderConfigurationClassNames) { - binderConfigurationClasses[i++] = ClassUtils.forName(binderConfigurationClassName, classLoader); - } - parsedBinderConfigurations.add(new BinderType(binderType, binderConfigurationClasses)); - } - return parsedBinderConfigurations; - } } diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindersHealthIndicatorAutoConfiguration.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindersHealthIndicatorAutoConfiguration.java index e0ecdf387..1e032a1e9 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindersHealthIndicatorAutoConfiguration.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindersHealthIndicatorAutoConfiguration.java @@ -58,7 +58,8 @@ public class BindersHealthIndicatorAutoConfiguration { } /** - * A {@link DefaultBinderFactory.Listener} that provides {@link HealthIndicator} support. + * A {@link DefaultBinderFactory.Listener} that provides {@link HealthIndicator} + * support. * * @author Ilayaperumal Gopinathan */ @@ -71,7 +72,8 @@ public class BindersHealthIndicatorAutoConfiguration { } @Override - public void afterBinderContextInitialized(String binderConfigurationName, ConfigurableApplicationContext binderContext) { + public void afterBinderContextInitialized(String binderConfigurationName, + ConfigurableApplicationContext binderContext) { if (this.bindersHealthIndicator != null) { OrderedHealthAggregator healthAggregator = new OrderedHealthAggregator(); Map indicators = binderContext.getBeansOfType(HealthIndicator.class); diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingProperties.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingProperties.java index ddaab9ec6..47b5d298b 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingProperties.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingProperties.java @@ -43,10 +43,12 @@ public class BindingProperties { private String destination; /** - * Unique name that the binding belongs to (applies to consumers only). Multiple consumers within the same group - * share the subscription. A null or empty String value indicates an anonymous group that is not shared. - * @see org.springframework.cloud.stream.binder.Binder#bindConsumer(java.lang.String, java.lang.String, - * java.lang.Object, org.springframework.cloud.stream.binder.ConsumerProperties) + * Unique name that the binding belongs to (applies to consumers only). Multiple + * consumers within the same group share the subscription. A null or empty String + * value indicates an anonymous group that is not shared. + * @see org.springframework.cloud.stream.binder.Binder#bindConsumer(java.lang.String, + * java.lang.String, java.lang.Object, + * org.springframework.cloud.stream.binder.ConsumerProperties) */ private String group; diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingServiceConfiguration.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingServiceConfiguration.java index 474fbd058..2f11ef8de 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingServiceConfiguration.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingServiceConfiguration.java @@ -79,10 +79,10 @@ import org.springframework.util.CollectionUtils; @EnableConfigurationProperties(BindingServiceProperties.class) public class BindingServiceConfiguration { - private static final String ERROR_CHANNEL_NAME = "error"; - public static final String STREAM_LISTENER_ANNOTATION_BEAN_POST_PROCESSOR_NAME = "streamListenerAnnotationBeanPostProcessor"; + private static final String ERROR_CHANNEL_NAME = "error"; + @Autowired(required = false) private ObjectMapper objectMapper; @@ -92,6 +92,20 @@ public class BindingServiceConfiguration { @Autowired(required = false) private List customMessageConverters; + @Bean + public static MessageHandlerMethodFactory messageHandlerMethodFactory( + CompositeMessageConverterFactory compositeMessageConverterFactory) { + DefaultMessageHandlerMethodFactory messageHandlerMethodFactory = new DefaultMessageHandlerMethodFactory(); + messageHandlerMethodFactory + .setMessageConverter(compositeMessageConverterFactory.getMessageConverterForAllRegistered()); + return messageHandlerMethodFactory; + } + + @Bean(name = STREAM_LISTENER_ANNOTATION_BEAN_POST_PROCESSOR_NAME) + public static StreamListenerAnnotationBeanPostProcessor streamListenerAnnotationBeanPostProcessor() { + return new StreamListenerAnnotationBeanPostProcessor(); + } + @Bean // This conditional is intentionally not in an autoconfig (usually a bad idea) because // it is used to detect a BindingService in the parent context (which we know @@ -168,15 +182,6 @@ public class BindingServiceConfiguration { return new CompositeMessageConverterFactory(messageConverters, this.objectMapper); } - @Bean - public static MessageHandlerMethodFactory messageHandlerMethodFactory( - CompositeMessageConverterFactory compositeMessageConverterFactory) { - DefaultMessageHandlerMethodFactory messageHandlerMethodFactory = new DefaultMessageHandlerMethodFactory(); - messageHandlerMethodFactory - .setMessageConverter(compositeMessageConverterFactory.getMessageConverterForAllRegistered()); - return messageHandlerMethodFactory; - } - @Bean // provided for backwards compatibility scenarios public ChannelBindingServiceProperties channelBindingServiceProperties( @@ -184,36 +189,12 @@ public class BindingServiceConfiguration { return new ChannelBindingServiceProperties(bindingServiceProperties); } - @Bean(name = STREAM_LISTENER_ANNOTATION_BEAN_POST_PROCESSOR_NAME) - public static StreamListenerAnnotationBeanPostProcessor streamListenerAnnotationBeanPostProcessor() { - return new StreamListenerAnnotationBeanPostProcessor(); - } - // IMPORTANT: Nested class to avoid instantiating all of the above early @Configuration protected static class PostProcessorConfiguration { private BinderAwareChannelResolver binderAwareChannelResolver; - @Bean - @ConditionalOnMissingBean(BinderAwareRouterBeanPostProcessor.class) - public BinderAwareRouterBeanPostProcessor binderAwareRouterBeanPostProcessor( - final ConfigurableListableBeanFactory beanFactory) { - // IMPORTANT: Lazy delegate to avoid instantiating all of the above early - return new BinderAwareRouterBeanPostProcessor(new DestinationResolver() { - - @Override - public MessageChannel resolveDestination(String name) throws DestinationResolutionException { - if (PostProcessorConfiguration.this.binderAwareChannelResolver == null) { - PostProcessorConfiguration.this.binderAwareChannelResolver = BeanFactoryUtils - .beanOfType(beanFactory, BinderAwareChannelResolver.class); - } - return PostProcessorConfiguration.this.binderAwareChannelResolver.resolveDestination(name); - } - - }); - } - /** * Adds property accessors for use in SpEL expression evaluation */ @@ -245,6 +226,25 @@ public class BindingServiceConfiguration { } }; } + + @Bean + @ConditionalOnMissingBean(BinderAwareRouterBeanPostProcessor.class) + public BinderAwareRouterBeanPostProcessor binderAwareRouterBeanPostProcessor( + final ConfigurableListableBeanFactory beanFactory) { + // IMPORTANT: Lazy delegate to avoid instantiating all of the above early + return new BinderAwareRouterBeanPostProcessor(new DestinationResolver() { + + @Override + public MessageChannel resolveDestination(String name) throws DestinationResolutionException { + if (PostProcessorConfiguration.this.binderAwareChannelResolver == null) { + PostProcessorConfiguration.this.binderAwareChannelResolver = BeanFactoryUtils + .beanOfType(beanFactory, BinderAwareChannelResolver.class); + } + return PostProcessorConfiguration.this.binderAwareChannelResolver.resolveDestination(name); + } + + }); + } } } diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingServiceProperties.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingServiceProperties.java index a7999d42c..226227c90 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingServiceProperties.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/config/BindingServiceProperties.java @@ -127,7 +127,8 @@ public class BindingServiceProperties implements ApplicationContextAware, Enviro if (environment instanceof ConfigurableEnvironment) { // override the bindings store with the environment-initializing version if in // a Spring context - Map delegate = new TreeMap(String.CASE_INSENSITIVE_ORDER); + Map delegate = new TreeMap( + String.CASE_INSENSITIVE_ORDER); delegate.putAll(this.bindings); this.bindings = new EnvironmentEntryInitializingTreeMap<>((ConfigurableEnvironment) environment, BindingProperties.class, "spring.cloud.stream.default", delegate); diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/CompositeMessageConverterFactory.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/CompositeMessageConverterFactory.java index 375ee1928..e57eb13d4 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/CompositeMessageConverterFactory.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/CompositeMessageConverterFactory.java @@ -32,9 +32,9 @@ import org.springframework.messaging.converter.MessageConverter; import org.springframework.util.CollectionUtils; import org.springframework.util.MimeType; - /** - * A factory for creating an instance of {@link CompositeMessageConverter} for a given target MIME type + * A factory for creating an instance of {@link CompositeMessageConverter} for a given + * target MIME type * @author David Turanski * @author Ilayaperumal Gopinathan * @author Marius Bogoevici @@ -66,7 +66,6 @@ public class CompositeMessageConverterFactory { initDefaultConverters(); } - private void initDefaultConverters() { this.converters.add(new TupleJsonMessageConverter(this.objectMapper)); diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/CustomMimeTypeConverter.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/CustomMimeTypeConverter.java index d71ccf30a..2a776e441 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/CustomMimeTypeConverter.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/CustomMimeTypeConverter.java @@ -21,8 +21,8 @@ import org.springframework.http.MediaType; import org.springframework.util.MimeType; /** - * A custom converter for {@link MediaType} that accepts a plain java class name as a shorthand for - * {@code application/x-java-object;type=the.qualified.ClassName}. + * A custom converter for {@link MediaType} that accepts a plain java class name as a + * shorthand for {@code application/x-java-object;type=the.qualified.ClassName}. * * * @author Eric Bottard diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/JsonUnmarshallingConverter.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/JsonUnmarshallingConverter.java index bfe5ae352..a4a04cdd6 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/JsonUnmarshallingConverter.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/JsonUnmarshallingConverter.java @@ -28,8 +28,8 @@ import org.springframework.util.MimeType; import org.springframework.util.MimeTypeUtils; /** - * Message converter providing backwards compatibility for applications using - * an Java type as input. + * Message converter providing backwards compatibility for applications using an Java type + * as input. * * @author Marius Bogoevici */ @@ -72,7 +72,8 @@ public class JsonUnmarshallingConverter extends AbstractMessageConverter { protected Object convertFromInternal(Message message, Class targetClass, Object conversionHint) { Object payload = message.getPayload(); try { - return payload instanceof byte[] ? objectMapper.readValue((byte[]) payload, targetClass) : objectMapper.readValue((String) payload, targetClass); + return payload instanceof byte[] ? objectMapper.readValue((byte[]) payload, targetClass) + : objectMapper.readValue((String) payload, targetClass); } catch (IOException e) { throw new MessageConversionException("Cannot parse payload ", e); diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/MessageConverterUtils.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/MessageConverterUtils.java index 490ff2952..ad1d15f24 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/MessageConverterUtils.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/MessageConverterUtils.java @@ -22,7 +22,6 @@ import org.springframework.util.ClassUtils; import org.springframework.util.MimeType; import org.springframework.util.StringUtils; - /** * Message conversion utility methods. * @@ -53,8 +52,9 @@ public abstract class MessageConverterUtils { * @return the class for the content type */ public static Class getJavaTypeForJavaObjectContentType(MimeType contentType) { - Assert.isTrue(X_JAVA_OBJECT.includes(contentType), "Content type must be " + X_JAVA_OBJECT.toString() + ", or " + - "included in it"); + Assert.isTrue(X_JAVA_OBJECT.includes(contentType), + "Content type must be " + X_JAVA_OBJECT.toString() + ", or " + + "included in it"); if (contentType.getParameter("type") != null) { try { return ClassUtils.forName(contentType.getParameter("type"), null); diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/ObjectStringMessageConverter.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/ObjectStringMessageConverter.java index d293f2ea2..dfaa66fb6 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/ObjectStringMessageConverter.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/ObjectStringMessageConverter.java @@ -27,8 +27,8 @@ import org.springframework.util.MimeType; * A {@link org.springframework.messaging.converter.MessageConverter} to convert a * non-String objects to a String, when expected content type is "text/plain". * - * It only performs conversions to internal format and is a wrapper - * around {@link Object#toString()}. + * It only performs conversions to internal format and is a wrapper around + * {@link Object#toString()}. * * @author Marius Bogoevici * @@ -66,7 +66,8 @@ public class ObjectStringMessageConverter extends AbstractMessageConverter { if (payload != null) { if ((payload instanceof byte[])) { return new String((byte[]) payload, Charset.forName("UTF-8")); - } else { + } + else { return payload.toString(); } } diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/TupleJsonMessageConverter.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/TupleJsonMessageConverter.java index bc7ca5261..f9041c9ab 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/TupleJsonMessageConverter.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/converter/TupleJsonMessageConverter.java @@ -31,28 +31,28 @@ import org.springframework.tuple.TupleBuilder; import org.springframework.util.MimeTypeUtils; /** - * A {@link org.springframework.messaging.converter.MessageConverter} - * to convert a {@link Tuple} to a JSON String + * A {@link org.springframework.messaging.converter.MessageConverter} to convert a + * {@link Tuple} to a JSON String * @author David Turanski * @author Ilayaperumal Gopinathan * @author Marius Bogoevici */ public class TupleJsonMessageConverter extends AbstractMessageConverter { - @Value("${typeconversion.json.prettyPrint:false}") - private volatile boolean prettyPrint; - private final ObjectMapper objectMapper; - public void setPrettyPrint(boolean prettyPrint) { - this.prettyPrint = prettyPrint; - } + @Value("${typeconversion.json.prettyPrint:false}") + private volatile boolean prettyPrint; public TupleJsonMessageConverter(ObjectMapper objectMapper) { super(Arrays.asList(MessageConverterUtils.X_SPRING_TUPLE, MimeTypeUtils.APPLICATION_JSON)); this.objectMapper = (objectMapper != null) ? objectMapper : new ObjectMapper(); } + public void setPrettyPrint(boolean prettyPrint) { + this.prettyPrint = prettyPrint; + } + @Override protected boolean supports(Class clazz) { return Tuple.class.isAssignableFrom(clazz); diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/provisioning/ProducerDestination.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/provisioning/ProducerDestination.java index baf4f53be..e0f411d55 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/provisioning/ProducerDestination.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/provisioning/ProducerDestination.java @@ -39,15 +39,16 @@ public interface ProducerDestination { /** * Provides the destination name for a given partition. * - * If the producer provision the destination with partitions, on certain middleware brokers - * there may exist multiple destinations distinguishable by the partition. For example, - * if the destination name is xyz and it is provisioned with 4 partitions, there may be - * 4 different destinations on the broker such as - xyz-0, xyz-1, xyz-2 and xyz-3. - * This behavior is dependent on the broker and the way the corresponding binder implements the logic. + * If the producer provision the destination with partitions, on certain middleware + * brokers there may exist multiple destinations distinguishable by the partition. For + * example, if the destination name is xyz and it is provisioned with 4 + * partitions, there may be 4 different destinations on the broker such as - xyz-0, + * xyz-1, xyz-2 and xyz-3. This behavior is dependent on the broker and the way + * the corresponding binder implements the logic. * - * On certain brokers (for instance, Kafka), this behavior is completely skipped - * and there is a one-to-one correspondence between the destination name in the provisioner and - * the physical destination on the broker. + * On certain brokers (for instance, Kafka), this behavior is completely skipped and + * there is a one-to-one correspondence between the destination name in the + * provisioner and the physical destination on the broker. * * @param partition the partition to find destination for * @return destination name for the given partition diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/provisioning/ProvisioningException.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/provisioning/ProvisioningException.java index 343eddb13..a5e8c5bb7 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/provisioning/ProvisioningException.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/provisioning/ProvisioningException.java @@ -40,8 +40,8 @@ public class ProvisioningException extends NestedRuntimeException { /** * Constructor that takes a message and a root cause. * @param msg the detail message - * @param cause the cause of the exception. This argument is generally - * expected to be middleware specific. + * @param cause the cause of the exception. This argument is generally expected to be + * middleware specific. */ public ProvisioningException(String msg, Throwable cause) { super(msg, cause); diff --git a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/provisioning/ProvisioningProvider.java b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/provisioning/ProvisioningProvider.java index 9b80d2592..eebc9c204 100644 --- a/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/provisioning/ProvisioningProvider.java +++ b/spring-cloud-stream/src/main/java/org/springframework/cloud/stream/provisioning/ProvisioningProvider.java @@ -20,19 +20,19 @@ import org.springframework.cloud.stream.binder.ConsumerProperties; import org.springframework.cloud.stream.binder.ProducerProperties; /** - * Provisioning SPI that allows the users to provision destinations such as queues and topics. - * This SPI will allow the binders to be separated from any provisioning concerns and only focus - * on setting up endpoints for sending/receiving messages. + * Provisioning SPI that allows the users to provision destinations such as queues and + * topics. This SPI will allow the binders to be separated from any provisioning concerns + * and only focus on setting up endpoints for sending/receiving messages. * * Implementations must implement the following methods: * *

    *
  • {@link #provisionProducerDestination(String, ProducerProperties)}
  • - *
  • {@link #provisionConsumerDestination(String, String, ConsumerProperties)}
  • + *
  • {@link #provisionConsumerDestination(String, String, ConsumerProperties)}
  • *
* - * @param the consumer properties type - * @param

the producer properties type + * @param the consumer properties type + * @param

the producer properties type * * @author Soby Chacko * @@ -41,10 +41,10 @@ import org.springframework.cloud.stream.binder.ProducerProperties; public interface ProvisioningProvider { /** - * Creates middleware destination on the physical broker for the producer to send data. The implementation - * is middleware-specific. + * Creates middleware destination on the physical broker for the producer to send + * data. The implementation is middleware-specific. * - * @param name the name of the producer destination + * @param name the name of the producer destination * @param properties producer properties * @return reference to {@link ProducerDestination} that represents a producer * @throws ProvisioningException on underlying provisioning errors from the middleware @@ -52,15 +52,16 @@ public interface ProvisioningProvider * {@code * class MessageChannelBinder implements Binder @@ -46,7 +46,8 @@ public abstract class GenericsUtils { * @param interfaceClass the parametrized interface * @param position the position * @return the parameter type if any - * @throws IllegalStateException if the evaluated class does not implement the interface or + * @throws IllegalStateException if the evaluated class does not implement the + * interface or */ public static Class getParameterType(Class evaluatedClass, Class interfaceClass, int position) { Class bindableType = null; diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/aggregation/AggregationTest.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/aggregation/AggregationTest.java index f0705a6c2..932cbc5dd 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/aggregation/AggregationTest.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/aggregation/AggregationTest.java @@ -71,9 +71,9 @@ public class AggregationTest { public void aggregation() { aggregatedApplicationContext = new AggregateApplicationBuilder( MockBinderRegistryConfiguration.class, "--server.port=0", "--debug=true") - .from(TestSource.class) - .to(TestProcessor.class) - .run(); + .from(TestSource.class) + .to(TestProcessor.class) + .run(); SharedBindingTargetRegistry sharedBindingTargetRegistry = aggregatedApplicationContext .getBean(SharedBindingTargetRegistry.class); BindingTargetFactory channelFactory = aggregatedApplicationContext @@ -83,13 +83,12 @@ public class AggregationTest { aggregatedApplicationContext.close(); } - @Test public void testModuleAggregationUsingSharedChannelRegistry() { // test backward compatibility aggregatedApplicationContext = new AggregateApplicationBuilder( MockBinderRegistryConfiguration.class, "--server.port=0") - .from(TestSource.class).to(TestProcessor.class).run(); + .from(TestSource.class).to(TestProcessor.class).run(); SharedChannelRegistry sharedChannelRegistry = aggregatedApplicationContext .getBean(SharedChannelRegistry.class); BindingTargetFactory channelFactory = aggregatedApplicationContext @@ -106,13 +105,13 @@ public class AggregationTest { argsToVerify.add("--foo2=bar2"); argsToVerify.add("--foo3=bar3"); argsToVerify.add("--server.port=0"); - AggregateApplicationBuilder aggregateApplicationBuilder = - new AggregateApplicationBuilder(MockBinderRegistryConfiguration.class, "--foo1=bar1"); - final ConfigurableApplicationContext context = - aggregateApplicationBuilder.parent(DummyConfig.class, "--foo2=bar2") - .from(TestSource.class) - .namespace("foo").to(TestProcessor.class).namespace("bar") - .run("--foo3=bar3", "--server.port=0"); + AggregateApplicationBuilder aggregateApplicationBuilder = new AggregateApplicationBuilder( + MockBinderRegistryConfiguration.class, "--foo1=bar1"); + final ConfigurableApplicationContext context = aggregateApplicationBuilder + .parent(DummyConfig.class, "--foo2=bar2") + .from(TestSource.class) + .namespace("foo").to(TestProcessor.class).namespace("bar") + .run("--foo3=bar3", "--server.port=0"); DirectFieldAccessor aggregateApplicationBuilderAccessor = new DirectFieldAccessor(aggregateApplicationBuilder); @SuppressWarnings("unchecked") final List parentArgs = (List) aggregateApplicationBuilderAccessor.getPropertyValue( @@ -120,20 +119,21 @@ public class AggregationTest { assertThat(parentArgs).containsExactlyInAnyOrder(argsToVerify.toArray(new String[argsToVerify.size()])); List sources = (List) aggregateApplicationBuilderAccessor.getPropertyValue("parentSources"); assertThat(sources).containsExactlyInAnyOrder(AggregateApplicationBuilder.ParentConfiguration.class, - MockBinderRegistryConfiguration.class, DummyConfig.class, EmbeddedServletContainerAutoConfiguration.class); + MockBinderRegistryConfiguration.class, DummyConfig.class, + EmbeddedServletContainerAutoConfiguration.class); context.close(); } @Test public void testParentArgsAndSourcesWithWebDisabled() { List argsToVerify = new ArrayList<>(); - AggregateApplicationBuilder aggregateApplicationBuilder = - new AggregateApplicationBuilder(MockBinderRegistryConfiguration.class, "--foo1=bar1"); - final ConfigurableApplicationContext context = - aggregateApplicationBuilder.parent(DummyConfig.class, "--foo2=bar2").web(false) - .from(TestSource.class) - .namespace("foo").to(TestProcessor.class).namespace("bar") - .run("--server.port=0"); + AggregateApplicationBuilder aggregateApplicationBuilder = new AggregateApplicationBuilder( + MockBinderRegistryConfiguration.class, "--foo1=bar1"); + final ConfigurableApplicationContext context = aggregateApplicationBuilder + .parent(DummyConfig.class, "--foo2=bar2").web(false) + .from(TestSource.class) + .namespace("foo").to(TestProcessor.class).namespace("bar") + .run("--server.port=0"); DirectFieldAccessor aggregateApplicationBuilderAccessor = new DirectFieldAccessor(aggregateApplicationBuilder); List sources = (List) aggregateApplicationBuilderAccessor.getPropertyValue("parentSources"); assertThat(sources).containsExactlyInAnyOrder(AggregateApplicationBuilder.ParentConfiguration.class, @@ -154,18 +154,17 @@ public class AggregationTest { assertTrue(Arrays.equals( ((SourceConfigurer) aggregateApplicationBuilderAccessor.getPropertyValue("sourceConfigurer")) .getArgs(), - new String[]{ "--foo1=bar1" })); - final List processorConfigurers = - (List) - aggregateApplicationBuilderAccessor.getPropertyValue("processorConfigurers"); + new String[] { "--foo1=bar1" })); + final List processorConfigurers = (List) aggregateApplicationBuilderAccessor + .getPropertyValue("processorConfigurers"); for (AggregateApplicationBuilder.ProcessorConfigurer processorConfigurer : processorConfigurers) { if (processorConfigurer.getNamespace().equals("b")) { assertTrue(Arrays.equals(processorConfigurer.getArgs(), - new String[]{ "--foo1=bar2" })); + new String[] { "--foo1=bar2" })); } if (processorConfigurer.getNamespace().equals("c")) { assertTrue(Arrays.equals(processorConfigurer.getArgs(), - new String[]{ "--foo1=bar3" })); + new String[] { "--foo1=bar3" })); } } aggregatedApplicationContext.close(); @@ -185,18 +184,17 @@ public class AggregationTest { assertTrue(Arrays.equals( ((SourceConfigurer) aggregateApplicationBuilderAccessor.getPropertyValue("sourceConfigurer")) .getArgs(), - new String[]{ "--fooValue=bara" })); - final List processorConfigurers = - (List) - aggregateApplicationBuilderAccessor.getPropertyValue("processorConfigurers"); + new String[] { "--fooValue=bara" })); + final List processorConfigurers = (List) aggregateApplicationBuilderAccessor + .getPropertyValue("processorConfigurers"); for (AggregateApplicationBuilder.ProcessorConfigurer processorConfigurer : processorConfigurers) { if (processorConfigurer.getNamespace().equals("b")) { assertTrue(Arrays.equals(processorConfigurer.getArgs(), - new String[]{ "--foo1=argbarb" })); + new String[] { "--foo1=argbarb" })); } if (processorConfigurer.getNamespace().equals("c")) { assertTrue(Arrays.equals(processorConfigurer.getArgs(), - new String[]{ "--foo1=barc" })); + new String[] { "--foo1=barc" })); } } aggregatedApplicationContext.close(); @@ -216,18 +214,17 @@ public class AggregationTest { assertTrue(Arrays.equals( ((SourceConfigurer) aggregateApplicationBuilderAccessor.getPropertyValue("sourceConfigurer")) .getArgs(), - new String[]{ "--fooValue=bara" })); - final List processorConfigurers = - (List) - aggregateApplicationBuilderAccessor.getPropertyValue("processorConfigurers"); + new String[] { "--fooValue=bara" })); + final List processorConfigurers = (List) aggregateApplicationBuilderAccessor + .getPropertyValue("processorConfigurers"); for (AggregateApplicationBuilder.ProcessorConfigurer processorConfigurer : processorConfigurers) { if (processorConfigurer.getNamespace().equals("b")) { assertTrue(Arrays.equals(processorConfigurer.getArgs(), - new String[]{ "--foo-value=barb" })); + new String[] { "--foo-value=barb" })); } if (processorConfigurer.getNamespace().equals("c")) { assertTrue(Arrays.equals(processorConfigurer.getArgs(), - new String[]{ "--foo1=barc" })); + new String[] { "--foo1=barc" })); } } aggregatedApplicationContext.close(); @@ -249,18 +246,17 @@ public class AggregationTest { assertTrue(Arrays.equals( ((SourceConfigurer) aggregateApplicationBuilderAccessor.getPropertyValue("sourceConfigurer")) .getArgs(), - new String[]{ "--fooValue=bara" })); - final List processorConfigurers = - (List) - aggregateApplicationBuilderAccessor.getPropertyValue("processorConfigurers"); + new String[] { "--fooValue=bara" })); + final List processorConfigurers = (List) aggregateApplicationBuilderAccessor + .getPropertyValue("processorConfigurers"); for (AggregateApplicationBuilder.ProcessorConfigurer processorConfigurer : processorConfigurers) { if (processorConfigurer.getNamespace().equals("b")) { assertTrue(Arrays.equals(processorConfigurer.getArgs(), - new String[]{ "--fooValue=argbarb" })); + new String[] { "--fooValue=argbarb" })); } if (processorConfigurer.getNamespace().equals("c")) { assertTrue(Arrays.equals(processorConfigurer.getArgs(), - new String[]{ "--fooValue=sysbarc" })); + new String[] { "--fooValue=sysbarc" })); } } aggregatedApplicationContext.close(); @@ -282,20 +278,19 @@ public class AggregationTest { assertTrue(Arrays.equals( ((SourceConfigurer) aggregateApplicationBuilderAccessor.getPropertyValue("sourceConfigurer")) .getArgs(), - new String[]{ "--foo-value=sysbara" })); - final List processorConfigurers = - (List) - aggregateApplicationBuilderAccessor.getPropertyValue("processorConfigurers"); - for (AggregateApplicationBuilder.ProcessorConfigurer processorConfigurer : ((List) aggregateApplicationBuilderAccessor.getPropertyValue( - "processorConfigurers"))) { + new String[] { "--foo-value=sysbara" })); + final List processorConfigurers = (List) aggregateApplicationBuilderAccessor + .getPropertyValue("processorConfigurers"); + for (AggregateApplicationBuilder.ProcessorConfigurer processorConfigurer : ((List) aggregateApplicationBuilderAccessor + .getPropertyValue( + "processorConfigurers"))) { if (processorConfigurer.getNamespace().equals("b")) { assertTrue(Arrays.equals(processorConfigurer.getArgs(), - new String[]{ "--fooValue=argbarb" })); + new String[] { "--fooValue=argbarb" })); } if (processorConfigurer.getNamespace().equals("c")) { assertTrue(Arrays.equals(processorConfigurer.getArgs(), - new String[]{ "--fooValue=sysbarc" })); + new String[] { "--fooValue=sysbarc" })); } } aggregatedApplicationContext.close(); @@ -317,18 +312,17 @@ public class AggregationTest { assertTrue(Arrays.equals( ((SourceConfigurer) aggregateApplicationBuilderAccessor.getPropertyValue("sourceConfigurer")) .getArgs(), - new String[]{ "--fooValue=highest" })); - final List processorConfigurers = - (List) - aggregateApplicationBuilderAccessor.getPropertyValue("processorConfigurers"); + new String[] { "--fooValue=highest" })); + final List processorConfigurers = (List) aggregateApplicationBuilderAccessor + .getPropertyValue("processorConfigurers"); for (AggregateApplicationBuilder.ProcessorConfigurer processorConfigurer : processorConfigurers) { if (processorConfigurer.getNamespace().equals("b")) { assertTrue(Arrays.equals(processorConfigurer.getArgs(), - new String[]{ "--fooValue=argbarb" })); + new String[] { "--fooValue=argbarb" })); } if (processorConfigurer.getNamespace().equals("c")) { assertTrue(Arrays.equals(processorConfigurer.getArgs(), - new String[]{ "--foo-value=sysbarc" })); + new String[] { "--foo-value=sysbarc" })); } } aggregatedApplicationContext.close(); @@ -338,8 +332,8 @@ public class AggregationTest { public void testNamespaces() { aggregatedApplicationContext = new AggregateApplicationBuilder( MockBinderRegistryConfiguration.class, "--server.port=0") - .from(TestSource.class).namespace("foo").to(TestProcessor.class) - .namespace("bar").run(); + .from(TestSource.class).namespace("foo").to(TestProcessor.class) + .namespace("bar").run(); SharedChannelRegistry sharedChannelRegistry = aggregatedApplicationContext .getBean(SharedChannelRegistry.class); BindingTargetFactory channelFactory = aggregatedApplicationContext @@ -357,7 +351,8 @@ public class AggregationTest { @Test public void testBindableProxyFactoryCaching() { - AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MockBinderRegistryConfiguration.class, + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( + MockBinderRegistryConfiguration.class, TestSource.class, TestProcessor.class); Map factories = context.getBeansOfType(BindableProxyFactory.class); assertThat(factories).hasSize(2); @@ -381,9 +376,11 @@ public class AggregationTest { Map targetCache = (Map) ReflectionUtils.getField(field, factory); if (factory.getObjectType() == Source.class) { assertThat(targetCache).hasSize(1); - } else if (factory.getObjectType() == Processor.class) { + } + else if (factory.getObjectType() == Processor.class) { assertThat(targetCache).hasSize(2); - } else { + } + else { Assert.fail("Found unexpected type"); } } diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/BinderAwareChannelResolverTests.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/BinderAwareChannelResolverTests.java index 40417f4c7..9a2509e4c 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/BinderAwareChannelResolverTests.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/BinderAwareChannelResolverTests.java @@ -90,7 +90,8 @@ public class BinderAwareChannelResolverTests { BinderFactory binderFactory = new BinderFactory() { @Override - public Binder getBinder(String configurationName, Class bindableType) { + public Binder getBinder( + String configurationName, Class bindableType) { return (Binder) binder; } }; @@ -165,7 +166,7 @@ public class BinderAwareChannelResolverTests { } @Test - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) public void propertyPassthrough() { Map bindings = new HashMap<>(); BindingProperties genericProperties = new BindingProperties(); @@ -187,9 +188,8 @@ public class BinderAwareChannelResolverTests { BindingService bindingService = new BindingService(bindingServiceProperties, mockBinderFactory); @SuppressWarnings("unchecked") - BinderAwareChannelResolver resolver = - new BinderAwareChannelResolver(bindingService, this.bindingTargetFactory, - new DynamicDestinationsBindable()); + BinderAwareChannelResolver resolver = new BinderAwareChannelResolver(bindingService, this.bindingTargetFactory, + new DynamicDestinationsBindable()); BeanFactory beanFactory = new DefaultListableBeanFactory(); resolver.setBeanFactory(beanFactory); SubscribableChannel resolved = (SubscribableChannel) resolver.resolveDestination("foo"); @@ -217,7 +217,6 @@ public class BinderAwareChannelResolverTests { return new TestBinding(name, directHandler); } - @Override public Binding bindProducer(String name, MessageChannel outboundBindTarget, ProducerProperties properties) { diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/BinderFactoryConfigurationTests.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/BinderFactoryConfigurationTests.java index dfeca100c..005c8afd0 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/BinderFactoryConfigurationTests.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/BinderFactoryConfigurationTests.java @@ -48,6 +48,39 @@ import static org.junit.Assert.fail; */ public class BinderFactoryConfigurationTests { + private static ClassLoader createClassLoader(String[] additionalClasspathDirectories, + String... properties) throws IOException { + URL[] urls = ObjectUtils.isEmpty(additionalClasspathDirectories) ? new URL[0] + : new URL[additionalClasspathDirectories.length]; + if (!ObjectUtils.isEmpty(additionalClasspathDirectories)) { + for (int i = 0; i < additionalClasspathDirectories.length; i++) { + urls[i] = new URL(new ClassPathResource(additionalClasspathDirectories[i]).getURL().toString() + "/"); + } + } + return new URLClassLoader(urls, BinderFactoryConfigurationTests.class.getClassLoader()); + } + + private static ConfigurableApplicationContext createBinderTestContext(String[] additionalClasspathDirectories, + String... properties) throws IOException { + ClassLoader classLoader = createClassLoader(additionalClasspathDirectories, properties); + return new SpringApplicationBuilder(SimpleApplication.class) + .resourceLoader(new DefaultResourceLoader(classLoader)) + .properties(properties) + .web(false) + .run(); + } + + private static ConfigurableApplicationContext createBinderTestContextWithSources(Class[] sources, + String[] additionalClasspathDirectories, + String... properties) throws IOException { + ClassLoader classLoader = createClassLoader(additionalClasspathDirectories, properties); + return new SpringApplicationBuilder(sources) + .resourceLoader(new DefaultResourceLoader(classLoader)) + .properties(properties) + .web(false) + .run(); + } + @Test public void loadBinderTypeRegistry() throws Exception { try { @@ -64,7 +97,7 @@ public class BinderFactoryConfigurationTests { public void loadBinderTypeRegistryWithNonSelfContainedAggregatorApp() throws Exception { try { createBinderTestContextWithSources( - new Class[]{SimpleApplication.class}, new String[]{}, + new Class[] { SimpleApplication.class }, new String[] {}, "spring.cloud.stream.internal.selfContained=false"); fail(); } @@ -77,15 +110,15 @@ public class BinderFactoryConfigurationTests { @Test public void loadBinderTypeRegistryWithSelfContainedAggregatorApp() throws Exception { - createBinderTestContextWithSources( - new Class[] { SimpleApplication.class}, new String[] {}, - "spring.cloud.stream.internal.selfContained=true"); + createBinderTestContextWithSources( + new Class[] { SimpleApplication.class }, new String[] {}, + "spring.cloud.stream.internal.selfContained=true"); } @Test public void loadBinderTypeRegistryWithOneBinder() throws Exception { ConfigurableApplicationContext context = createBinderTestContext( - new String[] {"binder1"}); + new String[] { "binder1" }); BinderTypeRegistry binderTypeRegistry = context.getBean(BinderTypeRegistry.class); assertThat(binderTypeRegistry).isNotNull(); @@ -106,7 +139,7 @@ public class BinderFactoryConfigurationTests { @Test public void loadBinderTypeRegistryWithOneBinderAndSharedEnvironment() throws Exception { ConfigurableApplicationContext context = createBinderTestContext( - new String[] {"binder1"}, "binder1.name=foo"); + new String[] { "binder1" }, "binder1.name=foo"); BinderFactory binderFactory = context.getBean(BinderFactory.class); @@ -117,7 +150,7 @@ public class BinderFactoryConfigurationTests { @Test public void loadBinderTypeRegistryWithOneCustomBinderAndSharedEnvironment() throws Exception { ConfigurableApplicationContext context = createBinderTestContext( - new String[] {"binder1"}, "binder1.name=foo", + new String[] { "binder1" }, "binder1.name=foo", "spring.cloud.stream.binders.custom.environment.foo=bar", "spring.cloud.stream.binders.custom.type=binder1"); @@ -132,7 +165,7 @@ public class BinderFactoryConfigurationTests { @Test public void loadBinderTypeRegistryWithOneCustomBinderAndIsolatedEnvironment() throws Exception { ConfigurableApplicationContext context = createBinderTestContext( - new String[] {"binder1"}, "binder1.name=foo", + new String[] { "binder1" }, "binder1.name=foo", "spring.cloud.stream.binders.custom.type=binder1", "spring.cloud.stream.binders.custom.environment.foo=bar", "spring.cloud.stream.binders.custom.inheritEnvironment=false"); @@ -177,7 +210,7 @@ public class BinderFactoryConfigurationTests { public void loadBinderTypeRegistryWithCustomNonDefaultCandidate() throws Exception { ConfigurableApplicationContext context = createBinderTestContext( - new String[] { "binder1"}, + new String[] { "binder1" }, "spring.cloud.stream.binders.custom.type=binder1", "spring.cloud.stream.binders.custom.environment.binder1.name=foo", "spring.cloud.stream.binders.custom.defaultCandidate=false", @@ -208,8 +241,7 @@ public class BinderFactoryConfigurationTests { @Test public void loadDefaultBinderWithTwoBinders() throws Exception { - ConfigurableApplicationContext context = - createBinderTestContext( + ConfigurableApplicationContext context = createBinderTestContext( new String[] { "binder1", "binder2" }, "spring.cloud.stream.defaultBinder:binder2"); BinderTypeRegistry binderTypeRegistry = context.getBean(BinderTypeRegistry.class); @@ -232,39 +264,7 @@ public class BinderFactoryConfigurationTests { assertThat(defaultBinder).isSameAs(binder2); } - private static ClassLoader createClassLoader(String[] additionalClasspathDirectories, - String... properties) throws IOException { - URL[] urls = ObjectUtils.isEmpty(additionalClasspathDirectories) ? - new URL[0] : new URL[additionalClasspathDirectories.length]; - if (!ObjectUtils.isEmpty(additionalClasspathDirectories)) { - for (int i = 0; i < additionalClasspathDirectories.length; i++) { - urls[i] = new URL(new ClassPathResource(additionalClasspathDirectories[i]).getURL().toString() + "/"); - } - } - return new URLClassLoader(urls, BinderFactoryConfigurationTests.class.getClassLoader()); - } - - private static ConfigurableApplicationContext createBinderTestContext(String[] additionalClasspathDirectories, - String... properties) throws IOException { - ClassLoader classLoader = createClassLoader(additionalClasspathDirectories, properties); - return new SpringApplicationBuilder(SimpleApplication.class) - .resourceLoader(new DefaultResourceLoader(classLoader)) - .properties(properties) - .web(false) - .run(); - } - - - private static ConfigurableApplicationContext createBinderTestContextWithSources(Class[] sources, String[] additionalClasspathDirectories, - String... properties) throws IOException { - ClassLoader classLoader = createClassLoader(additionalClasspathDirectories, properties); - return new SpringApplicationBuilder(sources) - .resourceLoader(new DefaultResourceLoader(classLoader)) - .properties(properties) - .web(false) - .run(); - } - @Import({BinderFactoryConfiguration.class, PropertyPlaceholderAutoConfiguration.class}) + @Import({ BinderFactoryConfiguration.class, PropertyPlaceholderAutoConfiguration.class }) @EnableBinding public static class SimpleApplication { diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/ErrorBindingTests.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/ErrorBindingTests.java index 534a809ea..e9972deec 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/ErrorBindingTests.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/ErrorBindingTests.java @@ -42,13 +42,15 @@ public class ErrorBindingTests { @Test public void testErrorChannelNotBoundByDefault() { - ConfigurableApplicationContext applicationContext = SpringApplication.run(TestProcessor.class, "--server.port=0"); + ConfigurableApplicationContext applicationContext = SpringApplication.run(TestProcessor.class, + "--server.port=0"); BinderFactory binderFactory = applicationContext.getBean(BinderFactory.class); @SuppressWarnings("unchecked") Binder binder = binderFactory.getBinder(null, MessageChannel.class); - Mockito.verify(binder).bindConsumer(eq("input"), isNull(String.class), any(MessageChannel.class), any(ConsumerProperties.class)); + Mockito.verify(binder).bindConsumer(eq("input"), isNull(String.class), any(MessageChannel.class), + any(ConsumerProperties.class)); Mockito.verify(binder).bindProducer(eq("output"), any(MessageChannel.class), any(ProducerProperties.class)); Mockito.verifyNoMoreInteractions(binder); applicationContext.close(); @@ -57,17 +59,18 @@ public class ErrorBindingTests { @Test public void testErrorChannelBoundIfConfigured() { - ConfigurableApplicationContext applicationContext = - SpringApplication.run(TestProcessor.class, "--spring.cloud.stream.bindings.error.destination=foo", "--server.port=0"); + ConfigurableApplicationContext applicationContext = SpringApplication.run(TestProcessor.class, + "--spring.cloud.stream.bindings.error.destination=foo", "--server.port=0"); BinderFactory binderFactory = applicationContext.getBean(BinderFactory.class, MessageChannel.class); @SuppressWarnings("unchecked") - Binder binder = binderFactory.getBinder(null, MessageChannel.class); + Binder binder = binderFactory.getBinder(null, MessageChannel.class); MessageChannel errorChannel = applicationContext.getBean(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME, MessageChannel.class); - Mockito.verify(binder).bindConsumer(eq("input"), isNull(String.class), any(MessageChannel.class), any(ConsumerProperties.class)); + Mockito.verify(binder).bindConsumer(eq("input"), isNull(String.class), any(MessageChannel.class), + any(ConsumerProperties.class)); Mockito.verify(binder).bindProducer(eq("output"), any(MessageChannel.class), any(ProducerProperties.class)); Mockito.verify(binder).bindProducer(eq("foo"), same(errorChannel), any(ProducerProperties.class)); Mockito.verifyNoMoreInteractions(binder); diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/ExtendedPropertiesBinderAwareChannelResolverTests.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/ExtendedPropertiesBinderAwareChannelResolverTests.java index 829fbe1df..6760a9452 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/ExtendedPropertiesBinderAwareChannelResolverTests.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/ExtendedPropertiesBinderAwareChannelResolverTests.java @@ -71,7 +71,8 @@ public class ExtendedPropertiesBinderAwareChannelResolverTests extends BinderAwa BinderFactory binderFactory = new BinderFactory() { @Override - public Binder getBinder(String configurationName, Class bindableType) { + public Binder getBinder( + String configurationName, Class bindableType) { return (Binder) binder; } }; @@ -143,7 +144,8 @@ public class ExtendedPropertiesBinderAwareChannelResolverTests extends BinderAwa /** * A simple test binder that creates queues for the destinations. Ignores groups. */ - class TestBinder implements ExtendedPropertiesBinder { + class TestBinder implements + ExtendedPropertiesBinder { private final Map destinations = new ConcurrentHashMap<>(); @@ -160,7 +162,6 @@ public class ExtendedPropertiesBinderAwareChannelResolverTests extends BinderAwa return new TestBinding(name, directHandler); } - @Override public Binding bindProducer(String name, MessageChannel outboundBindTarget, ExtendedProducerProperties properties) { diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/HealthIndicatorsConfigurationTests.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/HealthIndicatorsConfigurationTests.java index dd43515ed..f7c81148b 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/HealthIndicatorsConfigurationTests.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/HealthIndicatorsConfigurationTests.java @@ -51,6 +51,24 @@ import static org.junit.Assert.fail; */ public class HealthIndicatorsConfigurationTests { + public static ConfigurableApplicationContext createBinderTestContext( + String[] additionalClasspathDirectories, String... properties) + throws IOException { + URL[] urls = ObjectUtils.isEmpty(additionalClasspathDirectories) ? new URL[0] + : new URL[additionalClasspathDirectories.length]; + if (!ObjectUtils.isEmpty(additionalClasspathDirectories)) { + for (int i = 0; i < additionalClasspathDirectories.length; i++) { + urls[i] = new URL(new ClassPathResource(additionalClasspathDirectories[i]) + .getURL().toString() + "/"); + } + } + ClassLoader classLoader = new URLClassLoader(urls, + BinderFactoryConfigurationTests.class.getClassLoader()); + return new SpringApplicationBuilder(SimpleSource.class) + .resourceLoader(new DefaultResourceLoader(classLoader)) + .properties(properties).web(false).run(); + } + @Test public void healthIndicatorsCheck() throws Exception { ConfigurableApplicationContext context = createBinderTestContext(new String[] { "binder1", "binder2" }, @@ -97,24 +115,6 @@ public class HealthIndicatorsConfigurationTests { context.close(); } - public static ConfigurableApplicationContext createBinderTestContext( - String[] additionalClasspathDirectories, String... properties) - throws IOException { - URL[] urls = ObjectUtils.isEmpty(additionalClasspathDirectories) ? new URL[0] - : new URL[additionalClasspathDirectories.length]; - if (!ObjectUtils.isEmpty(additionalClasspathDirectories)) { - for (int i = 0; i < additionalClasspathDirectories.length; i++) { - urls[i] = new URL(new ClassPathResource(additionalClasspathDirectories[i]) - .getURL().toString() + "/"); - } - } - ClassLoader classLoader = new URLClassLoader(urls, - BinderFactoryConfigurationTests.class.getClassLoader()); - return new SpringApplicationBuilder(SimpleSource.class) - .resourceLoader(new DefaultResourceLoader(classLoader)) - .properties(properties).web(false).run(); - } - @EnableAutoConfiguration @EnableBinding public static class SimpleSource { diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/InputOutputBindingOrderTest.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/InputOutputBindingOrderTest.java index ace976474..786332962 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/InputOutputBindingOrderTest.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/InputOutputBindingOrderTest.java @@ -62,7 +62,7 @@ public class InputOutputBindingOrderTest { @EnableBinding(Processor.class) @EnableAutoConfiguration - @Import({MockBinderRegistryConfiguration.class, BinderFactoryConfiguration.class}) + @Import({ MockBinderRegistryConfiguration.class, BinderFactoryConfiguration.class }) public static class TestSource { @Bean diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/MessageConverterTests.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/MessageConverterTests.java index 2e527f68a..55e591966 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/MessageConverterTests.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/MessageConverterTests.java @@ -41,7 +41,8 @@ public class MessageConverterTests { assertThat(new String(embedded).substring(1)).isEqualTo( "\u0002\u0003foo\u0000\u0000\u0000\u0005\"bar\"\u0003baz\u0000\u0000\u0000\u0006\"quxx\"Hello"); - MessageValues extracted = EmbeddedHeaderUtils.extractHeaders(MessageBuilder.withPayload(embedded).build(), false); + MessageValues extracted = EmbeddedHeaderUtils.extractHeaders(MessageBuilder.withPayload(embedded).build(), + false); assertThat(new String((byte[]) extracted.getPayload())).isEqualTo("Hello"); assertThat(extracted.get("foo")).isEqualTo("bar"); assertThat(extracted.get("baz")).isEqualTo("quxx"); @@ -51,18 +52,21 @@ public class MessageConverterTests { public void testConfigurableHeaders() throws Exception { Message message = MessageBuilder.withPayload("Hello".getBytes()).setHeader("foo", "bar") .setHeader("baz", "quxx").setHeader("contentType", "text/plain").build(); - String[] headers = new String[]{"foo"}; - byte[] embedded = EmbeddedHeaderUtils.embedHeaders(new MessageValues(message), EmbeddedHeaderUtils.headersToEmbed(headers)); + String[] headers = new String[] { "foo" }; + byte[] embedded = EmbeddedHeaderUtils.embedHeaders(new MessageValues(message), + EmbeddedHeaderUtils.headersToEmbed(headers)); assertThat(embedded[0] & 0xff).isEqualTo(0xff); assertThat(new String(embedded).substring(1)).isEqualTo( "\u0002\u000BcontentType\u0000\u0000\u0000\u000C\"text/plain\"\u0003foo\u0000\u0000\u0000\u0005\"bar\"Hello"); - MessageValues extracted = EmbeddedHeaderUtils.extractHeaders(MessageBuilder.withPayload(embedded).build(), false); + MessageValues extracted = EmbeddedHeaderUtils.extractHeaders(MessageBuilder.withPayload(embedded).build(), + false); assertThat(new String((byte[]) extracted.getPayload())).isEqualTo("Hello"); assertThat(extracted.get("foo")).isEqualTo("bar"); assertThat(extracted.get("baz")).isNull(); assertThat(extracted.get("contentType")).isEqualTo("text/plain"); assertThat(extracted.get("timestamp")).isNull(); - MessageValues extractedWithRequestHeaders = EmbeddedHeaderUtils.extractHeaders(MessageBuilder.withPayload(embedded).build(), true); + MessageValues extractedWithRequestHeaders = EmbeddedHeaderUtils + .extractHeaders(MessageBuilder.withPayload(embedded).build(), true); assertThat(extractedWithRequestHeaders.get("foo")).isEqualTo("bar"); assertThat(extractedWithRequestHeaders.get("baz")).isNull(); assertThat(extractedWithRequestHeaders.get("contentType")).isEqualTo("text/plain"); @@ -84,7 +88,6 @@ public class MessageConverterTests { assertThat(extracted.get("baz")).isEqualTo("quxx"); } - @Test public void testUnicodeHeader() throws Exception { Message message = MessageBuilder.withPayload("Hello".getBytes()).setHeader("foo", "bar") @@ -94,7 +97,8 @@ public class MessageConverterTests { assertThat(new String(embedded, "UTF-8").substring(1)).isEqualTo( "\u0002\u0003foo\u0000\u0000\u0000\u0005\"bar\"\u0003baz\u0000\u0000\u0000\u0012\"ØØØØØØØØ\"Hello"); - MessageValues extracted = EmbeddedHeaderUtils.extractHeaders(MessageBuilder.withPayload(embedded).build(), false); + MessageValues extracted = EmbeddedHeaderUtils.extractHeaders(MessageBuilder.withPayload(embedded).build(), + false); assertThat(new String((byte[]) extracted.getPayload())).isEqualTo("Hello"); assertThat(extracted.get("foo")).isEqualTo("bar"); assertThat(extracted.get("baz")).isEqualTo("ØØØØØØØØ"); diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/SourceBindingWithGlobalPropertiesOnlyTest.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/SourceBindingWithGlobalPropertiesOnlyTest.java index 6b5a3e212..3236107c5 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/SourceBindingWithGlobalPropertiesOnlyTest.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/SourceBindingWithGlobalPropertiesOnlyTest.java @@ -37,7 +37,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = SourceBindingWithGlobalPropertiesOnlyTest.TestSource.class, properties = { - "spring.cloud.stream.default.contentType=application/json"}) + "spring.cloud.stream.default.contentType=application/json" }) public class SourceBindingWithGlobalPropertiesOnlyTest { @Autowired diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/SourceBindingWithGlobalPropertiesTest.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/SourceBindingWithGlobalPropertiesTest.java index 50345b4fe..b87b41578 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/SourceBindingWithGlobalPropertiesTest.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/SourceBindingWithGlobalPropertiesTest.java @@ -40,7 +40,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; "spring.cloud.stream.default.contentType=application/json", "spring.cloud.stream.bindings.output.destination=ticktock", "spring.cloud.stream.default.producer.requiredGroups=someGroup", - "spring.cloud.stream.bindings.output.producer.headerMode=raw"}) + "spring.cloud.stream.bindings.output.producer.headerMode=raw" }) public class SourceBindingWithGlobalPropertiesTest { @Autowired diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/stub1/StubBinder1.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/stub1/StubBinder1.java index 387bcc2fd..0f5ca7b77 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/stub1/StubBinder1.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/stub1/StubBinder1.java @@ -38,7 +38,8 @@ public class StubBinder1 implements Binder bindConsumer(String name, String group, Object inboundBindTarget, ConsumerProperties properties) { + public Binding bindConsumer(String name, String group, Object inboundBindTarget, + ConsumerProperties properties) { return null; } diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/stub2/StubBinder2.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/stub2/StubBinder2.java index 98ac2e25b..03f713623 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/stub2/StubBinder2.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binder/stub2/StubBinder2.java @@ -35,7 +35,8 @@ public class StubBinder2 implements Binder bindConsumer(String name, String group, Object inboundBindTarget, ConsumerProperties properties) { + public Binding bindConsumer(String name, String group, Object inboundBindTarget, + ConsumerProperties properties) { return null; } diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binding/BindingServiceTests.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binding/BindingServiceTests.java index 8df37b722..63056ddb7 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binding/BindingServiceTests.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binding/BindingServiceTests.java @@ -76,10 +76,9 @@ public class BindingServiceTests { final String inputChannelName = "input"; bindingProperties.put(inputChannelName, props); properties.setBindings(bindingProperties); - DefaultBinderFactory binderFactory = - new DefaultBinderFactory(Collections.singletonMap("mock", - new BinderConfiguration(new BinderType("mock", new Class[]{MockBinderConfiguration.class}), - new Properties(), true, true))); + DefaultBinderFactory binderFactory = new DefaultBinderFactory(Collections.singletonMap("mock", + new BinderConfiguration(new BinderType("mock", new Class[] { MockBinderConfiguration.class }), + new Properties(), true, true))); Binder binder = binderFactory.getBinder("mock", MessageChannel.class); BindingService service = new BindingService(properties, binderFactory); MessageChannel inputChannel = new DirectChannel(); @@ -269,10 +268,9 @@ public class BindingServiceTests { final String outputChannelName = "output"; bindingProperties.put(outputChannelName, props); serviceProperties.setBindings(bindingProperties); - DefaultBinderFactory binderFactory = - new DefaultBinderFactory(Collections.singletonMap("mock", - new BinderConfiguration(new BinderType("mock", new Class[]{MockBinderConfiguration.class}), - new Properties(), true, true))); + DefaultBinderFactory binderFactory = new DefaultBinderFactory(Collections.singletonMap("mock", + new BinderConfiguration(new BinderType("mock", new Class[] { MockBinderConfiguration.class }), + new Properties(), true, true))); BindingService service = new BindingService(serviceProperties, binderFactory); MessageChannel outputChannel = new DirectChannel(); try { @@ -310,13 +308,13 @@ public class BindingServiceTests { assertThat(e).hasMessageContaining("Concurrency should be greater than zero."); } } - + @Test public void testResolveBindableType() { Class bindableType = GenericsUtils.getParameterType(FooBinder.class, Binder.class, 0); assertThat(bindableType).isSameAs(SomeBindableType.class); } - + public static class FooBinder implements Binder { @Override @@ -333,7 +331,7 @@ public class BindingServiceTests { throw new UnsupportedOperationException(); } } - + public static class SomeBindableType { } } diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binding/CustomPartitionedProducerTest.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binding/CustomPartitionedProducerTest.java index a52ef25ed..841461c50 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binding/CustomPartitionedProducerTest.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/binding/CustomPartitionedProducerTest.java @@ -62,15 +62,22 @@ public class CustomPartitionedProducerTest { DirectChannel messageChannel = (DirectChannel) this.testSource.output(); for (ChannelInterceptor channelInterceptor : messageChannel.getChannelInterceptors()) { if (channelInterceptor instanceof MessageConverterConfigurer.PartitioningInterceptor) { - Field partitionHandlerField = ReflectionUtils.findField(MessageConverterConfigurer.PartitioningInterceptor.class, "partitionHandler"); + Field partitionHandlerField = ReflectionUtils + .findField(MessageConverterConfigurer.PartitioningInterceptor.class, "partitionHandler"); ReflectionUtils.makeAccessible(partitionHandlerField); - PartitionHandler partitionHandler = (PartitionHandler) ReflectionUtils.getField(partitionHandlerField, channelInterceptor); - Field partitonKeyExtractorField = ReflectionUtils.findField(PartitionHandler.class, "partitionKeyExtractorStrategy"); + PartitionHandler partitionHandler = (PartitionHandler) ReflectionUtils.getField(partitionHandlerField, + channelInterceptor); + Field partitonKeyExtractorField = ReflectionUtils.findField(PartitionHandler.class, + "partitionKeyExtractorStrategy"); ReflectionUtils.makeAccessible(partitonKeyExtractorField); - Field partitonSelectorField = ReflectionUtils.findField(PartitionHandler.class, "partitionSelectorStrategy"); + Field partitonSelectorField = ReflectionUtils.findField(PartitionHandler.class, + "partitionSelectorStrategy"); ReflectionUtils.makeAccessible(partitonSelectorField); - Assert.assertTrue(((PartitionKeyExtractorStrategy) ReflectionUtils.getField(partitonKeyExtractorField, partitionHandler)).getClass().equals(CustomPartitionKeyExtractorClass.class)); - Assert.assertTrue(((PartitionSelectorStrategy) ReflectionUtils.getField(partitonSelectorField, partitionHandler)).getClass().equals(CustomPartitionSelectorClass.class)); + Assert.assertTrue(((PartitionKeyExtractorStrategy) ReflectionUtils.getField(partitonKeyExtractorField, + partitionHandler)).getClass().equals(CustomPartitionKeyExtractorClass.class)); + Assert.assertTrue( + ((PartitionSelectorStrategy) ReflectionUtils.getField(partitonSelectorField, partitionHandler)) + .getClass().equals(CustomPartitionSelectorClass.class)); } } } diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/config/BinderConfigurationParsingTests.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/config/BinderConfigurationParsingTests.java index 6d6b65b24..65d94eaab 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/config/BinderConfigurationParsingTests.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/config/BinderConfigurationParsingTests.java @@ -53,28 +53,28 @@ public class BinderConfigurationParsingTests { String oneBinderConfiguration = "binder1=org.springframework.cloud.stream.binder.stub1.StubBinder1Configuration"; Resource resource = new InputStreamResource(new ByteArrayInputStream(oneBinderConfiguration.getBytes())); - Collection binderConfigurations - = BinderFactoryConfiguration.parseBinderConfigurations(classLoader, resource); + Collection binderConfigurations = BinderFactoryConfiguration.parseBinderConfigurations(classLoader, + resource); Assert.assertNotNull(binderConfigurations); Assert.assertThat(binderConfigurations.size(), equalTo(1)); Assert.assertThat(binderConfigurations, contains( both(hasProperty("defaultName", equalTo("binder1"))).and( - hasProperty("configurationClasses", hasItemInArray(StubBinder1Configuration.class))) - )); + hasProperty("configurationClasses", hasItemInArray(StubBinder1Configuration.class))))); } @Test public void testParseTwoBindersConfigurations() throws Exception { // this is just checking that resources are passed and classes are loaded properly // class values used here are not binder configurations - String binderConfiguration = "binder1=org.springframework.cloud.stream.binder.stub1.StubBinder1Configuration\n" + + String binderConfiguration = "binder1=org.springframework.cloud.stream.binder.stub1.StubBinder1Configuration\n" + + "binder2=org.springframework.cloud.stream.binder.stub2.StubBinder2ConfigurationA"; - Resource twoBinderConfigurationResource = - new InputStreamResource(new ByteArrayInputStream(binderConfiguration.getBytes())); + Resource twoBinderConfigurationResource = new InputStreamResource( + new ByteArrayInputStream(binderConfiguration.getBytes())); - Collection twoBinderConfigurations - = BinderFactoryConfiguration.parseBinderConfigurations(classLoader, + Collection twoBinderConfigurations = BinderFactoryConfiguration.parseBinderConfigurations( + classLoader, twoBinderConfigurationResource); Assert.assertThat(twoBinderConfigurations.size(), equalTo(2)); @@ -82,8 +82,7 @@ public class BinderConfigurationParsingTests { both(hasProperty("defaultName", equalTo("binder1"))).and( hasProperty("configurationClasses", hasItemInArray(StubBinder1Configuration.class))), both(hasProperty("defaultName", equalTo("binder2"))).and( - hasProperty("configurationClasses", hasItemInArray(StubBinder2ConfigurationA.class))) - )); + hasProperty("configurationClasses", hasItemInArray(StubBinder2ConfigurationA.class))))); } @@ -92,14 +91,15 @@ public class BinderConfigurationParsingTests { public void testParseTwoBindersWithMultipleClasses() throws Exception { // this is just checking that resources are passed and classes are loaded properly // class values used here are not binder configurations - String binderConfiguration = "binder1=org.springframework.cloud.stream.binder.stub1.StubBinder1Configuration\n" + + String binderConfiguration = "binder1=org.springframework.cloud.stream.binder.stub1.StubBinder1Configuration\n" + + "binder2=org.springframework.cloud.stream.binder.stub2.StubBinder2ConfigurationA," + "org.springframework.cloud.stream.binder.stub2.StubBinder2ConfigurationB"; - Resource binderConfigurationResource = - new InputStreamResource(new ByteArrayInputStream(binderConfiguration.getBytes())); + Resource binderConfigurationResource = new InputStreamResource( + new ByteArrayInputStream(binderConfiguration.getBytes())); - Collection binderConfigurations - = BinderFactoryConfiguration.parseBinderConfigurations(classLoader, binderConfigurationResource); + Collection binderConfigurations = BinderFactoryConfiguration.parseBinderConfigurations(classLoader, + binderConfigurationResource); Assert.assertThat(binderConfigurations.size(), equalTo(2)); Assert.assertThat(binderConfigurations, containsInAnyOrder( @@ -107,8 +107,7 @@ public class BinderConfigurationParsingTests { hasProperty("configurationClasses", hasItemInArray(StubBinder1Configuration.class))), both(hasProperty("defaultName", equalTo("binder2"))).and( hasProperty("configurationClasses", arrayContainingInAnyOrder(StubBinder2ConfigurationA.class, - StubBinder2ConfigurationB.class))) - )); + StubBinder2ConfigurationB.class))))); } } diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/interceptor/BoundChannelsInterceptedTest.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/interceptor/BoundChannelsInterceptedTest.java index d72502bc6..db6664a17 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/interceptor/BoundChannelsInterceptedTest.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/interceptor/BoundChannelsInterceptedTest.java @@ -50,13 +50,13 @@ public class BoundChannelsInterceptedTest { public static final Message TEST_MESSAGE = MessageBuilder.withPayload("bar").build(); - @Autowired - ChannelInterceptor channelInterceptor; - @Autowired @Bindings(BoundChannelsInterceptedTest.Foo.class) public Sink fooSink; + @Autowired + ChannelInterceptor channelInterceptor; + @Test public void testBoundChannelsIntercepted() { this.fooSink.input().send(TEST_MESSAGE); @@ -64,7 +64,6 @@ public class BoundChannelsInterceptedTest { verifyNoMoreInteractions(this.channelInterceptor); } - @SpringBootApplication @EnableBinding(Sink.class) @Import(MockBinderRegistryConfiguration.class) diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/partitioning/PartitionedConsumerTest.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/partitioning/PartitionedConsumerTest.java index 2e1e7a2ba..c8b487b9c 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/partitioning/PartitionedConsumerTest.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/partitioning/PartitionedConsumerTest.java @@ -74,7 +74,7 @@ public class PartitionedConsumerTest { @EnableBinding(Sink.class) @EnableAutoConfiguration - @Import({MockBinderRegistryConfiguration.class, BinderFactoryConfiguration.class}) + @Import({ MockBinderRegistryConfiguration.class, BinderFactoryConfiguration.class }) @PropertySource("classpath:/org/springframework/cloud/stream/binder/partitioned-consumer-test.properties") public static class TestSink { diff --git a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/partitioning/PartitionedProducerTest.java b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/partitioning/PartitionedProducerTest.java index 7d0b7d6aa..c03ef86d5 100644 --- a/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/partitioning/PartitionedProducerTest.java +++ b/spring-cloud-stream/src/test/java/org/springframework/cloud/stream/partitioning/PartitionedProducerTest.java @@ -67,7 +67,6 @@ public class PartitionedProducerTest { verifyNoMoreInteractions(binder); } - @EnableBinding(Source.class) @EnableAutoConfiguration @Import(MockBinderRegistryConfiguration.class)