From 9225c514fed70f5f1b0840465438d911d808f832 Mon Sep 17 00:00:00 2001 From: Gary Russell Date: Wed, 26 Oct 2016 13:37:03 -0400 Subject: [PATCH] Core Lambdas - Phase 1 src/main Also package-protect private inner class ctors. Core Lambdas - Phase 2 src/test --- .../AbstractCorrelatingMessageHandler.java | 4 + .../aop/PublisherAnnotationAdvisor.java | 6 +- .../channel/DefaultHeaderChannelRegistry.java | 2 +- .../integration/channel/ExecutorChannel.java | 19 +- .../integration/channel/PriorityChannel.java | 4 +- .../channel/PublishSubscribeChannel.java | 19 +- ...eadStatePropagationChannelInterceptor.java | 2 +- .../codec/kryo/AbstractKryoCodec.java | 31 +-- ...rviceActivatorAnnotationPostProcessor.java | 2 +- .../AbstractIntegrationNamespaceHandler.java | 4 + .../core/AsyncMessagingTemplate.java | 157 ++--------- .../dispatcher/BroadcastingDispatcher.java | 19 +- .../dispatcher/UnicastingDispatcher.java | 20 +- .../endpoint/AbstractPollingEndpoint.java | 47 ++-- .../endpoint/ReactiveConsumer.java | 2 +- .../expression/ExpressionEvalMap.java | 12 +- ...oadableResourceBundleExpressionSource.java | 12 +- ...ewayCompletableFutureProxyFactoryBean.java | 2 +- .../gateway/GatewayProxyFactoryBean.java | 12 +- .../gateway/MessagingGatewaySupport.java | 4 + .../AbstractReplyProducingMessageHandler.java | 4 + .../integration/handler/DelayHandler.java | 49 ++-- .../ExpressionCommandMessageProcessor.java | 2 +- .../handler/MessageHandlerChain.java | 6 +- .../advice/AbstractRequestHandlerAdvice.java | 4 +- .../RequestHandlerCircuitBreakerAdvice.java | 6 +- .../advice/RequestHandlerRetryAdvice.java | 19 +- .../handler/advice/RetryStateGenerator.java | 2 + .../scattergather/ScatterGatherHandler.java | 29 +- .../scheduling/PollSkipAdvice.java | 6 +- .../store/AbstractKeyValueMessageStore.java | 2 +- .../store/PersistentMessageGroup.java | 8 +- .../support/SmartLifecycleRoleController.java | 23 +- .../converter/SimpleMessageConverter.java | 8 + .../support/json/BoonJsonObjectMapper.java | 8 +- .../leader/LockRegistryLeaderInitiator.java | 8 + .../graph/IntegrationGraphServer.java | 4 + .../management/graph/MessageChannelNode.java | 2 +- .../management/graph/MessageGatewayNode.java | 2 +- .../management/graph/MessageHandlerNode.java | 2 +- .../management/graph/MessageSourceNode.java | 2 +- ...aultTransactionSynchronizationFactory.java | 2 +- .../transformer/ContentEnricher.java | 4 + .../util/ErrorHandlingTaskExecutor.java | 15 +- .../util/MessagingAnnotationUtils.java | 18 +- .../util/MessagingMethodInvokerHelper.java | 2 +- ...bstractCorrelatingMessageHandlerTests.java | 148 +++------- ...atingMessageGroupProcessorHeaderTests.java | 4 + .../aggregator/AggregatorTests.java | 58 +--- .../aggregator/ConcurrentAggregatorTests.java | 8 + .../CorrelatingMessageBarrierTests.java | 24 +- .../CorrelatingMessageHandlerTests.java | 10 +- .../CorrelationStrategyAdapterTests.java | 20 ++ .../aggregator/ResequencerTests.java | 7 +- .../AggregatorSupportedUseCasesTests.java | 25 +- ...regatorWithCustomReleaseStrategyTests.java | 60 ++-- .../PartialSequencesWithGapsTests.java | 9 +- .../MessagePublishingInterceptorTests.java | 8 + .../channel/ChannelPurgerTests.java | 31 +-- .../channel/DatatypeChannelTests.java | 20 ++ .../channel/DirectChannelTests.java | 40 +-- .../DispatchingChannelErrorHandlingTests.java | 24 +- .../channel/ExecutorChannelTests.java | 4 + ...dDispatcherConfigurationScenarioTests.java | 260 +++++++----------- .../integration/channel/P2pChannelTests.java | 51 +--- .../channel/PriorityChannelTests.java | 39 +-- .../channel/QueueChannelTests.java | 94 +++---- .../config/ThreadLocalChannelParserTests.java | 24 +- .../interceptor/ChannelInterceptorTests.java | 34 ++- .../registry/HeaderChannelRegistryTests.java | 18 +- .../config/AggregatorParserTests.java | 12 +- .../integration/config/ChainParserTests.java | 11 +- .../PublishSubscribeChannelParserTests.java | 12 +- ...PollingChannelAdapterFactoryBeanTests.java | 4 + .../FilterAnnotationPostProcessorTests.java | 21 +- ...MessagingAnnotationPostProcessorTests.java | 12 +- ...ingAnnotationsWithBeanAnnotationTests.java | 9 +- ...serWithExistingConversionServiceTests.java | 14 + .../xml/DelegatingConsumerParserTests.java | 9 +- ...herMaxSubscribersOverrideDefaultTests.java | 15 +- .../config/xml/GatewayParserTests.java | 63 ++--- .../ObjectToStringTransformerParserTests.java | 4 + ...adDeserializingTransformerParserTests.java | 7 +- ...loadSerializingTransformerParserTests.java | 8 +- .../xml/PublishingInterceptorParserTests.java | 24 +- .../xml/ServiceActivatorParserTests.java | 8 + .../configuration/EnableIntegrationTests.java | 29 +- .../core/AsyncMessagingTemplateTests.java | 23 +- .../integration/core/MessageHistoryTests.java | 2 +- .../core/MessageIdGenerationTests.java | 7 +- .../BroadcastingDispatcherTests.java | 35 +-- .../OrderedAwareCopyOnWriteArraySetTests.java | 75 +++-- .../RoundRobinDispatcherConcurrentTests.java | 61 ++-- .../dispatcher/UnicastingDispatcherTests.java | 13 +- .../endpoint/CorrelationIdTests.java | 9 +- ...aluatingMessageSourceIntegrationTests.java | 9 +- .../endpoint/MessageProducerSupportTests.java | 46 ++-- .../PollingConsumerEndpointTests.java | 31 ++- .../endpoint/PollingLifecycleTests.java | 28 +- ...PseudoTransactionalMessageSourceTests.java | 176 +++++------- ...ServiceActivatorMethodResolutionTests.java | 21 +- .../expression/ForeignClassloaderTests.java | 17 +- .../filter/MessageFilterTests.java | 51 +--- .../filter/MethodInvokingSelectorTests.java | 4 + .../gateway/AsyncGatewayTests.java | 41 ++- .../gateway/GatewayInterfaceTests.java | 92 +++---- .../GatewayInvokingMessageHandlerTests.java | 23 +- .../gateway/GatewayProxyFactoryBeanTests.java | 57 ++-- .../gateway/MessagingGatewayTests.java | 98 +++---- .../handler/AsyncHandlerTests.java | 52 ++-- .../handler/DelayHandlerTests.java | 83 ++---- ...essionEvaluatingMessageProcessorTests.java | 11 +- .../MethodInvokingMessageProcessorTests.java | 33 +++ .../advice/AdvisedMessageHandlerTests.java | 120 ++------ ...AnotatedTests.java => AnnotatedTests.java} | 2 +- .../MessageHistoryIntegrationTests.java | 25 +- ...actJsonSymmetricalMessageMappingTests.java | 4 +- .../json/JsonOutboundMessageMapperTests.java | 2 +- .../mapping/HeaderMapperTests.java | 5 +- .../message/MessageBuilderAtConfigTests.java | 7 + .../MethodInvokingMessageHandlerTests.java | 6 + .../MethodInvokingMessageSourceTests.java | 4 + .../message/PayloadAndHeaderMappingTests.java | 14 +- .../router/HeaderValueRouterTests.java | 9 +- .../router/MethodInvokingRouterTests.java | 9 +- .../router/RecipientListRouterTests.java | 8 + .../router/RouterConcurrencyTest.java | 24 +- .../selector/MessageSelectorChainTests.java | 5 +- .../splitter/MethodInvokingSplitterTests.java | 4 +- .../splitter/StreamingSplitterTests.java | 44 +-- .../store/MessageGroupQueueTests.java | 45 ++- .../integration/store/MessageStoreTests.java | 21 +- .../store/SimpleMessageStoreTests.java | 41 +-- .../MethodInvokingTransformerTests.java | 4 + .../ObjectToStringTransformerTests.java | 5 + .../PayloadDeserializingTransformerTests.java | 11 +- .../PayloadSerializingTransformerTests.java | 11 +- .../transformer/PayloadTransformerTests.java | 5 + ...PayloadTypeConvertingTransformerTests.java | 11 +- .../util/BeanFactoryTypeConverterTests.java | 28 +- .../util/CallerBlocksPolicyTests.java | 49 ++-- 141 files changed, 1392 insertions(+), 2128 deletions(-) rename spring-integration-core/src/test/java/org/springframework/integration/history/{AnotatedTests.java => AnnotatedTests.java} (98%) diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandler.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandler.java index 13643b6143..70461f4007 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandler.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandler.java @@ -733,6 +733,10 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP private class ForceReleaseMessageGroupProcessor implements MessageGroupProcessor { + ForceReleaseMessageGroupProcessor() { + super(); + } + @Override public Object processMessageGroup(MessageGroup group) { forceComplete(group); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aop/PublisherAnnotationAdvisor.java b/spring-integration-core/src/main/java/org/springframework/integration/aop/PublisherAnnotationAdvisor.java index 5b31225f78..34c72b4f7c 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aop/PublisherAnnotationAdvisor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aop/PublisherAnnotationAdvisor.java @@ -122,7 +122,7 @@ public class PublisherAnnotationAdvisor extends AbstractPointcutAdvisor implemen * interfaces for the annotation type as well (even if the annotation type * is not marked as inherited itself) */ - private MetaAnnotationMatchingPointcut(Class classAnnotationType, boolean checkInherited) { + MetaAnnotationMatchingPointcut(Class classAnnotationType, boolean checkInherited) { this.classFilter = new AnnotationClassFilter(classAnnotationType, checkInherited); this.methodMatcher = MethodMatcher.TRUE; } @@ -134,7 +134,7 @@ public class PublisherAnnotationAdvisor extends AbstractPointcutAdvisor implemen * @param methodAnnotationType the annotation type to look for at the method level * (can be null) */ - private MetaAnnotationMatchingPointcut( + MetaAnnotationMatchingPointcut( Class classAnnotationType, Class methodAnnotationType) { Assert.isTrue((classAnnotationType != null || methodAnnotationType != null), @@ -177,7 +177,7 @@ public class PublisherAnnotationAdvisor extends AbstractPointcutAdvisor implemen * Create a new AnnotationClassFilter for the given annotation type. * @param annotationType the annotation type to look for */ - private MetaAnnotationMethodMatcher(Class annotationType) { + MetaAnnotationMethodMatcher(Class annotationType) { super(annotationType); this.annotationType = annotationType; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/channel/DefaultHeaderChannelRegistry.java b/spring-integration-core/src/main/java/org/springframework/integration/channel/DefaultHeaderChannelRegistry.java index e60a1b864e..258ac63407 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/channel/DefaultHeaderChannelRegistry.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/channel/DefaultHeaderChannelRegistry.java @@ -235,7 +235,7 @@ public class DefaultHeaderChannelRegistry extends IntegrationObjectSupport private final long expireAt; - private MessageChannelWrapper(MessageChannel channel, long expireAt) { + MessageChannelWrapper(MessageChannel channel, long expireAt) { this.channel = channel; this.expireAt = expireAt; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/channel/ExecutorChannel.java b/spring-integration-core/src/main/java/org/springframework/integration/channel/ExecutorChannel.java index e780579d33..a58369b1ac 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/channel/ExecutorChannel.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/channel/ExecutorChannel.java @@ -20,13 +20,11 @@ import java.util.concurrent.Executor; import org.springframework.integration.context.IntegrationProperties; import org.springframework.integration.dispatcher.LoadBalancingStrategy; -import org.springframework.integration.dispatcher.MessageHandlingTaskDecorator; import org.springframework.integration.dispatcher.RoundRobinLoadBalancingStrategy; import org.springframework.integration.dispatcher.UnicastingDispatcher; import org.springframework.integration.support.channel.BeanFactoryChannelResolver; import org.springframework.integration.util.ErrorHandlingTaskExecutor; import org.springframework.messaging.MessageChannel; -import org.springframework.messaging.support.MessageHandlingRunnable; import org.springframework.util.Assert; import org.springframework.util.ErrorHandler; @@ -120,18 +118,13 @@ public class ExecutorChannel extends AbstractExecutorChannel { unicastingDispatcher.setLoadBalancingStrategy(this.loadBalancingStrategy); } - unicastingDispatcher.setMessageHandlingTaskDecorator(new MessageHandlingTaskDecorator() { - - @Override - public Runnable decorate(MessageHandlingRunnable task) { - if (ExecutorChannel.this.executorInterceptorsSize > 0) { - return new MessageHandlingTask(task); - } - else { - return task; - } + unicastingDispatcher.setMessageHandlingTaskDecorator(task -> { + if (ExecutorChannel.this.executorInterceptorsSize > 0) { + return new MessageHandlingTask(task); + } + else { + return task; } - }); this.dispatcher = unicastingDispatcher; diff --git a/spring-integration-core/src/main/java/org/springframework/integration/channel/PriorityChannel.java b/spring-integration-core/src/main/java/org/springframework/integration/channel/PriorityChannel.java index 60dd1f00fb..c61775cbfd 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/channel/PriorityChannel.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/channel/PriorityChannel.java @@ -112,7 +112,7 @@ public class PriorityChannel extends QueueChannel { private final Comparator> targetComparator; - private SequenceFallbackComparator(Comparator> targetComparator) { + SequenceFallbackComparator(Comparator> targetComparator) { this.targetComparator = targetComparator; } @@ -145,7 +145,7 @@ public class PriorityChannel extends QueueChannel { private final Message rootMessage; private final long sequence; - private MessageWrapper(Message rootMessage) { + MessageWrapper(Message rootMessage) { this.rootMessage = rootMessage; this.sequence = PriorityChannel.this.sequenceCounter.incrementAndGet(); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/channel/PublishSubscribeChannel.java b/spring-integration-core/src/main/java/org/springframework/integration/channel/PublishSubscribeChannel.java index f377e920c7..3e732ee84a 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/channel/PublishSubscribeChannel.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/channel/PublishSubscribeChannel.java @@ -20,10 +20,8 @@ import java.util.concurrent.Executor; import org.springframework.integration.context.IntegrationProperties; import org.springframework.integration.dispatcher.BroadcastingDispatcher; -import org.springframework.integration.dispatcher.MessageHandlingTaskDecorator; import org.springframework.integration.support.channel.BeanFactoryChannelResolver; import org.springframework.integration.util.ErrorHandlingTaskExecutor; -import org.springframework.messaging.support.MessageHandlingRunnable; import org.springframework.util.Assert; import org.springframework.util.ErrorHandler; @@ -158,18 +156,13 @@ public class PublishSubscribeChannel extends AbstractExecutorChannel { } getDispatcher().setBeanFactory(this.getBeanFactory()); - getDispatcher().setMessageHandlingTaskDecorator(new MessageHandlingTaskDecorator() { - - @Override - public Runnable decorate(MessageHandlingRunnable task) { - if (PublishSubscribeChannel.this.executorInterceptorsSize > 0) { - return new MessageHandlingTask(task); - } - else { - return task; - } + getDispatcher().setMessageHandlingTaskDecorator(task -> { + if (PublishSubscribeChannel.this.executorInterceptorsSize > 0) { + return new MessageHandlingTask(task); + } + else { + return task; } - }); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/channel/interceptor/ThreadStatePropagationChannelInterceptor.java b/spring-integration-core/src/main/java/org/springframework/integration/channel/interceptor/ThreadStatePropagationChannelInterceptor.java index 5e7212b6c7..5b8fd27f46 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/channel/interceptor/ThreadStatePropagationChannelInterceptor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/channel/interceptor/ThreadStatePropagationChannelInterceptor.java @@ -99,7 +99,7 @@ public abstract class ThreadStatePropagationChannelInterceptor private final S state; @SuppressWarnings("unchecked") - private MessageWithThreadState(Message message, S state) { + MessageWithThreadState(Message message, S state) { this.message = (Message) message; this.state = state; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/codec/kryo/AbstractKryoCodec.java b/spring-integration-core/src/main/java/org/springframework/integration/codec/kryo/AbstractKryoCodec.java index f4a5991a14..f884e4df60 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/codec/kryo/AbstractKryoCodec.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/codec/kryo/AbstractKryoCodec.java @@ -27,7 +27,6 @@ import org.springframework.util.Assert; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; -import com.esotericsoftware.kryo.pool.KryoCallback; import com.esotericsoftware.kryo.pool.KryoFactory; import com.esotericsoftware.kryo.pool.KryoPool; @@ -43,13 +42,11 @@ public abstract class AbstractKryoCodec implements Codec { protected final KryoPool pool; protected AbstractKryoCodec() { - KryoFactory factory = new KryoFactory() { - public Kryo create() { - Kryo kryo = new Kryo(); - // configure Kryo instance, customize settings - configureKryoInstance(kryo); - return kryo; - } + KryoFactory factory = () -> { + Kryo kryo = new Kryo(); + // configure Kryo instance, customize settings + configureKryoInstance(kryo); + return kryo; }; // Build pool with SoftReferences enabled (optional) this.pool = new KryoPool.Builder(factory).softReferences().build(); @@ -60,13 +57,9 @@ public abstract class AbstractKryoCodec implements Codec { Assert.notNull(object, "cannot encode a null object"); Assert.notNull(outputStream, "'outputSteam' cannot be null"); final Output output = (outputStream instanceof Output ? (Output) outputStream : new Output(outputStream)); - this.pool.run(new KryoCallback() { - - public Object execute(Kryo kryo) { - doEncode(kryo, object, output); - return Void.class; - } - + this.pool.run(kryo -> { + doEncode(kryo, object, output); + return Void.class; }); output.close(); } @@ -90,13 +83,7 @@ public abstract class AbstractKryoCodec implements Codec { final Input input = (inputStream instanceof Input ? (Input) inputStream : new Input(inputStream)); T result = null; try { - result = this.pool.run(new KryoCallback() { - - public T execute(Kryo kryo) { - return doDecode(kryo, input, type); - } - - }); + result = this.pool.run(kryo -> doDecode(kryo, input, type)); } finally { input.close(); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/config/annotation/ServiceActivatorAnnotationPostProcessor.java b/spring-integration-core/src/main/java/org/springframework/integration/config/annotation/ServiceActivatorAnnotationPostProcessor.java index 1bb7ff3161..d9c10716a4 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/config/annotation/ServiceActivatorAnnotationPostProcessor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/config/annotation/ServiceActivatorAnnotationPostProcessor.java @@ -89,7 +89,7 @@ public class ServiceActivatorAnnotationPostProcessor extends AbstractMethodAnnot private final MessageHandler target; - private ReplyProducingMessageHandlerWrapper(MessageHandler target) { + ReplyProducingMessageHandlerWrapper(MessageHandler target) { this.target = target; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/config/xml/AbstractIntegrationNamespaceHandler.java b/spring-integration-core/src/main/java/org/springframework/integration/config/xml/AbstractIntegrationNamespaceHandler.java index 58d54df809..510ccae28e 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/config/xml/AbstractIntegrationNamespaceHandler.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/config/xml/AbstractIntegrationNamespaceHandler.java @@ -93,6 +93,10 @@ public abstract class AbstractIntegrationNamespaceHandler implements NamespaceHa private class NamespaceHandlerDelegate extends NamespaceHandlerSupport { + NamespaceHandlerDelegate() { + super(); + } + @Override public void init() { AbstractIntegrationNamespaceHandler.this.init(); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/core/AsyncMessagingTemplate.java b/spring-integration-core/src/main/java/org/springframework/integration/core/AsyncMessagingTemplate.java index 8e403de014..fe4ecdf5cb 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/core/AsyncMessagingTemplate.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/core/AsyncMessagingTemplate.java @@ -16,7 +16,6 @@ package org.springframework.integration.core; -import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.Future; @@ -47,221 +46,119 @@ public class AsyncMessagingTemplate extends MessagingTemplate implements AsyncMe @Override public Future asyncSend(final Message message) { - return this.executor.submit(new Runnable() { - @Override - public void run() { - send(message); - } - }); + return this.executor.submit(() -> send(message)); } @Override public Future asyncSend(final MessageChannel channel, final Message message) { - return this.executor.submit(new Runnable() { - @Override - public void run() { - send(channel, message); - } - }); + return this.executor.submit(() -> send(channel, message)); } @Override public Future asyncSend(final String channelName, final Message message) { - return this.executor.submit(new Runnable() { - @Override - public void run() { - send(channelName, message); - } - }); + return this.executor.submit(() -> send(channelName, message)); } @Override public Future asyncConvertAndSend(final Object object) { - return this.executor.submit(new Runnable() { - @Override - public void run() { - convertAndSend(object); - } - }); + return this.executor.submit(() -> convertAndSend(object)); } @Override public Future asyncConvertAndSend(final MessageChannel channel, final Object object) { - return this.executor.submit(new Runnable() { - @Override - public void run() { - convertAndSend(channel, object); - } - }); + return this.executor.submit(() -> convertAndSend(channel, object)); } @Override public Future asyncConvertAndSend(final String channelName, final Object object) { - return this.executor.submit(new Runnable() { - @Override - public void run() { - convertAndSend(channelName, object); - } - }); + return this.executor.submit(() -> convertAndSend(channelName, object)); } @Override public Future> asyncReceive() { - return this.executor.submit(new Callable>() { - @Override - public Message call() throws Exception { - return receive(); - } - }); + return this.executor.submit(() -> receive()); } @Override public Future> asyncReceive(final PollableChannel channel) { - return this.executor.submit(new Callable>() { - @Override - public Message call() throws Exception { - return receive(channel); - } - }); + return this.executor.submit(() -> receive(channel)); } @Override public Future> asyncReceive(final String channelName) { - return this.executor.submit(new Callable>() { - @Override - public Message call() throws Exception { - return receive(channelName); - } - }); + return this.executor.submit(() -> receive(channelName)); } @Override @SuppressWarnings("unchecked") public Future asyncReceiveAndConvert() { - return this.executor.submit(new Callable() { - @Override - public R call() throws Exception { - return (R) receiveAndConvert(null); - } - }); + return this.executor.submit(() -> (R) receiveAndConvert(null)); } @Override @SuppressWarnings("unchecked") public Future asyncReceiveAndConvert(final PollableChannel channel) { - return this.executor.submit(new Callable() { - @Override - public R call() throws Exception { - return (R) receiveAndConvert(channel, null); - } - }); + return this.executor.submit(() -> (R) receiveAndConvert(channel, null)); } @Override @SuppressWarnings("unchecked") public Future asyncReceiveAndConvert(final String channelName) { - return this.executor.submit(new Callable() { - @Override - public R call() throws Exception { - return (R) receiveAndConvert(channelName, null); - } - }); + return this.executor.submit(() -> (R) receiveAndConvert(channelName, null)); } @Override public Future> asyncSendAndReceive(final Message requestMessage) { - return this.executor.submit(new Callable>() { - @Override - public Message call() throws Exception { - return sendAndReceive(requestMessage); - } - }); + return this.executor.submit(() -> sendAndReceive(requestMessage)); } @Override public Future> asyncSendAndReceive(final MessageChannel channel, final Message requestMessage) { - return this.executor.submit(new Callable>() { - @Override - public Message call() throws Exception { - return sendAndReceive(channel, requestMessage); - } - }); + return this.executor.submit(() -> sendAndReceive(channel, requestMessage)); } @Override public Future> asyncSendAndReceive(final String channelName, final Message requestMessage) { - return this.executor.submit(new Callable>() { - @Override - public Message call() throws Exception { - return sendAndReceive(channelName, requestMessage); - } - }); + return this.executor.submit(() -> sendAndReceive(channelName, requestMessage)); } @Override @SuppressWarnings("unchecked") public Future asyncConvertSendAndReceive(final Object request) { - return this.executor.submit(new Callable() { - @Override - public R call() throws Exception { - return (R) convertSendAndReceive(request, null); - } - }); + return this.executor.submit(() -> (R) convertSendAndReceive(request, null)); } @Override @SuppressWarnings("unchecked") public Future asyncConvertSendAndReceive(final MessageChannel channel, final Object request) { - return this.executor.submit(new Callable() { - @Override - public R call() throws Exception { - return (R) convertSendAndReceive(channel, request, null); - } - }); + return this.executor.submit(() -> (R) convertSendAndReceive(channel, request, null)); } @Override @SuppressWarnings("unchecked") public Future asyncConvertSendAndReceive(final String channelName, final Object request) { - return this.executor.submit(new Callable() { - @Override - public R call() throws Exception { - return (R) convertSendAndReceive(channelName, request, null); - } - }); + return this.executor.submit(() -> (R) convertSendAndReceive(channelName, request, null)); } @Override @SuppressWarnings("unchecked") - public Future asyncConvertSendAndReceive(final Object request, final MessagePostProcessor requestPostProcessor) { - return this.executor.submit(new Callable() { - @Override - public R call() throws Exception { - return (R) convertSendAndReceive(request, null, requestPostProcessor); - } - }); + public Future asyncConvertSendAndReceive(final Object request, + final MessagePostProcessor requestPostProcessor) { + return this.executor.submit(() -> (R) convertSendAndReceive(request, null, requestPostProcessor)); } @Override @SuppressWarnings("unchecked") - public Future asyncConvertSendAndReceive(final MessageChannel channel, final Object request, final MessagePostProcessor requestPostProcessor) { - return this.executor.submit(new Callable() { - @Override - public R call() throws Exception { - return (R) convertSendAndReceive(channel, request, null, requestPostProcessor); - } - }); + public Future asyncConvertSendAndReceive(final MessageChannel channel, final Object request, + final MessagePostProcessor requestPostProcessor) { + return this.executor.submit(() -> (R) convertSendAndReceive(channel, request, null, requestPostProcessor)); } @Override @SuppressWarnings("unchecked") - public Future asyncConvertSendAndReceive(final String channelName, final Object request, final MessagePostProcessor requestPostProcessor) { - return this.executor.submit(new Callable() { - @Override - public R call() throws Exception { - return (R) convertSendAndReceive(channelName, request, null, requestPostProcessor); - } - }); + public Future asyncConvertSendAndReceive(final String channelName, final Object request, + final MessagePostProcessor requestPostProcessor) { + return this.executor.submit(() -> (R) convertSendAndReceive(channelName, request, null, requestPostProcessor)); } } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/dispatcher/BroadcastingDispatcher.java b/spring-integration-core/src/main/java/org/springframework/integration/dispatcher/BroadcastingDispatcher.java index 9f2f35c923..ec973b0488 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/dispatcher/BroadcastingDispatcher.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/dispatcher/BroadcastingDispatcher.java @@ -66,15 +66,7 @@ public class BroadcastingDispatcher extends AbstractDispatcher implements BeanFa private volatile boolean messageBuilderFactorySet; - private volatile MessageHandlingTaskDecorator messageHandlingTaskDecorator = - new MessageHandlingTaskDecorator() { - - @Override - public Runnable decorate(MessageHandlingRunnable task) { - return task; - } - - }; + private volatile MessageHandlingTaskDecorator messageHandlingTaskDecorator = task -> task; private BeanFactory beanFactory; @@ -202,14 +194,7 @@ public class BroadcastingDispatcher extends AbstractDispatcher implements BeanFa private Runnable createMessageHandlingTask(final MessageHandler handler, final Message message) { MessageHandlingRunnable task = new MessageHandlingRunnable() { - private final MessageHandler delegate = new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - invokeHandler(handler, message); - } - - }; + private final MessageHandler delegate = message1 -> invokeHandler(handler, message1); @Override public void run() { diff --git a/spring-integration-core/src/main/java/org/springframework/integration/dispatcher/UnicastingDispatcher.java b/spring-integration-core/src/main/java/org/springframework/integration/dispatcher/UnicastingDispatcher.java index d6d8ba7af2..32801cbccc 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/dispatcher/UnicastingDispatcher.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/dispatcher/UnicastingDispatcher.java @@ -25,7 +25,6 @@ import org.springframework.integration.MessageDispatchingException; import org.springframework.messaging.Message; import org.springframework.messaging.MessageDeliveryException; import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.MessageHandlingRunnable; import org.springframework.util.Assert; @@ -52,14 +51,7 @@ import org.springframework.util.Assert; */ public class UnicastingDispatcher extends AbstractDispatcher { - private final MessageHandler dispatchHandler = new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - doDispatch(message); - } - - }; + private final MessageHandler dispatchHandler = message -> doDispatch(message); private final Executor executor; @@ -67,15 +59,7 @@ public class UnicastingDispatcher extends AbstractDispatcher { private volatile LoadBalancingStrategy loadBalancingStrategy; - private volatile MessageHandlingTaskDecorator messageHandlingTaskDecorator = - new MessageHandlingTaskDecorator() { - - @Override - public Runnable decorate(MessageHandlingRunnable task) { - return task; - } - - }; + private volatile MessageHandlingTaskDecorator messageHandlingTaskDecorator = task -> task; public UnicastingDispatcher() { this.executor = null; diff --git a/spring-integration-core/src/main/java/org/springframework/integration/endpoint/AbstractPollingEndpoint.java b/spring-integration-core/src/main/java/org/springframework/integration/endpoint/AbstractPollingEndpoint.java index 2a3866a2da..1b2fb85d79 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/endpoint/AbstractPollingEndpoint.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/endpoint/AbstractPollingEndpoint.java @@ -183,13 +183,7 @@ public abstract class AbstractPollingEndpoint extends AbstractEndpoint implement } } - Callable pollingTask = new Callable() { - - @Override - public Boolean call() throws Exception { - return doPoll(); - } - }; + Callable pollingTask = () -> doPoll(); List adviceChain = this.adviceChain; if (!CollectionUtils.isEmpty(adviceChain)) { @@ -335,37 +329,32 @@ public abstract class AbstractPollingEndpoint extends AbstractEndpoint implement private final Callable pollingTask; - private Poller(Callable pollingTask) { + Poller(Callable pollingTask) { this.pollingTask = pollingTask; } @Override public void run() { - AbstractPollingEndpoint.this.taskExecutor.execute(new Runnable() { - - @Override - public void run() { - int count = 0; - while (AbstractPollingEndpoint.this.initialized - && (AbstractPollingEndpoint.this.maxMessagesPerPoll <= 0 - || count < AbstractPollingEndpoint.this.maxMessagesPerPoll)) { - try { - if (!Poller.this.pollingTask.call()) { - break; - } - count++; + AbstractPollingEndpoint.this.taskExecutor.execute(() -> { + int count = 0; + while (AbstractPollingEndpoint.this.initialized + && (AbstractPollingEndpoint.this.maxMessagesPerPoll <= 0 + || count < AbstractPollingEndpoint.this.maxMessagesPerPoll)) { + try { + if (!Poller.this.pollingTask.call()) { + break; } - catch (Exception e) { - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } - else { - throw new MessageHandlingException(new ErrorMessage(e), e); - } + count++; + } + catch (Exception e) { + if (e instanceof RuntimeException) { + throw (RuntimeException) e; + } + else { + throw new MessageHandlingException(new ErrorMessage(e), e); } } } - }); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/endpoint/ReactiveConsumer.java b/spring-integration-core/src/main/java/org/springframework/integration/endpoint/ReactiveConsumer.java index 4161bc3220..acd9ef245d 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/endpoint/ReactiveConsumer.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/endpoint/ReactiveConsumer.java @@ -153,7 +153,7 @@ public class ReactiveConsumer extends AbstractEndpoint { private Subscription actualSubscription; - private SubscribableChannelPublisherAdapter(SubscribableChannel channel) { + SubscribableChannelPublisherAdapter(SubscribableChannel channel) { this.channel = channel; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/expression/ExpressionEvalMap.java b/spring-integration-core/src/main/java/org/springframework/integration/expression/ExpressionEvalMap.java index 81fe87b284..f341b3be5f 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/expression/ExpressionEvalMap.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/expression/ExpressionEvalMap.java @@ -64,14 +64,7 @@ import org.springframework.util.Assert; */ public final class ExpressionEvalMap extends AbstractMap { - public static final EvaluationCallback SIMPLE_CALLBACK = new EvaluationCallback() { - - @Override - public Object evaluate(Expression expression) { - return expression.getValue(); - } - - }; + public static final EvaluationCallback SIMPLE_CALLBACK = expression -> expression.getValue(); private final Map original; @@ -187,6 +180,7 @@ public final class ExpressionEvalMap extends AbstractMap { * Implementations of this interface can be provided to build 'on demand {@link #get(Object)} logic' * for {@link ExpressionEvalMap}. */ + @FunctionalInterface public interface EvaluationCallback { Object evaluate(Expression expression); @@ -313,7 +307,7 @@ public final class ExpressionEvalMap extends AbstractMap { } - + @FunctionalInterface public interface ExpressionEvalMapFinalBuilder { ExpressionEvalMap build(); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/expression/ReloadableResourceBundleExpressionSource.java b/spring-integration-core/src/main/java/org/springframework/integration/expression/ReloadableResourceBundleExpressionSource.java index 03ac013c8e..3d4d1e7382 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/expression/ReloadableResourceBundleExpressionSource.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/expression/ReloadableResourceBundleExpressionSource.java @@ -537,7 +537,7 @@ public class ReloadableResourceBundleExpressionSource implements ExpressionSourc * change detection, and the timestamp of the last refresh attempt * (updated every time the cache entry gets re-validated). */ - private final class PropertiesHolder { + private static final class PropertiesHolder { private Properties properties; @@ -545,13 +545,13 @@ public class ReloadableResourceBundleExpressionSource implements ExpressionSourc private long refreshTimestamp = -1; - - private PropertiesHolder(Properties properties, long fileTimestamp) { - this.properties = properties; - this.fileTimestamp = fileTimestamp; + PropertiesHolder() { + super(); } - private PropertiesHolder() { + PropertiesHolder(Properties properties, long fileTimestamp) { + this.properties = properties; + this.fileTimestamp = fileTimestamp; } public Properties getProperties() { diff --git a/spring-integration-core/src/main/java/org/springframework/integration/gateway/GatewayCompletableFutureProxyFactoryBean.java b/spring-integration-core/src/main/java/org/springframework/integration/gateway/GatewayCompletableFutureProxyFactoryBean.java index 3f77344ed9..4c939c6ea3 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/gateway/GatewayCompletableFutureProxyFactoryBean.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/gateway/GatewayCompletableFutureProxyFactoryBean.java @@ -69,7 +69,7 @@ public class GatewayCompletableFutureProxyFactoryBean extends GatewayProxyFactor private final MethodInvocation invocation; - private Invoker(MethodInvocation methodInvocation) { + Invoker(MethodInvocation methodInvocation) { this.invocation = methodInvocation; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/gateway/GatewayProxyFactoryBean.java b/spring-integration-core/src/main/java/org/springframework/integration/gateway/GatewayProxyFactoryBean.java index 2969959e67..d12b9460dc 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/gateway/GatewayProxyFactoryBean.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/gateway/GatewayProxyFactoryBean.java @@ -325,13 +325,7 @@ public class GatewayProxyFactoryBean extends AbstractEndpoint } this.serviceProxy = new ProxyFactory(proxyInterface, this).getProxy(this.beanClassLoader); if (this.asyncExecutor != null) { - Callable task = new Callable() { - - @Override - public String call() throws Exception { - return null; - } - }; + Callable task = () -> null; Future submitType = this.asyncExecutor.submit(task); this.asyncSubmitType = submitType.getClass(); if (this.asyncExecutor instanceof AsyncListenableTaskExecutor) { @@ -661,7 +655,7 @@ public class GatewayProxyFactoryBean extends AbstractEndpoint private static final class MethodInvocationGateway extends MessagingGatewaySupport { - private MethodInvocationGateway(GatewayMethodInboundMessageMapper messageMapper) { + MethodInvocationGateway(GatewayMethodInboundMessageMapper messageMapper) { this.setRequestMapper(messageMapper); } @@ -672,7 +666,7 @@ public class GatewayProxyFactoryBean extends AbstractEndpoint private final MethodInvocation invocation; - private AsyncInvocationTask(MethodInvocation invocation) { + AsyncInvocationTask(MethodInvocation invocation) { this.invocation = invocation; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/gateway/MessagingGatewaySupport.java b/spring-integration-core/src/main/java/org/springframework/integration/gateway/MessagingGatewaySupport.java index 31dac5d3a3..a322c560d5 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/gateway/MessagingGatewaySupport.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/gateway/MessagingGatewaySupport.java @@ -563,6 +563,10 @@ public abstract class MessagingGatewaySupport extends AbstractEndpoint private volatile MessageBuilderFactory messageBuilderFactory = new DefaultMessageBuilderFactory(); + DefaultRequestMapper() { + super(); + } + void setMessageBuilderFactory(MessageBuilderFactory messageBuilderFactory) { this.messageBuilderFactory = messageBuilderFactory; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/handler/AbstractReplyProducingMessageHandler.java b/spring-integration-core/src/main/java/org/springframework/integration/handler/AbstractReplyProducingMessageHandler.java index beda2d4c8f..758e391ee5 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/handler/AbstractReplyProducingMessageHandler.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/handler/AbstractReplyProducingMessageHandler.java @@ -173,6 +173,10 @@ public abstract class AbstractReplyProducingMessageHandler extends AbstractMessa private class AdvisedRequestHandler implements RequestHandler { + AdvisedRequestHandler() { + super(); + } + @Override public Object handleRequestMessage(Message requestMessage) { return AbstractReplyProducingMessageHandler.this.handleRequestMessage(requestMessage); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/handler/DelayHandler.java b/spring-integration-core/src/main/java/org/springframework/integration/handler/DelayHandler.java index fad0f8717f..199f862381 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/handler/DelayHandler.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/handler/DelayHandler.java @@ -321,28 +321,16 @@ public class DelayHandler extends AbstractReplyProducingMessageHandler implement if (this.messageStore instanceof SimpleMessageStore) { final Message messageToSchedule = delayedMessage; - releaseTask = new Runnable() { - - @Override - public void run() { - releaseMessage(messageToSchedule); - } - - }; + releaseTask = () -> releaseMessage(messageToSchedule); } else { final UUID messageId = delayedMessage.getHeaders().getId(); - releaseTask = new Runnable() { - - @Override - public void run() { - Message messageToRelease = getMessageById(messageId); - if (messageToRelease != null) { - releaseMessage(messageToRelease); - } + releaseTask = () -> { + Message messageToRelease = getMessageById(messageId); + if (messageToRelease != null) { + releaseMessage(messageToRelease); } - }; } @@ -417,21 +405,16 @@ public class DelayHandler extends AbstractReplyProducingMessageHandler implement public synchronized void reschedulePersistedMessages() { MessageGroup messageGroup = this.messageStore.getMessageGroup(this.messageGroupId); for (final Message message : messageGroup.getMessages()) { - getTaskScheduler().schedule(new Runnable() { - - @Override - public void run() { - // This is fine to keep the reference to the message, - // because the scheduled task is performed immediately. - long delay = determineDelayForMessage(message); - if (delay > 0) { - releaseMessageAfterDelay(message, delay); - } - else { - releaseMessage(message); - } + getTaskScheduler().schedule((Runnable) () -> { + // This is fine to keep the reference to the message, + // because the scheduled task is performed immediately. + long delay = determineDelayForMessage(message); + if (delay > 0) { + releaseMessageAfterDelay(message, delay); + } + else { + releaseMessage(message); } - }, new Date()); } } @@ -465,6 +448,10 @@ public class DelayHandler extends AbstractReplyProducingMessageHandler implement */ private class ReleaseMessageHandler implements MessageHandler { + ReleaseMessageHandler() { + super(); + } + @Override public void handleMessage(Message message) throws MessagingException { DelayHandler.this.doReleaseMessage(message); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/handler/ExpressionCommandMessageProcessor.java b/spring-integration-core/src/main/java/org/springframework/integration/handler/ExpressionCommandMessageProcessor.java index 9bf2c7dae7..e1f5b48f06 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/handler/ExpressionCommandMessageProcessor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/handler/ExpressionCommandMessageProcessor.java @@ -84,7 +84,7 @@ public class ExpressionCommandMessageProcessor extends AbstractMessageProcessor< private final MethodFilter methodFilter; - private ExpressionCommandMethodResolver(MethodFilter methodFilter) { + ExpressionCommandMethodResolver(MethodFilter methodFilter) { this.methodFilter = methodFilter; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/handler/MessageHandlerChain.java b/spring-integration-core/src/main/java/org/springframework/integration/handler/MessageHandlerChain.java index e8b1dfa701..ae31ee71c8 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/handler/MessageHandlerChain.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/handler/MessageHandlerChain.java @@ -232,7 +232,11 @@ public class MessageHandlerChain extends AbstractMessageProducingHandler impleme } } - private class ReplyForwardingMessageChannel implements MessageChannel { + private final class ReplyForwardingMessageChannel implements MessageChannel { + + ReplyForwardingMessageChannel() { + super(); + } @Override public boolean send(Message message) { diff --git a/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/AbstractRequestHandlerAdvice.java b/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/AbstractRequestHandlerAdvice.java index 3b30ef1a2f..fff3c6714e 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/AbstractRequestHandlerAdvice.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/AbstractRequestHandlerAdvice.java @@ -182,9 +182,9 @@ public abstract class AbstractRequestHandlerAdvice extends IntegrationObjectSupp } @SuppressWarnings("serial") - private final class ThrowableHolderException extends RuntimeException { + private static final class ThrowableHolderException extends RuntimeException { - private ThrowableHolderException(Throwable cause) { + ThrowableHolderException(Throwable cause) { super(cause); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/RequestHandlerCircuitBreakerAdvice.java b/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/RequestHandlerCircuitBreakerAdvice.java index 2410d828ae..0566141bfb 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/RequestHandlerCircuitBreakerAdvice.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/RequestHandlerCircuitBreakerAdvice.java @@ -79,6 +79,10 @@ public class RequestHandlerCircuitBreakerAdvice extends AbstractRequestHandlerAd private volatile long lastFailure; + AdvisedMetadata() { + super(); + } + private long getLastFailure() { return this.lastFailure; } @@ -99,7 +103,7 @@ public class RequestHandlerCircuitBreakerAdvice extends AbstractRequestHandlerAd private static final long serialVersionUID = 1L; - private CircuitBreakerOpenException(String message) { + CircuitBreakerOpenException(String message) { super(message); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/RequestHandlerRetryAdvice.java b/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/RequestHandlerRetryAdvice.java index 1656362d95..85f834cd8a 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/RequestHandlerRetryAdvice.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/RequestHandlerRetryAdvice.java @@ -48,15 +48,7 @@ public class RequestHandlerRetryAdvice extends AbstractRequestHandlerAdvice private static final ThreadLocal> messageHolder = new ThreadLocal>(); // Stateless unless a state generator is provided - private volatile RetryStateGenerator retryStateGenerator = - new RetryStateGenerator() { - - @Override - public RetryState determineRetryState(Message message) { - return null; - } - - }; + private volatile RetryStateGenerator retryStateGenerator = message -> null; public void setRetryTemplate(RetryTemplate retryTemplate) { Assert.notNull(retryTemplate, "'retryTemplate' cannot be null"); @@ -86,14 +78,7 @@ public class RequestHandlerRetryAdvice extends AbstractRequestHandlerAdvice messageHolder.set(message); try { - return this.retryTemplate.execute(new RetryCallback() { - - @Override - public Object doWithRetry(RetryContext context) throws Exception { - return callback.cloneAndExecute(); - } - - }, this.recoveryCallback, retryState); + return this.retryTemplate.execute(context -> callback.cloneAndExecute(), this.recoveryCallback, retryState); } catch (MessagingException e) { if (e.getFailedMessage() == null) { diff --git a/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/RetryStateGenerator.java b/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/RetryStateGenerator.java index f24739b0c7..3956f9bd46 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/RetryStateGenerator.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/handler/advice/RetryStateGenerator.java @@ -26,7 +26,9 @@ import org.springframework.retry.RetryState; * @since 2.2 * */ +@FunctionalInterface public interface RetryStateGenerator { RetryState determineRetryState(Message message); + } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/scattergather/ScatterGatherHandler.java b/spring-integration-core/src/main/java/org/springframework/integration/scattergather/ScatterGatherHandler.java index e96acbb822..362fe089d0 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/scattergather/ScatterGatherHandler.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/scattergather/ScatterGatherHandler.java @@ -107,26 +107,21 @@ public class ScatterGatherHandler extends AbstractReplyProducingMessageHandler i this.gatherEndpoint.afterPropertiesSet(); } - ((MessageProducer) this.gatherer).setOutputChannel(new FixedSubscriberChannel(new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - MessageHeaders headers = message.getHeaders(); - if (headers.containsKey(GATHER_RESULT_CHANNEL)) { - Object gatherResultChannel = headers.get(GATHER_RESULT_CHANNEL); - if (gatherResultChannel instanceof MessageChannel) { - messagingTemplate.send((MessageChannel) gatherResultChannel, message); - } - else if (gatherResultChannel instanceof String) { - messagingTemplate.send((String) gatherResultChannel, message); - } + ((MessageProducer) this.gatherer).setOutputChannel(new FixedSubscriberChannel(message -> { + MessageHeaders headers = message.getHeaders(); + if (headers.containsKey(GATHER_RESULT_CHANNEL)) { + Object gatherResultChannel = headers.get(GATHER_RESULT_CHANNEL); + if (gatherResultChannel instanceof MessageChannel) { + messagingTemplate.send((MessageChannel) gatherResultChannel, message); } - else { - throw new MessageDeliveryException(message, - "The 'gatherResultChannel' header is required to delivery gather result."); + else if (gatherResultChannel instanceof String) { + messagingTemplate.send((String) gatherResultChannel, message); } } - + else { + throw new MessageDeliveryException(message, + "The 'gatherResultChannel' header is required to delivery gather result."); + } })); this.replyChannelRegistry = getBeanFactory() diff --git a/spring-integration-core/src/main/java/org/springframework/integration/scheduling/PollSkipAdvice.java b/spring-integration-core/src/main/java/org/springframework/integration/scheduling/PollSkipAdvice.java index 45e3850864..dfdd33175c 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/scheduling/PollSkipAdvice.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/scheduling/PollSkipAdvice.java @@ -62,7 +62,11 @@ public class PollSkipAdvice implements MethodInterceptor { } - private static class DefaultPollSkipStrategy implements PollSkipStrategy { + private static final class DefaultPollSkipStrategy implements PollSkipStrategy { + + DefaultPollSkipStrategy() { + super(); + } @Override public boolean skipPoll() { diff --git a/spring-integration-core/src/main/java/org/springframework/integration/store/AbstractKeyValueMessageStore.java b/spring-integration-core/src/main/java/org/springframework/integration/store/AbstractKeyValueMessageStore.java index d959a18fee..514583799e 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/store/AbstractKeyValueMessageStore.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/store/AbstractKeyValueMessageStore.java @@ -335,7 +335,7 @@ public abstract class AbstractKeyValueMessageStore extends AbstractMessageGroupS private final Iterator idIterator; - private MessageGroupIterator(Iterator idIterator) { + MessageGroupIterator(Iterator idIterator) { this.idIterator = idIterator; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/store/PersistentMessageGroup.java b/spring-integration-core/src/main/java/org/springframework/integration/store/PersistentMessageGroup.java index f1e4645f7b..f5a2c7303f 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/store/PersistentMessageGroup.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/store/PersistentMessageGroup.java @@ -35,7 +35,7 @@ class PersistentMessageGroup implements MessageGroup { private static final Log logger = LogFactory.getLog(PersistentMessageGroup.class); - private MessageGroupStore messageGroupStore; + private final MessageGroupStore messageGroupStore; private final Collection> messages = new PersistentCollection(); @@ -168,10 +168,14 @@ class PersistentMessageGroup implements MessageGroup { } - private class PersistentCollection extends AbstractCollection> { + private final class PersistentCollection extends AbstractCollection> { private volatile Collection> collection; + PersistentCollection() { + super(); + } + private void load() { if (this.collection == null) { synchronized (this) { diff --git a/spring-integration-core/src/main/java/org/springframework/integration/support/SmartLifecycleRoleController.java b/spring-integration-core/src/main/java/org/springframework/integration/support/SmartLifecycleRoleController.java index 28c3f73a18..cbb0b37e4f 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/support/SmartLifecycleRoleController.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/support/SmartLifecycleRoleController.java @@ -18,7 +18,6 @@ package org.springframework.integration.support; import java.util.ArrayList; import java.util.Collections; -import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; @@ -133,15 +132,8 @@ public class SmartLifecycleRoleController implements ApplicationListener lifecycles = this.lifecycles.get(role); if (lifecycles != null) { lifecycles = new ArrayList(lifecycles); - Collections.sort(lifecycles, new Comparator() { - - @Override - public int compare(SmartLifecycle o1, SmartLifecycle o2) { - return o1.getPhase() < o2.getPhase() ? -1 - : o1.getPhase() > o2.getPhase() ? 1 : 0; - } - - }); + Collections.sort(lifecycles, (o1, o2) -> + o1.getPhase() < o2.getPhase() ? -1 : o1.getPhase() > o2.getPhase() ? 1 : 0); if (logger.isDebugEnabled()) { logger.debug("Zookeeper leadership granted: Starting: " + lifecycles); } @@ -172,15 +164,8 @@ public class SmartLifecycleRoleController implements ApplicationListener lifecycles = this.lifecycles.get(role); if (lifecycles != null) { lifecycles = new ArrayList(lifecycles); - Collections.sort(lifecycles, new Comparator() { - - @Override - public int compare(SmartLifecycle o1, SmartLifecycle o2) { - return o1.getPhase() < o2.getPhase() ? 1 - : o1.getPhase() > o2.getPhase() ? -1 : 0; - } - - }); + Collections.sort(lifecycles, (o1, o2) -> + o1.getPhase() < o2.getPhase() ? 1 : o1.getPhase() > o2.getPhase() ? -1 : 0); if (logger.isDebugEnabled()) { logger.debug("Zookeeper leadership revoked: Stopping: " + lifecycles); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/support/converter/SimpleMessageConverter.java b/spring-integration-core/src/main/java/org/springframework/integration/support/converter/SimpleMessageConverter.java index 0683469fac..7fd9f90477 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/support/converter/SimpleMessageConverter.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/support/converter/SimpleMessageConverter.java @@ -123,6 +123,10 @@ public class SimpleMessageConverter implements MessageConverter, BeanFactoryAwar private class DefaultInboundMessageMapper implements InboundMessageMapper { + DefaultInboundMessageMapper() { + super(); + } + @Override public Message toMessage(Object object) throws Exception { if (object == null) { @@ -139,6 +143,10 @@ public class SimpleMessageConverter implements MessageConverter, BeanFactoryAwar private class DefaultOutboundMessageMapper implements OutboundMessageMapper { + DefaultOutboundMessageMapper() { + super(); + } + @Override public Object fromMessage(Message message) throws Exception { return (message != null) ? message.getPayload() : null; diff --git a/spring-integration-core/src/main/java/org/springframework/integration/support/json/BoonJsonObjectMapper.java b/spring-integration-core/src/main/java/org/springframework/integration/support/json/BoonJsonObjectMapper.java index a4b8b56cda..accb5e798d 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/support/json/BoonJsonObjectMapper.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/support/json/BoonJsonObjectMapper.java @@ -91,13 +91,7 @@ public class BoonJsonObjectMapper extends JsonObjectMapperAdapter toJsonNode(final Object value) throws Exception { PipedReader in = new PipedReader(); final PipedWriter out = new PipedWriter(in); - Executors.newSingleThreadExecutor() - .execute(new Runnable() { - @Override - public void run() { - toJson(value, out); - } - }); + Executors.newSingleThreadExecutor().execute(() -> toJson(value, out)); return (Map) this.slurper.parse(in); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/support/leader/LockRegistryLeaderInitiator.java b/spring-integration-core/src/main/java/org/springframework/integration/support/leader/LockRegistryLeaderInitiator.java index 82588a6e9c..c57cf0eb38 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/support/leader/LockRegistryLeaderInitiator.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/support/leader/LockRegistryLeaderInitiator.java @@ -386,6 +386,10 @@ public class LockRegistryLeaderInitiator implements SmartLifecycle, DisposableBe */ private class LockContext implements Context { + LockContext() { + super(); + } + @Override public boolean isLeader() { return LockRegistryLeaderInitiator.this.leaderSelector.isLeader(); @@ -412,6 +416,10 @@ public class LockRegistryLeaderInitiator implements SmartLifecycle, DisposableBe private static final class NullContext implements Context { + NullContext() { + super(); + } + @Override public boolean isLeader() { return false; diff --git a/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/IntegrationGraphServer.java b/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/IntegrationGraphServer.java index ba0bb66f59..76c90d8742 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/IntegrationGraphServer.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/IntegrationGraphServer.java @@ -267,6 +267,10 @@ public class IntegrationGraphServer implements ApplicationContextAware, Applicat private final AtomicInteger nodeId = new AtomicInteger(); + NodeFactory() { + super(); + } + private MessageChannelNode channelNode(String name, MessageChannel channel) { return new MessageChannelNode(this.nodeId.incrementAndGet(), name, channel); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageChannelNode.java b/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageChannelNode.java index 8a8c1260d2..55e4918ceb 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageChannelNode.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageChannelNode.java @@ -39,7 +39,7 @@ public class MessageChannelNode extends IntegrationNode { private final MessageChannelMetrics channel; - private Stats(MessageChannelMetrics channel) { + Stats(MessageChannelMetrics channel) { this.channel = channel; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageGatewayNode.java b/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageGatewayNode.java index 4440bde846..a53bf7d126 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageGatewayNode.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageGatewayNode.java @@ -36,7 +36,7 @@ public class MessageGatewayNode extends ErrorCapableEndpointNode { private final MessagingGatewaySupport gateway; - private Stats(MessagingGatewaySupport gateway) { + Stats(MessagingGatewaySupport gateway) { this.gateway = gateway; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageHandlerNode.java b/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageHandlerNode.java index 4a07e947fc..80c6302f1f 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageHandlerNode.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageHandlerNode.java @@ -45,7 +45,7 @@ public class MessageHandlerNode extends EndpointNode { private final MessageHandlerMetrics handler; - private Stats(MessageHandlerMetrics handler) { + Stats(MessageHandlerMetrics handler) { this.handler = handler; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageSourceNode.java b/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageSourceNode.java index c2ab49b447..b06339c091 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageSourceNode.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/support/management/graph/MessageSourceNode.java @@ -38,7 +38,7 @@ public class MessageSourceNode extends ErrorCapableEndpointNode { private final MessageSourceMetrics source; - private Stats(MessageSourceMetrics source) { + Stats(MessageSourceMetrics source) { this.source = source; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/transaction/DefaultTransactionSynchronizationFactory.java b/spring-integration-core/src/main/java/org/springframework/integration/transaction/DefaultTransactionSynchronizationFactory.java index c57f69280f..df971df0ab 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/transaction/DefaultTransactionSynchronizationFactory.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/transaction/DefaultTransactionSynchronizationFactory.java @@ -55,7 +55,7 @@ public class DefaultTransactionSynchronizationFactory implements TransactionSync */ private final class DefaultTransactionalResourceSynchronization extends IntegrationResourceHolderSynchronization { - private DefaultTransactionalResourceSynchronization(Object resourceKey) { + DefaultTransactionalResourceSynchronization(Object resourceKey) { super(new IntegrationResourceHolder(), resourceKey); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/transformer/ContentEnricher.java b/spring-integration-core/src/main/java/org/springframework/integration/transformer/ContentEnricher.java index 70f03d3e2a..b428488726 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/transformer/ContentEnricher.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/transformer/ContentEnricher.java @@ -458,6 +458,10 @@ public class ContentEnricher extends AbstractReplyProducingMessageHandler */ private static final class Gateway extends MessagingGatewaySupport { + Gateway() { + super(); + } + @Override protected Message sendAndReceiveMessage(Object object) { return super.sendAndReceiveMessage(object); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/util/ErrorHandlingTaskExecutor.java b/spring-integration-core/src/main/java/org/springframework/integration/util/ErrorHandlingTaskExecutor.java index e149dd4e2c..8f1f5b80f5 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/util/ErrorHandlingTaskExecutor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/util/ErrorHandlingTaskExecutor.java @@ -48,15 +48,12 @@ public class ErrorHandlingTaskExecutor implements TaskExecutor { @Override public void execute(final Runnable task) { - this.executor.execute(new Runnable() { - @Override - public void run() { - try { - task.run(); - } - catch (Throwable t) { //NOSONAR - ErrorHandlingTaskExecutor.this.errorHandler.handleError(t); - } + this.executor.execute(() -> { + try { + task.run(); + } + catch (Throwable t) { //NOSONAR + ErrorHandlingTaskExecutor.this.errorHandler.handleError(t); } }); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/util/MessagingAnnotationUtils.java b/spring-integration-core/src/main/java/org/springframework/integration/util/MessagingAnnotationUtils.java index 60f0030b8c..c25e110fdf 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/util/MessagingAnnotationUtils.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/util/MessagingAnnotationUtils.java @@ -78,20 +78,10 @@ public final class MessagingAnnotationUtils { public static Method findAnnotatedMethod(Object target, final Class annotationType) { final AtomicReference reference = new AtomicReference(); - ReflectionUtils.doWithMethods(getTargetClass(target), new ReflectionUtils.MethodCallback() { - - @Override - public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { - reference.compareAndSet(null, method); - } - }, new ReflectionUtils.MethodFilter() { - - @Override - public boolean matches(Method method) { - return ReflectionUtils.USER_DECLARED_METHODS.matches(method) && - AnnotatedElementUtils.isAnnotated(method, annotationType.getName()); - } - }); + ReflectionUtils.doWithMethods(getTargetClass(target), + method -> reference.compareAndSet(null, method), + method -> ReflectionUtils.USER_DECLARED_METHODS.matches(method) && + AnnotatedElementUtils.isAnnotated(method, annotationType.getName())); return reference.get(); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/util/MessagingMethodInvokerHelper.java b/spring-integration-core/src/main/java/org/springframework/integration/util/MessagingMethodInvokerHelper.java index db7b7c40d1..d6a38b092f 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/util/MessagingMethodInvokerHelper.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/util/MessagingMethodInvokerHelper.java @@ -914,7 +914,7 @@ public class MessagingMethodInvokerHelper extends AbstractExpressionEvaluator @SuppressWarnings("serial") private static final class IneligibleMethodException extends RuntimeException { - private IneligibleMethodException(String message) { + IneligibleMethodException(String message) { super(message); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandlerTests.java index e0021f3afb..8639b121af 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AbstractCorrelatingMessageHandlerTests.java @@ -63,45 +63,34 @@ public class AbstractCorrelatingMessageHandlerTests { final CountDownLatch waitForSendLatch = new CountDownLatch(1); final CountDownLatch waitReapStartLatch = new CountDownLatch(1); final CountDownLatch waitReapCompleteLatch = new CountDownLatch(1); - AbstractCorrelatingMessageHandler handler = new AbstractCorrelatingMessageHandler( - new MessageGroupProcessor() { - - @Override - public Object processMessageGroup(MessageGroup group) { - return group; - } - }, groupStore) { + AbstractCorrelatingMessageHandler handler = new AbstractCorrelatingMessageHandler(group -> group, groupStore) { @Override protected void afterRelease(MessageGroup group, Collection> completedMessages) { } + }; handler.setReleasePartialSequences(true); /* * Runs "reap" when group 'bar' is in completion */ - Executors.newSingleThreadExecutor().execute(new Runnable() { - - @Override - public void run() { - try { - waitReapStartLatch.await(10, TimeUnit.SECONDS); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - waitForSendLatch.countDown(); - try { - Thread.sleep(100); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - groupStore.expireMessageGroups(50); - waitReapCompleteLatch.countDown(); + Executors.newSingleThreadExecutor().execute(() -> { + try { + waitReapStartLatch.await(10, TimeUnit.SECONDS); } - + catch (InterruptedException e1) { + Thread.currentThread().interrupt(); + } + waitForSendLatch.countDown(); + try { + Thread.sleep(100); + } + catch (InterruptedException e2) { + Thread.currentThread().interrupt(); + } + groupStore.expireMessageGroups(50); + waitReapCompleteLatch.countDown(); }); final List> outputMessages = new ArrayList>(); @@ -133,14 +122,7 @@ public class AbstractCorrelatingMessageHandlerTests { return this.send(message, 0); } }); - handler.setReleaseStrategy(new ReleaseStrategy() { - - @Override - public boolean canRelease(MessageGroup group) { - return group.size() == 2; - } - - }); + handler.setReleaseStrategy(group -> group.size() == 2); QueueChannel discards = new QueueChannel(); handler.setDiscardChannel(discards); @@ -175,15 +157,7 @@ public class AbstractCorrelatingMessageHandlerTests { @Test // INT-2833 public void testReaperReapsAnEmptyGroup() throws Exception { final MessageGroupStore groupStore = new SimpleMessageStore(); - AggregatingMessageHandler handler = new AggregatingMessageHandler( - new MessageGroupProcessor() { - - @Override - public Object processMessageGroup(MessageGroup group) { - return group; - } - }, groupStore) { - }; + AggregatingMessageHandler handler = new AggregatingMessageHandler(group -> group, groupStore); final List> outputMessages = new ArrayList>(); handler.setOutputChannel(new MessageChannel() { @@ -202,13 +176,7 @@ public class AbstractCorrelatingMessageHandlerTests { return this.send(message, 0); } }); - handler.setReleaseStrategy(new ReleaseStrategy() { - - @Override - public boolean canRelease(MessageGroup group) { - return group.size() == 1; - } - }); + handler.setReleaseStrategy(group -> group.size() == 1); Message message = MessageBuilder.withPayload("foo") .setCorrelationId("bar") @@ -225,15 +193,7 @@ public class AbstractCorrelatingMessageHandlerTests { @Test // INT-2833 public void testReaperReapsAnEmptyGroupAfterConfiguredDelay() throws Exception { final MessageGroupStore groupStore = new SimpleMessageStore(); - AggregatingMessageHandler handler = new AggregatingMessageHandler( - new MessageGroupProcessor() { - - @Override - public Object processMessageGroup(MessageGroup group) { - return group; - } - }, groupStore) { - }; + AggregatingMessageHandler handler = new AggregatingMessageHandler(group -> group, groupStore); final List> outputMessages = new ArrayList>(); handler.setOutputChannel(new MessageChannel() { @@ -252,13 +212,7 @@ public class AbstractCorrelatingMessageHandlerTests { return this.send(message, 0); } }); - handler.setReleaseStrategy(new ReleaseStrategy() { - - @Override - public boolean canRelease(MessageGroup group) { - return group.size() == 1; - } - }); + handler.setReleaseStrategy(group -> group.size() == 1); handler.setMinimumTimeoutForEmptyGroups(1000); @@ -281,12 +235,7 @@ public class AbstractCorrelatingMessageHandlerTests { public void testReapWithChangeInSameMillisecond() throws Exception { MessageGroupProcessor mgp = new DefaultAggregatingMessageGroupProcessor(); AggregatingMessageHandler handler = new AggregatingMessageHandler(mgp); - handler.setReleaseStrategy(new ReleaseStrategy() { - @Override - public boolean canRelease(MessageGroup group) { - return true; - } - }); + handler.setReleaseStrategy(group -> true); QueueChannel outputChannel = new QueueChannel(); handler.setOutputChannel(outputChannel); MessageGroupStore mgs = TestUtils.getPropertyValue(handler, "messageStore", MessageGroupStore.class); @@ -312,14 +261,7 @@ public class AbstractCorrelatingMessageHandlerTests { public void testDontReapIfAlreadyComplete() throws Exception { MessageGroupProcessor mgp = new DefaultAggregatingMessageGroupProcessor(); AggregatingMessageHandler handler = new AggregatingMessageHandler(mgp); - handler.setReleaseStrategy(new ReleaseStrategy() { - - @Override - public boolean canRelease(MessageGroup group) { - return true; - } - - }); + handler.setReleaseStrategy(group -> true); QueueChannel outputChannel = new QueueChannel(); handler.setOutputChannel(outputChannel); MessageGroupStore mgs = TestUtils.getPropertyValue(handler, "messageStore", MessageGroupStore.class); @@ -345,14 +287,7 @@ public class AbstractCorrelatingMessageHandlerTests { public void testDontReapIfAlreadyCompleteAfterRefetch() throws Exception { MessageGroupProcessor mgp = new DefaultAggregatingMessageGroupProcessor(); AggregatingMessageHandler handler = new AggregatingMessageHandler(mgp); - handler.setReleaseStrategy(new ReleaseStrategy() { - - @Override - public boolean canRelease(MessageGroup group) { - return true; - } - - }); + handler.setReleaseStrategy(group -> true); QueueChannel outputChannel = new QueueChannel(); handler.setOutputChannel(outputChannel); MessageGroupStore mgs = TestUtils.getPropertyValue(handler, "messageStore", MessageGroupStore.class); @@ -381,14 +316,7 @@ public class AbstractCorrelatingMessageHandlerTests { public void testDontReapIfNewGroupFoundDuringRefetch() throws Exception { MessageGroupProcessor mgp = new DefaultAggregatingMessageGroupProcessor(); AggregatingMessageHandler handler = new AggregatingMessageHandler(mgp); - handler.setReleaseStrategy(new ReleaseStrategy() { - - @Override - public boolean canRelease(MessageGroup group) { - return true; - } - - }); + handler.setReleaseStrategy(group -> true); QueueChannel outputChannel = new QueueChannel(); handler.setOutputChannel(outputChannel); MessageGroupStore mgs = TestUtils.getPropertyValue(handler, "messageStore", MessageGroupStore.class); @@ -418,14 +346,7 @@ public class AbstractCorrelatingMessageHandlerTests { handler.setOutputChannel(new QueueChannel()); QueueChannel discardChannel = new QueueChannel(); handler.setDiscardChannel(discardChannel); - handler.setReleaseStrategy(new ReleaseStrategy() { - - @Override - public boolean canRelease(MessageGroup group) { - return true; - } - - }); + handler.setReleaseStrategy(group -> true); handler.setExpireGroupsUponTimeout(false); SimpleMessageStore messageStore = new SimpleMessageStore() { @Override @@ -447,16 +368,11 @@ public class AbstractCorrelatingMessageHandlerTests { //suppress an intentional 'removeMessageGroup' exception } ExecutorService executorService = Executors.newSingleThreadExecutor(); - executorService.execute(new Runnable() { - @Override - public void run() { - handler.handleMessage(MessageBuilder.withPayload("foo") - .setCorrelationId(1) - .setSequenceNumber(2) - .setSequenceSize(2) - .build()); - } - }); + executorService.execute(() -> handler.handleMessage(MessageBuilder.withPayload("foo") + .setCorrelationId(1) + .setSequenceNumber(2) + .setSequenceSize(2) + .build())); executorService.shutdown(); /* Previously lock for the groupId hasn't been unlocked from the 'forceComplete', because it wasn't reachable in case of exception from the BasicMessageGroupStore.removeMessageGroup diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatingMessageGroupProcessorHeaderTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatingMessageGroupProcessorHeaderTests.java index d9cfca1b6f..89610927f5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatingMessageGroupProcessorHeaderTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatingMessageGroupProcessorHeaderTests.java @@ -271,6 +271,10 @@ public class AggregatingMessageGroupProcessorHeaderTests { private static class TestAggregatorBean { + TestAggregatorBean() { + super(); + } + @SuppressWarnings("unused") public Object aggregate(List payloads) { StringBuilder sb = new StringBuilder(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatorTests.java index 5a61e7ab34..b51f29241c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/AggregatorTests.java @@ -40,8 +40,6 @@ import org.junit.Ignore; import org.junit.Test; import org.springframework.beans.factory.BeanFactory; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.ApplicationEventPublisher; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.handler.AbstractMessageHandler; @@ -51,10 +49,8 @@ import org.springframework.integration.store.SimpleMessageStore; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; -import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessageHandlingException; import org.springframework.messaging.MessageHeaders; -import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.GenericMessage; import org.springframework.util.StopWatch; @@ -79,19 +75,7 @@ public class AggregatorTests { public void configureAggregator() { this.aggregator = new AggregatingMessageHandler(new MultiplyingProcessor(), store); this.aggregator.setBeanFactory(mock(BeanFactory.class)); - this.aggregator.setApplicationEventPublisher(new ApplicationEventPublisher() { - - @Override - public void publishEvent(ApplicationEvent event) { - expiryEvents.add((MessageGroupExpiredEvent) event); - } - - @Override - public void publishEvent(Object event) { - - } - - }); + this.aggregator.setApplicationEventPublisher(event -> expiryEvents.add((MessageGroupExpiredEvent) event)); this.aggregator.setBeanName("testAggregator"); this.aggregator.afterPropertiesSet(); expiryEvents.clear(); @@ -100,14 +84,7 @@ public class AggregatorTests { @Test public void testAggPerf() throws InterruptedException, ExecutionException, TimeoutException { AggregatingMessageHandler handler = new AggregatingMessageHandler(new DefaultAggregatingMessageGroupProcessor()); - handler.setCorrelationStrategy(new CorrelationStrategy() { - - @Override - public Object getCorrelationKey(Message message) { - return "foo"; - } - - }); + handler.setCorrelationStrategy(message -> "foo"); handler.setReleaseStrategy(new MessageCountReleaseStrategy(60000)); handler.setExpireGroupsUponCompletion(true); handler.setSendPartialResultOnExpiry(true); @@ -115,15 +92,10 @@ public class AggregatorTests { handler.setOutputChannel(outputChannel); final CompletableFuture> resultFuture = new CompletableFuture<>(); - outputChannel.subscribe(new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - Collection payload = (Collection) message.getPayload(); - logger.warn("Received " + payload.size()); - resultFuture.complete(payload); - } - + outputChannel.subscribe(message -> { + Collection payload = (Collection) message.getPayload(); + logger.warn("Received " + payload.size()); + resultFuture.complete(payload); }); SimpleMessageStore store = new SimpleMessageStore(); @@ -200,15 +172,10 @@ public class AggregatorTests { CustomHandler handler = new CustomHandler(outputChannel); final CompletableFuture> resultFuture = new CompletableFuture<>(); - outputChannel.subscribe(new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - Collection payload = (Collection) message.getPayload(); - logger.warn("Received " + payload.size()); - resultFuture.complete(payload); - } - + outputChannel.subscribe(message -> { + Collection payload = (Collection) message.getPayload(); + logger.warn("Received " + payload.size()); + resultFuture.complete(payload); }); Message message = new GenericMessage("foo"); StopWatch stopwatch = new StopWatch(); @@ -441,6 +408,11 @@ public class AggregatorTests { private class MultiplyingProcessor implements MessageGroupProcessor { + + MultiplyingProcessor() { + super(); + } + @Override public Object processMessageGroup(MessageGroup group) { Integer product = 1; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ConcurrentAggregatorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ConcurrentAggregatorTests.java index 5a0ad740a5..5f0ebe9864 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ConcurrentAggregatorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ConcurrentAggregatorTests.java @@ -341,6 +341,10 @@ public class ConcurrentAggregatorTests { private class MultiplyingProcessor implements MessageGroupProcessor { + MultiplyingProcessor() { + super(); + } + @Override public Object processMessageGroup(MessageGroup group) { Integer product = 1; @@ -356,6 +360,10 @@ public class ConcurrentAggregatorTests { @SuppressWarnings("unused") private class NullReturningMessageProcessor implements MessageGroupProcessor { + NullReturningMessageProcessor() { + super(); + } + @Override public Object processMessageGroup(MessageGroup group) { return null; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageBarrierTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageBarrierTests.java index 99df1b79ef..311623def0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageBarrierTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageBarrierTests.java @@ -109,18 +109,15 @@ public class CorrelatingMessageBarrierTests { } private void sendAsynchronously(final MessageHandler handler, final Message message, final CountDownLatch start, final CountDownLatch sent) { - Executors.newSingleThreadExecutor().execute(new Runnable() { - @Override - public void run() { - try { - start.await(); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - handler.handleMessage(message); - sent.countDown(); + Executors.newSingleThreadExecutor().execute(() -> { + try { + start.await(); } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + handler.handleMessage(message); + sent.countDown(); }); } @@ -134,8 +131,13 @@ public class CorrelatingMessageBarrierTests { * ReleaseStrategy that emulates the use case described in INT-1068 */ private static class OneMessagePerKeyReleaseStrategy implements ReleaseStrategy { + private final ConcurrentMap keyLocks = new ConcurrentHashMap(); + OneMessagePerKeyReleaseStrategy() { + super(); + } + @Override public boolean canRelease(MessageGroup messageGroup) { Object correlationKey = messageGroup.getGroupId(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerTests.java index 420ab45d35..ef02899814 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelatingMessageHandlerTests.java @@ -146,12 +146,10 @@ public class CorrelatingMessageHandlerTests { handler.handleMessage(message1); bothMessagesHandled.countDown(); storedMessages.add(message1); - Executors.newSingleThreadExecutor().submit(new Runnable() { - public void run() { - handler.handleMessage(message2); - storedMessages.add(message2); - bothMessagesHandled.countDown(); - } + Executors.newSingleThreadExecutor().submit(() -> { + handler.handleMessage(message2); + storedMessages.add(message2); + bothMessagesHandled.countDown(); }); assertTrue(bothMessagesHandled.await(10, TimeUnit.SECONDS)); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelationStrategyAdapterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelationStrategyAdapterTests.java index 89ed76e7d2..5883832621 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelationStrategyAdapterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/CorrelationStrategyAdapterTests.java @@ -75,6 +75,11 @@ public class CorrelationStrategyAdapterTests { } private static class MultiHeaderCorrelator { + + MultiHeaderCorrelator() { + super(); + } + @SuppressWarnings("unused") public String getKey(@Header("a") String header, @Header("c") String other) { return header + other; @@ -83,6 +88,11 @@ public class CorrelationStrategyAdapterTests { } private static class SimpleHeaderCorrelator { + + SimpleHeaderCorrelator() { + super(); + } + @SuppressWarnings("unused") public String getKey(@Header("a") String header) { return header; @@ -91,6 +101,11 @@ public class CorrelationStrategyAdapterTests { } private static class SimplePojoCorrelator { + + SimplePojoCorrelator() { + super(); + } + @SuppressWarnings("unused") public String getKey(String message) { return message; @@ -99,6 +114,11 @@ public class CorrelationStrategyAdapterTests { } private static class SimpleMessageCorrelator { + + SimpleMessageCorrelator() { + super(); + } + @SuppressWarnings("unused") public String getKey(Message message) { return (String) message.getHeaders().get("a"); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencerTests.java index 35c1a2715a..ef0acd8007 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ResequencerTests.java @@ -113,12 +113,7 @@ public class ResequencerTests { releaseStrategy.setReleasePartialSequences(true); this.resequencer = new ResequencingMessageHandler(processor, store, null, releaseStrategy); QueueChannel replyChannel = new QueueChannel(); - this.resequencer.setCorrelationStrategy(new CorrelationStrategy() { - @Override - public Object getCorrelationKey(Message message) { - return "A"; - } - }); + this.resequencer.setCorrelationStrategy(message -> "A"); this.resequencer.setBeanFactory(mock(BeanFactory.class)); this.resequencer.afterPropertiesSet(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorSupportedUseCasesTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorSupportedUseCasesTests.java index 8cafb5a5e0..10bb4f8995 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorSupportedUseCasesTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/integration/AggregatorSupportedUseCasesTests.java @@ -16,9 +16,14 @@ package org.springframework.integration.aggregator.integration; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + import java.util.List; import org.junit.Test; + import org.springframework.integration.aggregator.AggregatingMessageHandler; import org.springframework.integration.aggregator.DefaultAggregatingMessageGroupProcessor; import org.springframework.integration.aggregator.ReleaseStrategy; @@ -28,10 +33,6 @@ import org.springframework.integration.store.MessageGroupStore; import org.springframework.integration.store.SimpleMessageStore; import org.springframework.integration.support.MessageBuilder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - /** * @author Oleg Zhurakousky * @author Artem Bilan @@ -39,11 +40,11 @@ import static org.junit.Assert.assertNull; */ public class AggregatorSupportedUseCasesTests { - private MessageGroupStore store = new SimpleMessageStore(100); + private final MessageGroupStore store = new SimpleMessageStore(100); - private DefaultAggregatingMessageGroupProcessor processor = new DefaultAggregatingMessageGroupProcessor(); + private final DefaultAggregatingMessageGroupProcessor processor = new DefaultAggregatingMessageGroupProcessor(); - private AggregatingMessageHandler defaultHandler = new AggregatingMessageHandler(processor, store); + private final AggregatingMessageHandler defaultHandler = new AggregatingMessageHandler(processor, store); @Test public void waitForAllDefaultReleaseStrategyWithLateArrivals() { @@ -151,6 +152,11 @@ public class AggregatorSupportedUseCasesTests { private class SampleSizeReleaseStrategy implements ReleaseStrategy { + SampleSizeReleaseStrategy() { + super(); + } + + @Override public boolean canRelease(MessageGroup group) { return group.getMessages().size() == 5; } @@ -159,6 +165,11 @@ public class AggregatorSupportedUseCasesTests { private class FirstBestReleaseStrategy implements ReleaseStrategy { + FirstBestReleaseStrategy() { + super(); + } + + @Override public boolean canRelease(MessageGroup group) { return true; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregatorWithCustomReleaseStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregatorWithCustomReleaseStrategyTests.java index bf2cf957b5..20859c1b2b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregatorWithCustomReleaseStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/AggregatorWithCustomReleaseStrategyTests.java @@ -108,29 +108,20 @@ public class AggregatorWithCustomReleaseStrategyTests { for (int i = 0; i < 600; i++) { final int counter = i; - executor.execute(new Runnable() { - @Override - public void run() { - inputChannel.send(MessageBuilder.withPayload("foo"). - setHeader("correlation", "foo" + counter).build()); - latch.countDown(); - } + executor.execute(() -> { + inputChannel.send(MessageBuilder.withPayload("foo"). + setHeader("correlation", "foo" + counter).build()); + latch.countDown(); }); - executor.execute(new Runnable() { - @Override - public void run() { - inputChannel.send(MessageBuilder.withPayload("bar"). - setHeader("correlation", "foo" + counter).build()); - latch.countDown(); - } + executor.execute(() -> { + inputChannel.send(MessageBuilder.withPayload("bar"). + setHeader("correlation", "foo" + counter).build()); + latch.countDown(); }); - executor.execute(new Runnable() { - @Override - public void run() { - inputChannel.send(MessageBuilder.withPayload("baz"). - setHeader("correlation", "foo" + counter).build()); - latch.countDown(); - } + executor.execute(() -> { + inputChannel.send(MessageBuilder.withPayload("baz"). + setHeader("correlation", "foo" + counter).build()); + latch.countDown(); }); } @@ -155,26 +146,17 @@ public class AggregatorWithCustomReleaseStrategyTests { final CountDownLatch latch = new CountDownLatch(1800); for (int i = 0; i < 600; i++) { - executor.execute(new Runnable() { - @Override - public void run() { - inputChannel.send(MessageBuilder.withPayload(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8}).build()); - latch.countDown(); - } + executor.execute(() -> { + inputChannel.send(MessageBuilder.withPayload(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8}).build()); + latch.countDown(); }); - executor.execute(new Runnable() { - @Override - public void run() { - inputChannel.send(MessageBuilder.withPayload(new Integer[]{9, 10, 11, 12, 13, 14, 15, 16}).build()); - latch.countDown(); - } + executor.execute(() -> { + inputChannel.send(MessageBuilder.withPayload(new Integer[]{9, 10, 11, 12, 13, 14, 15, 16}).build()); + latch.countDown(); }); - executor.execute(new Runnable() { - @Override - public void run() { - inputChannel.send(MessageBuilder.withPayload(new Integer[]{17, 18, 19, 20, 21, 22, 23, 24}).build()); - latch.countDown(); - } + executor.execute(() -> { + inputChannel.send(MessageBuilder.withPayload(new Integer[]{17, 18, 19, 20, 21, 22, 23, 24}).build()); + latch.countDown(); }); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/PartialSequencesWithGapsTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/PartialSequencesWithGapsTests.java index aac6eacbf8..1db0ebbaa9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/PartialSequencesWithGapsTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/scenarios/PartialSequencesWithGapsTests.java @@ -32,8 +32,6 @@ import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; -import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.MessagingException; import org.springframework.messaging.SubscribableChannel; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -57,12 +55,7 @@ public class PartialSequencesWithGapsTests { @Before public void collectOutput() { - out.subscribe(new MessageHandler() { - @Override - public void handleMessage(Message message) throws MessagingException { - received.add(message); - } - }); + out.subscribe(message -> received.add(message)); } @Test diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorTests.java index c0ebfc0ad5..7ec4b95650 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aop/MessagePublishingInterceptorTests.java @@ -109,6 +109,7 @@ public class MessagePublishingInterceptorTests { static class TestBeanImpl implements TestBean { + @Override public String test() { return "foo"; } @@ -118,14 +119,21 @@ public class MessagePublishingInterceptorTests { private static class TestPublisherMetadataSource implements PublisherMetadataSource { + TestPublisherMetadataSource() { + super(); + } + + @Override public String getPayloadExpression(Method method) { return "'test-' + #return"; } + @Override public Map getHeaderExpressions(Method method) { return null; } + @Override public String getChannelName(Method method) { return "c"; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/ChannelPurgerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/ChannelPurgerTests.java index e7c6ba322f..44713eeafd 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/ChannelPurgerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/ChannelPurgerTests.java @@ -25,7 +25,6 @@ import java.util.List; import org.junit.Test; import org.springframework.messaging.Message; -import org.springframework.integration.core.MessageSelector; import org.springframework.messaging.support.GenericMessage; /** @@ -51,11 +50,7 @@ public class ChannelPurgerTests { channel.send(new GenericMessage("test1")); channel.send(new GenericMessage("test2")); channel.send(new GenericMessage("test3")); - ChannelPurger purger = new ChannelPurger(new MessageSelector() { - public boolean accept(Message message) { - return false; - } - }, channel); + ChannelPurger purger = new ChannelPurger(message -> false, channel); List> purgedMessages = purger.purge(); assertEquals(3, purgedMessages.size()); assertNull(channel.receive(0)); @@ -67,11 +62,7 @@ public class ChannelPurgerTests { channel.send(new GenericMessage("test1")); channel.send(new GenericMessage("test2")); channel.send(new GenericMessage("test3")); - ChannelPurger purger = new ChannelPurger(new MessageSelector() { - public boolean accept(Message message) { - return true; - } - }, channel); + ChannelPurger purger = new ChannelPurger(message -> true, channel); List> purgedMessages = purger.purge(); assertEquals(0, purgedMessages.size()); assertNotNull(channel.receive(0)); @@ -85,11 +76,7 @@ public class ChannelPurgerTests { channel.send(new GenericMessage("test1")); channel.send(new GenericMessage("test2")); channel.send(new GenericMessage("test3")); - ChannelPurger purger = new ChannelPurger(new MessageSelector() { - public boolean accept(Message message) { - return (message.getPayload().equals("test2")); - } - }, channel); + ChannelPurger purger = new ChannelPurger(message -> (message.getPayload().equals("test2")), channel); List> purgedMessages = purger.purge(); assertEquals(2, purgedMessages.size()); Message message = channel.receive(0); @@ -123,11 +110,7 @@ public class ChannelPurgerTests { channel2.send(new GenericMessage("test1")); channel2.send(new GenericMessage("test2")); channel2.send(new GenericMessage("test3")); - ChannelPurger purger = new ChannelPurger(new MessageSelector() { - public boolean accept(Message message) { - return (message.getPayload().equals("test2")); - } - }, channel1, channel2); + ChannelPurger purger = new ChannelPurger(message -> (message.getPayload().equals("test2")), channel1, channel2); List> purgedMessages = purger.purge(); assertEquals(4, purgedMessages.size()); Message message1 = channel1.receive(0); @@ -148,11 +131,7 @@ public class ChannelPurgerTests { channel1.send(new GenericMessage("test2")); channel2.send(new GenericMessage("test1")); channel2.send(new GenericMessage("test2")); - ChannelPurger purger = new ChannelPurger(new MessageSelector() { - public boolean accept(Message message) { - return true; - } - }, channel1, channel2); + ChannelPurger purger = new ChannelPurger(message -> true, channel1, channel2); List> purgedMessages = purger.purge(); assertEquals(0, purgedMessages.size()); assertNotNull(channel1.receive(0)); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/DatatypeChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/DatatypeChannelTests.java index 02ef9d4158..9e44dab757 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/DatatypeChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/DatatypeChannelTests.java @@ -233,18 +233,34 @@ public class DatatypeChannelTests { private static class Foo { + Foo() { + super(); + } + } private static class Bar extends Foo { + Bar() { + super(); + } + } private static class Baz extends Foo { + Baz() { + super(); + } + } private static class StringToBarConverter implements GenericConverter { + StringToBarConverter() { + super(); + } + @Override public Set getConvertibleTypes() { Set pairs = new HashSet(); @@ -262,6 +278,10 @@ public class DatatypeChannelTests { private static class IntegerToBazConverter implements GenericConverter { + IntegerToBazConverter() { + super(); + } + @Override public Set getConvertibleTypes() { Set pairs = new HashSet(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/DirectChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/DirectChannelTests.java index 0b84430b03..cd745eb0d4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/DirectChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/DirectChannelTests.java @@ -45,7 +45,6 @@ import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.GenericMessage; import org.springframework.util.ReflectionUtils; @@ -93,13 +92,7 @@ public class DirectChannelTests { */ DirectChannel channel = new DirectChannel(); final AtomicInteger count = new AtomicInteger(); - channel.subscribe(new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - count.incrementAndGet(); - } - }); + channel.subscribe(message -> count.incrementAndGet()); GenericMessage message = new GenericMessage("test"); assertTrue(channel.send(message)); for (int i = 0; i < 10000000; i++) { @@ -119,20 +112,8 @@ public class DirectChannelTests { DirectChannel channel = new DirectChannel(); final AtomicInteger count1 = new AtomicInteger(); final AtomicInteger count2 = new AtomicInteger(); - channel.subscribe(new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - count1.incrementAndGet(); - } - }); - channel.subscribe(new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - count2.getAndIncrement(); - } - }); + channel.subscribe(message -> count1.incrementAndGet()); + channel.subscribe(message -> count2.getAndIncrement()); GenericMessage message = new GenericMessage("test"); assertTrue(channel.send(message)); for (int i = 0; i < 10000000; i++) { @@ -152,13 +133,7 @@ public class DirectChannelTests { * Added the same code to the other tests for comparison. */ final AtomicInteger count = new AtomicInteger(); - FixedSubscriberChannel channel = new FixedSubscriberChannel(new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - count.incrementAndGet(); - } - }); + FixedSubscriberChannel channel = new FixedSubscriberChannel(message -> count.incrementAndGet()); GenericMessage message = new GenericMessage("test"); assertTrue(channel.send(message)); for (int i = 0; i < 100000000; i++) { @@ -173,12 +148,7 @@ public class DirectChannelTests { ThreadNameExtractingTestTarget target = new ThreadNameExtractingTestTarget(latch); channel.subscribe(target); final GenericMessage message = new GenericMessage("test"); - new Thread(new Runnable() { - @Override - public void run() { - channel.send(message); - } - }, "test-thread").start(); + new Thread((Runnable) () -> channel.send(message), "test-thread").start(); latch.await(1000, TimeUnit.MILLISECONDS); assertEquals("test-thread", target.threadName); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/DispatchingChannelErrorHandlingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/DispatchingChannelErrorHandlingTests.java index 753b569565..16066e0cba 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/DispatchingChannelErrorHandlingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/DispatchingChannelErrorHandlingTests.java @@ -24,6 +24,7 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.junit.Test; + import org.springframework.context.support.StaticApplicationContext; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.core.task.TaskExecutor; @@ -46,10 +47,8 @@ public class DispatchingChannelErrorHandlingTests { @Test(expected = MessageDeliveryException.class) public void handlerThrowsExceptionPublishSubscribeWithoutExecutor() { PublishSubscribeChannel channel = new PublishSubscribeChannel(); - channel.subscribe(new MessageHandler() { - public void handleMessage(Message message) { - throw new UnsupportedOperationException("intentional test failure"); - } + channel.subscribe(message -> { + throw new UnsupportedOperationException("intentional test failure"); }); Message message = MessageBuilder.withPayload("test").build(); channel.send(message); @@ -69,11 +68,9 @@ public class DispatchingChannelErrorHandlingTests { channel.afterPropertiesSet(); ResultHandler resultHandler = new ResultHandler(); defaultErrorChannel.subscribe(resultHandler); - channel.subscribe(new MessageHandler() { - public void handleMessage(Message message) { - throw new MessagingException(message, - new UnsupportedOperationException("intentional test failure")); - } + channel.subscribe(message -> { + throw new MessagingException(message, + new UnsupportedOperationException("intentional test failure")); }); Message message = MessageBuilder.withPayload("test").build(); channel.send(message); @@ -100,11 +97,9 @@ public class DispatchingChannelErrorHandlingTests { channel.afterPropertiesSet(); ResultHandler resultHandler = new ResultHandler(); defaultErrorChannel.subscribe(resultHandler); - channel.subscribe(new MessageHandler() { - public void handleMessage(Message message) { - throw new MessagingException(message, - new UnsupportedOperationException("intentional test failure")); - } + channel.subscribe(message -> { + throw new MessagingException(message, + new UnsupportedOperationException("intentional test failure")); }); Message message = MessageBuilder.withPayload("test").build(); channel.send(message); @@ -137,6 +132,7 @@ public class DispatchingChannelErrorHandlingTests { private volatile Thread lastThread; + @Override public void handleMessage(Message message) { this.lastMessage = message; this.lastThread = Thread.currentThread(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/ExecutorChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/ExecutorChannelTests.java index 66c8552439..0b30d0b865 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/ExecutorChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/ExecutorChannelTests.java @@ -264,6 +264,10 @@ public class ExecutorChannelTests { private Message messageToReturn; + BeforeHandleInterceptor() { + super(); + } + public void setMessageToReturn(Message messageToReturn) { this.messageToReturn = messageToReturn; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/MixedDispatcherConfigurationScenarioTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/MixedDispatcherConfigurationScenarioTests.java index 152583ee06..bd6fecdea0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/MixedDispatcherConfigurationScenarioTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/MixedDispatcherConfigurationScenarioTests.java @@ -38,9 +38,7 @@ import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; import org.mockito.runners.MockitoJUnitRunner; -import org.mockito.stubbing.Answer; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -130,28 +128,24 @@ public class MixedDispatcherConfigurationScenarioTests { dispatcher.addHandler(handlerA); dispatcher.addHandler(handlerB); - Runnable messageSenderTask = new Runnable() { - - @Override - public void run() { - try { - start.await(); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - boolean sent = false; - try { - sent = channel.send(message); - } - catch (Exception e) { - exceptionRegistry.add(e); - } - if (!sent) { - failed.set(true); - } - allDone.countDown(); + Runnable messageSenderTask = () -> { + try { + start.await(); } + catch (InterruptedException e1) { + Thread.currentThread().interrupt(); + } + boolean sent = false; + try { + sent = channel.send(message); + } + catch (Exception e2) { + exceptionRegistry.add(e2); + } + if (!sent) { + failed.set(true); + } + allDone.countDown(); }; for (int i = 0; i < TOTAL_EXECUTIONS; i++) { executor.execute(messageSenderTask); @@ -176,39 +170,27 @@ public class MixedDispatcherConfigurationScenarioTests { dispatcher.addHandler(handlerA); dispatcher.addHandler(handlerB); - doAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) { - RuntimeException e = new RuntimeException(); - allDone.countDown(); - failed.set(true); - exceptionRegistry.add(e); - throw e; - } + doAnswer(invocation -> { + RuntimeException e = new RuntimeException(); + allDone.countDown(); + failed.set(true); + exceptionRegistry.add(e); + throw e; }).when(handlerA).handleMessage(message); - doAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) { - allDone.countDown(); - return null; - } + doAnswer(invocation -> { + allDone.countDown(); + return null; }).when(handlerB).handleMessage(message); - Runnable messageSenderTask = new Runnable() { - - @Override - public void run() { - try { - start.await(); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - channel.send(message); + Runnable messageSenderTask = () -> { + try { + start.await(); } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + channel.send(message); }; for (int i = 0; i < TOTAL_EXECUTIONS; i++) { executor.execute(messageSenderTask); @@ -272,28 +254,24 @@ public class MixedDispatcherConfigurationScenarioTests { final CountDownLatch allDone = new CountDownLatch(TOTAL_EXECUTIONS); final Message message = this.message; final AtomicBoolean failed = new AtomicBoolean(false); - Runnable messageSenderTask = new Runnable() { - - @Override - public void run() { - try { - start.await(); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - boolean sent = false; - try { - sent = channel.send(message); - } - catch (Exception e) { - exceptionRegistry.add(e); - } - if (!sent) { - failed.set(true); - } - allDone.countDown(); + Runnable messageSenderTask = () -> { + try { + start.await(); } + catch (InterruptedException e1) { + Thread.currentThread().interrupt(); + } + boolean sent = false; + try { + sent = channel.send(message); + } + catch (Exception e2) { + exceptionRegistry.add(e2); + } + if (!sent) { + failed.set(true); + } + allDone.countDown(); }; for (int i = 0; i < TOTAL_EXECUTIONS; i++) { executor.execute(messageSenderTask); @@ -323,46 +301,30 @@ public class MixedDispatcherConfigurationScenarioTests { final CountDownLatch allDone = new CountDownLatch(TOTAL_EXECUTIONS); final Message message = this.message; final AtomicBoolean failed = new AtomicBoolean(false); - doAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) { - failed.set(true); - RuntimeException e = new RuntimeException(); - exceptionRegistry.add(e); - allDone.countDown(); - throw e; - } + doAnswer(invocation -> { + failed.set(true); + RuntimeException e = new RuntimeException(); + exceptionRegistry.add(e); + allDone.countDown(); + throw e; }).when(handlerA).handleMessage(message); - doAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) { - allDone.countDown(); - return null; - } + doAnswer(invocation -> { + allDone.countDown(); + return null; }).when(handlerB).handleMessage(message); - doAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) { - allDone.countDown(); - return null; - } + doAnswer(invocation -> { + allDone.countDown(); + return null; }).when(handlerC).handleMessage(message); - Runnable messageSenderTask = new Runnable() { - - @Override - public void run() { - try { - start.await(); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - channel.send(message); + Runnable messageSenderTask = () -> { + try { + start.await(); } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + channel.send(message); }; for (int i = 0; i < TOTAL_EXECUTIONS; i++) { executor.execute(messageSenderTask); @@ -426,28 +388,24 @@ public class MixedDispatcherConfigurationScenarioTests { final CountDownLatch allDone = new CountDownLatch(TOTAL_EXECUTIONS); final Message message = this.message; final AtomicBoolean failed = new AtomicBoolean(false); - Runnable messageSenderTask = new Runnable() { - - @Override - public void run() { - try { - start.await(); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - boolean sent = false; - try { - sent = channel.send(message); - } - catch (Exception e) { - exceptionRegistry.add(e); - } - if (!sent) { - failed.set(true); - } - allDone.countDown(); + Runnable messageSenderTask = () -> { + try { + start.await(); } + catch (InterruptedException e1) { + Thread.currentThread().interrupt(); + } + boolean sent = false; + try { + sent = channel.send(message); + } + catch (Exception e2) { + exceptionRegistry.add(e2); + } + if (!sent) { + failed.set(true); + } + allDone.countDown(); }; for (int i = 0; i < TOTAL_EXECUTIONS; i++) { executor.execute(messageSenderTask); @@ -473,43 +431,25 @@ public class MixedDispatcherConfigurationScenarioTests { dispatcher.addHandler(handlerB); dispatcher.addHandler(handlerC); - doAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) { - RuntimeException e = new RuntimeException(); - failed.set(true); - throw e; - } + doAnswer(invocation -> { + RuntimeException e = new RuntimeException(); + failed.set(true); + throw e; }).when(handlerA).handleMessage(message); - doAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) { - allDone.countDown(); - return null; - } + doAnswer(invocation -> { + allDone.countDown(); + return null; }).when(handlerB).handleMessage(message); - doAnswer(new Answer() { + doAnswer(invocation -> null).when(handlerC).handleMessage(message); - @Override - public Object answer(InvocationOnMock invocation) { - return null; + Runnable messageSenderTask = () -> { + try { + start.await(); } - }).when(handlerC).handleMessage(message); - - Runnable messageSenderTask = new Runnable() { - - @Override - public void run() { - try { - start.await(); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - channel.send(message); + catch (InterruptedException e) { + Thread.currentThread().interrupt(); } + channel.send(message); }; for (int i = 0; i < TOTAL_EXECUTIONS; i++) { executor.execute(messageSenderTask); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/P2pChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/P2pChannelTests.java index 894a3fb909..02eb1d4607 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/P2pChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/P2pChannelTests.java @@ -23,7 +23,6 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; -import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; @@ -31,13 +30,10 @@ import java.util.concurrent.Executor; import org.apache.commons.logging.Log; import org.junit.Test; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.integration.dispatcher.MessageDispatcher; import org.springframework.messaging.MessageHandler; import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.FieldCallback; /** * @author Oleg Zhurakousky @@ -78,21 +74,14 @@ public class P2pChannelTests { final Log logger = mock(Log.class); when(logger.isInfoEnabled()).thenReturn(true); final List logs = new ArrayList(); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - logs.add((String) invocation.getArguments()[0]); - return null; - } + doAnswer(invocation -> { + logs.add((String) invocation.getArguments()[0]); + return null; }).when(logger).info(Mockito.anyString()); - ReflectionUtils.doWithFields(AbstractMessageChannel.class, new FieldCallback() { - @Override - public void doWith(Field field) throws IllegalArgumentException, - IllegalAccessException { - if ("logger".equals(field.getName())) { - field.setAccessible(true); - field.set(channel, logger); - } + ReflectionUtils.doWithFields(AbstractMessageChannel.class, field -> { + if ("logger".equals(field.getName())) { + field.setAccessible(true); + field.set(channel, logger); } }); String log = "Channel '" @@ -122,15 +111,10 @@ public class P2pChannelTests { final Log logger = mock(Log.class); when(logger.isInfoEnabled()).thenReturn(true); - ReflectionUtils.doWithFields(AbstractMessageChannel.class, new FieldCallback() { - - @Override - public void doWith(Field field) throws IllegalArgumentException, - IllegalAccessException { - if ("logger".equals(field.getName())) { - field.setAccessible(true); - field.set(channel, logger); - } + ReflectionUtils.doWithFields(AbstractMessageChannel.class, field -> { + if ("logger".equals(field.getName())) { + field.setAccessible(true); + field.set(channel, logger); } }); channel.subscribe(mock(MessageHandler.class)); @@ -145,15 +129,10 @@ public class P2pChannelTests { final Log logger = mock(Log.class); when(logger.isInfoEnabled()).thenReturn(true); - ReflectionUtils.doWithFields(AbstractMessageChannel.class, new FieldCallback() { - - @Override - public void doWith(Field field) throws IllegalArgumentException, - IllegalAccessException { - if ("logger".equals(field.getName())) { - field.setAccessible(true); - field.set(channel, logger); - } + ReflectionUtils.doWithFields(AbstractMessageChannel.class, field -> { + if ("logger".equals(field.getName())) { + field.setAccessible(true); + field.set(channel, logger); } }); channel.subscribe(mock(MessageHandler.class)); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/PriorityChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/PriorityChannelTests.java index 184a3f641c..60ae7f9f62 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/PriorityChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/PriorityChannelTests.java @@ -91,18 +91,8 @@ public class PriorityChannelTests { final Message message = new GenericMessage("hello"); for (int i = 0; i < 1000; i++) { channel.send(message); - new Thread(new Runnable() { - @Override - public void run() { - channel.receive(); - } - }).start(); - new Thread(new Runnable() { - @Override - public void run() { - message.getHeaders().toString(); - } - }).start(); + new Thread(() -> channel.receive()).start(); + new Thread(() -> message.getHeaders().toString()).start(); } } @@ -239,14 +229,7 @@ public class PriorityChannelTests { final AtomicBoolean sentSecondMessage = new AtomicBoolean(false); ExecutorService executor = Executors.newSingleThreadScheduledExecutor(); channel.send(new GenericMessage("test-1")); - executor.execute(new Runnable() { - - @Override - public void run() { - sentSecondMessage.set(channel.send(new GenericMessage("test-2"), 10)); - } - - }); + executor.execute(() -> sentSecondMessage.set(channel.send(new GenericMessage("test-2"), 10))); assertFalse(sentSecondMessage.get()); executor.shutdown(); @@ -265,12 +248,9 @@ public class PriorityChannelTests { final CountDownLatch latch = new CountDownLatch(1); Executor executor = Executors.newSingleThreadScheduledExecutor(); channel.send(new GenericMessage("test-1")); - executor.execute(new Runnable() { - @Override - public void run() { - sentSecondMessage.set(channel.send(new GenericMessage("test-2"), 3000)); - latch.countDown(); - } + executor.execute(() -> { + sentSecondMessage.set(channel.send(new GenericMessage("test-2"), 3000)); + latch.countDown(); }); assertFalse(sentSecondMessage.get()); Thread.sleep(500); @@ -290,12 +270,7 @@ public class PriorityChannelTests { final AtomicBoolean sentSecondMessage = new AtomicBoolean(false); ExecutorService executor = Executors.newSingleThreadScheduledExecutor(); channel.send(new GenericMessage("test-1")); - executor.execute(new Runnable() { - @Override - public void run() { - sentSecondMessage.set(channel.send(new GenericMessage("test-2"), -1)); - } - }); + executor.execute(() -> sentSecondMessage.set(channel.send(new GenericMessage("test-2"), -1))); assertFalse(sentSecondMessage.get()); Thread.sleep(500); Message message1 = channel.receive(1000); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/QueueChannelTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/QueueChannelTests.java index ec3ba54ae5..efb5b2e211 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/QueueChannelTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/QueueChannelTests.java @@ -49,14 +49,11 @@ public class QueueChannelTests { final AtomicBoolean messageReceived = new AtomicBoolean(false); final CountDownLatch latch = new CountDownLatch(1); final QueueChannel channel = new QueueChannel(); - new Thread(new Runnable() { - @Override - public void run() { - Message message = channel.receive(); - if (message != null) { - messageReceived.set(true); - latch.countDown(); - } + new Thread(() -> { + Message message = channel.receive(); + if (message != null) { + messageReceived.set(true); + latch.countDown(); } }).start(); assertFalse(messageReceived.get()); @@ -72,35 +69,24 @@ public class QueueChannelTests { final CountDownLatch latch1 = new CountDownLatch(1); final CountDownLatch latch2 = new CountDownLatch(1); Executor singleThreadExecutor = Executors.newSingleThreadExecutor(); - Runnable receiveTask1 = new Runnable() { - @Override - public void run() { - Message message = channel.receive(0); - if (message != null) { - messageReceived.set(true); - } - latch1.countDown(); - } - }; - Runnable sendTask = new Runnable() { - @Override - public void run() { - channel.send(new GenericMessage("testing")); + Runnable receiveTask1 = () -> { + Message message = channel.receive(0); + if (message != null) { + messageReceived.set(true); } + latch1.countDown(); }; + Runnable sendTask = () -> channel.send(new GenericMessage("testing")); singleThreadExecutor.execute(receiveTask1); latch1.await(); singleThreadExecutor.execute(sendTask); assertFalse(messageReceived.get()); - Runnable receiveTask2 = new Runnable() { - @Override - public void run() { - Message message = channel.receive(0); - if (message != null) { - messageReceived.set(true); - } - latch2.countDown(); + Runnable receiveTask2 = () -> { + Message message = channel.receive(0); + if (message != null) { + messageReceived.set(true); } + latch2.countDown(); }; singleThreadExecutor.execute(receiveTask2); latch2.await(); @@ -112,14 +98,11 @@ public class QueueChannelTests { final QueueChannel channel = new QueueChannel(); final AtomicBoolean receiveInterrupted = new AtomicBoolean(false); final CountDownLatch latch = new CountDownLatch(1); - Thread t = new Thread(new Runnable() { - @Override - public void run() { - Message message = channel.receive(); - receiveInterrupted.set(true); - assertTrue(message == null); - latch.countDown(); - } + Thread t = new Thread(() -> { + Message message = channel.receive(); + receiveInterrupted.set(true); + assertTrue(message == null); + latch.countDown(); }); t.start(); assertFalse(receiveInterrupted.get()); @@ -133,14 +116,11 @@ public class QueueChannelTests { final QueueChannel channel = new QueueChannel(); final AtomicBoolean receiveInterrupted = new AtomicBoolean(false); final CountDownLatch latch = new CountDownLatch(1); - Thread t = new Thread(new Runnable() { - @Override - public void run() { - Message message = channel.receive(10000); - receiveInterrupted.set(true); - assertTrue(message == null); - latch.countDown(); - } + Thread t = new Thread(() -> { + Message message = channel.receive(10000); + receiveInterrupted.set(true); + assertTrue(message == null); + latch.countDown(); }); t.start(); assertFalse(receiveInterrupted.get()); @@ -169,13 +149,10 @@ public class QueueChannelTests { assertTrue(result1); final AtomicBoolean sendInterrupted = new AtomicBoolean(false); final CountDownLatch latch = new CountDownLatch(1); - Thread t = new Thread(new Runnable() { - @Override - public void run() { - channel.send(new GenericMessage("test-2")); - sendInterrupted.set(true); - latch.countDown(); - } + Thread t = new Thread(() -> { + channel.send(new GenericMessage("test-2")); + sendInterrupted.set(true); + latch.countDown(); }); t.start(); assertFalse(sendInterrupted.get()); @@ -191,13 +168,10 @@ public class QueueChannelTests { assertTrue(result1); final AtomicBoolean sendInterrupted = new AtomicBoolean(false); final CountDownLatch latch = new CountDownLatch(1); - Thread t = new Thread(new Runnable() { - @Override - public void run() { - channel.send(new GenericMessage("test-2"), 10000); - sendInterrupted.set(true); - latch.countDown(); - } + Thread t = new Thread(() -> { + channel.send(new GenericMessage("test-2"), 10000); + sendInterrupted.set(true); + latch.countDown(); }); t.start(); assertFalse(sendInterrupted.get()); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ThreadLocalChannelParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ThreadLocalChannelParserTests.java index 9fd80d4e45..8f9c7b4e73 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ThreadLocalChannelParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/config/ThreadLocalChannelParserTests.java @@ -59,11 +59,9 @@ public class ThreadLocalChannelParserTests { simpleChannel.send(new GenericMessage("test")); Executor otherThreadExecutor = Executors.newSingleThreadExecutor(); final CountDownLatch latch = new CountDownLatch(1); - otherThreadExecutor.execute(new Runnable() { - public void run() { - simpleChannel.send(new GenericMessage("crap")); - latch.countDown(); - } + otherThreadExecutor.execute(() -> { + simpleChannel.send(new GenericMessage("crap")); + latch.countDown(); }); latch.await(1, TimeUnit.SECONDS); assertEquals("test", simpleChannel.receive(10).getPayload()); @@ -81,17 +79,13 @@ public class ThreadLocalChannelParserTests { Executor otherThreadExecutor = Executors.newSingleThreadExecutor(); final List otherThreadResults = new ArrayList(); final CountDownLatch latch = new CountDownLatch(2); - otherThreadExecutor.execute(new Runnable() { - public void run() { - otherThreadResults.add(simpleChannel.receive(0)); - latch.countDown(); - } + otherThreadExecutor.execute(() -> { + otherThreadResults.add(simpleChannel.receive(0)); + latch.countDown(); }); - otherThreadExecutor.execute(new Runnable() { - public void run() { - otherThreadResults.add(channelWithInterceptor.receive(0)); - latch.countDown(); - } + otherThreadExecutor.execute(() -> { + otherThreadResults.add(channelWithInterceptor.receive(0)); + latch.countDown(); }); latch.await(1, TimeUnit.SECONDS); assertEquals(2, otherThreadResults.size()); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/ChannelInterceptorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/ChannelInterceptorTests.java index 11bd471c46..5c756529f9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/ChannelInterceptorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/ChannelInterceptorTests.java @@ -45,7 +45,6 @@ import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.ChannelInterceptor; import org.springframework.messaging.support.ChannelInterceptorAdapter; import org.springframework.messaging.support.ExecutorChannelInterceptor; @@ -271,15 +270,10 @@ public class ChannelInterceptorTests { final CountDownLatch latch2 = new CountDownLatch(2); final List> messages = new ArrayList<>(); - PollingConsumer consumer = new PollingConsumer(channel, new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - messages.add(message); - latch1.countDown(); - latch2.countDown(); - } - + PollingConsumer consumer = new PollingConsumer(channel, message -> { + messages.add(message); + latch1.countDown(); + latch2.countDown(); }); testApplicationContext.registerBean("consumer", consumer); @@ -339,6 +333,10 @@ public class ChannelInterceptorTests { private static AtomicInteger counter = new AtomicInteger(); + PreSendReturnsNullInterceptor() { + super(); + } + protected int getCount() { return counter.get(); } @@ -359,6 +357,10 @@ public class ChannelInterceptorTests { private RuntimeException exceptionToRaise; + AfterCompletionTestInterceptor() { + super(); + } + public void setExceptionToRaise(RuntimeException exception) { this.exceptionToRaise = exception; } @@ -397,6 +399,10 @@ public class ChannelInterceptorTests { private RuntimeException exceptionToRaise; + PreReceiveReturnsTrueInterceptor() { + super(); + } + public void setExceptionToRaise(RuntimeException exception) { this.exceptionToRaise = exception; } @@ -430,6 +436,10 @@ public class ChannelInterceptorTests { private static AtomicInteger counter = new AtomicInteger(); + PreReceiveReturnsFalseInterceptor() { + super(); + } + @Override public boolean preReceive(MessageChannel channel) { counter.incrementAndGet(); @@ -441,6 +451,10 @@ public class ChannelInterceptorTests { private static class TestExecutorInterceptor extends ChannelInterceptorAdapter implements ExecutorChannelInterceptor { + TestExecutorInterceptor() { + super(); + } + @Override public Message beforeHandle(Message message, MessageChannel channel, MessageHandler handler) { return MessageBuilder.withPayload(((String) message.getPayload()).toUpperCase()) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/registry/HeaderChannelRegistryTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/registry/HeaderChannelRegistryTests.java index c3d953a4e6..005cf3cce4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/registry/HeaderChannelRegistryTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/registry/HeaderChannelRegistryTests.java @@ -36,8 +36,6 @@ import java.util.Map; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -226,12 +224,8 @@ public class HeaderChannelRegistryTests { when(beanFactory.getBean(IntegrationContextUtils.INTEGRATION_HEADER_CHANNEL_REGISTRY_BEAN_NAME, HeaderChannelRegistry.class)) .thenReturn(mock(HeaderChannelRegistry.class)); - doAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - throw new NoSuchBeanDefinitionException("bar"); - } + doAnswer(invocation -> { + throw new NoSuchBeanDefinitionException("bar"); }).when(beanFactory).getBean("foo", MessageChannel.class); resolver.setBeanFactory(beanFactory); try { @@ -248,12 +242,8 @@ public class HeaderChannelRegistryTests { public void testBFCRNoRegistry() { BeanFactoryChannelResolver resolver = new BeanFactoryChannelResolver(); BeanFactory beanFactory = mock(BeanFactory.class); - doAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - throw new NoSuchBeanDefinitionException("bar"); - } + doAnswer(invocation -> { + throw new NoSuchBeanDefinitionException("bar"); }).when(beanFactory).getBean("foo", MessageChannel.class); resolver.setBeanFactory(beanFactory); try { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorParserTests.java index cbddcb9719..3e3d9fb247 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorParserTests.java @@ -44,7 +44,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.expression.Expression; import org.springframework.integration.IntegrationMessageHeaderAccessor; -import org.springframework.integration.MessageRejectedException; import org.springframework.integration.aggregator.AggregatingMessageHandler; import org.springframework.integration.aggregator.CorrelationStrategy; import org.springframework.integration.aggregator.ExpressionEvaluatingCorrelationStrategy; @@ -61,9 +60,6 @@ import org.springframework.integration.support.utils.IntegrationUtils; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; -import org.springframework.messaging.MessageDeliveryException; -import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.MessageHandlingException; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.SubscribableChannel; @@ -142,13 +138,7 @@ public class AggregatorParserTests { MessageChannel input = (MessageChannel) context.getBean("aggregatorWithExpressionsInput"); SubscribableChannel outputChannel = (SubscribableChannel) context.getBean("aggregatorWithExpressionsOutput"); final AtomicReference> aggregatedMessage = new AtomicReference>(); - outputChannel.subscribe(new MessageHandler() { - @Override - public void handleMessage(Message message) throws MessageRejectedException, MessageHandlingException, - MessageDeliveryException { - aggregatedMessage.set(message); - } - }); + outputChannel.subscribe(message -> aggregatedMessage.set(message)); List> outboundMessages = new ArrayList>(); outboundMessages.add(MessageBuilder.withPayload("123").setHeader("foo", "1").build()); outboundMessages.add(MessageBuilder.withPayload("456").setHeader("foo", "1").build()); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/ChainParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/ChainParserTests.java index 89f8d0facf..aefb62ecfc 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/ChainParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/ChainParserTests.java @@ -37,8 +37,6 @@ import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.BeansException; import org.springframework.beans.DirectFieldAccessor; @@ -310,12 +308,9 @@ public class ChainParserTests { Log logger = mock(Log.class); final AtomicReference log = new AtomicReference(); when(logger.isWarnEnabled()).thenReturn(true); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - log.set((String) invocation.getArguments()[0]); - return null; - } + doAnswer(invocation -> { + log.set((String) invocation.getArguments()[0]); + return null; }).when(logger).warn(any()); @SuppressWarnings("unchecked") diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/PublishSubscribeChannelParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/PublishSubscribeChannelParserTests.java index a8cb2c0126..32695f0b4b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/PublishSubscribeChannelParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/PublishSubscribeChannelParserTests.java @@ -33,9 +33,6 @@ import org.springframework.integration.channel.PublishSubscribeChannel; import org.springframework.integration.dispatcher.BroadcastingDispatcher; import org.springframework.integration.support.utils.IntegrationUtils; import org.springframework.integration.util.ErrorHandlingTaskExecutor; -import org.springframework.messaging.Message; -import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.GenericMessage; import org.springframework.util.ErrorHandler; @@ -56,14 +53,7 @@ public class PublishSubscribeChannelParserTests { BroadcastingDispatcher dispatcher = (BroadcastingDispatcher) accessor.getPropertyValue("dispatcher"); dispatcher.setApplySequence(true); - dispatcher.addHandler(new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - - } - - }); + dispatcher.addHandler(message -> { }); dispatcher.dispatch(new GenericMessage("foo")); DirectFieldAccessor dispatcherAccessor = new DirectFieldAccessor(dispatcher); assertNull(dispatcherAccessor.getPropertyValue("executor")); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/SourcePollingChannelAdapterFactoryBeanTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/SourcePollingChannelAdapterFactoryBeanTests.java index 9e0ad823b1..5d23d62a8f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/SourcePollingChannelAdapterFactoryBeanTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/SourcePollingChannelAdapterFactoryBeanTests.java @@ -222,6 +222,10 @@ public class SourcePollingChannelAdapterFactoryBeanTests { private volatile boolean running; + LifecycleMessageSource() { + super(); + } + @Override public void start() { this.running = true; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/FilterAnnotationPostProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/FilterAnnotationPostProcessorTests.java index eed8baedd9..ba1cbc6eed 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/FilterAnnotationPostProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/FilterAnnotationPostProcessorTests.java @@ -194,34 +194,37 @@ public class FilterAnnotationPostProcessorTests { @MessageEndpoint - private static class TestFilterWithBooleanPrimitive { + public static class TestFilterWithBooleanPrimitive { @Filter(inputChannel = "input", outputChannel = "output") public boolean filter(String s) { return !s.contains("bad"); } + } @MessageEndpoint - private static class TestFilterWithAdviceDiscardWithin { + public static class TestFilterWithAdviceDiscardWithin { @Filter(inputChannel = "input", outputChannel = "output", adviceChain = "adviceChain") public boolean filter(String s) { return !s.contains("bad"); } + } @MessageEndpoint - private static class TestFilterWithAdviceDiscardWithinTwice { + public static class TestFilterWithAdviceDiscardWithinTwice { @Filter(inputChannel = "input", outputChannel = "output", adviceChain = {"adviceChain1", "adviceChain2"}) public boolean filter(String s) { return !s.contains("bad"); } + } @MessageEndpoint - private static class TestFilterWithAdviceDiscardWithout { + public static class TestFilterWithAdviceDiscardWithout { @Filter(inputChannel = "input", outputChannel = "output", adviceChain = "adviceChain", discardWithinAdvice = "false") @@ -231,31 +234,34 @@ public class FilterAnnotationPostProcessorTests { } @MessageEndpoint - private static class TestFilterWithBooleanWrapperClass { + public static class TestFilterWithBooleanWrapperClass { @Filter(inputChannel = "input", outputChannel = "output") public Boolean filter(String s) { return !s.contains("bad"); } + } @MessageEndpoint - private static class TestFilterWithStringReturnType { + public static class TestFilterWithStringReturnType { @Filter(inputChannel = "input", outputChannel = "output") public String filter(String s) { return s; } + } @MessageEndpoint - private static class TestFilterWithVoidReturnType { + public static class TestFilterWithVoidReturnType { @Filter(inputChannel = "input", outputChannel = "output") public void filter(String s) { } + } public static class TestAdvice extends AbstractRequestHandlerAdvice { @@ -266,4 +272,5 @@ public class FilterAnnotationPostProcessorTests { } } + } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorTests.java index 3d6ffd7803..cf009733e6 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationPostProcessorTests.java @@ -320,7 +320,7 @@ public class MessagingAnnotationPostProcessorTests { @MessageEndpoint - private static class OutboundOnlyTestBean { + public static class OutboundOnlyTestBean { private String messageText; @@ -343,17 +343,17 @@ public class MessagingAnnotationPostProcessorTests { } - private static class SimpleAnnotatedEndpointSubclass extends AnnotatedTestService { + public static class SimpleAnnotatedEndpointSubclass extends AnnotatedTestService { } @MessageEndpoint - private interface SimpleAnnotatedEndpointInterface { + public interface SimpleAnnotatedEndpointInterface { String test(String input); } - private static class SimpleAnnotatedEndpointImplementation implements SimpleAnnotatedEndpointInterface { + public static class SimpleAnnotatedEndpointImplementation implements SimpleAnnotatedEndpointInterface { @Override @ServiceActivator(inputChannel = "inputChannel", outputChannel = "outputChannel") @@ -364,7 +364,7 @@ public class MessagingAnnotationPostProcessorTests { @MessageEndpoint - private static class ServiceActivatorAnnotatedBean { + public static class ServiceActivatorAnnotatedBean { public final AtomicBoolean invoked = new AtomicBoolean(); @@ -385,7 +385,7 @@ public class MessagingAnnotationPostProcessorTests { @MessageEndpoint - private static class TransformerAnnotationTestBean { + public static class TransformerAnnotationTestBean { @Transformer(inputChannel = "inputChannel", outputChannel = "outputChannel") public String transformBefore(String input) { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationsWithBeanAnnotationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationsWithBeanAnnotationTests.java index 376d1efbe5..37ace48592 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationsWithBeanAnnotationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/MessagingAnnotationsWithBeanAnnotationTests.java @@ -74,7 +74,6 @@ import org.springframework.integration.transformer.ExpressionEvaluatingTransform import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.MessagingException; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.support.ErrorMessage; import org.springframework.messaging.support.GenericMessage; @@ -278,13 +277,7 @@ public class MessagingAnnotationsWithBeanAnnotationTests { @ServiceActivator(inputChannel = "serviceChannel") public MessageHandler service() { final List> collector = this.collector(); - return new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - collector.add(message); - } - }; + return message -> collector.add(message); } @Bean diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ConverterParserWithExistingConversionServiceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ConverterParserWithExistingConversionServiceTests.java index a20022297c..f340cd4e25 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ConverterParserWithExistingConversionServiceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ConverterParserWithExistingConversionServiceTests.java @@ -83,6 +83,7 @@ public class ConverterParserWithExistingConversionServiceTests { TestBean1(String text) { this.text = text; } + } @@ -99,6 +100,7 @@ public class ConverterParserWithExistingConversionServiceTests { public String toString() { return this.text.replace("-TEST", "_TARGET_CHANNEL"); } + } private static class TestBean3 { @@ -113,21 +115,33 @@ public class ConverterParserWithExistingConversionServiceTests { public String toString() { return this.text.replace("-TEST", "_TARGET_CHANNEL"); } + } private static class TestConverter implements Converter { + TestConverter() { + super(); + } + @Override public TestBean2 convert(TestBean1 source) { return new TestBean2(source.text.toUpperCase()); } + } private static class TestConverter3 implements Converter { + TestConverter3() { + super(); + } + @Override public TestBean3 convert(TestBean1 source) { return new TestBean3(source.text.toUpperCase()); } + } + } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelegatingConsumerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelegatingConsumerParserTests.java index ffb6bfab51..e7ca5c3a79 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelegatingConsumerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelegatingConsumerParserTests.java @@ -28,6 +28,7 @@ import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -201,13 +202,7 @@ public class DelegatingConsumerParserTests { public static class MyFilter extends MessageFilter { public MyFilter() { - super(new MessageSelector() { - - @Override - public boolean accept(Message message) { - return true; - } - }); + super(message -> true); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersOverrideDefaultTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersOverrideDefaultTests.java index 9cc6a36d03..3bd6d4c622 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersOverrideDefaultTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DispatcherMaxSubscribersOverrideDefaultTests.java @@ -21,10 +21,8 @@ import static org.junit.Assert.fail; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.messaging.Message; -import org.springframework.messaging.MessagingException; -import org.springframework.messaging.MessageHandler; import org.springframework.messaging.SubscribableChannel; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -49,19 +47,14 @@ public class DispatcherMaxSubscribersOverrideDefaultTests extends DispatcherMaxS @Test public void testExceed() { - oneSub.subscribe(new MessageHandler() { - public void handleMessage(Message message) throws MessagingException { - } - }); + oneSub.subscribe(message -> { }); try { - oneSub.subscribe(new MessageHandler() { - public void handleMessage(Message message) throws MessagingException { - } - }); + oneSub.subscribe(message -> { }); fail("Expected Exception"); } catch (IllegalArgumentException e) { assertEquals("Maximum subscribers exceeded", e.getMessage()); } } + } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/GatewayParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/GatewayParserTests.java index ce29fa8d4b..1cac5916f1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/GatewayParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/GatewayParserTests.java @@ -349,40 +349,37 @@ public class GatewayParserTests { } private void startResponder(final PollableChannel requestChannel, final MessageChannel replyChannel) { - Executors.newSingleThreadExecutor().execute(new Runnable() { - @Override - public void run() { - Message request = requestChannel.receive(60000); - assertNotNull("Request not received", request); - Message reply = MessageBuilder.fromMessage(request) - .setCorrelationId(request.getHeaders().getId()).build(); - Object payload = null; - if (request.getPayload().equals("futureSync")) { - payload = new AsyncResult>(reply); - } - else if (request.getPayload().equals("flowCompletable")) { - payload = CompletableFuture.completedFuture("SYNC_COMPLETABLE"); - } - else if (request.getPayload().equals("flowCustomCompletable")) { - MyCompletableFuture myCompletableFuture = new MyCompletableFuture(); - myCompletableFuture.complete("SYNC_CUSTOM_COMPLETABLE"); - payload = myCompletableFuture; - } - else if (request.getPayload().equals("flowCompletableM")) { - payload = CompletableFuture.>completedFuture(reply); - } - else if (request.getPayload().equals("flowCustomCompletableM")) { - MyCompletableMessageFuture myCompletableFuture = new MyCompletableMessageFuture(); - myCompletableFuture.complete(reply); - payload = myCompletableFuture; - } - if (payload != null) { - reply = MessageBuilder.withPayload(payload) - .copyHeaders(reply.getHeaders()) - .build(); - } - replyChannel.send(reply); + Executors.newSingleThreadExecutor().execute(() -> { + Message request = requestChannel.receive(60000); + assertNotNull("Request not received", request); + Message reply = MessageBuilder.fromMessage(request) + .setCorrelationId(request.getHeaders().getId()).build(); + Object payload = null; + if (request.getPayload().equals("futureSync")) { + payload = new AsyncResult>(reply); } + else if (request.getPayload().equals("flowCompletable")) { + payload = CompletableFuture.completedFuture("SYNC_COMPLETABLE"); + } + else if (request.getPayload().equals("flowCustomCompletable")) { + MyCompletableFuture myCompletableFuture1 = new MyCompletableFuture(); + myCompletableFuture1.complete("SYNC_CUSTOM_COMPLETABLE"); + payload = myCompletableFuture1; + } + else if (request.getPayload().equals("flowCompletableM")) { + payload = CompletableFuture.>completedFuture(reply); + } + else if (request.getPayload().equals("flowCustomCompletableM")) { + MyCompletableMessageFuture myCompletableFuture2 = new MyCompletableMessageFuture(); + myCompletableFuture2.complete(reply); + payload = myCompletableFuture2; + } + if (payload != null) { + reply = MessageBuilder.withPayload(payload) + .copyHeaders(reply.getHeaders()) + .build(); + } + replyChannel.send(reply); }); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToStringTransformerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToStringTransformerParserTests.java index 04262ecf27..4dd90dc5fb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToStringTransformerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToStringTransformerParserTests.java @@ -97,6 +97,10 @@ public class ObjectToStringTransformerParserTests { private static class TestBean { + TestBean() { + super(); + } + @Override public String toString() { return "test"; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadDeserializingTransformerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadDeserializingTransformerParserTests.java index 40c3e4c880..ef8d11e7f6 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadDeserializingTransformerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadDeserializingTransformerParserTests.java @@ -32,11 +32,11 @@ import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.serializer.Deserializer; +import org.springframework.integration.transformer.MessageTransformationException; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.support.GenericMessage; -import org.springframework.integration.transformer.MessageTransformationException; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.FileCopyUtils; @@ -128,6 +128,10 @@ public class PayloadDeserializingTransformerParserTests { @SuppressWarnings("serial") private static class TestBean implements Serializable { + TestBean() { + super(); + } + public final String name = "test"; } @@ -135,6 +139,7 @@ public class PayloadDeserializingTransformerParserTests { public static class TestDeserializer implements Deserializer { + @Override public Object deserialize(InputStream source) throws IOException { return FileCopyUtils.copyToString(new InputStreamReader(source, "UTF-8")).toUpperCase(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadSerializingTransformerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadSerializingTransformerParserTests.java index 2837f7d898..3cc63e800c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadSerializingTransformerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PayloadSerializingTransformerParserTests.java @@ -28,13 +28,14 @@ import java.io.Serializable; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.serializer.Serializer; +import org.springframework.integration.transformer.MessageTransformationException; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.support.GenericMessage; -import org.springframework.integration.transformer.MessageTransformationException; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -125,6 +126,10 @@ public class PayloadSerializingTransformerParserTests { @SuppressWarnings("serial") private static class TestBean implements Serializable { + TestBean() { + super(); + } + public final String name = "test"; } @@ -132,6 +137,7 @@ public class PayloadSerializingTransformerParserTests { public static class TestSerializer implements Serializer { + @Override public void serialize(Object source, OutputStream outputStream) throws IOException { outputStream.write(source.toString().toUpperCase().getBytes("UTF-8")); outputStream.flush(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PublishingInterceptorParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PublishingInterceptorParserTests.java index 02ca0a337d..0300fbf5d4 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PublishingInterceptorParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PublishingInterceptorParserTests.java @@ -25,8 +25,6 @@ import static org.mockito.Mockito.verify; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message; @@ -61,12 +59,10 @@ public class PublishingInterceptorParserTests { public void validateDefaultChannelPublishing() { MessageHandler handler = Mockito.mock(MessageHandler.class); defaultChannel.subscribe(handler); - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) { - Message message = (Message) invocation.getArguments()[0]; - assertEquals("hello", message.getPayload()); - return null; - } + doAnswer(invocation -> { + Message message = (Message) invocation.getArguments()[0]; + assertEquals("hello", message.getPayload()); + return null; }).when(handler).handleMessage((Message) anyObject()); testBean.echoDefaultChannel("hello"); verify(handler, times(1)).handleMessage((Message) anyObject()); @@ -76,13 +72,11 @@ public class PublishingInterceptorParserTests { public void validateEchoChannelPublishing() { MessageHandler handler = Mockito.mock(MessageHandler.class); echoChannel.subscribe(handler); - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) { - Message message = (Message) invocation.getArguments()[0]; - assertEquals("bar", message.getHeaders().get("foo")); - assertEquals("Echoing: hello", message.getPayload()); - return null; - } + doAnswer(invocation -> { + Message message = (Message) invocation.getArguments()[0]; + assertEquals("bar", message.getHeaders().get("foo")); + assertEquals("Echoing: hello", message.getPayload()); + return null; }).when(handler).handleMessage((Message) anyObject()); testBean.echo("hello"); verify(handler, times(1)).handleMessage((Message) anyObject()); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ServiceActivatorParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ServiceActivatorParserTests.java index cf57ba22fb..783b548e54 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ServiceActivatorParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ServiceActivatorParserTests.java @@ -211,6 +211,10 @@ public class ServiceActivatorParserTests { @SuppressWarnings("unused") private static class TestBean { + TestBean() { + super(); + } + public String caps(String s) { return s.toUpperCase(); } @@ -224,6 +228,10 @@ public class ServiceActivatorParserTests { @SuppressWarnings("unused") private static class TestPayload { + TestPayload() { + super(); + } + public String getSimpleClassName(Object o) { return o.getClass().getSimpleName(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java index aa96bd50b2..63391b7d86 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java @@ -35,11 +35,9 @@ import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import java.util.Date; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; @@ -48,8 +46,6 @@ import org.apache.commons.logging.Log; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.FactoryBean; @@ -103,6 +99,7 @@ import org.springframework.integration.scheduling.PollerMetadata; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.MutableMessageBuilder; import org.springframework.integration.support.SmartLifecycleRoleController; +import org.springframework.integration.test.util.OnlyOnceTrigger; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; @@ -115,7 +112,6 @@ import org.springframework.messaging.support.ChannelInterceptor; import org.springframework.messaging.support.ChannelInterceptorAdapter; import org.springframework.messaging.support.GenericMessage; import org.springframework.scheduling.Trigger; -import org.springframework.scheduling.TriggerContext; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.support.CronTrigger; @@ -294,15 +290,10 @@ public class EnableIntegrationTests { Log logger = spy(TestUtils.getPropertyValue(this.serviceActivatorEndpoint, "logger", Log.class)); when(logger.isDebugEnabled()).thenReturn(true); final CountDownLatch pollerInterruptedLatch = new CountDownLatch(1); - doAnswer(new Answer() { - - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - pollerInterruptedLatch.countDown(); - invocation.callRealMethod(); - return null; - } - + doAnswer(invocation -> { + pollerInterruptedLatch.countDown(); + invocation.callRealMethod(); + return null; }).when(logger).debug("Received no Message during the poll, returning 'false'"); new DirectFieldAccessor(this.serviceActivatorEndpoint).setPropertyValue("logger", logger); @@ -719,15 +710,7 @@ public class EnableIntegrationTests { @Bean public Trigger onlyOnceTrigger() { - return new Trigger() { - - private final AtomicBoolean invoked = new AtomicBoolean(); - - @Override - public Date nextExecutionTime(TriggerContext triggerContext) { - return this.invoked.getAndSet(true) ? null : new Date(); - } - }; + return new OnlyOnceTrigger(); } @Bean diff --git a/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java b/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java index 40c16a1370..cea759d9b6 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java @@ -50,7 +50,7 @@ import org.springframework.util.Assert; public class AsyncMessagingTemplateTests { // TODO: changed from 0 because of recurrent failure: is this right? - private long safety = 100; + private final long safety = 100; @Test public void asyncSendWithDefaultChannel() throws Exception { @@ -438,19 +438,15 @@ public class AsyncMessagingTemplateTests { private static void sendMessageAfterDelay(final MessageChannel channel, final GenericMessage message, final int delay) { - Executors.newSingleThreadExecutor().execute(new Runnable() { - - public void run() { - try { - Thread.sleep(delay); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return; - } - channel.send(message); + Executors.newSingleThreadExecutor().execute(() -> { + try { + Thread.sleep(delay); } - + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + channel.send(message); }); } @@ -490,6 +486,7 @@ public class AsyncMessagingTemplateTests { private static class TestMessagePostProcessor implements MessagePostProcessor { + @Override public Message postProcessMessage(Message message) { return MessageBuilder.fromMessage(message).setHeader("foo", "bar").build(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/core/MessageHistoryTests.java b/spring-integration-core/src/test/java/org/springframework/integration/core/MessageHistoryTests.java index ad339dddfd..4306468b7c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/core/MessageHistoryTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/core/MessageHistoryTests.java @@ -133,7 +133,7 @@ public class MessageHistoryTests { private final int id; - private TestComponent(int id) { + TestComponent(int id) { this.id = id; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/core/MessageIdGenerationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/core/MessageIdGenerationTests.java index af1c34bde7..6a91a2e004 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/core/MessageIdGenerationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/core/MessageIdGenerationTests.java @@ -158,12 +158,7 @@ public class MessageIdGenerationTests { Field idGeneratorField = ReflectionUtils.findField(MessageHeaders.class, "idGenerator"); ReflectionUtils.makeAccessible(idGeneratorField); - ReflectionUtils.setField(idGeneratorField, null, new IdGenerator() { - @Override - public UUID generateId() { - return TimeBasedUUIDGenerator.generateId(); - } - }); + ReflectionUtils.setField(idGeneratorField, null, (IdGenerator) () -> TimeBasedUUIDGenerator.generateId()); watch = new StopWatch(); watch.start(); for (int i = 0; i < times; i++) { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/BroadcastingDispatcherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/BroadcastingDispatcherTests.java index 408531acc0..aa5925030c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/BroadcastingDispatcherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/BroadcastingDispatcherTests.java @@ -27,8 +27,6 @@ import java.util.concurrent.atomic.AtomicInteger; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.core.task.TaskExecutor; import org.springframework.integration.IntegrationMessageHeaderAccessor; @@ -48,15 +46,15 @@ public class BroadcastingDispatcherTests { private BroadcastingDispatcher dispatcher; - private TaskExecutor taskExecutorMock = Mockito.mock(TaskExecutor.class); + private final TaskExecutor taskExecutorMock = Mockito.mock(TaskExecutor.class); - private Message messageMock = Mockito.mock(Message.class); + private final Message messageMock = Mockito.mock(Message.class); - private MessageHandler targetMock1 = Mockito.mock(MessageHandler.class); + private final MessageHandler targetMock1 = Mockito.mock(MessageHandler.class); - private MessageHandler targetMock2 = Mockito.mock(MessageHandler.class); + private final MessageHandler targetMock2 = Mockito.mock(MessageHandler.class); - private MessageHandler targetMock3 = Mockito.mock(MessageHandler.class); + private final MessageHandler targetMock3 = Mockito.mock(MessageHandler.class); @Before @@ -277,13 +275,9 @@ public class BroadcastingDispatcherTests { } private void defaultTaskExecutorMock() { - Mockito.doAnswer(new Answer() { - - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - ((Runnable) invocation.getArguments()[0]).run(); - return null; - } + Mockito.doAnswer(invocation -> { + ((Runnable) invocation.getArguments()[0]).run(); + return null; }).when(taskExecutorMock).execute(Mockito.any(Runnable.class)); } @@ -292,15 +286,11 @@ public class BroadcastingDispatcherTests { */ private void partialFailingExecutorMock(final boolean... passes) { final AtomicInteger count = new AtomicInteger(); - Mockito.doAnswer(new Answer() { - - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - if (passes[count.getAndIncrement()]) { - ((Runnable) invocation.getArguments()[0]).run(); - } - return null; + Mockito.doAnswer(invocation -> { + if (passes[count.getAndIncrement()]) { + ((Runnable) invocation.getArguments()[0]).run(); } + return null; }).when(taskExecutorMock).execute(Mockito.any(Runnable.class)); } @@ -313,6 +303,7 @@ public class BroadcastingDispatcherTests { this.messageList = messageList; } + @Override public void handleMessage(Message message) { this.messageList.add(message); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/OrderedAwareCopyOnWriteArraySetTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/OrderedAwareCopyOnWriteArraySetTests.java index 6d6a29171f..8ccd2cffef 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/OrderedAwareCopyOnWriteArraySetTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/OrderedAwareCopyOnWriteArraySetTests.java @@ -153,32 +153,26 @@ public class OrderedAwareCopyOnWriteArraySetTests { final Object o8 = new Foo(Ordered.HIGHEST_PRECEDENCE); final Object o9 = new Foo(4); final Object o10 = new Foo(2); - Thread t1 = new Thread(new Runnable() { - public void run() { - setToTest.add(o1); - setToTest.add(o3); - setToTest.add(o5); - setToTest.add(o7); - setToTest.add(o9); - } + Thread t1 = new Thread(() -> { + setToTest.add(o1); + setToTest.add(o3); + setToTest.add(o5); + setToTest.add(o7); + setToTest.add(o9); }); - Thread t2 = new Thread(new Runnable() { - public void run() { - setToTest.add(o2); - setToTest.add(o4); - setToTest.add(o6); - setToTest.add(o8); - setToTest.add(o10); - } + Thread t2 = new Thread(() -> { + setToTest.add(o2); + setToTest.add(o4); + setToTest.add(o6); + setToTest.add(o8); + setToTest.add(o10); }); - Thread t3 = new Thread(new Runnable() { - public void run() { - setToTest.add(1); - setToTest.add(new Foo(2)); - setToTest.add(3); - setToTest.add(new Foo(9)); - setToTest.add(8); - } + Thread t3 = new Thread(() -> { + setToTest.add(1); + setToTest.add(new Foo(2)); + setToTest.add(3); + setToTest.add(new Foo(9)); + setToTest.add(8); }); t1.start(); t2.start(); @@ -230,12 +224,10 @@ public class OrderedAwareCopyOnWriteArraySetTests { tempList.add(o9); tempList.add(o10); final OrderedAwareCopyOnWriteArraySet orderAwareSet = new OrderedAwareCopyOnWriteArraySet(); - Thread t1 = new Thread(new Runnable() { - public void run() { - orderAwareSet.addAll(tempList); - orderAwareSet.remove(o5); - orderAwareSet.remove(o7); - } + Thread t1 = new Thread(() -> { + orderAwareSet.addAll(tempList); + orderAwareSet.remove(o5); + orderAwareSet.remove(o7); }); final List tempList2 = new ArrayList(); final Foo foo5 = new Foo(5); @@ -249,17 +241,13 @@ public class OrderedAwareCopyOnWriteArraySetTests { tempList2.add(10); tempList2.add(13); tempList2.add(new Foo(63)); - Thread t2 = new Thread(new Runnable() { - public void run() { - orderAwareSet.addAll(tempList2); - orderAwareSet.remove(foo5); - } + Thread t2 = new Thread(() -> { + orderAwareSet.addAll(tempList2); + orderAwareSet.remove(foo5); }); - Thread t3 = new Thread(new Runnable() { - public void run() { - orderAwareSet.add("hello"); - orderAwareSet.add("hello again"); - } + Thread t3 = new Thread(() -> { + orderAwareSet.add("hello"); + orderAwareSet.add("hello again"); }); t1.start(); @@ -277,17 +265,24 @@ public class OrderedAwareCopyOnWriteArraySetTests { Object[] elements = orderAwareSet.toArray(); assertEquals(18, elements.length); } + private static class Foo implements Ordered { + private final int order; + Foo(int order) { this.order = order; } + + @Override public int getOrder() { return order; } + @Override public String toString() { return "Foo-" + order; } } + } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/RoundRobinDispatcherConcurrentTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/RoundRobinDispatcherConcurrentTests.java index 717677a21b..6d02696e42 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/RoundRobinDispatcherConcurrentTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/RoundRobinDispatcherConcurrentTests.java @@ -32,10 +32,10 @@ import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; -import org.springframework.messaging.Message; import org.springframework.integration.MessageRejectedException; -import org.springframework.messaging.MessagingException; +import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandler; +import org.springframework.messaging.MessagingException; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; @@ -47,9 +47,9 @@ public class RoundRobinDispatcherConcurrentTests { private static final int TOTAL_EXECUTIONS = 40; - private UnicastingDispatcher dispatcher = new UnicastingDispatcher(); + private final UnicastingDispatcher dispatcher = new UnicastingDispatcher(); - private ThreadPoolTaskExecutor scheduler = new ThreadPoolTaskExecutor(); + private final ThreadPoolTaskExecutor scheduler = new ThreadPoolTaskExecutor(); @Mock private MessageHandler handler1; @@ -84,19 +84,17 @@ public class RoundRobinDispatcherConcurrentTests { final CountDownLatch allDone = new CountDownLatch(TOTAL_EXECUTIONS); final Message message = this.message; final AtomicBoolean failed = new AtomicBoolean(false); - Runnable messageSenderTask = new Runnable() { - public void run() { - try { - start.await(); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - if (!dispatcher.dispatch(message)) { - failed.set(true); - } - allDone.countDown(); + Runnable messageSenderTask = () -> { + try { + start.await(); } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + if (!dispatcher.dispatch(message)) { + failed.set(true); + } + allDone.countDown(); }; for (int i = 0; i < TOTAL_EXECUTIONS; i++) { scheduler.execute(messageSenderTask); @@ -116,23 +114,21 @@ public class RoundRobinDispatcherConcurrentTests { final CountDownLatch start = new CountDownLatch(1); final CountDownLatch allDone = new CountDownLatch(TOTAL_EXECUTIONS); final Message message = this.message; - Runnable messageSenderTask = new Runnable() { - public void run() { - try { - start.await(); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } - try { - dispatcher.dispatch(message); - fail("this shouldn't happen"); - } - catch (MessagingException e) { - // expected - } - allDone.countDown(); + Runnable messageSenderTask = () -> { + try { + start.await(); } + catch (InterruptedException e1) { + Thread.currentThread().interrupt(); + } + try { + dispatcher.dispatch(message); + fail("this shouldn't happen"); + } + catch (MessagingException e2) { + // expected + } + allDone.countDown(); }; for (int i = 0; i < TOTAL_EXECUTIONS; i++) { scheduler.execute(messageSenderTask); @@ -151,6 +147,7 @@ public class RoundRobinDispatcherConcurrentTests { final Message message = this.message; final AtomicBoolean failed = new AtomicBoolean(false); Runnable messageSenderTask = new Runnable() { + @Override public void run() { try { start.await(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/UnicastingDispatcherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/UnicastingDispatcherTests.java index 39fad329f8..69cb3fd4f1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/UnicastingDispatcherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/UnicastingDispatcherTests.java @@ -27,7 +27,6 @@ import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageDeliveryException; import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.MessagingException; import org.springframework.messaging.SubscribableChannel; import org.springframework.messaging.support.GenericMessage; @@ -44,14 +43,10 @@ public class UnicastingDispatcherTests { public void withInboundGatewayAsyncRequestChannelAndExplicitErrorChannel() throws Exception { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("unicasting-with-async.xml", this.getClass()); SubscribableChannel errorChannel = context.getBean("errorChannel", SubscribableChannel.class); - MessageHandler errorHandler = new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); - assertTrue(message.getPayload() instanceof MessageDeliveryException); - replyChannel.send(new GenericMessage("reply")); - } + MessageHandler errorHandler = message -> { + MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); + assertTrue(message.getPayload() instanceof MessageDeliveryException); + replyChannel.send(new GenericMessage("reply")); }; errorChannel.subscribe(errorHandler); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/CorrelationIdTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/CorrelationIdTests.java index 70eec47964..21efa73e19 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/CorrelationIdTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/CorrelationIdTests.java @@ -20,14 +20,15 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; -import org.springframework.messaging.Message; + import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.handler.ServiceActivatingHandler; -import org.springframework.messaging.support.GenericMessage; import org.springframework.integration.splitter.MethodInvokingSplitter; import org.springframework.integration.support.MessageBuilder; +import org.springframework.messaging.Message; +import org.springframework.messaging.support.GenericMessage; /** * @author Mark Fisher @@ -132,6 +133,10 @@ public class CorrelationIdTests { @SuppressWarnings("unused") private static class TestBean { + TestBean() { + super(); + } + public String upperCase(String input) { return input.toUpperCase(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceIntegrationTests.java index b2f0d0d28c..213d048de8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ExpressionEvaluatingMessageSourceIntegrationTests.java @@ -31,12 +31,11 @@ import org.springframework.beans.factory.BeanFactory; import org.springframework.expression.Expression; import org.springframework.expression.common.LiteralExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; -import org.springframework.messaging.Message; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.config.ExpressionFactoryBean; +import org.springframework.messaging.Message; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.scheduling.support.PeriodicTrigger; -import org.springframework.util.ErrorHandler; /** * @author Mark Fisher @@ -69,10 +68,8 @@ public class ExpressionEvaluatingMessageSourceIntegrationTests { adapter.setMaxMessagesPerPoll(3); adapter.setTrigger(new PeriodicTrigger(60000)); adapter.setOutputChannel(channel); - adapter.setErrorHandler(new ErrorHandler() { - public void handleError(Throwable t) { - throw new IllegalStateException("unexpected exception in test", t); - } + adapter.setErrorHandler(t -> { + throw new IllegalStateException("unexpected exception in test", t); }); adapter.start(); List> messages = new ArrayList>(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageProducerSupportTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageProducerSupportTests.java index 20143f9f93..d3be8d1cbc 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageProducerSupportTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/MessageProducerSupportTests.java @@ -35,8 +35,6 @@ import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.test.util.TestUtils.TestApplicationContext; import org.springframework.messaging.Message; import org.springframework.messaging.MessageDeliveryException; -import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.ErrorMessage; import org.springframework.messaging.support.GenericMessage; @@ -53,11 +51,8 @@ public class MessageProducerSupportTests { public void validateExceptionIfNoErrorChannel() { DirectChannel outChannel = new DirectChannel(); - outChannel.subscribe(new MessageHandler() { - @Override - public void handleMessage(Message message) throws MessagingException { - throw new RuntimeException("problems"); - } + outChannel.subscribe(message -> { + throw new RuntimeException("problems"); }); MessageProducerSupport mps = new MessageProducerSupport() { }; mps.setOutputChannel(outChannel); @@ -70,18 +65,12 @@ public class MessageProducerSupportTests { @Test(expected = MessageDeliveryException.class) public void validateExceptionIfSendToErrorChannelFails() { DirectChannel outChannel = new DirectChannel(); - outChannel.subscribe(new MessageHandler() { - @Override - public void handleMessage(Message message) throws MessagingException { - throw new RuntimeException("problems"); - } + outChannel.subscribe(message -> { + throw new RuntimeException("problems"); }); PublishSubscribeChannel errorChannel = new PublishSubscribeChannel(); - errorChannel.subscribe(new MessageHandler() { - @Override - public void handleMessage(Message message) throws MessagingException { - throw new RuntimeException("ooops"); - } + errorChannel.subscribe(message -> { + throw new RuntimeException("ooops"); }); MessageProducerSupport mps = new MessageProducerSupport() { }; mps.setOutputChannel(outChannel); @@ -95,11 +84,8 @@ public class MessageProducerSupportTests { @Test public void validateSuccessfulErrorFlowDoesNotThrowErrors() { DirectChannel outChannel = new DirectChannel(); - outChannel.subscribe(new MessageHandler() { - @Override - public void handleMessage(Message message) throws MessagingException { - throw new RuntimeException("problems"); - } + outChannel.subscribe(message -> { + throw new RuntimeException("problems"); }); PublishSubscribeChannel errorChannel = new PublishSubscribeChannel(); SuccessfulErrorService errorService = new SuccessfulErrorService(); @@ -143,11 +129,8 @@ public class MessageProducerSupportTests { assertTrue(endpoint.isStopped()); endpoint.start(); assertFalse(endpoint.isStopped()); - endpoint.stop(new Runnable() { - @Override - public void run() { - // Do nothing - } + endpoint.stop(() -> { + // Do nothing }); assertEquals(1, endpoint.getCount()); assertTrue(endpoint.isStopped()); @@ -157,6 +140,10 @@ public class MessageProducerSupportTests { private volatile Message lastMessage; + SuccessfulErrorService() { + super(); + } + @SuppressWarnings("unused") public void handleErrorMessage(Message errorMessage) { this.lastMessage = errorMessage; @@ -166,8 +153,13 @@ public class MessageProducerSupportTests { private static class CustomEndpoint extends AbstractEndpoint { private final AtomicInteger count = new AtomicInteger(0); + private final AtomicBoolean stopped = new AtomicBoolean(true); + CustomEndpoint() { + super(); + } + public int getCount() { return this.count.get(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingConsumerEndpointTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingConsumerEndpointTests.java index ca913088b9..73019d3932 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingConsumerEndpointTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingConsumerEndpointTests.java @@ -31,8 +31,8 @@ import org.junit.Test; import org.mockito.Mockito; import org.springframework.beans.factory.BeanFactory; -import org.springframework.messaging.Message; import org.springframework.integration.MessageRejectedException; +import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.support.GenericMessage; @@ -50,21 +50,21 @@ public class PollingConsumerEndpointTests { private PollingConsumer endpoint; - private TestTrigger trigger = new TestTrigger(); + private final TestTrigger trigger = new TestTrigger(); - private TestConsumer consumer = new TestConsumer(); + private final TestConsumer consumer = new TestConsumer(); @SuppressWarnings("rawtypes") - private Message message = new GenericMessage("test"); + private final Message message = new GenericMessage("test"); @SuppressWarnings("rawtypes") - private Message badMessage = new GenericMessage("bad"); + private final Message badMessage = new GenericMessage("bad"); - private TestErrorHandler errorHandler = new TestErrorHandler(); + private final TestErrorHandler errorHandler = new TestErrorHandler(); - private PollableChannel channelMock = Mockito.mock(PollableChannel.class); + private final PollableChannel channelMock = Mockito.mock(PollableChannel.class); - private ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); + private final ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); @Before @@ -176,6 +176,11 @@ public class PollingConsumerEndpointTests { private volatile AtomicInteger counter = new AtomicInteger(); + TestConsumer() { + super(); + } + + @Override public void handleMessage(Message message) { this.counter.incrementAndGet(); if ("bad".equals(message.getPayload().toString())) { @@ -192,6 +197,11 @@ public class PollingConsumerEndpointTests { private volatile CountDownLatch latch = new CountDownLatch(1); + TestTrigger() { + super(); + } + + @Override public Date nextExecutionTime(TriggerContext triggerContext) { if (!this.hasRun.getAndSet(true)) { return new Date(); @@ -223,6 +233,11 @@ public class PollingConsumerEndpointTests { private volatile Throwable lastError; + TestErrorHandler() { + super(); + } + + @Override public void handleError(Throwable t) { this.lastError = t; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingLifecycleTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingLifecycleTests.java index 1c5fa06aef..9a85339226 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingLifecycleTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PollingLifecycleTests.java @@ -55,9 +55,9 @@ import org.springframework.scheduling.support.PeriodicTrigger; */ public class PollingLifecycleTests { - private ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); + private final ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); - private TestErrorHandler errorHandler = new TestErrorHandler(); + private final TestErrorHandler errorHandler = new TestErrorHandler(); @Before public void init() throws Exception { @@ -71,6 +71,7 @@ public class PollingLifecycleTests { channel.send(new GenericMessage("foo")); MessageHandler handler = Mockito.spy(new MessageHandler() { + @Override public void handleMessage(Message message) throws MessagingException { latch.countDown(); } @@ -105,6 +106,7 @@ public class PollingLifecycleTests { pollerMetadata.setTrigger(new PeriodicTrigger(2000)); adapterFactory.setPollerMetadata(pollerMetadata); MessageSource source = spy(new MessageSource() { + @Override public Message receive() { latch.countDown(); return new GenericMessage("hello"); @@ -135,21 +137,19 @@ public class PollingLifecycleTests { pollerMetadata.setTrigger(new PeriodicTrigger(2000)); adapterFactory.setPollerMetadata(pollerMetadata); final Runnable coughtInterrupted = mock(Runnable.class); - MessageSource source = new MessageSource() { - public Message receive() { + MessageSource source = () -> { - try { - for (int i = 0; i < 10; i++) { - Thread.sleep(1000); - latch.countDown(); - } + try { + for (int i = 0; i < 10; i++) { + Thread.sleep(1000); + latch.countDown(); } - catch (InterruptedException e) { - coughtInterrupted.run(); - } - - return new GenericMessage("hello"); } + catch (InterruptedException e) { + coughtInterrupted.run(); + } + + return new GenericMessage("hello"); }; adapterFactory.setSource(source); adapterFactory.setOutputChannel(channel); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PseudoTransactionalMessageSourceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PseudoTransactionalMessageSourceTests.java index 4eb65a18ab..94ffffb161 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PseudoTransactionalMessageSourceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/PseudoTransactionalMessageSourceTests.java @@ -52,8 +52,6 @@ import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.support.GenericMessage; -import org.springframework.transaction.TransactionStatus; -import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionSynchronization; import org.springframework.transaction.support.TransactionSynchronizationAdapter; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -217,42 +215,38 @@ public class PseudoTransactionalMessageSourceTests { public void testCommitWithManager() { final PollableChannel queueChannel = new QueueChannel(); TransactionTemplate transactionTemplate = new TransactionTemplate(new PseudoTransactionManager()); - transactionTemplate.execute(new TransactionCallback() { + transactionTemplate.execute(status -> { + SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter(); + ExpressionEvaluatingTransactionSynchronizationProcessor syncProcessor = + new ExpressionEvaluatingTransactionSynchronizationProcessor(); + syncProcessor.setBeanFactory(mock(BeanFactory.class)); + syncProcessor.setBeforeCommitExpression(new SpelExpressionParser().parseExpression("#bix")); + syncProcessor.setBeforeCommitChannel(queueChannel); + syncProcessor.setAfterCommitChannel(queueChannel); + syncProcessor.setAfterCommitExpression(new SpelExpressionParser().parseExpression("#baz")); - @Override - public Object doInTransaction(TransactionStatus status) { - SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter(); - ExpressionEvaluatingTransactionSynchronizationProcessor syncProcessor = - new ExpressionEvaluatingTransactionSynchronizationProcessor(); - syncProcessor.setBeanFactory(mock(BeanFactory.class)); - syncProcessor.setBeforeCommitExpression(new SpelExpressionParser().parseExpression("#bix")); - syncProcessor.setBeforeCommitChannel(queueChannel); - syncProcessor.setAfterCommitChannel(queueChannel); - syncProcessor.setAfterCommitExpression(new SpelExpressionParser().parseExpression("#baz")); + DefaultTransactionSynchronizationFactory syncFactory = + new DefaultTransactionSynchronizationFactory(syncProcessor); - DefaultTransactionSynchronizationFactory syncFactory = - new DefaultTransactionSynchronizationFactory(syncProcessor); + adapter.setTransactionSynchronizationFactory(syncFactory); - adapter.setTransactionSynchronizationFactory(syncFactory); + QueueChannel outputChannel = new QueueChannel(); + adapter.setOutputChannel(outputChannel); + adapter.setSource(new MessageSource() { - QueueChannel outputChannel = new QueueChannel(); - adapter.setOutputChannel(outputChannel); - adapter.setSource(new MessageSource() { + @Override + public Message receive() { + GenericMessage message = new GenericMessage("foo"); + IntegrationResourceHolder holder = + (IntegrationResourceHolder) TransactionSynchronizationManager.getResource(this); + holder.addAttribute("baz", "qux"); + holder.addAttribute("bix", "qox"); + return message; + } + }); - @Override - public Message receive() { - GenericMessage message = new GenericMessage("foo"); - IntegrationResourceHolder holder = - (IntegrationResourceHolder) TransactionSynchronizationManager.getResource(this); - holder.addAttribute("baz", "qux"); - holder.addAttribute("bix", "qox"); - return message; - } - }); - - doPoll(adapter); - return null; - } + doPoll(adapter); + return null; }); Message beforeCommitMessage = queueChannel.receive(1000); assertNotNull(beforeCommitMessage); @@ -267,57 +261,7 @@ public class PseudoTransactionalMessageSourceTests { final PollableChannel queueChannel = new QueueChannel(); TransactionTemplate transactionTemplate = new TransactionTemplate(new PseudoTransactionManager()); try { - transactionTemplate.execute(new TransactionCallback() { - - @Override - public Object doInTransaction(TransactionStatus status) { - - SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter(); - ExpressionEvaluatingTransactionSynchronizationProcessor syncProcessor = - new ExpressionEvaluatingTransactionSynchronizationProcessor(); - syncProcessor.setBeanFactory(mock(BeanFactory.class)); - syncProcessor.setAfterRollbackChannel(queueChannel); - syncProcessor.setAfterRollbackExpression(new SpelExpressionParser().parseExpression("#baz")); - - DefaultTransactionSynchronizationFactory syncFactory = - new DefaultTransactionSynchronizationFactory(syncProcessor); - - adapter.setTransactionSynchronizationFactory(syncFactory); - - QueueChannel outputChannel = new QueueChannel(); - adapter.setOutputChannel(outputChannel); - adapter.setSource(new MessageSource() { - - @Override - public Message receive() { - GenericMessage message = new GenericMessage("foo"); - ((IntegrationResourceHolder) TransactionSynchronizationManager.getResource(this)) - .addAttribute("baz", "qux"); - return message; - } - }); - - doPoll(adapter); - throw new RuntimeException("Force rollback"); - } - }); - } - catch (Exception e) { - assertEquals("Force rollback", e.getMessage()); - } - Message rollbackMessage = queueChannel.receive(1000); - assertNotNull(rollbackMessage); - assertEquals("qux", rollbackMessage.getPayload()); - } - - @Test - public void testRollbackWithManagerUsingStatus() { - final PollableChannel queueChannel = new QueueChannel(); - TransactionTemplate transactionTemplate = new TransactionTemplate(new PseudoTransactionManager()); - transactionTemplate.execute(new TransactionCallback() { - - @Override - public Object doInTransaction(TransactionStatus status) { + transactionTemplate.execute(status -> { SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter(); ExpressionEvaluatingTransactionSynchronizationProcessor syncProcessor = @@ -345,9 +289,51 @@ public class PseudoTransactionalMessageSourceTests { }); doPoll(adapter); - status.setRollbackOnly(); - return null; - } + throw new RuntimeException("Force rollback"); + }); + } + catch (Exception e) { + assertEquals("Force rollback", e.getMessage()); + } + Message rollbackMessage = queueChannel.receive(1000); + assertNotNull(rollbackMessage); + assertEquals("qux", rollbackMessage.getPayload()); + } + + @Test + public void testRollbackWithManagerUsingStatus() { + final PollableChannel queueChannel = new QueueChannel(); + TransactionTemplate transactionTemplate = new TransactionTemplate(new PseudoTransactionManager()); + transactionTemplate.execute(status -> { + + SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter(); + ExpressionEvaluatingTransactionSynchronizationProcessor syncProcessor = + new ExpressionEvaluatingTransactionSynchronizationProcessor(); + syncProcessor.setBeanFactory(mock(BeanFactory.class)); + syncProcessor.setAfterRollbackChannel(queueChannel); + syncProcessor.setAfterRollbackExpression(new SpelExpressionParser().parseExpression("#baz")); + + DefaultTransactionSynchronizationFactory syncFactory = + new DefaultTransactionSynchronizationFactory(syncProcessor); + + adapter.setTransactionSynchronizationFactory(syncFactory); + + QueueChannel outputChannel = new QueueChannel(); + adapter.setOutputChannel(outputChannel); + adapter.setSource(new MessageSource() { + + @Override + public Message receive() { + GenericMessage message = new GenericMessage("foo"); + ((IntegrationResourceHolder) TransactionSynchronizationManager.getResource(this)) + .addAttribute("baz", "qux"); + return message; + } + }); + + doPoll(adapter); + status.setRollbackOnly(); + return null; }); Message rollbackMessage = queueChannel.receive(1000); assertNotNull(rollbackMessage); @@ -358,13 +344,7 @@ public class PseudoTransactionalMessageSourceTests { public void testInt2777UnboundResourceAfterTransactionComplete() { SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter(); - adapter.setSource(new MessageSource() { - - @Override - public Message receive() { - return null; - } - }); + adapter.setSource(() -> null); TransactionSynchronizationManager.setActualTransactionActive(true); doPoll(adapter); @@ -396,13 +376,7 @@ public class PseudoTransactionalMessageSourceTests { }; adapter.setTransactionSynchronizationFactory(syncFactory); - adapter.setSource(new MessageSource() { - - @Override - public Message receive() { - return null; - } - }); + adapter.setSource(() -> null); TransactionSynchronizationManager.initSynchronization(); TransactionSynchronizationManager.setActualTransactionActive(true); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorMethodResolutionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorMethodResolutionTests.java index b058d39f76..61792e42a7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorMethodResolutionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorMethodResolutionTests.java @@ -235,6 +235,10 @@ public class ServiceActivatorMethodResolutionTests { @SuppressWarnings("unused") private static class SingleAnnotationTestBean { + SingleAnnotationTestBean() { + super(); + } + @ServiceActivator public String upperCase(String s) { return s.toUpperCase(); @@ -243,12 +247,16 @@ public class ServiceActivatorMethodResolutionTests { public String lowerCase(String s) { return s.toLowerCase(); } + } - @SuppressWarnings("unused") private static class MultipleAnnotationTestBean { + MultipleAnnotationTestBean() { + super(); + } + @ServiceActivator public String upperCase(String s) { return s.toUpperCase(); @@ -258,12 +266,17 @@ public class ServiceActivatorMethodResolutionTests { public String lowerCase(String s) { return s.toLowerCase(); } + } @SuppressWarnings("unused") private static class SinglePublicMethodTestBean { + SinglePublicMethodTestBean() { + super(); + } + public String upperCase(String s) { return s.toUpperCase(); } @@ -271,12 +284,17 @@ public class ServiceActivatorMethodResolutionTests { String lowerCase(String s) { return s.toLowerCase(); } + } @SuppressWarnings("unused") private static class MultiplePublicMethodTestBean { + MultiplePublicMethodTestBean() { + super(); + } + public String upperCase(String s) { return s.toUpperCase(); } @@ -284,6 +302,7 @@ public class ServiceActivatorMethodResolutionTests { public String lowerCase(String s) { return s.toLowerCase(); } + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/expression/ForeignClassloaderTests.java b/spring-integration-core/src/test/java/org/springframework/integration/expression/ForeignClassloaderTests.java index d4143c834f..8c307dc0e1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/expression/ForeignClassloaderTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/expression/ForeignClassloaderTests.java @@ -53,18 +53,13 @@ public class ForeignClassloaderTests { */ @Test public void testThreadHasWrongClassLoader() { - Thread t = new Thread(new Runnable() { - - @Override - public void run() { - try { - foo.send(new GenericMessage("foo")); - } - catch (Exception e) { - e.printStackTrace(); - } + Thread t = new Thread(() -> { + try { + foo.send(new GenericMessage("foo")); + } + catch (Exception e) { + e.printStackTrace(); } - }); t.setContextClassLoader(new ClassLoader() { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/filter/MessageFilterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/filter/MessageFilterTests.java index 51c21efcfb..d5db8dc1cd 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/filter/MessageFilterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/filter/MessageFilterTests.java @@ -23,12 +23,11 @@ import static org.junit.Assert.assertTrue; import org.junit.Test; -import org.springframework.messaging.Message; import org.springframework.integration.MessageRejectedException; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; -import org.springframework.integration.core.MessageSelector; import org.springframework.integration.endpoint.EventDrivenConsumer; +import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; /** @@ -38,11 +37,7 @@ public class MessageFilterTests { @Test public void filterAcceptsMessage() { - MessageFilter filter = new MessageFilter(new MessageSelector() { - public boolean accept(Message message) { - return true; - } - }); + MessageFilter filter = new MessageFilter(message -> true); Message message = new GenericMessage("test"); QueueChannel output = new QueueChannel(); filter.setOutputChannel(output); @@ -54,11 +49,7 @@ public class MessageFilterTests { @Test public void filterRejectsMessageSilently() { - MessageFilter filter = new MessageFilter(new MessageSelector() { - public boolean accept(Message message) { - return false; - } - }); + MessageFilter filter = new MessageFilter(message -> false); QueueChannel output = new QueueChannel(); filter.setOutputChannel(output); filter.handleMessage(new GenericMessage("test")); @@ -67,11 +58,7 @@ public class MessageFilterTests { @Test(expected = MessageRejectedException.class) public void filterThrowsException() { - MessageFilter filter = new MessageFilter(new MessageSelector() { - public boolean accept(Message message) { - return false; - } - }); + MessageFilter filter = new MessageFilter(message -> false); filter.setThrowExceptionOnRejection(true); QueueChannel output = new QueueChannel(); filter.setOutputChannel(output); @@ -82,11 +69,7 @@ public class MessageFilterTests { public void filterAcceptsWithChannels() { DirectChannel inputChannel = new DirectChannel(); QueueChannel outputChannel = new QueueChannel(); - MessageFilter filter = new MessageFilter(new MessageSelector() { - public boolean accept(Message message) { - return true; - } - }); + MessageFilter filter = new MessageFilter(message -> true); filter.setOutputChannel(outputChannel); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, filter); endpoint.start(); @@ -101,11 +84,7 @@ public class MessageFilterTests { public void filterRejectsSilentlyWithChannels() { DirectChannel inputChannel = new DirectChannel(); QueueChannel outputChannel = new QueueChannel(); - MessageFilter filter = new MessageFilter(new MessageSelector() { - public boolean accept(Message message) { - return false; - } - }); + MessageFilter filter = new MessageFilter(message -> false); filter.setOutputChannel(outputChannel); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, filter); endpoint.start(); @@ -118,11 +97,7 @@ public class MessageFilterTests { public void filterThrowsExceptionWithChannels() { DirectChannel inputChannel = new DirectChannel(); QueueChannel outputChannel = new QueueChannel(); - MessageFilter filter = new MessageFilter(new MessageSelector() { - public boolean accept(Message message) { - return false; - } - }); + MessageFilter filter = new MessageFilter(message -> false); filter.setOutputChannel(outputChannel); filter.setThrowExceptionOnRejection(true); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, filter); @@ -136,11 +111,7 @@ public class MessageFilterTests { DirectChannel inputChannel = new DirectChannel(); QueueChannel outputChannel = new QueueChannel(); QueueChannel discardChannel = new QueueChannel(); - MessageFilter filter = new MessageFilter(new MessageSelector() { - public boolean accept(Message message) { - return false; - } - }); + MessageFilter filter = new MessageFilter(message -> false); filter.setOutputChannel(outputChannel); filter.setDiscardChannel(discardChannel); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, filter); @@ -158,11 +129,7 @@ public class MessageFilterTests { DirectChannel inputChannel = new DirectChannel(); QueueChannel outputChannel = new QueueChannel(); QueueChannel discardChannel = new QueueChannel(); - MessageFilter filter = new MessageFilter(new MessageSelector() { - public boolean accept(Message message) { - return false; - } - }); + MessageFilter filter = new MessageFilter(message -> false); filter.setOutputChannel(outputChannel); filter.setDiscardChannel(discardChannel); filter.setThrowExceptionOnRejection(true); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/filter/MethodInvokingSelectorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/filter/MethodInvokingSelectorTests.java index 3ba09e2da2..7ed3dfc29e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/filter/MethodInvokingSelectorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/filter/MethodInvokingSelectorTests.java @@ -92,6 +92,10 @@ public class MethodInvokingSelectorTests { @SuppressWarnings("unused") private static class TestBean { + TestBean() { + super(); + } + public boolean acceptString(Message message) { return (message.getPayload() instanceof String); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/AsyncGatewayTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/AsyncGatewayTests.java index 39b38067d0..23ccd0dfa5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/AsyncGatewayTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/AsyncGatewayTests.java @@ -301,32 +301,27 @@ public class AsyncGatewayTests { } private static void startResponder(final PollableChannel requestChannel) { - new Thread(new Runnable() { - - @Override - public void run() { - Message input = requestChannel.receive(); - String payload = input.getPayload() + "bar"; - Message reply = MessageBuilder.withPayload(payload) + new Thread(() -> { + Message input = requestChannel.receive(); + String payload = input.getPayload() + "bar"; + Message reply = MessageBuilder.withPayload(payload) + .copyHeaders(input.getHeaders()) + .build(); + try { + Thread.sleep(200); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + String header = (String) input.getHeaders().get("method"); + if (header != null && header.startsWith("returnCustomFuture")) { + reply = MessageBuilder.withPayload(new CustomFuture(payload, + (Thread) input.getHeaders().get("thread"))) .copyHeaders(input.getHeaders()) .build(); - try { - Thread.sleep(200); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return; - } - String header = (String) input.getHeaders().get("method"); - if (header != null && header.startsWith("returnCustomFuture")) { - reply = MessageBuilder.withPayload(new CustomFuture(payload, - (Thread) input.getHeaders().get("thread"))) - .copyHeaders(input.getHeaders()) - .build(); - } - ((MessageChannel) input.getHeaders().getReplyChannel()).send(reply); } - + ((MessageChannel) input.getHeaders().getReplyChannel()).send(reply); }).start(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInterfaceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInterfaceTests.java index 378f2fd5fb..67603539fa 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInterfaceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInterfaceTests.java @@ -124,19 +124,15 @@ public class GatewayInterfaceTests { DirectChannel channel = ac.getBean("requestChannelFoo", DirectChannel.class); final Method fooMethod = Foo.class.getMethod("foo", String.class); final AtomicBoolean called = new AtomicBoolean(); - MessageHandler handler = new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - assertThat((String) message.getHeaders().get("name"), equalTo("foo")); - assertThat( - (String) message.getHeaders().get("string"), - equalTo("public abstract void org.springframework.integration.gateway.GatewayInterfaceTests$Foo.foo(java.lang.String)")); - assertThat((Method) message.getHeaders().get("object"), equalTo(fooMethod)); - assertThat((String) message.getPayload(), equalTo("hello")); - assertThat(new MessageHeaderAccessor(message).getErrorChannel(), equalTo("errorChannel")); - called.set(true); - } + MessageHandler handler = message -> { + assertThat((String) message.getHeaders().get("name"), equalTo("foo")); + assertThat( + (String) message.getHeaders().get("string"), + equalTo("public abstract void org.springframework.integration.gateway.GatewayInterfaceTests$Foo.foo(java.lang.String)")); + assertThat((Method) message.getHeaders().get("object"), equalTo(fooMethod)); + assertThat((String) message.getPayload(), equalTo("hello")); + assertThat(new MessageHeaderAccessor(message).getErrorChannel(), equalTo("errorChannel")); + called.set(true); }; channel.subscribe(handler); Bar bar = ac.getBean(Bar.class); @@ -153,18 +149,14 @@ public class GatewayInterfaceTests { DirectChannel channel = ac.getBean("requestChannelFoo", DirectChannel.class); final Method fooMethod = Foo.class.getMethod("foo", String.class); final AtomicBoolean called = new AtomicBoolean(); - MessageHandler handler = new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - assertThat((String) message.getHeaders().get("name"), equalTo("foo")); - assertThat( - (String) message.getHeaders().get("string"), - equalTo("public abstract void org.springframework.integration.gateway.GatewayInterfaceTests$Foo.foo(java.lang.String)")); - assertThat((Method) message.getHeaders().get("object"), equalTo(fooMethod)); - assertThat((String) message.getPayload(), equalTo("foo")); - called.set(true); - } + MessageHandler handler = message -> { + assertThat((String) message.getHeaders().get("name"), equalTo("foo")); + assertThat( + (String) message.getHeaders().get("string"), + equalTo("public abstract void org.springframework.integration.gateway.GatewayInterfaceTests$Foo.foo(java.lang.String)")); + assertThat((Method) message.getHeaders().get("object"), equalTo(fooMethod)); + assertThat((String) message.getPayload(), equalTo("foo")); + called.set(true); }; channel.subscribe(handler); Bar bar = ac.getBean(Bar.class); @@ -191,18 +183,14 @@ public class GatewayInterfaceTests { DirectChannel channel = ac.getBean("requestChannelBaz", DirectChannel.class); final Method bazMethod = Foo.class.getMethod("baz", String.class); final AtomicBoolean called = new AtomicBoolean(); - MessageHandler handler = new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - assertThat((String) message.getHeaders().get("name"), equalTo("overrideGlobal")); - assertThat( - (String) message.getHeaders().get("string"), - equalTo("public abstract void org.springframework.integration.gateway.GatewayInterfaceTests$Foo.baz(java.lang.String)")); - assertThat((Method) message.getHeaders().get("object"), equalTo(bazMethod)); - assertThat((String) message.getPayload(), equalTo("hello")); - called.set(true); - } + MessageHandler handler = message -> { + assertThat((String) message.getHeaders().get("name"), equalTo("overrideGlobal")); + assertThat( + (String) message.getHeaders().get("string"), + equalTo("public abstract void org.springframework.integration.gateway.GatewayInterfaceTests$Foo.baz(java.lang.String)")); + assertThat((Method) message.getHeaders().get("object"), equalTo(bazMethod)); + assertThat((String) message.getPayload(), equalTo("hello")); + called.set(true); }; channel.subscribe(handler); Bar bar = ac.getBean(Bar.class); @@ -217,18 +205,14 @@ public class GatewayInterfaceTests { DirectChannel channel = ac.getBean("requestChannelBaz", DirectChannel.class); final Method quxMethod = Bar.class.getMethod("qux", String.class, String.class); final AtomicBoolean called = new AtomicBoolean(); - MessageHandler handler = new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - assertThat((String) message.getHeaders().get("name"), equalTo("arg1")); - assertThat( - (String) message.getHeaders().get("string"), - equalTo("public abstract void org.springframework.integration.gateway.GatewayInterfaceTests$Bar.qux(java.lang.String,java.lang.String)")); - assertThat((Method) message.getHeaders().get("object"), equalTo(quxMethod)); - assertThat((String) message.getPayload(), equalTo("hello")); - called.set(true); - } + MessageHandler handler = message -> { + assertThat((String) message.getHeaders().get("name"), equalTo("arg1")); + assertThat( + (String) message.getHeaders().get("string"), + equalTo("public abstract void org.springframework.integration.gateway.GatewayInterfaceTests$Bar.qux(java.lang.String,java.lang.String)")); + assertThat((Method) message.getHeaders().get("object"), equalTo(quxMethod)); + assertThat((String) message.getPayload(), equalTo("hello")); + called.set(true); }; channel.subscribe(handler); Bar bar = ac.getBean(Bar.class); @@ -327,13 +311,9 @@ public class GatewayInterfaceTests { ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext("GatewayInterfaceTests-context.xml", this.getClass()); DirectChannel channel = ac.getBean("requestChannelBaz", DirectChannel.class); final AtomicBoolean called = new AtomicBoolean(); - MessageHandler handler = new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - assertThat((String) message.getPayload(), equalTo("fizbuz")); - called.set(true); - } + MessageHandler handler = message -> { + assertThat((String) message.getPayload(), equalTo("fizbuz")); + called.set(true); }; channel.subscribe(handler); Baz baz = ac.getBean(Baz.class); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInvokingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInvokingMessageHandlerTests.java index e362d6d480..fcf2a9a7f8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInvokingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayInvokingMessageHandlerTests.java @@ -24,7 +24,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; -import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessageHandlingException; import org.springframework.messaging.SubscribableChannel; import org.springframework.messaging.support.GenericMessage; @@ -69,26 +68,20 @@ public class GatewayInvokingMessageHandlerTests { @Test public void validateGatewayInTheChainViaChannel() { - output.subscribe(new MessageHandler() { - @Override - public void handleMessage(Message message) { - Assert.assertEquals("echo:echo:echo:hello", message.getPayload()); - Assert.assertEquals("foo", message.getHeaders().get("foo")); - Assert.assertEquals("oleg", message.getHeaders().get("name")); - } + output.subscribe(message -> { + Assert.assertEquals("echo:echo:echo:hello", message.getPayload()); + Assert.assertEquals("foo", message.getHeaders().get("foo")); + Assert.assertEquals("oleg", message.getHeaders().get("name")); }); channel.send(new GenericMessage("hello")); } @Test public void validateGatewayInTheChainViaAnotherGateway() { - output.subscribe(new MessageHandler() { - @Override - public void handleMessage(Message message) { - Assert.assertEquals("echo:echo:echo:hello", message.getPayload()); - Assert.assertEquals("foo", message.getHeaders().get("foo")); - Assert.assertEquals("oleg", message.getHeaders().get("name")); - } + output.subscribe(message -> { + Assert.assertEquals("echo:echo:echo:hello", message.getPayload()); + Assert.assertEquals("foo", message.getHeaders().get("foo")); + Assert.assertEquals("oleg", message.getHeaders().get("name")); }); String result = gateway.process("hello"); Assert.assertEquals("echo:echo:echo:hello", result); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyFactoryBeanTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyFactoryBeanTests.java index 4f57dfa8e0..7774c1e4d1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyFactoryBeanTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/GatewayProxyFactoryBeanTests.java @@ -21,6 +21,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import java.lang.reflect.Method; import java.util.Collections; @@ -87,7 +88,7 @@ public class GatewayProxyFactoryBeanTests { return source.getBytes(); } }; - stringToByteConverter = Mockito.spy(stringToByteConverter); + stringToByteConverter = spy(stringToByteConverter); cs.addConverter(stringToByteConverter); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean(); DefaultListableBeanFactory bf = new DefaultListableBeanFactory(); @@ -156,13 +157,10 @@ public class GatewayProxyFactoryBeanTests { @Test public void testRequestReplyWithTypeConversion() throws Exception { final QueueChannel requestChannel = new QueueChannel(); - new Thread(new Runnable() { - @Override - public void run() { - Message input = requestChannel.receive(); - GenericMessage reply = new GenericMessage(input.getPayload() + "456"); - ((MessageChannel) input.getHeaders().getReplyChannel()).send(reply); - } + new Thread(() -> { + Message input = requestChannel.receive(); + GenericMessage reply = new GenericMessage(input.getPayload() + "456"); + ((MessageChannel) input.getHeaders().getReplyChannel()).send(reply); }).start(); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean(); proxyFactory.setServiceInterface(TestService.class); @@ -209,19 +207,16 @@ public class GatewayProxyFactoryBeanTests { Executor executor = Executors.newFixedThreadPool(numRequests); for (int i = 0; i < numRequests; i++) { final int count = i; - executor.execute(new Runnable() { - @Override - public void run() { - // add some randomness to the ordering of requests - try { - Thread.sleep(new Random().nextInt(100)); - } - catch (InterruptedException e) { - // ignore - } - results[count] = service.requestReply("test-" + count); - latch.countDown(); + executor.execute(() -> { + // add some randomness to the ordering of requests + try { + Thread.sleep(new Random().nextInt(100)); } + catch (InterruptedException e) { + // ignore + } + results[count] = service.requestReply("test-" + count); + latch.countDown(); }); } latch.await(30, TimeUnit.SECONDS); @@ -267,13 +262,10 @@ public class GatewayProxyFactoryBeanTests { @Test public void testMessageAsReturnValue() throws Exception { final QueueChannel requestChannel = new QueueChannel(); - new Thread(new Runnable() { - @Override - public void run() { - Message input = requestChannel.receive(); - GenericMessage reply = new GenericMessage(input.getPayload() + "bar"); - ((MessageChannel) input.getHeaders().getReplyChannel()).send(reply); - } + new Thread(() -> { + Message input = requestChannel.receive(); + GenericMessage reply = new GenericMessage(input.getPayload() + "bar"); + ((MessageChannel) input.getHeaders().getReplyChannel()).send(reply); }).start(); GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean(); proxyFactory.setServiceInterface(TestService.class); @@ -339,13 +331,10 @@ public class GatewayProxyFactoryBeanTests { private static void startResponder(final PollableChannel requestChannel) { - new Thread(new Runnable() { - @Override - public void run() { - Message input = requestChannel.receive(); - GenericMessage reply = new GenericMessage(input.getPayload() + "bar"); - ((MessageChannel) input.getHeaders().getReplyChannel()).send(reply); - } + new Thread(() -> { + Message input = requestChannel.receive(); + GenericMessage reply = new GenericMessage(input.getPayload() + "bar"); + ((MessageChannel) input.getHeaders().getReplyChannel()).send(reply); }).start(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/gateway/MessagingGatewayTests.java b/spring-integration-core/src/test/java/org/springframework/integration/gateway/MessagingGatewayTests.java index c54ff35af6..aa48d11618 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/gateway/MessagingGatewayTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/gateway/MessagingGatewayTests.java @@ -28,8 +28,6 @@ import java.util.UUID; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.channel.DirectChannel; @@ -40,7 +38,6 @@ import org.springframework.integration.test.util.TestUtils.TestApplicationContex import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageDeliveryException; -import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessageHeaders; import org.springframework.messaging.MessagingException; import org.springframework.messaging.PollableChannel; @@ -96,13 +93,9 @@ public class MessagingGatewayTests { @Test public void sendObject() { - Mockito.doAnswer(new Answer() { - - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - assertEquals("test", ((Message) invocation.getArguments()[0]).getPayload()); - return true; - } + Mockito.doAnswer(invocation -> { + assertEquals("test", ((Message) invocation.getArguments()[0]).getPayload()); + return true; }).when(requestChannel).send(Mockito.any(Message.class), Mockito.eq(1000L)); this.messagingGateway.send("test"); @@ -111,13 +104,9 @@ public class MessagingGatewayTests { @Test(expected = MessageDeliveryException.class) public void sendObject_failure() { - Mockito.doAnswer(new Answer() { - - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - assertEquals("test", ((Message) invocation.getArguments()[0]).getPayload()); - return false; - } + Mockito.doAnswer(invocation -> { + assertEquals("test", ((Message) invocation.getArguments()[0]).getPayload()); + return false; }).when(requestChannel).send(Mockito.any(Message.class), Mockito.eq(1000L)); this.messagingGateway.send("test"); @@ -151,15 +140,11 @@ public class MessagingGatewayTests { public void sendObjectAndReceiveObject() { Mockito.when(replyChannel.receive(100L)).thenReturn(messageMock); Mockito.when(messageMock.getPayload()).thenReturn("test"); - Mockito.doAnswer(new Answer() { - - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - Message message = (Message) invocation.getArguments()[0]; - MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); - replyChannel.send(message); - return true; - } + Mockito.doAnswer(invocation -> { + Message message = (Message) invocation.getArguments()[0]; + MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); + replyChannel.send(message); + return true; }).when(requestChannel).send(Mockito.any(Message.class), Mockito.anyLong()); // TODO: if timeout is 0, this will fail occasionally @@ -177,15 +162,11 @@ public class MessagingGatewayTests { Mockito.when(messageMock.getHeaders()).thenReturn(messageHeadersMock); Mockito.when(messageMock.getPayload()).thenReturn("foo"); - Mockito.doAnswer(new Answer() { - - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - Message message = (Message) invocation.getArguments()[0]; - MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); - replyChannel.send(message); - return true; - } + Mockito.doAnswer(invocation -> { + Message message = (Message) invocation.getArguments()[0]; + MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); + replyChannel.send(message); + return true; }).when(requestChannel).send(Mockito.any(Message.class), Mockito.anyLong()); this.messagingGateway.setReplyTimeout(0); @@ -202,15 +183,11 @@ public class MessagingGatewayTests { public void sendObjectAndReceiveMessage() { Mockito.when(messageMock.getPayload()).thenReturn("foo"); Mockito.when(replyChannel.receive(100L)).thenReturn(messageMock); - Mockito.doAnswer(new Answer() { - - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - Message message = (Message) invocation.getArguments()[0]; - MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); - replyChannel.send(messageMock); - return true; - } + Mockito.doAnswer(invocation -> { + Message message = (Message) invocation.getArguments()[0]; + MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); + replyChannel.send(messageMock); + return true; }).when(requestChannel).send(Mockito.any(Message.class), Mockito.anyLong()); this.messagingGateway.setReplyTimeout(100L); @@ -227,15 +204,11 @@ public class MessagingGatewayTests { Mockito.when(replyChannel.receive(Mockito.anyLong())).thenReturn(messageMock); Mockito.when(messageMock.getHeaders()).thenReturn(messageHeadersMock); Mockito.when(messageMock.getPayload()).thenReturn("foo"); - Mockito.doAnswer(new Answer() { - - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - Message message = (Message) invocation.getArguments()[0]; - MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); - replyChannel.send(messageMock); - return true; - } + Mockito.doAnswer(invocation -> { + Message message = (Message) invocation.getArguments()[0]; + MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); + replyChannel.send(messageMock); + return true; }).when(requestChannel).send(Mockito.any(Message.class), Mockito.anyLong()); Message receiveMessage = this.messagingGateway.sendAndReceiveMessage(messageMock); @@ -251,11 +224,8 @@ public class MessagingGatewayTests { @Test(expected = MessagingException.class) public void validateErroMessageCanNotBeReplyMessage() { DirectChannel reqChannel = new DirectChannel(); - reqChannel.subscribe(new MessageHandler() { - @Override - public void handleMessage(Message message) throws MessagingException { - throw new RuntimeException("ooops"); - } + reqChannel.subscribe(message -> { + throw new RuntimeException("ooops"); }); PublishSubscribeChannel errorChannel = new PublishSubscribeChannel(); ServiceActivatingHandler handler = new ServiceActivatingHandler(new MyErrorService()); @@ -279,11 +249,8 @@ public class MessagingGatewayTests { @Test public void validateErrorChannelWithSuccessfulReply() { DirectChannel reqChannel = new DirectChannel(); - reqChannel.subscribe(new MessageHandler() { - @Override - public void handleMessage(Message message) throws MessagingException { - throw new RuntimeException("ooops"); - } + reqChannel.subscribe(message -> { + throw new RuntimeException("ooops"); }); PublishSubscribeChannel errorChannel = new PublishSubscribeChannel(); ServiceActivatingHandler handler = new ServiceActivatingHandler(new MyOneWayErrorService()); @@ -302,15 +269,20 @@ public class MessagingGatewayTests { this.messagingGateway.send("hello"); } + public static class MyErrorService { + public Message handleErrorMessage(Message errorMessage) { return errorMessage; } + } public static class MyOneWayErrorService { + public void handleErrorMessage(Message errorMessage) { } + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/AsyncHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/AsyncHandlerTests.java index 9cfe439dad..bcd2666135 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/AsyncHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/AsyncHandlerTests.java @@ -38,8 +38,6 @@ import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.junit.Before; import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.BeanFactory; @@ -84,28 +82,23 @@ public class AsyncHandlerTests { @Override protected Object handleRequestMessage(Message requestMessage) { final SettableListenableFuture future = new SettableListenableFuture(); - Executors.newSingleThreadExecutor().execute(new Runnable() { - - @Override - public void run() { - try { - latch.await(10, TimeUnit.SECONDS); - switch (whichTest) { - case 0: - future.set("reply"); - break; - case 1: - future.setException(new RuntimeException("foo")); - break; - case 2: - future.setException(new MessagingException(requestMessage)); - } - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); + Executors.newSingleThreadExecutor().execute(() -> { + try { + latch.await(10, TimeUnit.SECONDS); + switch (whichTest) { + case 0: + future.set("reply"); + break; + case 1: + future.setException(new RuntimeException("foo")); + break; + case 2: + future.setException(new MessagingException(requestMessage)); } } - + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } }); return future; } @@ -117,16 +110,11 @@ public class AsyncHandlerTests { this.latch = new CountDownLatch(1); Log logger = spy(TestUtils.getPropertyValue(this.handler, "logger", Log.class)); new DirectFieldAccessor(this.handler).setPropertyValue("logger", logger); - doAnswer(new Answer() { - - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - failedCallbackMessage = (String) invocation.getArguments()[0]; - failedCallbackException = (Exception) invocation.getArguments()[1]; - exceptionLatch.countDown(); - return null; - } - + doAnswer(invocation -> { + failedCallbackMessage = (String) invocation.getArguments()[0]; + failedCallbackException = (Exception) invocation.getArguments()[1]; + exceptionLatch.countDown(); + return null; }).when(logger).error(anyString(), any(Throwable.class)); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/DelayHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/DelayHandlerTests.java index f6f6a4b436..6dc86c6d9e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/DelayHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/DelayHandlerTests.java @@ -34,8 +34,6 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.BeanFactory; @@ -240,19 +238,14 @@ public class DelayHandlerTests { taskScheduler.destroy(); final CountDownLatch latch = new CountDownLatch(1); - new Thread(new Runnable() { - - @Override - public void run() { - try { - taskScheduler.getScheduledExecutor().awaitTermination(10000, TimeUnit.MILLISECONDS); - latch.countDown(); - } - catch (InterruptedException e) { - // won't countDown - } + new Thread(() -> { + try { + taskScheduler.getScheduledExecutor().awaitTermination(10000, TimeUnit.MILLISECONDS); + latch.countDown(); + } + catch (InterruptedException e) { + // won't countDown } - }).start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); @@ -267,16 +260,13 @@ public class DelayHandlerTests { taskScheduler.destroy(); final CountDownLatch latch = new CountDownLatch(1); - new Thread(new Runnable() { - @Override - public void run() { - try { - taskScheduler.getScheduledExecutor().awaitTermination(10000, TimeUnit.MILLISECONDS); - latch.countDown(); - } - catch (InterruptedException e) { - // won't countDown - } + new Thread(() -> { + try { + taskScheduler.getScheduledExecutor().awaitTermination(10000, TimeUnit.MILLISECONDS); + latch.countDown(); + } + catch (InterruptedException e) { + // won't countDown } }).start(); latch.await(50, TimeUnit.MILLISECONDS); @@ -287,11 +277,8 @@ public class DelayHandlerTests { public void handlerThrowsExceptionWithNoDelay() throws Exception { this.startDelayerHandler(); output.unsubscribe(resultHandler); - output.subscribe(new MessageHandler() { - @Override - public void handleMessage(Message message) { - throw new UnsupportedOperationException("intentional test failure"); - } + output.subscribe(message -> { + throw new UnsupportedOperationException("intentional test failure"); }); Message message = MessageBuilder.withPayload("test").build(); input.send(message); @@ -307,13 +294,8 @@ public class DelayHandlerTests { this.startDelayerHandler(); output.unsubscribe(resultHandler); errorChannel.subscribe(resultHandler); - output.subscribe(new MessageHandler() { - - @Override - public void handleMessage(Message message) { - throw new UnsupportedOperationException("intentional test failure"); - } - + output.subscribe(message -> { + throw new UnsupportedOperationException("intentional test failure"); }); Message message = MessageBuilder.withPayload("test") .setHeader("delay", "10") @@ -343,13 +325,8 @@ public class DelayHandlerTests { this.startDelayerHandler(); output.unsubscribe(resultHandler); customErrorChannel.subscribe(resultHandler); - output.subscribe(new MessageHandler() { - - @Override - public void handleMessage(Message message) { - throw new UnsupportedOperationException("intentional test failure"); - } - + output.subscribe(message -> { + throw new UnsupportedOperationException("intentional test failure"); }); Message message = MessageBuilder.withPayload("test") .setHeader("delay", "10") @@ -377,13 +354,8 @@ public class DelayHandlerTests { this.startDelayerHandler(); output.unsubscribe(resultHandler); defaultErrorChannel.subscribe(resultHandler); - output.subscribe(new MessageHandler() { - - @Override - public void handleMessage(Message message) { - throw new UnsupportedOperationException("intentional test failure"); - } - + output.subscribe(message -> { + throw new UnsupportedOperationException("intentional test failure"); }); Message message = MessageBuilder.withPayload("test") .setHeader("delay", "10").build(); @@ -441,12 +413,7 @@ public class DelayHandlerTests { // Can happen in the parent-child context e.g. Spring-MVC applications public void testDoubleOnApplicationEvent() throws Exception { this.delayHandler = Mockito.spy(this.delayHandler); - Mockito.doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return null; - } - }).when(this.delayHandler).reschedulePersistedMessages(); + Mockito.doAnswer(invocation -> null).when(this.delayHandler).reschedulePersistedMessages(); ContextRefreshedEvent contextRefreshedEvent = new ContextRefreshedEvent(TestUtils.createTestApplicationContext()); this.delayHandler.onApplicationEvent(contextRefreshedEvent); @@ -531,6 +498,10 @@ public class DelayHandlerTests { private volatile Thread lastThread; + ResultHandler() { + super(); + } + @Override public void handleMessage(Message message) { this.lastMessage = message; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/ExpressionEvaluatingMessageProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/ExpressionEvaluatingMessageProcessorTests.java index 8813f2eeaa..cc5998d719 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/ExpressionEvaluatingMessageProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/ExpressionEvaluatingMessageProcessorTests.java @@ -45,10 +45,10 @@ import org.springframework.expression.spel.SpelParserConfiguration; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.integration.config.IntegrationEvaluationContextFactoryBean; import org.springframework.integration.context.IntegrationContextUtils; -import org.springframework.messaging.support.GenericMessage; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; +import org.springframework.messaging.support.GenericMessage; /** * @author Dave Syer @@ -218,6 +218,7 @@ public class ExpressionEvaluatingMessageProcessorTests { cause = item.getCause(); return cause instanceof EvaluationException; } + @Override public void describeTo(Description description) { description.appendText("cause to be EvaluationException but was ").appendValue(cause); } @@ -239,6 +240,7 @@ public class ExpressionEvaluatingMessageProcessorTests { cause = item.getCause(); return cause instanceof UnsupportedOperationException; } + @Override public void describeTo(Description description) { description.appendText("cause to be UnsupportedOperationException but was ").appendValue(cause); } @@ -260,6 +262,7 @@ public class ExpressionEvaluatingMessageProcessorTests { cause = item.getCause(); return cause instanceof CheckedException; } + @Override public void describeTo(Description description) { description.appendText("cause to be CheckedException but was ").appendValue(cause); } @@ -274,6 +277,10 @@ public class ExpressionEvaluatingMessageProcessorTests { @SuppressWarnings("unused") private static class TestPayload { + TestPayload() { + super(); + } + public String throwRuntimeException() { throw new UnsupportedOperationException("Expected test exception"); } @@ -285,9 +292,11 @@ public class ExpressionEvaluatingMessageProcessorTests { @SuppressWarnings("serial") private static final class CheckedException extends Exception { + CheckedException(String string) { super(string); } + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java index f9fec67b85..bab5ec2ce6 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java @@ -592,6 +592,11 @@ public class MethodInvokingMessageProcessorTests { @SuppressWarnings("unused") private static class TestErrorService { + + TestErrorService() { + super(); + } + public String error(String input) { throw new UnsupportedOperationException("Expected test exception"); } @@ -599,10 +604,16 @@ public class MethodInvokingMessageProcessorTests { public String checked(String input) throws Exception { throw new CheckedException("Expected test exception"); } + } @SuppressWarnings("unused") private static class TestDifferentErrorService { + + TestDifferentErrorService() { + super(); + } + public String checked(String input) throws Exception { throw new CheckedException("Expected test exception"); } @@ -610,14 +621,20 @@ public class MethodInvokingMessageProcessorTests { @SuppressWarnings("serial") public static final class CheckedException extends Exception { + public CheckedException(String string) { super(string); } + } @SuppressWarnings("unused") private static class TestBean { + TestBean() { + super(); + } + public String acceptPayloadAndReturnObject(String s) { return s + "-1"; } @@ -659,6 +676,10 @@ public class MethodInvokingMessageProcessorTests { @SuppressWarnings("unused") private static class AnnotatedTestService { + AnnotatedTestService() { + super(); + } + public String messageOnly(Message message) { return (String) message.getPayload(); } @@ -707,6 +728,10 @@ public class MethodInvokingMessageProcessorTests { private volatile Object lastArg = null; + AmbiguousMethodBean() { + super(); + } + public void foo(boolean b) { this.lastArg = b; } @@ -732,6 +757,10 @@ public class MethodInvokingMessageProcessorTests { private volatile Object lastArg = null; + OverloadedMethodBean() { + super(); + } + public void foo(boolean b) { this.lastArg = b; } @@ -748,6 +777,10 @@ public class MethodInvokingMessageProcessorTests { private volatile Object lastArg = null; + IneligibleMethodBean() { + super(); + } + @SuppressWarnings("unused") public void foo(String s) { this.lastArg = s; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/AdvisedMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/AdvisedMessageHandlerTests.java index c5e3eb2652..3ba7233459 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/AdvisedMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/advice/AdvisedMessageHandlerTests.java @@ -50,8 +50,6 @@ import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.AopUtils; @@ -59,7 +57,6 @@ import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.integration.channel.QueueChannel; -import org.springframework.integration.core.MessageSelector; import org.springframework.integration.endpoint.PollingConsumer; import org.springframework.integration.filter.MessageFilter; import org.springframework.integration.handler.AbstractReplyProducingMessageHandler; @@ -69,15 +66,12 @@ import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.util.ErrorHandlingTaskExecutor; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; -import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessageHandlingException; import org.springframework.messaging.MessagingException; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.support.ErrorMessage; import org.springframework.messaging.support.GenericMessage; -import org.springframework.retry.RecoveryCallback; import org.springframework.retry.RetryContext; -import org.springframework.retry.RetryState; import org.springframework.retry.policy.SimpleRetryPolicy; import org.springframework.retry.support.DefaultRetryState; import org.springframework.retry.support.RetryTemplate; @@ -85,7 +79,6 @@ import org.springframework.scheduling.TaskScheduler; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.util.ErrorHandler; /** * @author Gary Russell @@ -511,13 +504,7 @@ public class AdvisedMessageHandlerTests { handler.setOutputChannel(replies); RequestHandlerRetryAdvice advice = new RequestHandlerRetryAdvice(); - advice.setRetryStateGenerator(new RetryStateGenerator() { - - @Override - public RetryState determineRetryState(Message message) { - return new DefaultRetryState(message.getHeaders().getId()); - } - }); + advice.setRetryStateGenerator(message -> new DefaultRetryState(message.getHeaders().getId())); List adviceChain = new ArrayList(); adviceChain.add(advice); @@ -558,13 +545,7 @@ public class AdvisedMessageHandlerTests { handler.setOutputChannel(replies); RequestHandlerRetryAdvice advice = new RequestHandlerRetryAdvice(); - advice.setRetryStateGenerator(new RetryStateGenerator() { - - @Override - public RetryState determineRetryState(Message message) { - return new DefaultRetryState(message.getHeaders().getId()); - } - }); + advice.setRetryStateGenerator(message -> new DefaultRetryState(message.getHeaders().getId())); defaultStatefulRetryRecoverAfterThirdTryGuts(counter, handler, replies, advice); @@ -595,14 +576,7 @@ public class AdvisedMessageHandlerTests { private void defaultStatefulRetryRecoverAfterThirdTryGuts(final AtomicInteger counter, AbstractReplyProducingMessageHandler handler, QueueChannel replies, RequestHandlerRetryAdvice advice) { - advice.setRecoveryCallback(new RecoveryCallback() { - - @Override - public Object recover(RetryContext context) throws Exception { - return "baz"; - } - - }); + advice.setRecoveryCallback(context -> "baz"); List adviceChain = new ArrayList(); adviceChain.add(advice); @@ -707,13 +681,9 @@ public class AdvisedMessageHandlerTests { List adviceChain = new ArrayList(); adviceChain.add(new RequestHandlerRetryAdvice()); - adviceChain.add(new MethodInterceptor() { - - @Override - public Object invoke(MethodInvocation invocation) throws Throwable { - counter.getAndDecrement(); - throw new RuntimeException("intentional"); - } + adviceChain.add((MethodInterceptor) invocation -> { + counter.getAndDecrement(); + throw new RuntimeException("intentional"); }); handler.setBeanFactory(mock(BeanFactory.class)); @@ -765,12 +735,8 @@ public class AdvisedMessageHandlerTests { }); adviceChain.add(expressionAdvice); adviceChain.add(new RequestHandlerRetryAdvice()); - adviceChain.add(new MethodInterceptor() { - - @Override - public Object invoke(MethodInvocation invocation) throws Throwable { - throw new RuntimeException("intentional: " + counter.incrementAndGet()); - } + adviceChain.add((MethodInterceptor) invocation -> { + throw new RuntimeException("intentional: " + counter.incrementAndGet()); }); handler.setAdviceChain(adviceChain); @@ -808,12 +774,8 @@ public class AdvisedMessageHandlerTests { adviceChain.add(new RequestHandlerRetryAdvice()); adviceChain.add(expressionAdvice); - adviceChain.add(new MethodInterceptor() { - - @Override - public Object invoke(MethodInvocation invocation) throws Throwable { - throw new RuntimeException("intentional: " + counter.incrementAndGet()); - } + adviceChain.add((MethodInterceptor) invocation -> { + throw new RuntimeException("intentional: " + counter.incrementAndGet()); }); handler.setAdviceChain(adviceChain); @@ -866,12 +828,8 @@ public class AdvisedMessageHandlerTests { when(methodInvocation.getMethod()).thenReturn(method); when(methodInvocation.getArguments()).thenReturn(new Object[] { new GenericMessage("foo") }); try { - doAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - throw theThrowable; - } + doAnswer(invocation -> { + throw theThrowable; }).when(methodInvocation).proceed(); advice.invoke(methodInvocation); fail("Expected throwable"); @@ -924,21 +882,9 @@ public class AdvisedMessageHandlerTests { } }; PollableChannel inputChannel = new QueueChannel(); - PollingConsumer consumer = new PollingConsumer(inputChannel, new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - } - }); + PollingConsumer consumer = new PollingConsumer(inputChannel, message -> { }); consumer.setAdviceChain(Collections.singletonList(advice)); - consumer.setTaskExecutor(new ErrorHandlingTaskExecutor( - Executors.newSingleThreadExecutor(), - new ErrorHandler() { - - @Override - public void handleError(Throwable t) { - } - })); + consumer.setTaskExecutor(new ErrorHandlingTaskExecutor(Executors.newSingleThreadExecutor(), t -> { })); consumer.setBeanFactory(mock(BeanFactory.class)); consumer.afterPropertiesSet(); consumer.setTaskScheduler(mock(TaskScheduler.class)); @@ -950,13 +896,9 @@ public class AdvisedMessageHandlerTests { logger = spy(logger); when(logger.isWarnEnabled()).thenReturn(Boolean.TRUE); final AtomicReference logMessage = new AtomicReference(); - doAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - logMessage.set((String) invocation.getArguments()[0]); - return null; - } + doAnswer(invocation -> { + logMessage.set((String) invocation.getArguments()[0]); + return null; }).when(logger).warn(Mockito.anyString()); DirectFieldAccessor accessor = new DirectFieldAccessor(advice); accessor.setPropertyValue("logger", logger); @@ -964,20 +906,14 @@ public class AdvisedMessageHandlerTests { pollingTask.call(); assertFalse(called.get()); assertNotNull(logMessage.get()); - assertTrue(logMessage.get().endsWith("can only be used for MessageHandlers; " + + assertThat(logMessage.get(), Matchers.containsString("can only be used for MessageHandlers; " + "an attempt to advise method 'call' in " + - "'org.springframework.integration.endpoint.AbstractPollingEndpoint$1' is ignored")); + "'org.springframework.integration.endpoint.AbstractPollingEndpoint")); consumer.stop(); } public void filterDiscardNoAdvice() { - MessageFilter filter = new MessageFilter(new MessageSelector() { - - @Override - public boolean accept(Message message) { - return false; - } - }); + MessageFilter filter = new MessageFilter(message -> false); QueueChannel discardChannel = new QueueChannel(); filter.setDiscardChannel(discardChannel); filter.handleMessage(new GenericMessage("foo")); @@ -986,13 +922,7 @@ public class AdvisedMessageHandlerTests { @Test public void filterDiscardWithinAdvice() { - MessageFilter filter = new MessageFilter(new MessageSelector() { - - @Override - public boolean accept(Message message) { - return false; - } - }); + MessageFilter filter = new MessageFilter(message -> false); final QueueChannel discardChannel = new QueueChannel(); filter.setDiscardChannel(discardChannel); List adviceChain = new ArrayList(); @@ -1016,13 +946,7 @@ public class AdvisedMessageHandlerTests { @Test public void filterDiscardOutsideAdvice() { - MessageFilter filter = new MessageFilter(new MessageSelector() { - - @Override - public boolean accept(Message message) { - return false; - } - }); + MessageFilter filter = new MessageFilter(message -> false); final QueueChannel discardChannel = new QueueChannel(); filter.setDiscardChannel(discardChannel); List adviceChain = new ArrayList(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/history/AnotatedTests.java b/spring-integration-core/src/test/java/org/springframework/integration/history/AnnotatedTests.java similarity index 98% rename from spring-integration-core/src/test/java/org/springframework/integration/history/AnotatedTests.java rename to spring-integration-core/src/test/java/org/springframework/integration/history/AnnotatedTests.java index 72a24716d3..8de80ad379 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/history/AnotatedTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/history/AnnotatedTests.java @@ -43,7 +43,7 @@ import org.springframework.messaging.support.GenericMessage; * @author Gary Russell * */ -public class AnotatedTests { +public class AnnotatedTests { @Test public void testHistoryWithAnnotatedComponents() throws Exception { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/history/MessageHistoryIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/history/MessageHistoryIntegrationTests.java index aaec6d2bdd..b2e3cf3d5f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/history/MessageHistoryIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/history/MessageHistoryIntegrationTests.java @@ -36,14 +36,11 @@ import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.BeanCreationException; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.integration.MessageRejectedException; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.config.ConsumerEndpointFactoryBean; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; -import org.springframework.messaging.MessageDeliveryException; import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.MessageHandlingException; import org.springframework.util.StopWatch; /** @@ -236,26 +233,16 @@ public class MessageHistoryIntegrationTests { SampleGateway gatewayHistory = acWithHistory.getBean("sampleGateway", SampleGateway.class); DirectChannel endOfThePipeChannelHistory = acWithHistory.getBean("endOfThePipeChannel", DirectChannel.class); - endOfThePipeChannelHistory.subscribe(new MessageHandler() { - @Override - public void handleMessage(Message message) - throws MessageRejectedException, MessageHandlingException, - MessageDeliveryException { - MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); - replyChannel.send(message); - } + endOfThePipeChannelHistory.subscribe(message -> { + MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); + replyChannel.send(message); }); SampleGateway gateway = acWithoutHistory.getBean("sampleGateway", SampleGateway.class); DirectChannel endOfThePipeChannel = acWithoutHistory.getBean("endOfThePipeChannel", DirectChannel.class); - endOfThePipeChannel.subscribe(new MessageHandler() { - @Override - public void handleMessage(Message message) - throws MessageRejectedException, MessageHandlingException, - MessageDeliveryException { - MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); - replyChannel.send(message); - } + endOfThePipeChannel.subscribe(message -> { + MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); + replyChannel.send(message); }); StopWatch stopWatch = new StopWatch(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/AbstractJsonSymmetricalMessageMappingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/AbstractJsonSymmetricalMessageMappingTests.java index 29e80e2799..4b9806f8d1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/AbstractJsonSymmetricalMessageMappingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/AbstractJsonSymmetricalMessageMappingTests.java @@ -65,14 +65,16 @@ public abstract class AbstractJsonSymmetricalMessageMappingTests { private final int id; - private TestNamedComponent(int id) { + TestNamedComponent(int id) { this.id = id; } + @Override public String getComponentName() { return "testName-" + this.id; } + @Override public String getComponentType() { return "testType-" + this.id; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonOutboundMessageMapperTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonOutboundMessageMapperTests.java index 8cd3981181..66d82804de 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonOutboundMessageMapperTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonOutboundMessageMapperTests.java @@ -127,7 +127,7 @@ public class JsonOutboundMessageMapperTests { private final int id; - private TestNamedComponent(int id) { + TestNamedComponent(int id) { this.id = id; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/mapping/HeaderMapperTests.java b/spring-integration-core/src/test/java/org/springframework/integration/mapping/HeaderMapperTests.java index 9c7a676aff..9ad7ea7aef 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/mapping/HeaderMapperTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/mapping/HeaderMapperTests.java @@ -454,7 +454,7 @@ public class HeaderMapperTests { private static class GenericTestHeaderMapper extends AbstractHeaderMapper { - private GenericTestHeaderMapper() { + GenericTestHeaderMapper() { super(GenericTestHeaders.PREFIX, Arrays.asList(GenericTestHeaders.APP_ID, GenericTestHeaders.TRANSACTION_SIZE, GenericTestHeaders.REDELIVERED, GenericTestHeaders.REQUEST_ONLY), @@ -535,7 +535,8 @@ public class HeaderMapperTests { private final Map userDefinedHeaders = new HashMap(); - private GenericTestProperties() { + GenericTestProperties() { + super(); } public String getAppId() { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderAtConfigTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderAtConfigTests.java index b7ae20e286..22ea872f7d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderAtConfigTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderAtConfigTests.java @@ -140,9 +140,16 @@ public class MessageBuilderAtConfigTests { } private static class RequestHeaderCopyingEchoHandler extends AbstractReplyProducingMessageHandler { + + RequestHeaderCopyingEchoHandler() { + super(); + } + @Override protected Object handleRequestMessage(Message requestMessage) { return requestMessage; } + } + } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java index 9a9419afe5..c837c9c4ca 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java @@ -110,6 +110,7 @@ public class MethodInvokingMessageHandlerTests { Thread.currentThread().interrupt(); } } + } @@ -119,6 +120,10 @@ public class MethodInvokingMessageHandlerTests { private String result; + TestSink() { + super(); + } + public void validMethod(String s) { } @@ -136,6 +141,7 @@ public class MethodInvokingMessageHandlerTests { public String get() { return this.result; } + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageSourceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageSourceTests.java index 229a1ceb11..769012325c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageSourceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageSourceTests.java @@ -111,6 +111,10 @@ public class MethodInvokingMessageSourceTests { @SuppressWarnings("unused") private static class TestBean { + TestBean() { + super(); + } + public String validMethod() { return "valid"; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java index 7b457cb3ed..dc6e80ae57 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java @@ -30,13 +30,13 @@ import java.util.Properties; import org.junit.Before; import org.junit.Test; +import org.springframework.integration.handler.ServiceActivatingHandler; +import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; +import org.springframework.messaging.MessageHandler; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.Headers; import org.springframework.messaging.handler.annotation.Payload; -import org.springframework.messaging.MessageHandler; -import org.springframework.integration.handler.ServiceActivatingHandler; -import org.springframework.integration.support.MessageBuilder; /** * @author Mark Fisher @@ -696,6 +696,10 @@ public class PayloadAndHeaderMappingTests { @SuppressWarnings("unused") private static class SingleAmbiguousMethodTestBean { + SingleAmbiguousMethodTestBean() { + super(); + } + public String concat(String s1, String s2) { return "s1" + "s2"; } @@ -709,6 +713,10 @@ public class PayloadAndHeaderMappingTests { private volatile Object lastPayload; + TestBean() { + super(); + } + public void headerPropertiesAndObjectPayload(Properties headers, Object payload) { this.lastHeaders = headers; this.lastPayload = payload; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/HeaderValueRouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/HeaderValueRouterTests.java index b645b410fe..9af27bd1f7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/HeaderValueRouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/HeaderValueRouterTests.java @@ -128,12 +128,9 @@ public class HeaderValueRouterTests { routerBeanDefinition.getPropertyValues().addPropertyValue("resolutionRequired", "true"); routerBeanDefinition.getPropertyValues().addPropertyValue("channelMappings", channelMappings); routerBeanDefinition.getPropertyValues().addPropertyValue("beanFactory", context); - routerBeanDefinition.getPropertyValues().addPropertyValue("channelResolver", new DestinationResolver() { - @Override - public MessageChannel resolveDestination(String channelName) { - return context.getBean("anotherChannel", MessageChannel.class); - } - }); + routerBeanDefinition.getPropertyValues().addPropertyValue("channelResolver", + (DestinationResolver) channelName -> context.getBean("anotherChannel", + MessageChannel.class)); context.registerBeanDefinition("router", routerBeanDefinition); context.registerBeanDefinition("testChannel", new RootBeanDefinition(QueueChannel.class)); context.registerBeanDefinition("anotherChannel", new RootBeanDefinition(QueueChannel.class)); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/MethodInvokingRouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/MethodInvokingRouterTests.java index e0ebfaa509..93a16d0c59 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/MethodInvokingRouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/MethodInvokingRouterTests.java @@ -634,7 +634,7 @@ public class MethodInvokingRouterTests { public static class SingleChannelInstanceRoutingTestBean { - private DestinationResolver channelResolver; + private final DestinationResolver channelResolver; public SingleChannelInstanceRoutingTestBean(DestinationResolver channelResolver) { this.channelResolver = channelResolver; @@ -659,7 +659,7 @@ public class MethodInvokingRouterTests { public static class MultiChannelInstanceRoutingTestBean { - private DestinationResolver channelResolver; + private final DestinationResolver channelResolver; public MultiChannelInstanceRoutingTestBean(DestinationResolver channelResolver) { this.channelResolver = channelResolver; @@ -697,6 +697,11 @@ public class MethodInvokingRouterTests { private static class ClassAsKeyTestBean { + ClassAsKeyTestBean() { + super(); + } + + @SuppressWarnings("unused") public Class routePayload(Object payload) { return payload.getClass(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/RecipientListRouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/RecipientListRouterTests.java index faa9eb0086..b816f06435 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/RecipientListRouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/RecipientListRouterTests.java @@ -445,6 +445,10 @@ public class RecipientListRouterTests { private static class AlwaysTrueSelector implements MessageSelector { + AlwaysTrueSelector() { + super(); + } + @Override public boolean accept(Message message) { return true; @@ -454,6 +458,10 @@ public class RecipientListRouterTests { private static class AlwaysFalseSelector implements MessageSelector { + AlwaysFalseSelector() { + super(); + } + @Override public boolean accept(Message message) { return false; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/RouterConcurrencyTest.java b/spring-integration-core/src/test/java/org/springframework/integration/router/RouterConcurrencyTest.java index 9a536db71c..9d01e44b5d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/RouterConcurrencyTest.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/RouterConcurrencyTest.java @@ -32,8 +32,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.factory.BeanFactory; import org.springframework.core.convert.ConversionService; @@ -77,28 +75,20 @@ public class RouterConcurrencyTest { final AtomicInteger beanCounter = new AtomicInteger(); BeanFactory beanFactory = mock(BeanFactory.class); - doAnswer(new Answer() { - - @Override - public Boolean answer(InvocationOnMock invocation) throws Throwable { - if (beanCounter.getAndIncrement() < 2) { - semaphore.tryAcquire(4, TimeUnit.SECONDS); - } - return false; + doAnswer(invocation -> { + if (beanCounter.getAndIncrement() < 2) { + semaphore.tryAcquire(4, TimeUnit.SECONDS); } + return false; }).when(beanFactory).containsBean(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME); router.setBeanFactory(beanFactory); ExecutorService exec = Executors.newFixedThreadPool(2); final List returns = Collections.synchronizedList( new ArrayList()); - Runnable runnable = new Runnable() { - - @Override - public void run() { - ConversionService requiredConversionService = router.getRequiredConversionService(); - returns.add(requiredConversionService); - } + Runnable runnable = () -> { + ConversionService requiredConversionService = router.getRequiredConversionService(); + returns.add(requiredConversionService); }; exec.execute(runnable); exec.execute(runnable); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/selector/MessageSelectorChainTests.java b/spring-integration-core/src/test/java/org/springframework/integration/selector/MessageSelectorChainTests.java index e0a9e6fb1e..836771154d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/selector/MessageSelectorChainTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/selector/MessageSelectorChainTests.java @@ -21,8 +21,8 @@ import static org.junit.Assert.assertTrue; import org.junit.Test; -import org.springframework.messaging.Message; import org.springframework.integration.core.MessageSelector; +import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; /** @@ -164,10 +164,11 @@ public class MessageSelectorChainTests { private final boolean accept; - private TestSelector(boolean accept) { + TestSelector(boolean accept) { this.accept = accept; } + @Override public boolean accept(Message message) { return this.accept; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/splitter/MethodInvokingSplitterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/splitter/MethodInvokingSplitterTests.java index b8568aefcd..1f75e60f42 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/splitter/MethodInvokingSplitterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/splitter/MethodInvokingSplitterTests.java @@ -42,7 +42,7 @@ import org.springframework.messaging.support.GenericMessage; */ public class MethodInvokingSplitterTests { - private SplitterTestBean testBean = new SplitterTestBean(); + private final SplitterTestBean testBean = new SplitterTestBean(); @Test public void splitStringToStringArray() throws Exception { @@ -609,7 +609,7 @@ public class MethodInvokingSplitterTests { @SuppressWarnings("serial") private static class TestStringMessage extends GenericMessage { - private TestStringMessage(String payload) { + TestStringMessage(String payload) { super(payload); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/splitter/StreamingSplitterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/splitter/StreamingSplitterTests.java index 99e40ac87f..17b8498cac 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/splitter/StreamingSplitterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/splitter/StreamingSplitterTests.java @@ -22,7 +22,6 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.Collections; -import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.UUID; @@ -32,18 +31,13 @@ import org.junit.Before; import org.junit.Test; import org.springframework.integration.IntegrationMessageHeaderAccessor; -import org.springframework.integration.MessageRejectedException; import org.springframework.integration.annotation.Splitter; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.endpoint.EventDrivenConsumer; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; -import org.springframework.messaging.MessageDeliveryException; -import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.MessageHandlingException; import org.springframework.messaging.MessageHeaders; -import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.GenericMessage; /** @@ -73,15 +67,9 @@ public class StreamingSplitterTests { splitter.handleMessage(message); List> receivedMessages = replyChannel.clear(); - Collections.sort(receivedMessages, new Comparator>() { - - @Override - public int compare(Message o1, Message o2) { - return o1.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class) - .compareTo(o2.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class)); - } - - }); + Collections.sort(receivedMessages, (o1, o2) -> + o1.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class) + .compareTo(o2.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class))); assertThat(receivedMessages.get(4) .getHeaders() .get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class), @@ -148,15 +136,9 @@ public class StreamingSplitterTests { DirectChannel replyChannel = new DirectChannel(); splitter.setOutputChannel(replyChannel); - new EventDrivenConsumer(replyChannel, new MessageHandler() { - - @Override - public void handleMessage(Message message) throws MessagingException { - assertThat("Failure with msg: " + message, - message.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class), - is(Integer.valueOf((String) message.getPayload()))); - } - }).start(); + new EventDrivenConsumer(replyChannel, message -> assertThat("Failure with msg: " + message, + message.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class), + is(Integer.valueOf((String) message.getPayload())))).start(); splitter.handleMessage(message); } @@ -170,18 +152,10 @@ public class StreamingSplitterTests { splitter.setOutputChannel(replyChannel); final AtomicInteger receivedMessageCounter = new AtomicInteger(0); - new EventDrivenConsumer(replyChannel, new MessageHandler() { + new EventDrivenConsumer(replyChannel, message -> { + assertThat("Failure with msg: " + message, message.getPayload(), is(notNullValue())); + receivedMessageCounter.incrementAndGet(); - @Override - public void handleMessage(Message message) - throws MessageRejectedException, MessageHandlingException, - MessageDeliveryException { - assertThat("Failure with msg: " + message, - message.getPayload(), - is(notNullValue())); - receivedMessageCounter.incrementAndGet(); - - } }).start(); splitter.handleMessage(message); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/store/MessageGroupQueueTests.java b/spring-integration-core/src/test/java/org/springframework/integration/store/MessageGroupQueueTests.java index 11f2b1a322..b6eb9507b9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/store/MessageGroupQueueTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/store/MessageGroupQueueTests.java @@ -23,7 +23,6 @@ import static org.junit.Assert.assertTrue; import java.util.HashSet; import java.util.Set; -import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; @@ -112,37 +111,33 @@ public class MessageGroupQueueTests { final int big = i; - completionService.submit(new Callable() { - public Boolean call() throws Exception { - boolean result = true; - for (int j = 0; j < maxPerTask; j++) { - result &= queue.add(new GenericMessage("count=" + big + ":" + j)); - if (!result) { - logger.warn("Failed to add"); - } + completionService.submit(() -> { + boolean result = true; + for (int j = 0; j < maxPerTask; j++) { + result &= queue.add(new GenericMessage("count=" + big + ":" + j)); + if (!result) { + logger.warn("Failed to add"); } - return result; } + return result; }); - completionService.submit(new Callable() { - public Boolean call() throws Exception { - boolean result = true; - for (int j = 0; j < maxPerTask; j++) { - @SuppressWarnings("unchecked") - Message item = (Message) queue.poll(10, TimeUnit.SECONDS); - result &= item != null; - if (!result) { - logger.warn("Failed to poll"); - } - else if (set != null) { - synchronized (set) { - set.add(item.getPayload()); - } + completionService.submit(() -> { + boolean result = true; + for (int j = 0; j < maxPerTask; j++) { + @SuppressWarnings("unchecked") + Message item = (Message) queue.poll(10, TimeUnit.SECONDS); + result &= item != null; + if (!result) { + logger.warn("Failed to poll"); + } + else if (set != null) { + synchronized (set) { + set.add(item.getPayload()); } } - return result; } + return result; }); messageGroupStore.expireMessageGroups(-10000); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/store/MessageStoreTests.java b/spring-integration-core/src/test/java/org/springframework/integration/store/MessageStoreTests.java index 961634c137..3bef21791c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/store/MessageStoreTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/store/MessageStoreTests.java @@ -41,12 +41,7 @@ public class MessageStoreTests { @Test public void shouldRegisterCallbacks() throws Exception { TestMessageStore store = new TestMessageStore(); - store.setExpiryCallbacks(Collections.singletonList(new MessageGroupCallback() { - - @Override - public void execute(MessageGroupStore messageGroupStore, MessageGroup group) { - } - })); + store.setExpiryCallbacks(Collections.singletonList((messageGroupStore, group) -> { })); assertEquals(1, ((Collection) ReflectionTestUtils.getField(store, "expiryCallbacks")).size()); } @@ -55,12 +50,9 @@ public class MessageStoreTests { TestMessageStore store = new TestMessageStore(); final List list = new ArrayList(); - store.registerMessageGroupExpiryCallback(new MessageGroupCallback() { - @Override - public void execute(MessageGroupStore messageGroupStore, MessageGroup group) { - list.add(group.getOne().getPayload().toString()); - messageGroupStore.removeMessageGroup(group.getGroupId()); - } + store.registerMessageGroupExpiryCallback((messageGroupStore, group) -> { + list.add(group.getOne().getPayload().toString()); + messageGroupStore.removeMessageGroup(group.getGroupId()); }); store.expireMessageGroups(-10000); @@ -83,13 +75,16 @@ public class MessageStoreTests { private static class TestMessageStore extends SimpleMessageStore { - @SuppressWarnings("unchecked") MessageGroup testMessages = new SimpleMessageGroup(Collections.singletonList(new GenericMessage("foo")), "bar"); private boolean removed = false; + TestMessageStore() { + super(); + } + @Override public Iterator iterator() { return Collections.singletonList(testMessages).iterator(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/store/SimpleMessageStoreTests.java b/spring-integration-core/src/test/java/org/springframework/integration/store/SimpleMessageStoreTests.java index 2bf4c3832a..9fa3b2048f 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/store/SimpleMessageStoreTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/store/SimpleMessageStoreTests.java @@ -107,14 +107,9 @@ public class SimpleMessageStoreTests { final CountDownLatch message2Latch = new CountDownLatch(1); - Executors.newSingleThreadExecutor().execute(new Runnable() { - - @Override - public void run() { - store2.addMessage(testMessage2); - message2Latch.countDown(); - } - + Executors.newSingleThreadExecutor().execute(() -> { + store2.addMessage(testMessage2); + message2Latch.countDown(); }); // Simulate a blocked consumer Thread.sleep(10); @@ -155,14 +150,9 @@ public class SimpleMessageStoreTests { final CountDownLatch message2Latch = new CountDownLatch(1); - Executors.newSingleThreadExecutor().execute(new Runnable() { - - @Override - public void run() { - store2.addMessageToGroup("foo", testMessage2); - message2Latch.countDown(); - } - + Executors.newSingleThreadExecutor().execute(() -> { + store2.addMessageToGroup("foo", testMessage2); + message2Latch.countDown(); }); // Simulate a blocked consumer Thread.sleep(10); @@ -264,13 +254,7 @@ public class SimpleMessageStoreTests { @Test public void shouldRegisterCallbacks() throws Exception { SimpleMessageStore store = new SimpleMessageStore(); - store.setExpiryCallbacks(Arrays.asList(new MessageGroupStore.MessageGroupCallback() { - - @Override - public void execute(MessageGroupStore messageGroupStore, MessageGroup group) { - } - - })); + store.setExpiryCallbacks(Arrays.asList((messageGroupStore, group) -> { })); assertEquals(1, ((Collection) ReflectionTestUtils.getField(store, "expiryCallbacks")).size()); } @@ -279,14 +263,9 @@ public class SimpleMessageStoreTests { SimpleMessageStore store = new SimpleMessageStore(); final List list = new ArrayList(); - store.registerMessageGroupExpiryCallback(new MessageGroupCallback() { - - @Override - public void execute(MessageGroupStore messageGroupStore, MessageGroup group) { - list.add(group.getOne().getPayload().toString()); - messageGroupStore.removeMessageGroup(group.getGroupId()); - } - + store.registerMessageGroupExpiryCallback((messageGroupStore, group) -> { + list.add(group.getOne().getPayload().toString()); + messageGroupStore.removeMessageGroup(group.getGroupId()); }); Message testMessage1 = MessageBuilder.withPayload("foo").build(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MethodInvokingTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MethodInvokingTransformerTests.java index aa56a4dfa5..a54eab23d0 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MethodInvokingTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MethodInvokingTransformerTests.java @@ -253,6 +253,10 @@ public class MethodInvokingTransformerTests { @SuppressWarnings("unused") private static class TestBean { + TestBean() { + super(); + } + @Transformer public String exclaim(String s) { return s.toUpperCase() + "!"; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/ObjectToStringTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/ObjectToStringTransformerTests.java index 9720c2b27e..cf04f44b39 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/ObjectToStringTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/ObjectToStringTransformerTests.java @@ -21,6 +21,7 @@ import static org.junit.Assert.assertEquals; import java.nio.charset.Charset; import org.junit.Test; + import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; @@ -69,6 +70,10 @@ public class ObjectToStringTransformerTests { private static class TestBean { + TestBean() { + super(); + } + @Override public String toString() { return "test"; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadDeserializingTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadDeserializingTransformerTests.java index dd865163ed..5f646db104 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadDeserializingTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadDeserializingTransformerTests.java @@ -25,10 +25,9 @@ import java.io.Serializable; import org.junit.Test; -import org.springframework.core.convert.converter.Converter; +import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; -import org.springframework.integration.support.MessageBuilder; /** * @author Mark Fisher @@ -74,11 +73,7 @@ public class PayloadDeserializingTransformerTests { @Test public void customDeserializer() { PayloadDeserializingTransformer transformer = new PayloadDeserializingTransformer(); - transformer.setConverter(new Converter() { - public Object convert(byte[] source) { - return "Converted"; - } - }); + transformer.setConverter(source -> "Converted"); Message message = transformer.transform(MessageBuilder.withPayload("Test".getBytes()).build()); assertEquals("Converted", message.getPayload()); } @@ -86,7 +81,7 @@ public class PayloadDeserializingTransformerTests { @SuppressWarnings("serial") private static class TestBean implements Serializable { - private String name; + private final String name; TestBean(String name) { this.name = name; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadSerializingTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadSerializingTransformerTests.java index 0e7851beaa..c300b4376c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadSerializingTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadSerializingTransformerTests.java @@ -26,10 +26,9 @@ import java.io.Serializable; import org.junit.Test; -import org.springframework.core.convert.converter.Converter; +import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; -import org.springframework.integration.support.MessageBuilder; /** * @author Mark Fisher @@ -73,11 +72,7 @@ public class PayloadSerializingTransformerTests { @Test public void customSerializer() { PayloadSerializingTransformer transformer = new PayloadSerializingTransformer(); - transformer.setConverter(new Converter() { - public byte[] convert(Object source) { - return "Converted".getBytes(); - } - }); + transformer.setConverter(source -> "Converted".getBytes()); Message message = transformer.transform(MessageBuilder.withPayload("Test").build()); assertEquals("Converted", new String((byte[]) message.getPayload())); } @@ -86,7 +81,7 @@ public class PayloadSerializingTransformerTests { @SuppressWarnings("serial") private static class TestBean implements Serializable { - private String name; + private final String name; TestBean(String name) { this.name = name; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTransformerTests.java index 5199cd903e..49723295d8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTransformerTests.java @@ -56,6 +56,11 @@ public class PayloadTransformerTests { private static class TestPayloadTransformer extends AbstractPayloadTransformer { + TestPayloadTransformer() { + super(); + } + + @Override public Integer transformPayload(String s) throws Exception { if (s.equals("bad")) { throw new Exception("bad input!"); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTypeConvertingTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTypeConvertingTransformerTests.java index 642ac8f7e3..50005ae5cb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTypeConvertingTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/PayloadTypeConvertingTransformerTests.java @@ -20,8 +20,6 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; -import org.springframework.core.convert.converter.Converter; - /** * @author Gary Russell * @since 2.0 @@ -37,14 +35,7 @@ public class PayloadTypeConvertingTransformerTests { @Test public void testTransformPayloadObject() throws Exception { PayloadTypeConvertingTransformer tx = new PayloadTypeConvertingTransformer(); - tx.setConverter(new Converter() { - - @Override - public String convert(String source) { - return source.toUpperCase(); - } - - }); + tx.setConverter(source -> source.toUpperCase()); String in = "abcd"; String out = tx.transformPayload(in); assertEquals("ABCD", out); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/util/BeanFactoryTypeConverterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/util/BeanFactoryTypeConverterTests.java index b0466b972d..e5f8b515cc 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/util/BeanFactoryTypeConverterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/util/BeanFactoryTypeConverterTests.java @@ -47,8 +47,6 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.SimpleTypeConverter; import org.springframework.beans.factory.config.ConfigurableBeanFactory; @@ -293,27 +291,21 @@ public class BeanFactoryTypeConverterTests { final AtomicBoolean inGetDefaultEditor = new AtomicBoolean(); final AtomicBoolean concurrentlyInGetDefaultEditor = new AtomicBoolean(); final AtomicInteger count = new AtomicInteger(); - doAnswer(new Answer() { - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - count.incrementAndGet(); - Thread.sleep(500); - concurrentlyInGetDefaultEditor.set(inGetDefaultEditor.getAndSet(true)); - Thread.sleep(500); - inGetDefaultEditor.set(false); - return invocation.callRealMethod(); - } + doAnswer(invocation -> { + count.incrementAndGet(); + Thread.sleep(500); + concurrentlyInGetDefaultEditor.set(inGetDefaultEditor.getAndSet(true)); + Thread.sleep(500); + inGetDefaultEditor.set(false); + return invocation.callRealMethod(); }).when(typeConverter).getDefaultEditor(UUID.class); beanFactoryTypeConverter.setBeanFactory(beanFactory); final TypeDescriptor sourceType = TypeDescriptor.valueOf(UUID.class); final TypeDescriptor targetType = TypeDescriptor.valueOf(String.class); ExecutorService exec = Executors.newFixedThreadPool(2); - Runnable test = new Runnable() { - @Override - public void run() { - beanFactoryTypeConverter.canConvert(sourceType, targetType); - beanFactoryTypeConverter.convertValue(UUID.randomUUID(), sourceType, targetType); - } + Runnable test = () -> { + beanFactoryTypeConverter.canConvert(sourceType, targetType); + beanFactoryTypeConverter.convertValue(UUID.randomUUID(), sourceType, targetType); }; exec.execute(test); exec.execute(test); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/util/CallerBlocksPolicyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/util/CallerBlocksPolicyTests.java index cffb9ac382..4d4db12413 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/util/CallerBlocksPolicyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/util/CallerBlocksPolicyTests.java @@ -49,7 +49,7 @@ public class CallerBlocksPolicyTests { te.initialize(); final AtomicReference e = new AtomicReference(); final CountDownLatch latch = new CountDownLatch(1); - te.execute(new Runnable() { + Runnable task = new Runnable() { @Override public void run() { @@ -61,7 +61,8 @@ public class CallerBlocksPolicyTests { } latch.countDown(); } - }); + }; + te.execute(task); assertTrue(latch.await(10, TimeUnit.SECONDS)); assertThat(e.get(), instanceOf(RejectedExecutionException.class)); assertEquals("Max wait time expired to queue task", e.get().getMessage()); @@ -77,32 +78,28 @@ public class CallerBlocksPolicyTests { te.initialize(); final AtomicReference e = new AtomicReference(); final CountDownLatch latch = new CountDownLatch(3); - te.execute(new Runnable() { + te.execute(() -> { + try { + Runnable foo = new Runnable() { - @Override - public void run() { - try { - Runnable foo = new Runnable() { - - @Override - public void run() { - try { - Thread.sleep(1000); - } - catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new RuntimeException(); - } - latch.countDown(); + @Override + public void run() { + try { + Thread.sleep(1000); } - }; - te.execute(foo); - te.execute(foo); // this one will be queued - te.execute(foo); // this one will be blocked and successful later - } - catch (TaskRejectedException tre) { - e.set(tre.getCause()); - } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new RuntimeException(); + } + latch.countDown(); + } + }; + te.execute(foo); + te.execute(foo); // this one will be queued + te.execute(foo); // this one will be blocked and successful later + } + catch (TaskRejectedException tre) { + e.set(tre.getCause()); } }); assertTrue(latch.await(10, TimeUnit.SECONDS));