From 0027357ce9a93c2e4f08464cfa0c62ced06d2bba Mon Sep 17 00:00:00 2001 From: Artem Bilan Date: Thu, 10 Jan 2019 13:22:30 -0500 Subject: [PATCH 1/2] Fix BeanFactory propagation for MMInvokerHelper * Remove check for `null` in the `MessagingMethodInvokerHelper.isProvidedMessageHandlerFactoryBean()` * Fix `RecipientListRouter` for `BeanFactory` propagation to the `Recipient.selector` * Fix tests for `BeanFactory` population and propagation * Add `errorChannel` into the `TestUtils.createTestApplicationContext()` * Fix some Sonar smell, including new reported --- ...AbstractMethodAnnotationPostProcessor.java | 21 +- .../handler/BeanNameMessageProcessor.java | 5 +- .../support/MessagingMethodInvokerHelper.java | 9 +- .../router/RecipientListRouter.java | 35 ++-- .../CorrelationStrategyAdapterTests.java | 13 +- ...hodInvokingMessageGroupProcessorTests.java | 183 +++++++++++------- .../MethodInvokingReleaseStrategyTests.java | 123 ++++++++---- .../ApplicationContextMessageBusTests.java | 30 +-- .../bus/DirectChannelSubscriptionTests.java | 22 +-- .../ReactiveStreamsConsumerTests.java | 4 +- .../CustomMessagingAnnotationTests.java | 1 + .../FilterAnnotationPostProcessorTests.java | 29 +-- ...MessagingAnnotationPostProcessorTests.java | 63 +++--- .../RouterAnnotationPostProcessorTests.java | 11 +- .../SplitterAnnotationPostProcessorTests.java | 11 +- .../dispatcher/FailOverDispatcherTests.java | 15 +- .../reactivestreams/ReactiveStreamsTests.java | 13 +- .../endpoint/CorrelationIdTests.java | 27 ++- .../endpoint/MessageProducerSupportTests.java | 55 ++++-- .../ServiceActivatorEndpointTests.java | 63 +++--- ...ServiceActivatorMethodResolutionTests.java | 36 +++- .../filter/MethodInvokingSelectorTests.java | 39 ++-- .../gateway/GatewayProxyFactoryBeanTests.java | 89 ++++----- .../gateway/MessagingGatewayTests.java | 63 +++--- .../handler/DelayHandlerTests.java | 17 +- .../MethodInvokingHeaderEnricherTests.java | 8 +- ...vokingMessageProcessorAnnotationTests.java | 54 ++++-- .../MethodInvokingMessageProcessorTests.java | 113 ++++++++--- .../MethodInvokingMessageHandlerTests.java | 20 +- .../ErrorMessageExceptionTypeRouterTests.java | 79 ++++---- .../router/MethodInvokingRouterTests.java | 119 ++++++++---- .../splitter/MethodInvokingSplitterTests.java | 60 ++++-- .../splitter/StreamingSplitterTests.java | 88 +++++---- .../MapToObjectTransformerTests.java | 39 ++-- .../MethodInvokingTransformerTests.java | 55 ++++-- .../util/BeanFactoryTypeConverterTests.java | 8 +- ...ionEventListeningMessageProducerTests.java | 12 +- .../outbound/UriVariableExpressionTests.java | 49 ++--- .../ip/tcp/TcpInboundGatewayTests.java | 30 ++- .../tcp/TcpReceivingChannelAdapterTests.java | 2 + ...AbstractMongoDbMessageGroupStoreTests.java | 18 +- .../AbstractMongoDbMessageStoreTests.java | 17 +- ...igurableMongoDbMessageGroupStoreTests.java | 10 +- .../ConfigurableMongoDbMessageStoreTests.java | 8 +- ...essageStoreClaimCheckIntegrationTests.java | 26 ++- .../integration/test/util/TestUtils.java | 7 + .../integration/xml/xpath/XPathUtils.java | 10 +- 47 files changed, 1146 insertions(+), 663 deletions(-) diff --git a/spring-integration-core/src/main/java/org/springframework/integration/config/annotation/AbstractMethodAnnotationPostProcessor.java b/spring-integration-core/src/main/java/org/springframework/integration/config/annotation/AbstractMethodAnnotationPostProcessor.java index 154037e86a1..7868ec550a5 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/config/annotation/AbstractMethodAnnotationPostProcessor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/config/annotation/AbstractMethodAnnotationPostProcessor.java @@ -98,17 +98,17 @@ public abstract class AbstractMethodAnnotationPostProcessor messageHandlerAttributes = new ArrayList<>(); + protected final List messageHandlerAttributes = new ArrayList<>(); // NOSONAR - protected final ConfigurableListableBeanFactory beanFactory; + protected final ConfigurableListableBeanFactory beanFactory; // NOSONAR - protected final ConversionService conversionService; + protected final ConversionService conversionService; // NOSONAR - protected final DestinationResolver channelResolver; + protected final DestinationResolver channelResolver; // NOSONAR - protected final Class annotationType; + protected final Class annotationType; // NOSONAR protected final Disposables disposables; // NOSONAR @@ -192,7 +192,8 @@ public Object postProcess(Object bean, String beanName, Method method, List adviceChainEntries = (Collection) adviceChainBean; - for (Advice advice : adviceChainEntries) { - adviceChain.add(advice); - } + adviceChain.addAll(adviceChainEntries); } else { throw new IllegalArgumentException("Invalid advice chain type:" + @@ -346,7 +345,7 @@ protected AbstractEndpoint doCreateEndpoint(MessageHandler handler, MessageChann } protected void configurePollingEndpoint(AbstractPollingEndpoint pollingEndpoint, List annotations) { - PollerMetadata pollerMetadata = null; + PollerMetadata pollerMetadata; Poller[] pollers = MessagingAnnotationUtils.resolveAttribute(annotations, "poller", Poller[].class); if (!ObjectUtils.isEmpty(pollers)) { Assert.state(pollers.length == 1, diff --git a/spring-integration-core/src/main/java/org/springframework/integration/handler/BeanNameMessageProcessor.java b/spring-integration-core/src/main/java/org/springframework/integration/handler/BeanNameMessageProcessor.java index 9fcb67228e6..77404ad2921 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/handler/BeanNameMessageProcessor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/handler/BeanNameMessageProcessor.java @@ -56,7 +56,10 @@ public void setBeanFactory(BeanFactory beanFactory) throws BeansException { public T processMessage(Message message) { if (this.delegate == null) { Object target = this.beanFactory.getBean(this.beanName); - this.delegate = new MethodInvokingMessageProcessor<>(target, this.methodName); + MethodInvokingMessageProcessor methodInvokingMessageProcessor = + new MethodInvokingMessageProcessor<>(target, this.methodName); + methodInvokingMessageProcessor.setBeanFactory(this.beanFactory); + this.delegate = methodInvokingMessageProcessor; } return this.delegate.processMessage(message); } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/handler/support/MessagingMethodInvokerHelper.java b/spring-integration-core/src/main/java/org/springframework/integration/handler/support/MessagingMethodInvokerHelper.java index b97d954d2dc..6f900479d4b 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/handler/support/MessagingMethodInvokerHelper.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/handler/support/MessagingMethodInvokerHelper.java @@ -398,9 +398,7 @@ private MessagingMethodInvokerHelper(Object targetObject, Class recipients) { Assert.notEmpty(recipients, "'recipients' must not be empty"); Queue newRecipients = new ConcurrentLinkedQueue<>(recipients); - if (getBeanFactory() != null) { - newRecipients.forEach(recipient -> recipient.setChannelResolver(getChannelResolver())); - } + newRecipients.forEach(this::setupRecipient); + if (logger.isDebugEnabled()) { logger.debug("Channel Recipients: " + this.recipients + " replaced with: " + newRecipients); } @@ -145,9 +146,7 @@ private void addRecipient(String channelName, String selectorExpression, Queue recipients) { Assert.hasText(channelName, "'channelName' must not be empty."); Recipient recipient = new Recipient(channelName, selector); - if (getBeanFactory() != null) { - recipient.setChannelResolver(getChannelResolver()); - } + setupRecipient(recipient); recipients.add(recipient); } @@ -176,10 +173,18 @@ public void addRecipient(MessageChannel channel) { public void addRecipient(MessageChannel channel, MessageSelector selector) { Recipient recipient = new Recipient(channel, selector); - if (getBeanFactory() != null) { + setupRecipient(recipient); + this.recipients.add(recipient); + } + + private void setupRecipient(Recipient recipient) { + BeanFactory beanFactory = getBeanFactory(); + if (beanFactory != null) { recipient.setChannelResolver(getChannelResolver()); + if (recipient.selector instanceof BeanFactoryAware) { + ((BeanFactoryAware) recipient.selector).setBeanFactory(beanFactory); + } } - this.recipients.add(recipient); } @Override @@ -225,14 +230,14 @@ public void replaceRecipients(Properties recipientMappings) { for (String key : keys) { Assert.notNull(key, "channelName can't be null."); if (StringUtils.hasText(recipientMappings.getProperty(key))) { - this.addRecipient(key, recipientMappings.getProperty(key)); + addRecipient(key, recipientMappings.getProperty(key)); } else { - this.addRecipient(key); + addRecipient(key); } } if (logger.isDebugEnabled()) { - logger.debug("Channel Recipients:" + originalRecipients + " replaced with:" + this.recipients); + logger.debug("Channel Recipients:" + originalRecipients + " replaced with:" + this.recipients); } } @@ -259,7 +264,7 @@ protected Collection determineTargetChannels(Message message) @Override protected void onInit() { super.onInit(); - this.recipients.forEach(recipient -> recipient.setChannelResolver(getChannelResolver())); + this.recipients.forEach(this::setupRecipient); } public static class Recipient { 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 5883832621c..08bd86bc1f3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,10 +17,12 @@ package org.springframework.integration.aggregator; import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.mock; import org.junit.Before; import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.handler.annotation.Header; @@ -28,6 +30,7 @@ /** * @author Dave Syer + * @author Artem Bilan * */ public class CorrelationStrategyAdapterTests { @@ -43,13 +46,16 @@ public void init() { public void testMethodName() { MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new SimpleMessageCorrelator(), "getKey"); + adapter.setBeanFactory(mock(BeanFactory.class)); assertEquals("b", adapter.getCorrelationKey(message)); } @Test public void testCorrelationStrategyAdapterObjectMethod() { - MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new SimpleMessageCorrelator(), + MethodInvokingCorrelationStrategy adapter = + new MethodInvokingCorrelationStrategy(new SimpleMessageCorrelator(), ReflectionUtils.findMethod(SimpleMessageCorrelator.class, "getKey", Message.class)); + adapter.setBeanFactory(mock(BeanFactory.class)); assertEquals("b", adapter.getCorrelationKey(message)); } @@ -57,6 +63,7 @@ public void testCorrelationStrategyAdapterObjectMethod() { public void testCorrelationStrategyAdapterPojoMethod() { MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new SimplePojoCorrelator(), "getKey"); + adapter.setBeanFactory(mock(BeanFactory.class)); assertEquals("foo", adapter.getCorrelationKey(message)); } @@ -64,6 +71,7 @@ public void testCorrelationStrategyAdapterPojoMethod() { public void testHeaderPojoMethod() { MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new SimpleHeaderCorrelator(), "getKey"); + adapter.setBeanFactory(mock(BeanFactory.class)); assertEquals("b", adapter.getCorrelationKey(message)); } @@ -71,6 +79,7 @@ public void testHeaderPojoMethod() { public void testHeadersPojoMethod() { MethodInvokingCorrelationStrategy adapter = new MethodInvokingCorrelationStrategy(new MultiHeaderCorrelator(), ReflectionUtils.findMethod(MultiHeaderCorrelator.class, "getKey", String.class, String.class)); + adapter.setBeanFactory(mock(BeanFactory.class)); assertEquals("bd", adapter.getCorrelationKey(message)); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java index a04e6361374..cfb41740c7e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,11 +16,13 @@ package org.springframework.integration.aggregator; +import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import java.util.ArrayList; @@ -37,6 +39,7 @@ import org.mockito.junit.MockitoJUnitRunner; import org.springframework.aop.framework.ProxyFactory; +import org.springframework.beans.factory.BeanFactory; import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.support.DefaultConversionService; import org.springframework.core.convert.support.GenericConversionService; @@ -66,17 +69,16 @@ @RunWith(MockitoJUnitRunner.class) public class MethodInvokingMessageGroupProcessorTests { - private final List> messagesUpForProcessing = new ArrayList>(3); + private final List> messagesUpForProcessing = new ArrayList<>(3); @Mock private MessageGroup messageGroupMock; - @Before public void initializeMessagesUpForProcessing() { - messagesUpForProcessing.add(MessageBuilder.withPayload(1).build()); - messagesUpForProcessing.add(MessageBuilder.withPayload(2).build()); - messagesUpForProcessing.add(MessageBuilder.withPayload(4).build()); + this.messagesUpForProcessing.add(MessageBuilder.withPayload(1).build()); + this.messagesUpForProcessing.add(MessageBuilder.withPayload(2).build()); + this.messagesUpForProcessing.add(MessageBuilder.withPayload(4).build()); } @@ -98,16 +100,19 @@ public Integer and(List flags) { public String know(List flags) { return "I'm not the one "; } + } - MessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new AnnotatedAggregatorMethod()); - when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); - Object result = processor.processMessageGroup(messageGroupMock); + MethodInvokingMessageGroupProcessor processor = + new MethodInvokingMessageGroupProcessor(new AnnotatedAggregatorMethod()); + processor.setBeanFactory(mock(BeanFactory.class)); + when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); + Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); } @Test - public void shouldFindSimpleAggregatorMethod() throws Exception { + public void shouldFindSimpleAggregatorMethod() { @SuppressWarnings("unused") class SimpleAggregator { @@ -119,16 +124,19 @@ public Integer and(List flags) { } return result; } + } - MessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); - Object result = processor.processMessageGroup(messageGroupMock); + MethodInvokingMessageGroupProcessor processor = + new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); + processor.setBeanFactory(mock(BeanFactory.class)); + when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); + Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); } @Test - public void shouldFindSimpleAggregatorMethodForMessages() throws Exception { + public void shouldFindSimpleAggregatorMethodForMessages() { @SuppressWarnings("unused") class SimpleAggregator { @@ -140,16 +148,19 @@ public Integer and(List> flags) { } return result; } + } - MessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); - Object result = processor.processMessageGroup(messageGroupMock); + MethodInvokingMessageGroupProcessor processor = + new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); + processor.setBeanFactory(mock(BeanFactory.class)); + when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); + Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); } @Test - public void shouldFindListPayloads() throws Exception { + public void shouldFindListPayloads() { @SuppressWarnings("unused") class SimpleAggregator { @@ -164,9 +175,12 @@ public String and(List flags, @Header("foo") List header) { } return result.toString(); } + } - MessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); + MethodInvokingMessageGroupProcessor processor = + new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); + processor.setBeanFactory(mock(BeanFactory.class)); messagesUpForProcessing.add(MessageBuilder.withPayload(3).setHeader("foo", Arrays.asList(101, 102)).build()); when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); Object result = processor.processMessageGroup(messageGroupMock); @@ -174,7 +188,7 @@ public String and(List flags, @Header("foo") List header) { } @Test - public void shouldFindAnnotatedPayloadsWithNoType() throws Exception { + public void shouldFindAnnotatedPayloadsWithNoType() { @SuppressWarnings("unused") class SimpleAggregator { @@ -191,43 +205,48 @@ public String and(@Payloads List rawFlags, @Header("foo") List heade } return result.toString(); } + } - MessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - messagesUpForProcessing.add(MessageBuilder.withPayload(3).setHeader("foo", Arrays.asList(101, 102)).build()); - when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); - Object result = processor.processMessageGroup(messageGroupMock); + MethodInvokingMessageGroupProcessor processor = + new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); + processor.setBeanFactory(mock(BeanFactory.class)); + this.messagesUpForProcessing.add( + MessageBuilder.withPayload(3) + .setHeader("foo", Arrays.asList(101, 102)) + .build()); + when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); + Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is("[1, 2, 4, 3, 101, 102]")); } @Test - public void shouldUseAnnotatedPayloads() throws Exception { + public void shouldUseAnnotatedPayloads() { @SuppressWarnings("unused") class SimpleAggregator { @Aggregator public String and(@Payloads List flags) { - List result = new ArrayList(); - for (int flag : flags) { - result.add(flag); - } - return result.toString(); + return flags.toString(); } public String or(List flags) { throw new UnsupportedOperationException("Not expected"); } + } - MessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); - Object result = processor.processMessageGroup(messageGroupMock); + MethodInvokingMessageGroupProcessor processor = + new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); + processor.setBeanFactory(mock(BeanFactory.class)); + when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); + Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is("[1, 2, 4]")); } @Test - public void shouldFindSimpleAggregatorMethodWithCollection() throws Exception { + public void shouldFindSimpleAggregatorMethodWithCollection() { @SuppressWarnings("unused") class SimpleAggregator { @@ -239,16 +258,19 @@ public Integer and(Collection flags) { } return result; } + } - MessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); - Object result = processor.processMessageGroup(messageGroupMock); + MethodInvokingMessageGroupProcessor processor = + new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); + processor.setBeanFactory(mock(BeanFactory.class)); + when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); + Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); } @Test - public void shouldFindSimpleAggregatorMethodWithArray() throws Exception { + public void shouldFindSimpleAggregatorMethodWithArray() { @SuppressWarnings("unused") class SimpleAggregator { @@ -260,17 +282,20 @@ public Integer and(int[] flags) { } return result; } + } - MessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); - when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); - Object result = processor.processMessageGroup(messageGroupMock); + MethodInvokingMessageGroupProcessor processor = + new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); + processor.setBeanFactory(mock(BeanFactory.class)); + when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); + Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); } @Test - public void shouldFindSimpleAggregatorMethodWithIterator() throws Exception { + public void shouldFindSimpleAggregatorMethodWithIterator() { @SuppressWarnings("unused") class SimpleAggregator { @@ -282,11 +307,14 @@ public Integer and(Iterator flags) { } return result; } + } - MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); + MethodInvokingMessageGroupProcessor processor = + new MethodInvokingMessageGroupProcessor(new SimpleAggregator()); + processor.setBeanFactory(mock(BeanFactory.class)); GenericConversionService conversionService = new DefaultConversionService(); - conversionService.addConverter(new Converter, Iterator>() { + conversionService.addConverter(new Converter, Iterator>() { // Must not be lambda @Override public Iterator convert(ArrayList source) { @@ -295,8 +323,8 @@ public Iterator convert(ArrayList source) { }); processor.setConversionService(conversionService); - when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); - Object result = processor.processMessageGroup(messageGroupMock); + when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); + Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); } @@ -322,11 +350,14 @@ public String methodAcceptingNoCollectionShouldBeIgnored(String irrelevant) { fail("this method should not be invoked"); return null; } + } - MessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new UnannotatedAggregator()); - when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); - Object result = processor.processMessageGroup(messageGroupMock); + MethodInvokingMessageGroupProcessor processor = + new MethodInvokingMessageGroupProcessor(new UnannotatedAggregator()); + processor.setBeanFactory(mock(BeanFactory.class)); + when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); + Object result = processor.processMessageGroup(this.messageGroupMock); assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), is(7)); } @@ -349,12 +380,15 @@ public String methodAcceptingNoCollectionShouldBeIgnored(String irrelevant) { fail("this method should not be invoked"); return null; } + } - MessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new UnannotatedAggregator()); - when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); - Object result = processor.processMessageGroup(messageGroupMock); - assertTrue(((AbstractIntegrationMessageBuilder) result).build().getPayload() instanceof Iterator); + MethodInvokingMessageGroupProcessor processor = + new MethodInvokingMessageGroupProcessor(new UnannotatedAggregator()); + processor.setBeanFactory(mock(BeanFactory.class)); + when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); + Object result = processor.processMessageGroup(this.messageGroupMock); + assertThat(((AbstractIntegrationMessageBuilder) result).build().getPayload(), instanceOf(Iterator.class)); } @Test @@ -376,11 +410,14 @@ public String listHeaderShouldBeIgnored(@Header List flags) { fail("this method should not be invoked"); return ""; } + } - MessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(new AnnotatedParametersAggregator()); - when(messageGroupMock.getMessages()).thenReturn(messagesUpForProcessing); - Object result = processor.processMessageGroup(messageGroupMock); + MethodInvokingMessageGroupProcessor processor = + new MethodInvokingMessageGroupProcessor(new AnnotatedParametersAggregator()); + processor.setBeanFactory(mock(BeanFactory.class)); + when(this.messageGroupMock.getMessages()).thenReturn(this.messagesUpForProcessing); + Object result = processor.processMessageGroup(this.messageGroupMock); Object payload = ((AbstractIntegrationMessageBuilder) result).build().getPayload(); assertTrue(payload instanceof Integer); assertEquals(7, payload); @@ -388,7 +425,7 @@ public String listHeaderShouldBeIgnored(@Header List flags) { } @Test - public void singleAnnotation() throws Exception { + public void singleAnnotation() { @SuppressWarnings("unused") class SingleAnnotationTestBean { @@ -401,18 +438,20 @@ public String method1(List input) { public String method2(List input) { return input.get(1); } + } SingleAnnotationTestBean bean = new SingleAnnotationTestBean(); MethodInvokingMessageGroupProcessor aggregator = new MethodInvokingMessageGroupProcessor(bean); + aggregator.setBeanFactory(mock(BeanFactory.class)); SimpleMessageGroup group = new SimpleMessageGroup("FOO"); - group.add(new GenericMessage("foo")); - group.add(new GenericMessage("bar")); + group.add(new GenericMessage<>("foo")); + group.add(new GenericMessage<>("bar")); assertEquals("foo", aggregator.aggregatePayloads(group, null)); } @Test - public void testHeaderParameters() throws Exception { + public void testHeaderParameters() { class SingleAnnotationTestBean { @@ -424,15 +463,16 @@ public String method1(List input, @Header("foo") String foo) { } SingleAnnotationTestBean bean = new SingleAnnotationTestBean(); - MethodInvokingMessageGroupProcessor aggregator = new MethodInvokingMessageGroupProcessor(bean); + MethodInvokingMessageGroupProcessor processor = new MethodInvokingMessageGroupProcessor(bean); + processor.setBeanFactory(mock(BeanFactory.class)); SimpleMessageGroup group = new SimpleMessageGroup("FOO"); group.add(MessageBuilder.withPayload("foo").setHeader("foo", "bar").build()); group.add(MessageBuilder.withPayload("bar").setHeader("foo", "bar").build()); - assertEquals("foobar", aggregator.aggregatePayloads(group, aggregator.aggregateHeaders(group))); + assertEquals("foobar", processor.aggregatePayloads(group, processor.aggregateHeaders(group))); } @Test - public void testHeadersParameters() throws Exception { + public void testHeadersParameters() { class SingleAnnotationTestBean { @@ -445,6 +485,7 @@ public String method1(List input, @Headers Map map) { SingleAnnotationTestBean bean = new SingleAnnotationTestBean(); MethodInvokingMessageGroupProcessor aggregator = new MethodInvokingMessageGroupProcessor(bean); + aggregator.setBeanFactory(mock(BeanFactory.class)); SimpleMessageGroup group = new SimpleMessageGroup("FOO"); group.add(MessageBuilder.withPayload("foo").setHeader("foo", "bar").build()); group.add(MessageBuilder.withPayload("bar").setHeader("foo", "bar").build()); @@ -465,6 +506,7 @@ public String method1(List input) { public String method2(List input) { return input.get(0); } + } MultipleAnnotationTestBean bean = new MultipleAnnotationTestBean(); @@ -472,7 +514,7 @@ public String method2(List input) { } @Test - public void noAnnotations() throws Exception { + public void noAnnotations() { @SuppressWarnings("unused") class NoAnnotationTestBean { @@ -484,13 +526,15 @@ public String method1(List input) { String method2(List input) { return input.get(1); } + } NoAnnotationTestBean bean = new NoAnnotationTestBean(); MethodInvokingMessageGroupProcessor aggregator = new MethodInvokingMessageGroupProcessor(bean); + aggregator.setBeanFactory(mock(BeanFactory.class)); SimpleMessageGroup group = new SimpleMessageGroup("FOO"); - group.add(new GenericMessage("foo")); - group.add(new GenericMessage("bar")); + group.add(new GenericMessage<>("foo")); + group.add(new GenericMessage<>("bar")); assertEquals("foo", aggregator.aggregatePayloads(group, null)); } @@ -507,6 +551,7 @@ public String upperCase(String s) { public String lowerCase(String s) { return s.toLowerCase(); } + } MultiplePublicMethodTestBean bean = new MultiplePublicMethodTestBean(); @@ -522,6 +567,7 @@ class NoPublicMethodTestBean { String lowerCase(String s) { return s.toLowerCase(); } + } NoPublicMethodTestBean bean = new NoPublicMethodTestBean(); @@ -540,7 +586,8 @@ public void jdkProxy() { AggregatingMessageHandler handler = new AggregatingMessageHandler(aggregator); handler.setReleaseStrategy(new MessageCountReleaseStrategy()); handler.setOutputChannel(output); - + handler.setBeanFactory(mock(BeanFactory.class)); + handler.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(input, handler); endpoint.start(); @@ -561,6 +608,8 @@ public void cglibProxy() { AggregatingMessageHandler handler = new AggregatingMessageHandler(aggregator); handler.setReleaseStrategy(new MessageCountReleaseStrategy()); handler.setOutputChannel(output); + handler.setBeanFactory(mock(BeanFactory.class)); + handler.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(input, handler); endpoint.start(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java index bd0bdca570a..add00e6d274 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,6 +16,8 @@ package org.springframework.integration.aggregator; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.util.ArrayList; @@ -23,9 +25,9 @@ import java.util.LinkedList; import java.util.List; -import org.junit.Assert; import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; import org.springframework.core.convert.ConversionFailedException; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.store.MessageGroup; @@ -44,104 +46,125 @@ public class MethodInvokingReleaseStrategyTests { public void testTrueConvertedProperly() { MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new AlwaysTrueReleaseStrategy(), "checkCompleteness"); - Assert.assertTrue(adapter.canRelease(createListOfMessages(0))); + adapter.setBeanFactory(mock(BeanFactory.class)); + assertTrue(adapter.canRelease(createListOfMessages(0))); } @Test public void testFalseConvertedProperly() { MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new AlwaysFalseReleaseStrategy(), "checkCompleteness"); - Assert.assertTrue(!adapter.canRelease(createListOfMessages(0))); + adapter.setBeanFactory(mock(BeanFactory.class)); + assertFalse(adapter.canRelease(createListOfMessages(0))); } @Test public void testAdapterWithNonParameterizedMessageListBasedMethod() { class TestReleaseStrategy { + @SuppressWarnings("unused") public boolean checkCompletenessOnNonParameterizedListOfMessages(List> messages) { - Assert.assertTrue(messages.size() > 0); - return messages.size() > new IntegrationMessageHeaderAccessor(messages.iterator().next()).getSequenceSize(); + assertTrue(messages.size() > 0); + return messages.size() > + new IntegrationMessageHeaderAccessor(messages.iterator().next()).getSequenceSize(); } + } - ReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), + MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "checkCompletenessOnNonParameterizedListOfMessages"); + adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - Assert.assertTrue(adapter.canRelease(messages)); + assertTrue(adapter.canRelease(messages)); } @Test public void testAdapterWithWildcardParametrizedMessageBasedMethod() { class TestReleaseStrategy { + @SuppressWarnings("unused") public boolean checkCompletenessOnListOfMessagesParametrizedWithWildcard(List> messages) { - Assert.assertTrue(messages.size() > 0); - return messages.size() > new IntegrationMessageHeaderAccessor(messages.iterator().next()).getSequenceSize(); + assertTrue(messages.size() > 0); + return messages.size() > + new IntegrationMessageHeaderAccessor(messages.iterator().next()).getSequenceSize(); } + } - ReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), + MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "checkCompletenessOnListOfMessagesParametrizedWithWildcard"); + adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - Assert.assertTrue(adapter.canRelease(messages)); + assertTrue(adapter.canRelease(messages)); } @Test public void testAdapterWithTypeParametrizedMessageBasedMethod() { class TestReleaseStrategy { + @SuppressWarnings("unused") public boolean checkCompletenessOnListOfMessagesParametrizedWithString(List> messages) { - Assert.assertTrue(messages.size() > 0); - return messages.size() > new IntegrationMessageHeaderAccessor(messages.iterator().next()).getSequenceSize(); + assertTrue(messages.size() > 0); + return messages.size() > new IntegrationMessageHeaderAccessor(messages.iterator().next()) + .getSequenceSize(); } + } - ReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), + MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "checkCompletenessOnListOfMessagesParametrizedWithString"); + adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - Assert.assertTrue(adapter.canRelease(messages)); + assertTrue(adapter.canRelease(messages)); } @Test public void testAdapterWithPojoBasedMethod() { class TestReleaseStrategy { + @SuppressWarnings("unused") // Example for the case when completeness is checked on the structure of // the data public boolean checkCompletenessOnListOfStrings(List messages) { - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(); for (String content : messages) { buffer.append(content); } return buffer.length() >= 9; } + } - ReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), + MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "checkCompletenessOnListOfStrings"); + adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - Assert.assertTrue(adapter.canRelease(messages)); + assertTrue(adapter.canRelease(messages)); } @Test public void testAdapterWithPojoBasedMethodReturningObject() { class TestReleaseStrategy { + @SuppressWarnings("unused") // Example for the case when completeness is checked on the structure of // the data public boolean checkCompletenessOnListOfStrings(List messages) { - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(); for (String content : messages) { buffer.append(content); } return buffer.length() >= 9; } + } - ReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), + MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "checkCompletenessOnListOfStrings"); + adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - Assert.assertTrue(adapter.canRelease(messages)); + assertTrue(adapter.canRelease(messages)); } @Test(expected = IllegalStateException.class) public void testAdapterWithWrongMethodName() { class TestReleaseStrategy { + } new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "methodThatDoesNotExist"); } @@ -149,23 +172,29 @@ class TestReleaseStrategy { @Test(expected = IllegalStateException.class) public void testInvalidParameterTypeUsingMethodName() { class TestReleaseStrategy { + @SuppressWarnings("unused") public boolean invalidParameterType(Date invalid) { return true; } + } - ReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "invalidParameterType"); + MethodInvokingReleaseStrategy adapter = + new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "invalidParameterType"); + adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - Assert.assertTrue(adapter.canRelease(messages)); + assertTrue(adapter.canRelease(messages)); } @Test(expected = IllegalStateException.class) public void testTooManyParametersUsingMethodName() { class TestReleaseStrategy { + @SuppressWarnings("unused") public boolean tooManyParameters(List c1, List c2) { return false; } + } new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "tooManyParameters"); } @@ -173,10 +202,12 @@ public boolean tooManyParameters(List c1, List c2) { @Test public void testNotEnoughParametersUsingMethodName() { class TestReleaseStrategy { + @SuppressWarnings("unused") public boolean notEnoughParameters() { return false; } + } new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "notEnoughParameters"); } @@ -184,10 +215,12 @@ public boolean notEnoughParameters() { @Test public void testNotEnoughParametersUsingMethodObject() throws SecurityException, NoSuchMethodException { class TestReleaseStrategy { + @SuppressWarnings("unused") public boolean notEnoughParameters() { return false; } + } new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), TestReleaseStrategy.class.getMethod( "notEnoughParameters")); @@ -196,36 +229,46 @@ public boolean notEnoughParameters() { @Test public void testListSubclassParameterUsingMethodName() { class TestReleaseStrategy { + @SuppressWarnings("unused") public boolean listSubclassParameter(LinkedList l1) { return true; } + } - ReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "listSubclassParameter"); + MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), + "listSubclassParameter"); + adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - Assert.assertTrue(adapter.canRelease(messages)); + assertTrue(adapter.canRelease(messages)); } @Test(expected = ConversionFailedException.class) public void testWrongReturnType() throws SecurityException, NoSuchMethodError { class TestReleaseStrategy { + @SuppressWarnings("unused") public String wrongReturnType(List> messages) { return "foo"; } + } - ReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "wrongReturnType"); + MethodInvokingReleaseStrategy adapter = + new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), "wrongReturnType"); + adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - Assert.assertTrue(adapter.canRelease(messages)); + assertTrue(adapter.canRelease(messages)); } @Test(expected = IllegalArgumentException.class) public void testTooManyParametersUsingMethodObject() throws SecurityException, NoSuchMethodException { class TestReleaseStrategy { + @SuppressWarnings("unused") public boolean tooManyParameters(List c1, List c2) { return false; } + } new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), TestReleaseStrategy.class.getMethod( "tooManyParameters", List.class, List.class)); @@ -234,15 +277,18 @@ public boolean tooManyParameters(List c1, List c2) { @Test public void testListSubclassParameterUsingMethodObject() throws SecurityException, NoSuchMethodException { class TestReleaseStrategy { + @SuppressWarnings("unused") public boolean listSubclassParameter(LinkedList l1) { return true; } + } - ReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), - TestReleaseStrategy.class.getMethod("listSubclassParameter", new Class[] { LinkedList.class })); + MethodInvokingReleaseStrategy adapter = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), + TestReleaseStrategy.class.getMethod("listSubclassParameter", LinkedList.class)); + adapter.setBeanFactory(mock(BeanFactory.class)); MessageGroup messages = createListOfMessages(3); - Assert.assertTrue(adapter.canRelease(messages)); + assertTrue(adapter.canRelease(messages)); } @Test(expected = IllegalStateException.class) @@ -258,36 +304,41 @@ public int wrongReturnType(List> message) { MethodInvokingReleaseStrategy wrongReturnType = new MethodInvokingReleaseStrategy(new TestReleaseStrategy(), TestReleaseStrategy.class.getMethod( - "wrongReturnType", new Class[] {List.class})); + "wrongReturnType", List.class)); + wrongReturnType.setBeanFactory(mock(BeanFactory.class)); wrongReturnType.canRelease(mock(MessageGroup.class)); } private static MessageGroup createListOfMessages(int size) { - List> messages = new ArrayList>(); + List> messages = new ArrayList<>(); if (size > 0) { - messages.add(new GenericMessage("123")); + messages.add(new GenericMessage<>("123")); } if (size > 1) { - messages.add(new GenericMessage("456")); + messages.add(new GenericMessage<>("456")); } if (size > 2) { - messages.add(new GenericMessage("789")); + messages.add(new GenericMessage<>("789")); } return new SimpleMessageGroup(messages, "ABC"); } @SuppressWarnings("unused") private static class AlwaysTrueReleaseStrategy { + public boolean checkCompleteness(List> messages) { return true; } + } @SuppressWarnings("unused") private static class AlwaysFalseReleaseStrategy { + public boolean checkCompleteness(List> messages) { return false; } + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/bus/ApplicationContextMessageBusTests.java b/spring-integration-core/src/test/java/org/springframework/integration/bus/ApplicationContextMessageBusTests.java index bcc5b7d941d..fb4f86e08f2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/bus/ApplicationContextMessageBusTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/bus/ApplicationContextMessageBusTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,6 +65,7 @@ public void endpointRegistrationWithInputChannelReference() { .setReplyChannelName("targetChannel").build(); sourceChannel.send(message); AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() { + @Override public Object handleRequestMessage(Message message) { return message; @@ -78,7 +79,7 @@ public Object handleRequestMessage(Message message) { context.refresh(); Message result = targetChannel.receive(10000); assertEquals("test", result.getPayload()); - context.stop(); + context.close(); } @Test @@ -86,21 +87,22 @@ public void channelsWithoutHandlers() { TestApplicationContext context = TestUtils.createTestApplicationContext(); QueueChannel sourceChannel = new QueueChannel(); context.registerChannel("sourceChannel", sourceChannel); - sourceChannel.send(new GenericMessage("test")); + sourceChannel.send(new GenericMessage<>("test")); QueueChannel targetChannel = new QueueChannel(); context.registerChannel("targetChannel", targetChannel); context.refresh(); Message result = targetChannel.receive(10); assertNull(result); - context.stop(); + context.close(); } @Test public void autoDetectionWithApplicationContext() { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("messageBusTests.xml", this.getClass()); + ClassPathXmlApplicationContext context = + new ClassPathXmlApplicationContext("messageBusTests.xml", this.getClass()); context.start(); PollableChannel sourceChannel = (PollableChannel) context.getBean("sourceChannel"); - sourceChannel.send(new GenericMessage("test")); + sourceChannel.send(new GenericMessage<>("test")); PollableChannel targetChannel = (PollableChannel) context.getBean("targetChannel"); Message result = targetChannel.receive(10000); assertEquals("test", result.getPayload()); @@ -114,12 +116,14 @@ public void exactlyOneConsumerReceivesPointToPointMessage() { QueueChannel outputChannel1 = new QueueChannel(); QueueChannel outputChannel2 = new QueueChannel(); AbstractReplyProducingMessageHandler handler1 = new AbstractReplyProducingMessageHandler() { + @Override public Object handleRequestMessage(Message message) { return message; } }; AbstractReplyProducingMessageHandler handler2 = new AbstractReplyProducingMessageHandler() { + @Override public Object handleRequestMessage(Message message) { return message; @@ -137,10 +141,10 @@ public Object handleRequestMessage(Message message) { context.registerEndpoint("testEndpoint1", endpoint1); context.registerEndpoint("testEndpoint2", endpoint2); context.refresh(); - inputChannel.send(new GenericMessage("testing")); + inputChannel.send(new GenericMessage<>("testing")); Message message1 = outputChannel1.receive(10000); Message message2 = outputChannel2.receive(0); - context.stop(); + context.close(); assertTrue("exactly one message should be null", message1 == null ^ message2 == null); } @@ -152,6 +156,7 @@ public void bothConsumersReceivePublishSubscribeMessage() throws InterruptedExce QueueChannel outputChannel2 = new QueueChannel(); final CountDownLatch latch = new CountDownLatch(2); AbstractReplyProducingMessageHandler handler1 = new AbstractReplyProducingMessageHandler() { + @Override public Object handleRequestMessage(Message message) { latch.countDown(); @@ -159,6 +164,7 @@ public Object handleRequestMessage(Message message) { } }; AbstractReplyProducingMessageHandler handler2 = new AbstractReplyProducingMessageHandler() { + @Override public Object handleRequestMessage(Message message) { latch.countDown(); @@ -180,7 +186,7 @@ public Object handleRequestMessage(Message message) { assertEquals("both handlers should have been invoked", 0, latch.getCount()); Message message1 = outputChannel1.receive(500); Message message2 = outputChannel2.receive(500); - context.stop(); + context.close(); assertNotNull("both handlers should have replied to the message", message1); assertNotNull("both handlers should have replied to the message", message2); } @@ -201,7 +207,7 @@ public void errorChannelWithFailedDispatch() throws InterruptedException { context.refresh(); latch.await(2000, TimeUnit.MILLISECONDS); Message message = errorChannel.receive(5000); - context.stop(); + context.close(); assertNull(outputChannel.receive(100)); assertNotNull("message should not be null", message); assertTrue(message instanceof ErrorMessage); @@ -216,6 +222,7 @@ public void consumerSubscribedToErrorChannel() throws InterruptedException { context.registerChannel(IntegrationContextUtils.ERROR_CHANNEL_BEAN_NAME, errorChannel); final CountDownLatch latch = new CountDownLatch(1); AbstractReplyProducingMessageHandler handler = new AbstractReplyProducingMessageHandler() { + @Override public Object handleRequestMessage(Message message) { latch.countDown(); @@ -229,7 +236,7 @@ public Object handleRequestMessage(Message message) { errorChannel.send(new ErrorMessage(new RuntimeException("test-exception"))); latch.await(1000, TimeUnit.MILLISECONDS); assertEquals("handler should have received error message", 0, latch.getCount()); - context.stop(); + context.close(); } @@ -246,6 +253,7 @@ public Message receive() { latch.countDown(); throw new RuntimeException("intentional test failure"); } + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/bus/DirectChannelSubscriptionTests.java b/spring-integration-core/src/test/java/org/springframework/integration/bus/DirectChannelSubscriptionTests.java index 4949d442ae9..d7a15119cd7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/bus/DirectChannelSubscriptionTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/bus/DirectChannelSubscriptionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,16 +65,15 @@ public void tearDown() { @Test public void sendAndReceiveForRegisteredEndpoint() { - TestApplicationContext context = TestUtils.createTestApplicationContext(); ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(new TestBean(), "handle"); serviceActivator.setOutputChannel(this.targetChannel); + context.registerBean("testServiceActivator", serviceActivator); EventDrivenConsumer endpoint = new EventDrivenConsumer(this.sourceChannel, serviceActivator); context.registerEndpoint("testEndpoint", endpoint); context.refresh(); - this.sourceChannel.send(new GenericMessage("foo")); + this.sourceChannel.send(new GenericMessage<>("foo")); Message response = this.targetChannel.receive(); assertEquals("foo!", response.getPayload()); - context.stop(); } @Test @@ -88,7 +87,6 @@ public void sendAndReceiveForAnnotatedEndpoint() { this.sourceChannel.send(new GenericMessage<>("foo")); Message response = this.targetChannel.receive(); assertEquals("foo-from-annotated-endpoint", response.getPayload()); - this.context.stop(); } @Test(expected = MessagingException.class) @@ -104,12 +102,7 @@ public Object handleRequestMessage(Message message) { EventDrivenConsumer endpoint = new EventDrivenConsumer(sourceChannel, handler); this.context.registerEndpoint("testEndpoint", endpoint); this.context.refresh(); - try { - this.sourceChannel.send(new GenericMessage<>("foo")); - } - finally { - this.context.stop(); - } + this.sourceChannel.send(new GenericMessage<>("foo")); } @Test(expected = MessagingException.class) @@ -122,12 +115,7 @@ public void exceptionThrownFromAnnotatedEndpoint() { FailingTestEndpoint endpoint = new FailingTestEndpoint(); postProcessor.postProcessAfterInitialization(endpoint, "testEndpoint"); this.context.refresh(); - try { - this.sourceChannel.send(new GenericMessage("foo")); - } - finally { - this.context.stop(); - } + this.sourceChannel.send(new GenericMessage<>("foo")); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/ReactiveStreamsConsumerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/ReactiveStreamsConsumerTests.java index bc51a5d90ce..51a903e9095 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/ReactiveStreamsConsumerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/reactive/ReactiveStreamsConsumerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2017 the original author or authors. + * Copyright 2016-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,7 +77,7 @@ public void testReactiveStreamsConsumerFluxMessageChannel() throws InterruptedEx }; MessageHandler testSubscriber = new MethodInvokingMessageHandler(messageHandler, (String) null); - + ((MethodInvokingMessageHandler) testSubscriber).setBeanFactory(mock(BeanFactory.class)); ReactiveStreamsConsumer reactiveConsumer = new ReactiveStreamsConsumer(testChannel, testSubscriber); reactiveConsumer.setBeanFactory(mock(BeanFactory.class)); reactiveConsumer.afterPropertiesSet(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/CustomMessagingAnnotationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/CustomMessagingAnnotationTests.java index 0908872a91e..01cbef3e5bb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/CustomMessagingAnnotationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/CustomMessagingAnnotationTests.java @@ -146,6 +146,7 @@ protected MessageHandler createHandler(Object bean, Method method, List processor = new MethodInvokingMessageProcessor<>(bean, method); + processor.setBeanFactory(this.beanFactory); loggingHandler.setLogExpression(new FunctionExpression<>(processor::processMessage)); return loggingHandler; } 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 ba1cbc6eede..d1d2964d027 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,9 +23,10 @@ import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import java.util.Arrays; +import java.util.Collections; import java.util.List; +import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -44,6 +45,7 @@ * @author Mark Fisher * @author Gary Russell * @author Artem Bilan + * * @since 2.0 */ public class FilterAnnotationPostProcessorTests { @@ -64,6 +66,10 @@ public void init() { postProcessor.afterPropertiesSet(); } + @After + public void tearDown() { + this.context.close(); + } @Test public void filterAnnotationWithBooleanPrimitive() { @@ -108,7 +114,7 @@ public void filterAnnotationWithAdviceDiscardWithout() { @Test public void filterAnnotationWithAdviceArray() { TestAdvice advice = new TestAdvice(); - context.registerBean("adviceChain", new TestAdvice[] {advice}); + context.registerBean("adviceChain", new TestAdvice[] { advice }); testValidFilter(new TestFilterWithAdviceDiscardWithin()); EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("testFilter.filter.filter"); assertSame(advice, TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class).get(0)); @@ -119,10 +125,10 @@ public void filterAnnotationWithAdviceArray() { public void filterAnnotationWithAdviceArrayTwice() { TestAdvice advice1 = new TestAdvice(); TestAdvice advice2 = new TestAdvice(); - context.registerBean("adviceChain1", new TestAdvice[] {advice1, advice2}); + context.registerBean("adviceChain1", new TestAdvice[] { advice1, advice2 }); TestAdvice advice3 = new TestAdvice(); TestAdvice advice4 = new TestAdvice(); - context.registerBean("adviceChain2", new TestAdvice[] {advice3, advice4}); + context.registerBean("adviceChain2", new TestAdvice[] { advice3, advice4 }); testValidFilter(new TestFilterWithAdviceDiscardWithinTwice()); EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("testFilter.filter.filter"); List adviceList = TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class); @@ -137,7 +143,7 @@ public void filterAnnotationWithAdviceArrayTwice() { @Test public void filterAnnotationWithAdviceCollection() { TestAdvice advice = new TestAdvice(); - context.registerBean("adviceChain", Arrays.asList(new TestAdvice[] {advice})); + context.registerBean("adviceChain", Collections.singletonList(advice)); testValidFilter(new TestFilterWithAdviceDiscardWithin()); EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("testFilter.filter.filter"); assertSame(advice, TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class).get(0)); @@ -148,10 +154,10 @@ public void filterAnnotationWithAdviceCollection() { public void filterAnnotationWithAdviceCollectionTwice() { TestAdvice advice1 = new TestAdvice(); TestAdvice advice2 = new TestAdvice(); - context.registerBean("adviceChain1", new TestAdvice[] {advice1, advice2}); + context.registerBean("adviceChain1", new TestAdvice[] { advice1, advice2 }); TestAdvice advice3 = new TestAdvice(); TestAdvice advice4 = new TestAdvice(); - context.registerBean("adviceChain2", new TestAdvice[] {advice3, advice4}); + context.registerBean("adviceChain2", new TestAdvice[] { advice3, advice4 }); testValidFilter(new TestFilterWithAdviceDiscardWithinTwice()); EventDrivenConsumer endpoint = (EventDrivenConsumer) context.getBean("testFilter.filter.filter"); List adviceList = TestUtils.getPropertyValue(endpoint, "handler.adviceChain", List.class); @@ -184,10 +190,10 @@ public void invalidMethodWithVoidReturnType() { private void testValidFilter(Object filter) { postProcessor.postProcessAfterInitialization(filter, "testFilter"); context.refresh(); - inputChannel.send(new GenericMessage("good")); + inputChannel.send(new GenericMessage<>("good")); Message passed = outputChannel.receive(0); assertNotNull(passed); - inputChannel.send(new GenericMessage("bad")); + inputChannel.send(new GenericMessage<>("bad")); assertNull(outputChannel.receive(0)); context.stop(); } @@ -216,7 +222,7 @@ public boolean filter(String s) { @MessageEndpoint public static class TestFilterWithAdviceDiscardWithinTwice { - @Filter(inputChannel = "input", outputChannel = "output", adviceChain = {"adviceChain1", "adviceChain2"}) + @Filter(inputChannel = "input", outputChannel = "output", adviceChain = { "adviceChain1", "adviceChain2" }) public boolean filter(String s) { return !s.contains("bad"); } @@ -231,6 +237,7 @@ public static class TestFilterWithAdviceDiscardWithout { public boolean filter(String s) { return !s.contains("bad"); } + } @MessageEndpoint 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 cf009733e63..94320ee95a9 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,10 +72,11 @@ public void serviceActivatorAnnotation() { assertTrue(context.containsBean("testBean.test.serviceActivator")); Object endpoint = context.getBean("testBean.test.serviceActivator"); assertTrue(endpoint instanceof AbstractEndpoint); + context.close(); } @Test - public void serviceActivatorInApplicationContext() throws Exception { + public void serviceActivatorInApplicationContext() { AbstractApplicationContext context = new ClassPathXmlApplicationContext( "serviceActivatorAnnotationPostProcessorTests.xml", this.getClass()); MessageChannel inputChannel = (MessageChannel) context.getBean("inputChannel"); @@ -87,8 +88,10 @@ public void serviceActivatorInApplicationContext() throws Exception { } @Test - public void testSimpleHandler() throws InterruptedException { - AbstractApplicationContext context = new ClassPathXmlApplicationContext("simpleAnnotatedEndpointTests.xml", this.getClass()); + public void testSimpleHandler() { + AbstractApplicationContext context = new ClassPathXmlApplicationContext("simpleAnnotatedEndpointTests.xml", + this + .getClass()); context.start(); MessageChannel inputChannel = (MessageChannel) context.getBean("inputChannel"); PollableChannel outputChannel = (PollableChannel) context.getBean("outputChannel"); @@ -106,26 +109,26 @@ public void testSimpleHandler() throws InterruptedException { } @Test - public void messageAsMethodParameter() throws InterruptedException { + public void messageAsMethodParameter() { AbstractApplicationContext context = new ClassPathXmlApplicationContext( "messageParameterAnnotatedEndpointTests.xml", this.getClass()); context.start(); MessageChannel inputChannel = (MessageChannel) context.getBean("inputChannel"); PollableChannel outputChannel = (PollableChannel) context.getBean("outputChannel"); - inputChannel.send(new GenericMessage("world")); + inputChannel.send(new GenericMessage<>("world")); Message message = outputChannel.receive(1000); assertEquals("hello world", message.getPayload()); context.close(); } @Test - public void typeConvertingHandler() throws InterruptedException { + public void typeConvertingHandler() { AbstractApplicationContext context = new ClassPathXmlApplicationContext( "typeConvertingEndpointTests.xml", this.getClass()); context.start(); MessageChannel inputChannel = (MessageChannel) context.getBean("inputChannel"); PollableChannel outputChannel = (PollableChannel) context.getBean("outputChannel"); - inputChannel.send(new GenericMessage("123")); + inputChannel.send(new GenericMessage<>("123")); Message message = outputChannel.receive(1000); assertEquals(246, message.getPayload()); context.close(); @@ -148,7 +151,7 @@ public void outboundOnlyServiceActivator() throws InterruptedException { latch.await(1000, TimeUnit.MILLISECONDS); assertEquals(0, latch.getCount()); assertEquals("foo", testBean.getMessageText()); - context.stop(); + context.close(); } @Test(expected = IllegalArgumentException.class) @@ -179,10 +182,10 @@ public void testChannelResolution() { Message reply = outputChannel.receive(0); assertNotNull(reply); - eventBus.send(new GenericMessage("foo")); + eventBus.send(new GenericMessage<>("foo")); assertTrue(bean.getInvoked()); - context.stop(); + context.close(); } @Test @@ -199,10 +202,10 @@ public void testProxiedMessageEndpointAnnotation() { Object proxy = proxyFactory.getProxy(); postProcessor.postProcessAfterInitialization(proxy, "proxy"); context.refresh(); - inputChannel.send(new GenericMessage("world")); + inputChannel.send(new GenericMessage<>("world")); Message message = outputChannel.receive(1000); assertEquals("hello world", message.getPayload()); - context.stop(); + context.close(); } @Test @@ -217,10 +220,10 @@ public void testMessageEndpointAnnotationInherited() { postProcessor.afterPropertiesSet(); postProcessor.postProcessAfterInitialization(new SimpleAnnotatedEndpointSubclass(), "subclass"); context.refresh(); - inputChannel.send(new GenericMessage("world")); + inputChannel.send(new GenericMessage<>("world")); Message message = outputChannel.receive(1000); assertEquals("hello world", message.getPayload()); - context.stop(); + context.close(); } @Test @@ -237,10 +240,10 @@ public void testMessageEndpointAnnotationInheritedWithProxy() { Object proxy = proxyFactory.getProxy(); postProcessor.postProcessAfterInitialization(proxy, "proxy"); context.refresh(); - inputChannel.send(new GenericMessage("world")); + inputChannel.send(new GenericMessage<>("world")); Message message = outputChannel.receive(1000); assertEquals("hello world", message.getPayload()); - context.stop(); + context.close(); } @Test @@ -255,10 +258,10 @@ public void testMessageEndpointAnnotationInheritedFromInterface() { postProcessor.afterPropertiesSet(); postProcessor.postProcessAfterInitialization(new SimpleAnnotatedEndpointImplementation(), "impl"); context.refresh(); - inputChannel.send(new GenericMessage("ABC")); + inputChannel.send(new GenericMessage<>("ABC")); Message message = outputChannel.receive(1000); assertEquals("test-ABC", message.getPayload()); - context.stop(); + context.close(); } @Test @@ -273,10 +276,10 @@ public void testMessageEndpointAnnotationInheritedFromInterfaceWithAutoCreatedCh postProcessor.afterPropertiesSet(); postProcessor.postProcessAfterInitialization(new SimpleAnnotatedEndpointImplementation(), "impl"); context.refresh(); - inputChannel.send(new GenericMessage("ABC")); + inputChannel.send(new GenericMessage<>("ABC")); Message message = outputChannel.receive(1000); assertEquals("test-ABC", message.getPayload()); - context.stop(); + context.close(); } @Test @@ -293,10 +296,10 @@ public void testMessageEndpointAnnotationInheritedFromInterfaceWithProxy() { Object proxy = proxyFactory.getProxy(); postProcessor.postProcessAfterInitialization(proxy, "proxy"); context.refresh(); - inputChannel.send(new GenericMessage("ABC")); + inputChannel.send(new GenericMessage<>("ABC")); Message message = outputChannel.receive(1000); assertEquals("test-ABC", message.getPayload()); - context.stop(); + context.close(); } @Test @@ -312,10 +315,10 @@ public void testTransformer() { TransformerAnnotationTestBean testBean = new TransformerAnnotationTestBean(); postProcessor.postProcessAfterInitialization(testBean, "testBean"); context.refresh(); - inputChannel.send(new GenericMessage("foo")); + inputChannel.send(new GenericMessage<>("foo")); Message reply = outputChannel.receive(0); assertEquals("FOO", reply.getPayload()); - context.stop(); + context.close(); } @@ -340,16 +343,20 @@ public void countdown(String input) { this.messageText = input; latch.countDown(); } + } public static class SimpleAnnotatedEndpointSubclass extends AnnotatedTestService { + } @MessageEndpoint public interface SimpleAnnotatedEndpointInterface { + String test(String input); + } @@ -358,8 +365,9 @@ public static class SimpleAnnotatedEndpointImplementation implements SimpleAnnot @Override @ServiceActivator(inputChannel = "inputChannel", outputChannel = "outputChannel") public String test(String input) { - return "test-" + input; + return "test-" + input; } + } @@ -381,6 +389,7 @@ public void eventBus(Object payload) { public Boolean getInvoked() { return invoked.get(); } + } @@ -391,6 +400,7 @@ public static class TransformerAnnotationTestBean { public String transformBefore(String input) { return input.toUpperCase(); } + } public static class ServiceActivatorAdvice extends AbstractRequestHandlerAdvice { @@ -406,6 +416,7 @@ protected Object doInvoke(ExecutionCallback callback, Object target, Message @Retention(RetentionPolicy.RUNTIME) @ServiceActivator(inputChannel = "eventBus") public static @interface EventHandler { + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/RouterAnnotationPostProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/RouterAnnotationPostProcessorTests.java index 8cabd8754e7..45dc5e17933 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/RouterAnnotationPostProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/RouterAnnotationPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import java.util.Collections; import java.util.List; +import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -61,6 +62,10 @@ public void init() { context.registerChannel("stringChannel", stringChannel); } + @After + public void tearDown() { + this.context.close(); + } @Test public void testRouter() { @@ -70,7 +75,7 @@ public void testRouter() { TestRouter testRouter = new TestRouter(); postProcessor.postProcessAfterInitialization(testRouter, "test"); context.refresh(); - inputChannel.send(new GenericMessage("foo")); + inputChannel.send(new GenericMessage<>("foo")); Message replyMessage = outputChannel.receive(0); assertEquals("foo", replyMessage.getPayload()); context.stop(); @@ -90,7 +95,7 @@ public void testRouterWithListParam() { assertEquals(Collections.singletonList("foo"), replyMessage.getPayload()); // The SpEL ReflectiveMethodExecutor does a conversion of a single value to a List - routingChannel.send(new GenericMessage(2)); + routingChannel.send(new GenericMessage<>(2)); replyMessage = integerChannel.receive(0); assertEquals(2, replyMessage.getPayload()); context.stop(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/SplitterAnnotationPostProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/SplitterAnnotationPostProcessorTests.java index b9114047479..00f7680d92c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/SplitterAnnotationPostProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/SplitterAnnotationPostProcessorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,6 +22,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -55,16 +56,20 @@ public void init() { context.registerChannel("output", outputChannel); } + @After + public void tearDown() { + this.context.close(); + } @Test - public void testSplitterAnnotation() throws InterruptedException { + public void testSplitterAnnotation() { MessagingAnnotationPostProcessor postProcessor = new MessagingAnnotationPostProcessor(); postProcessor.setBeanFactory(context.getBeanFactory()); postProcessor.afterPropertiesSet(); TestSplitter splitter = new TestSplitter(); postProcessor.postProcessAfterInitialization(splitter, "testSplitter"); context.refresh(); - inputChannel.send(new GenericMessage("this.is.a.test")); + inputChannel.send(new GenericMessage<>("this.is.a.test")); Message message1 = outputChannel.receive(500); assertNotNull(message1); assertEquals("this", message1.getPayload()); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/FailOverDispatcherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/FailOverDispatcherTests.java index a80a9db77da..269e5043812 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/FailOverDispatcherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dispatcher/FailOverDispatcherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @@ -26,6 +27,7 @@ import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.MessageRejectedException; import org.springframework.integration.handler.ServiceActivatingHandler; import org.springframework.integration.message.TestHandlers; @@ -46,8 +48,7 @@ public void singleMessage() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); dispatcher.addHandler(createConsumer(TestHandlers.countDownHandler(latch))); dispatcher.dispatch(new GenericMessage<>("test")); - latch.await(500, TimeUnit.MILLISECONDS); - assertEquals(0, latch.getCount()); + assertTrue(latch.await(500, TimeUnit.MILLISECONDS)); } @Test @@ -59,8 +60,7 @@ public void pointToPoint() throws InterruptedException { dispatcher.addHandler(createConsumer(TestHandlers.countingCountDownHandler(counter1, latch))); dispatcher.addHandler(createConsumer(TestHandlers.countingCountDownHandler(counter2, latch))); dispatcher.dispatch(new GenericMessage<>("test")); - latch.await(500, TimeUnit.MILLISECONDS); - assertEquals(0, latch.getCount()); + assertTrue(latch.await(500, TimeUnit.MILLISECONDS)); assertEquals("only 1 handler should have received the message", 1, counter1.get() + counter2.get()); } @@ -201,7 +201,10 @@ public void allHandlersReturnFalse() { private static ServiceActivatingHandler createConsumer(Object object) { - return new ServiceActivatingHandler(object); + ServiceActivatingHandler handler = new ServiceActivatingHandler(object); + handler.setBeanFactory(mock(BeanFactory.class)); + handler.afterPropertiesSet(); + return handler; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/reactivestreams/ReactiveStreamsTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/reactivestreams/ReactiveStreamsTests.java index 5077253b00d..df5eeb3bc28 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/reactivestreams/ReactiveStreamsTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/reactivestreams/ReactiveStreamsTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2018 the original author or authors. + * Copyright 2016-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,6 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; import java.util.stream.Collectors; import org.junit.Test; @@ -113,7 +112,7 @@ public void testReactiveFlow() throws Exception { }); this.messageSource.start(); assertTrue(latch.await(10, TimeUnit.SECONDS)); - String[] strings = results.toArray(new String[results.size()]); + String[] strings = results.toArray(new String[0]); assertArrayEquals(new String[] { "A", "B", "C", "D", "E", "F" }, strings); this.messageSource.stop(); } @@ -127,7 +126,6 @@ public void testPollableReactiveFlow() throws Exception { Flux.from(this.pollablePublisher) .take(6) .filter(m -> m.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER)) - .log("org.springframework.integration.flux2", Level.WARNING) .doOnNext(p -> latch.countDown()) .subscribe(); @@ -138,11 +136,10 @@ public void testPollableReactiveFlow() throws Exception { .map(v -> v.split(",")) .flatMapIterable(Arrays::asList) .map(Integer::parseInt) - .>map(GenericMessage::new) + .>map(GenericMessage::new) .concatWith(this.pollablePublisher) .take(7) .map(Message::getPayload) - .log("org.springframework.integration.flux", Level.WARNING) .collectList() .block(Duration.ofSeconds(10)) ); @@ -163,14 +160,12 @@ public void testFromPublisher() { .map(v -> v.split(",")) .flatMapIterable(Arrays::asList) .map(Integer::parseInt) - .log("org.springframework.integration.flux") - .map(GenericMessage::new); + .map(GenericMessage::new); QueueChannel resultChannel = new QueueChannel(); IntegrationFlow integrationFlow = IntegrationFlows.from(messageFlux) - .log("org.springframework.integration.flux2") .transform(p -> p * 2) .channel(resultChannel) .get(); 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 21efa73e194..28b45a4883b 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 @@ -18,9 +18,11 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; @@ -45,6 +47,8 @@ public void testCorrelationIdPassedIfAvailable() { QueueChannel outputChannel = new QueueChannel(1); ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(new TestBean(), "upperCase"); serviceActivator.setOutputChannel(outputChannel); + serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, serviceActivator); endpoint.start(); assertTrue(inputChannel.send(message)); @@ -60,16 +64,18 @@ public void testCorrelationIdCopiedFromMessageCorrelationIdIfAvailable() { QueueChannel outputChannel = new QueueChannel(1); ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(new TestBean(), "upperCase"); serviceActivator.setOutputChannel(outputChannel); + serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, serviceActivator); endpoint.start(); assertTrue(inputChannel.send(message)); Message reply = outputChannel.receive(0); - assertEquals(new IntegrationMessageHeaderAccessor(message).getCorrelationId(), new IntegrationMessageHeaderAccessor(reply).getCorrelationId()); - assertTrue(new IntegrationMessageHeaderAccessor(message).getCorrelationId().equals(new IntegrationMessageHeaderAccessor(reply).getCorrelationId())); + assertEquals(new IntegrationMessageHeaderAccessor(message).getCorrelationId(), + new IntegrationMessageHeaderAccessor(reply).getCorrelationId()); } @Test - public void testCorrelationNotPassedFromRequestHeaderIfAlreadySetByHandler() throws Exception { + public void testCorrelationNotPassedFromRequestHeaderIfAlreadySetByHandler() { Object correlationId = "123-ABC"; Message message = MessageBuilder.withPayload("test") .setCorrelationId(correlationId).build(); @@ -77,6 +83,8 @@ public void testCorrelationNotPassedFromRequestHeaderIfAlreadySetByHandler() thr QueueChannel outputChannel = new QueueChannel(1); ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(new TestBean(), "createMessage"); serviceActivator.setOutputChannel(outputChannel); + serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, serviceActivator); endpoint.start(); assertTrue(inputChannel.send(message)); @@ -91,6 +99,8 @@ public void testCorrelationNotCopiedFromRequestMessgeIdIfAlreadySetByHandler() t QueueChannel outputChannel = new QueueChannel(1); ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(new TestBean(), "createMessage"); serviceActivator.setOutputChannel(outputChannel); + serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.afterPropertiesSet(); EventDrivenConsumer endpoint = new EventDrivenConsumer(inputChannel, serviceActivator); endpoint.start(); assertTrue(inputChannel.send(message)); @@ -105,6 +115,8 @@ public void testCorrelationIdWithSplitterWhenNotValueSetOnIncomingMessage() thro MethodInvokingSplitter splitter = new MethodInvokingSplitter( new TestBean(), TestBean.class.getMethod("split", String.class)); splitter.setOutputChannel(testChannel); + splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.afterPropertiesSet(); splitter.handleMessage(message); Message reply1 = testChannel.receive(100); Message reply2 = testChannel.receive(100); @@ -114,20 +126,23 @@ public void testCorrelationIdWithSplitterWhenNotValueSetOnIncomingMessage() thro @Test public void testCorrelationIdWithSplitterWhenValueSetOnIncomingMessage() throws Exception { - final String correlationIdForTest = "#FOR_TEST#"; Message message = MessageBuilder.withPayload("test1,test2").setCorrelationId(correlationIdForTest).build(); QueueChannel testChannel = new QueueChannel(); MethodInvokingSplitter splitter = new MethodInvokingSplitter( new TestBean(), TestBean.class.getMethod("split", String.class)); splitter.setOutputChannel(testChannel); + splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.afterPropertiesSet(); splitter.handleMessage(message); Message reply1 = testChannel.receive(100); Message reply2 = testChannel.receive(100); assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(reply1).getCorrelationId()); assertEquals(message.getHeaders().getId(), new IntegrationMessageHeaderAccessor(reply2).getCorrelationId()); - assertTrue("Sequence details missing", reply1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); - assertTrue("Sequence details missing", reply2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertTrue("Sequence details missing", + reply1.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); + assertTrue("Sequence details missing", + reply2.getHeaders().containsKey(IntegrationMessageHeaderAccessor.SEQUENCE_DETAILS)); } @SuppressWarnings("unused") 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 a44719b516f..40050777e76 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.After; import org.junit.Test; import org.springframework.integration.channel.DirectChannel; @@ -44,10 +45,18 @@ * @author Gary Russell * @author Kris Jacyna * @author Artem Bilan + * * @since 2.0.1 */ public class MessageProducerSupportTests { + private TestApplicationContext context = TestUtils.createTestApplicationContext(); + + @After + public void tearDown() { + this.context.close(); + } + @Test(expected = MessageDeliveryException.class) public void validateExceptionIfNoErrorChannel() { DirectChannel outChannel = new DirectChannel(); @@ -55,12 +64,14 @@ public void validateExceptionIfNoErrorChannel() { outChannel.subscribe(message -> { throw new RuntimeException("problems"); }); - MessageProducerSupport mps = new MessageProducerSupport() { }; + MessageProducerSupport mps = new MessageProducerSupport() { + + }; mps.setOutputChannel(outChannel); - mps.setBeanFactory(TestUtils.createTestApplicationContext()); + mps.setBeanFactory(this.context); mps.afterPropertiesSet(); mps.start(); - mps.sendMessage(new GenericMessage("hello")); + mps.sendMessage(new GenericMessage<>("hello")); } @Test(expected = MessageDeliveryException.class) @@ -73,54 +84,57 @@ public void validateExceptionIfSendToErrorChannelFails() { errorChannel.subscribe(message -> { throw new RuntimeException("ooops"); }); - MessageProducerSupport mps = new MessageProducerSupport() { }; + MessageProducerSupport mps = new MessageProducerSupport() { + + }; mps.setOutputChannel(outChannel); mps.setErrorChannel(errorChannel); - mps.setBeanFactory(TestUtils.createTestApplicationContext()); + mps.setBeanFactory(this.context); mps.afterPropertiesSet(); mps.start(); - mps.sendMessage(new GenericMessage("hello")); + mps.sendMessage(new GenericMessage<>("hello")); } @Test public void validateSuccessfulErrorFlowDoesNotThrowErrors() { - TestApplicationContext testApplicationContext = TestUtils.createTestApplicationContext(); - testApplicationContext.refresh(); + this.context.refresh(); DirectChannel outChannel = new DirectChannel(); outChannel.subscribe(message -> { throw new RuntimeException("problems"); }); PublishSubscribeChannel errorChannel = new PublishSubscribeChannel(); SuccessfulErrorService errorService = new SuccessfulErrorService(); - ServiceActivatingHandler handler = new ServiceActivatingHandler(errorService); - handler.setBeanFactory(testApplicationContext); + ServiceActivatingHandler handler = new ServiceActivatingHandler(errorService); + handler.setBeanFactory(this.context); handler.afterPropertiesSet(); errorChannel.subscribe(handler); - MessageProducerSupport mps = new MessageProducerSupport() { }; + MessageProducerSupport mps = new MessageProducerSupport() { + + }; mps.setOutputChannel(outChannel); mps.setErrorChannel(errorChannel); - mps.setBeanFactory(testApplicationContext); + mps.setBeanFactory(this.context); mps.afterPropertiesSet(); mps.start(); - Message message = new GenericMessage("hello"); + Message message = new GenericMessage<>("hello"); mps.sendMessage(message); assertThat(errorService.lastMessage, instanceOf(ErrorMessage.class)); ErrorMessage errorMessage = (ErrorMessage) errorService.lastMessage; assertEquals(MessageDeliveryException.class, errorMessage.getPayload().getClass()); MessageDeliveryException exception = (MessageDeliveryException) errorMessage.getPayload(); assertEquals(message, exception.getFailedMessage()); - testApplicationContext.close(); } @Test public void testWithChannelName() { DirectChannel outChannel = new DirectChannel(); - MessageProducerSupport mps = new MessageProducerSupport() { }; + MessageProducerSupport mps = new MessageProducerSupport() { + + }; mps.setOutputChannelName("foo"); - TestApplicationContext testApplicationContext = TestUtils.createTestApplicationContext(); - testApplicationContext.registerBean("foo", outChannel); - testApplicationContext.refresh(); - mps.setBeanFactory(testApplicationContext); + this.context.registerBean("foo", outChannel); + this.context.refresh(); + mps.setBeanFactory(this.context); mps.afterPropertiesSet(); mps.start(); assertSame(outChannel, mps.getOutputChannel()); @@ -152,6 +166,7 @@ private static class SuccessfulErrorService { public void handleErrorMessage(Message errorMessage) { this.lastMessage = errorMessage; } + } private static class CustomEndpoint extends AbstractEndpoint { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java index 5530bda9501..bfd76ee83e3 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,7 @@ package org.springframework.integration.endpoint; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; @@ -47,7 +47,7 @@ public class ServiceActivatorEndpointTests { @Test public void outputChannel() { QueueChannel channel = new QueueChannel(1); - ServiceActivatingHandler endpoint = this.createEndpoint(); + ServiceActivatingHandler endpoint = createEndpoint(); endpoint.setOutputChannel(channel); Message message = MessageBuilder.withPayload("foo").build(); endpoint.handleMessage(message); @@ -60,7 +60,7 @@ public void outputChannel() { public void outputChannelTakesPrecedence() { QueueChannel channel1 = new QueueChannel(1); QueueChannel channel2 = new QueueChannel(1); - ServiceActivatingHandler endpoint = this.createEndpoint(); + ServiceActivatingHandler endpoint = createEndpoint(); endpoint.setOutputChannel(channel1); Message message = MessageBuilder.withPayload("foo").setReplyChannel(channel2).build(); endpoint.handleMessage(message); @@ -163,9 +163,10 @@ public void noReplyTarget() { @Test public void noReplyMessage() { QueueChannel channel = new QueueChannel(1); - ServiceActivatingHandler endpoint = new ServiceActivatingHandler( - new TestNullReplyBean(), "handle"); + ServiceActivatingHandler endpoint = new ServiceActivatingHandler(new TestNullReplyBean(), "handle"); endpoint.setOutputChannel(channel); + endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.afterPropertiesSet(); Message message = MessageBuilder.withPayload("foo").build(); endpoint.handleMessage(message); assertNull(channel.receive(0)); @@ -174,10 +175,11 @@ public void noReplyMessage() { @Test(expected = ReplyRequiredException.class) public void noReplyMessageWithRequiresReply() { QueueChannel channel = new QueueChannel(1); - ServiceActivatingHandler endpoint = new ServiceActivatingHandler( - new TestNullReplyBean(), "handle"); + ServiceActivatingHandler endpoint = new ServiceActivatingHandler(new TestNullReplyBean(), "handle"); endpoint.setRequiresReply(true); endpoint.setOutputChannel(channel); + endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.afterPropertiesSet(); Message message = MessageBuilder.withPayload("foo").build(); endpoint.handleMessage(message); } @@ -185,13 +187,17 @@ public void noReplyMessageWithRequiresReply() { @Test public void correlationIdNotSetIfMessageIsReturnedUnaltered() { QueueChannel replyChannel = new QueueChannel(1); - ServiceActivatingHandler endpoint = new ServiceActivatingHandler(new Object() { + ServiceActivatingHandler endpoint = + new ServiceActivatingHandler(new Object() { + + @SuppressWarnings("unused") + public Message handle(Message message) { + return message; + } + }, "handle"); + endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.afterPropertiesSet(); - @SuppressWarnings("unused") - public Message handle(Message message) { - return message; - } - }, "handle"); Message message = MessageBuilder.withPayload("test") .setReplyChannel(replyChannel).build(); endpoint.handleMessage(message); @@ -202,20 +208,24 @@ public Message handle(Message message) { @Test public void correlationIdSetByHandlerTakesPrecedence() { QueueChannel replyChannel = new QueueChannel(1); - ServiceActivatingHandler endpoint = new ServiceActivatingHandler(new Object() { + ServiceActivatingHandler endpoint = + new ServiceActivatingHandler(new Object() { + + @SuppressWarnings("unused") + public Message handle(Message message) { + return MessageBuilder.fromMessage(message) + .setCorrelationId("ABC-123").build(); + } + }, "handle"); + endpoint.setBeanFactory(mock(BeanFactory.class)); + endpoint.afterPropertiesSet(); - @SuppressWarnings("unused") - public Message handle(Message message) { - return MessageBuilder.fromMessage(message) - .setCorrelationId("ABC-123").build(); - } - }, "handle"); Message message = MessageBuilder.withPayload("test") .setReplyChannel(replyChannel).build(); endpoint.handleMessage(message); Message reply = replyChannel.receive(500); Object correlationId = new IntegrationMessageHeaderAccessor(reply).getCorrelationId(); - assertFalse(message.getHeaders().getId().equals(correlationId)); + assertNotEquals(message.getHeaders().getId(), correlationId); assertEquals("ABC-123", correlationId); } @@ -232,7 +242,10 @@ public void testBeanFactoryPopulation() { private ServiceActivatingHandler createEndpoint() { - return new ServiceActivatingHandler(new TestBean(), "handle"); + ServiceActivatingHandler handler = new ServiceActivatingHandler(new TestBean(), "handle"); + handler.setBeanFactory(mock(BeanFactory.class)); + handler.afterPropertiesSet(); + return handler; } @@ -240,8 +253,9 @@ private static class TestBean { @SuppressWarnings("unused") public Message handle(Message message) { - return new GenericMessage(message.getPayload().toString().toUpperCase()); + return new GenericMessage<>(message.getPayload().toString().toUpperCase()); } + } @@ -251,6 +265,7 @@ private static class TestNullReplyBean { public Message handle(Message message) { return null; } + } } 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 6b5cb868926..6356eb45ee3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,11 +19,13 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertSame; +import static org.mockito.Mockito.mock; import java.util.Date; import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.annotation.ServiceActivator; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.gateway.RequestReplyExchanger; @@ -36,6 +38,7 @@ /** * @author Mark Fisher * @author Gary Russell + * @author Artem Bilan */ public class ServiceActivatorMethodResolutionTests { @@ -45,7 +48,10 @@ public void singleAnnotationMatches() { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); QueueChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); - serviceActivator.handleMessage(new GenericMessage("foo")); + serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.afterPropertiesSet(); + + serviceActivator.handleMessage(new GenericMessage<>("foo")); Message result = outputChannel.receive(0); assertEquals("FOO", result.getPayload()); } @@ -62,7 +68,10 @@ public void singlePublicMethodMatches() { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); QueueChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); - serviceActivator.handleMessage(new GenericMessage("foo")); + serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.afterPropertiesSet(); + + serviceActivator.handleMessage(new GenericMessage<>("foo")); Message result = outputChannel.receive(0); assertEquals("FOO", result.getPayload()); } @@ -76,13 +85,7 @@ public void multiplePublicMethodFails() { @Test public void testRequestReplyExchanger() { - RequestReplyExchanger testBean = new RequestReplyExchanger() { - - @Override - public Message exchange(Message request) { - return request; - } - }; + RequestReplyExchanger testBean = request -> request; final Message test = new GenericMessage("foo"); @@ -95,6 +98,8 @@ protected Object handleRequestMessage(Message message) { return null; } }; + serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.afterPropertiesSet(); serviceActivator.handleMessage(test); } @@ -120,6 +125,8 @@ public String foo(String request) { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); PollableChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); + serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.afterPropertiesSet(); Message test = new GenericMessage(new Date()); serviceActivator.handleMessage(test); @@ -151,6 +158,8 @@ public String foo(Message request) { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); PollableChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); + serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.afterPropertiesSet(); Message test = new GenericMessage(new Date()); serviceActivator.handleMessage(test); @@ -187,6 +196,8 @@ public String bar(Message request) { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); PollableChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); + serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.afterPropertiesSet(); Message test = new GenericMessage(new Date()); serviceActivator.handleMessage(test); @@ -223,6 +234,8 @@ public String bar(String request) { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); PollableChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); + serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.afterPropertiesSet(); Message test = new GenericMessage(new Date()); serviceActivator.handleMessage(test); @@ -239,6 +252,9 @@ public void nullOk() { ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(testBean); QueueChannel outputChannel = new QueueChannel(); serviceActivator.setOutputChannel(outputChannel); + serviceActivator.setBeanFactory(mock(BeanFactory.class)); + serviceActivator.afterPropertiesSet(); + serviceActivator.handleMessage(new GenericMessage<>(new KafkaNull())); Message result = outputChannel.receive(0); assertEquals("gotNull", result.getPayload()); 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 7ed3dfc29ed..29416826063 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2013 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,11 +18,13 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; import java.lang.reflect.Method; import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; import org.springframework.messaging.Message; import org.springframework.messaging.support.GenericMessage; @@ -30,62 +32,72 @@ * @author Mark Fisher * @author Oleg Zhurakousky * @author Gunnar Hillert + * @author Artem Bilan */ public class MethodInvokingSelectorTests { @Test public void acceptedWithMethodName() { MethodInvokingSelector selector = new MethodInvokingSelector(new TestBean(), "acceptString"); - assertTrue(selector.accept(new GenericMessage("should accept"))); + selector.setBeanFactory(mock(BeanFactory.class)); + assertTrue(selector.accept(new GenericMessage<>("should accept"))); } @Test public void acceptedWithMethodReference() throws Exception { TestBean testBean = new TestBean(); - Method method = testBean.getClass().getMethod("acceptString", new Class[] { Message.class }); + Method method = testBean.getClass().getMethod("acceptString", Message.class); MethodInvokingSelector selector = new MethodInvokingSelector(testBean, method); - assertTrue(selector.accept(new GenericMessage("should accept"))); + selector.setBeanFactory(mock(BeanFactory.class)); + assertTrue(selector.accept(new GenericMessage<>("should accept"))); } @Test public void rejectedWithMethodName() { MethodInvokingSelector selector = new MethodInvokingSelector(new TestBean(), "acceptString"); - assertFalse(selector.accept(new GenericMessage(99))); + selector.setBeanFactory(mock(BeanFactory.class)); + assertFalse(selector.accept(new GenericMessage<>(99))); } @Test public void rejectedWithMethodReference() throws Exception { TestBean testBean = new TestBean(); - Method method = testBean.getClass().getMethod("acceptString", new Class[] { Message.class }); + Method method = testBean.getClass().getMethod("acceptString", Message.class); MethodInvokingSelector selector = new MethodInvokingSelector(testBean, method); - assertFalse(selector.accept(new GenericMessage(99))); + selector.setBeanFactory(mock(BeanFactory.class)); + assertFalse(selector.accept(new GenericMessage<>(99))); } @Test public void noArgMethodWithMethodName() { MethodInvokingSelector selector = new MethodInvokingSelector(new TestBean(), "noArgs"); - selector.accept(new GenericMessage("test")); + selector.setBeanFactory(mock(BeanFactory.class)); + assertTrue(selector.accept(new GenericMessage<>("test"))); } @Test public void noArgMethodWithMethodReference() throws Exception { TestBean testBean = new TestBean(); - Method method = testBean.getClass().getMethod("noArgs", new Class[] {}); - new MethodInvokingSelector(testBean, method); + Method method = testBean.getClass().getMethod("noArgs"); + MethodInvokingSelector selector = new MethodInvokingSelector(testBean, method); + selector.setBeanFactory(mock(BeanFactory.class)); + assertTrue(selector.accept(new GenericMessage<>("test"))); } @Test(expected = IllegalArgumentException.class) public void voidReturningMethodWithMethodName() { MethodInvokingSelector selector = new MethodInvokingSelector(new TestBean(), "returnVoid"); - selector.accept(new GenericMessage("test")); + selector.setBeanFactory(mock(BeanFactory.class)); + selector.accept(new GenericMessage<>("test")); } @Test(expected = IllegalArgumentException.class) public void voidReturningMethodWithMethodReference() throws Exception { TestBean testBean = new TestBean(); - Method method = testBean.getClass().getMethod("returnVoid", new Class[] { Message.class }); + Method method = testBean.getClass().getMethod("returnVoid", Message.class); MethodInvokingSelector selector = new MethodInvokingSelector(testBean, method); - selector.accept(new GenericMessage("test")); + selector.setBeanFactory(mock(BeanFactory.class)); + selector.accept(new GenericMessage<>("test")); } @@ -106,6 +118,7 @@ public void returnVoid(Message message) { public boolean noArgs() { return true; } + } } 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 2ee0c8937c3..1158a64f274 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -389,8 +389,8 @@ public void testIdHeaderOverrideHeaderExpression() { } catch (Exception e) { assertThat(e, instanceOf(BeanInitializationException.class)); - assertThat(e - .getMessage(), containsString("Messaging Gateway cannot override 'id' and 'timestamp' read-only headers")); + assertThat(e.getMessage(), + containsString("Messaging Gateway cannot override 'id' and 'timestamp' read-only headers")); } } @@ -406,8 +406,8 @@ public void testIdHeaderOverrideGatewayHeaderAnnotation() { } catch (Exception e) { assertThat(e, instanceOf(BeanInitializationException.class)); - assertThat(e - .getMessage(), containsString("Messaging Gateway cannot override 'id' and 'timestamp' read-only headers")); + assertThat(e.getMessage(), + containsString("Messaging Gateway cannot override 'id' and 'timestamp' read-only headers")); } } @@ -423,48 +423,48 @@ public void testTimeStampHeaderOverrideParamHeaderAnnotation() { } catch (Exception e) { assertThat(e, instanceOf(BeanInitializationException.class)); - assertThat(e - .getMessage(), containsString("Messaging Gateway cannot override 'id' and 'timestamp' read-only headers")); + assertThat(e.getMessage(), + containsString("Messaging Gateway cannot override 'id' and 'timestamp' read-only headers")); } } -// @Test -// public void testHistory() throws Exception { -// GenericApplicationContext context = new GenericApplicationContext(); -// context.getBeanFactory().registerSingleton("historyWriter", new MessageHistoryWriter()); -// GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean(); -// proxyFactory.setBeanFactory(context); -// proxyFactory.setBeanName("testGateway"); -// DirectChannel channel = new DirectChannel(); -// channel.setBeanName("testChannel"); -// channel.setBeanFactory(context); -// channel.afterPropertiesSet(); -// BridgeHandler bridgeHandler = new BridgeHandler(); -// bridgeHandler.setBeanFactory(context); -// bridgeHandler.afterPropertiesSet(); -// bridgeHandler.setBeanName("testBridge"); -// EventDrivenConsumer consumer = new EventDrivenConsumer(channel, bridgeHandler); -// consumer.setBeanFactory(context); -// consumer.afterPropertiesSet(); -// consumer.start(); -// proxyFactory.setDefaultRequestChannel(channel); -// proxyFactory.setServiceInterface(TestEchoService.class); -// proxyFactory.afterPropertiesSet(); -// TestEchoService proxy = (TestEchoService) proxyFactory.getObject(); -// Message message = proxy.echo("test"); -// Iterator historyIterator = message.getHeaders().getHistory().iterator(); -// MessageHistoryEvent event1 = historyIterator.next(); -// MessageHistoryEvent event2 = historyIterator.next(); -// MessageHistoryEvent event3 = historyIterator.next(); -// -// //assertEquals("echo", event1.getAttribute("method", String.class)); -// assertEquals("gateway", event1.getType()); -// assertEquals("testGateway", event1.getName()); -// assertEquals("channel", event2.getType()); -// assertEquals("testChannel", event2.getName()); -// assertEquals("bridge", event3.getType()); -// assertEquals("testBridge", event3.getName()); -// } + // @Test + // public void testHistory() throws Exception { + // GenericApplicationContext context = new GenericApplicationContext(); + // context.getBeanFactory().registerSingleton("historyWriter", new MessageHistoryWriter()); + // GatewayProxyFactoryBean proxyFactory = new GatewayProxyFactoryBean(); + // proxyFactory.setBeanFactory(context); + // proxyFactory.setBeanName("testGateway"); + // DirectChannel channel = new DirectChannel(); + // channel.setBeanName("testChannel"); + // channel.setBeanFactory(context); + // channel.afterPropertiesSet(); + // BridgeHandler bridgeHandler = new BridgeHandler(); + // bridgeHandler.setBeanFactory(context); + // bridgeHandler.afterPropertiesSet(); + // bridgeHandler.setBeanName("testBridge"); + // EventDrivenConsumer consumer = new EventDrivenConsumer(channel, bridgeHandler); + // consumer.setBeanFactory(context); + // consumer.afterPropertiesSet(); + // consumer.start(); + // proxyFactory.setDefaultRequestChannel(channel); + // proxyFactory.setServiceInterface(TestEchoService.class); + // proxyFactory.afterPropertiesSet(); + // TestEchoService proxy = (TestEchoService) proxyFactory.getObject(); + // Message message = proxy.echo("test"); + // Iterator historyIterator = message.getHeaders().getHistory().iterator(); + // MessageHistoryEvent event1 = historyIterator.next(); + // MessageHistoryEvent event2 = historyIterator.next(); + // MessageHistoryEvent event3 = historyIterator.next(); + // + // //assertEquals("echo", event1.getAttribute("method", String.class)); + // assertEquals("gateway", event1.getType()); + // assertEquals("testGateway", event1.getName()); + // assertEquals("channel", event2.getType()); + // assertEquals("testChannel", event2.getName()); + // assertEquals("bridge", event3.getType()); + // assertEquals("testBridge", event3.getName()); + // } @Test public void autowiredGateway() { @@ -474,6 +474,7 @@ public void autowiredGateway() { @Test public void testOverriddenMethod() { GatewayProxyFactoryBean gpfb = new GatewayProxyFactoryBean(InheritChild.class); + gpfb.setBeanFactory(mock(BeanFactory.class)); gpfb.afterPropertiesSet(); Map gateways = gpfb.getGateways(); assertThat(gateways.size(), equalTo(2)); 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 77180db506d..7e5d0a0bd18 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,13 +19,17 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.UUID; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -52,6 +56,8 @@ @SuppressWarnings("unchecked") public class MessagingGatewayTests { + private final TestApplicationContext applicationContext = TestUtils.createTestApplicationContext(); + private volatile MessagingGatewaySupport messagingGateway; private volatile MessageChannel requestChannel = Mockito.mock(MessageChannel.class); @@ -63,18 +69,25 @@ public class MessagingGatewayTests { @Before public void initializeSample() { - this.messagingGateway = new MessagingGatewaySupport() { }; - this.messagingGateway.setRequestChannel(requestChannel); - this.messagingGateway.setReplyChannel(replyChannel); - TestApplicationContext applicationContext = TestUtils.createTestApplicationContext(); - this.messagingGateway.setBeanFactory(applicationContext); + this.messagingGateway = new MessagingGatewaySupport() { + + }; + this.messagingGateway.setRequestChannel(this.requestChannel); + this.messagingGateway.setReplyChannel(this.replyChannel); + + this.messagingGateway.setBeanFactory(this.applicationContext); this.messagingGateway.setCountsEnabled(true); this.messagingGateway.afterPropertiesSet(); this.messagingGateway.start(); - applicationContext.refresh(); + this.applicationContext.refresh(); Mockito.when(this.messageMock.getHeaders()).thenReturn(new MessageHeaders(Collections.emptyMap())); } + @After + public void tearDown() { + this.messagingGateway.stop(); + this.applicationContext.close(); + } /* send tests */ @@ -157,7 +170,7 @@ public void sendObjectAndReceiveObject() { @Test public void sendMessageAndReceiveObject() { - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put(MessageHeaders.ID, UUID.randomUUID()); MessageHeaders messageHeadersMock = new MessageHeaders(headers); Mockito.when(replyChannel.receive(0)).thenReturn(messageMock); @@ -199,7 +212,7 @@ public void sendObjectAndReceiveMessage() { @Test public void sendMessageAndReceiveMessage() { - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put(MessageHeaders.ID, UUID.randomUUID()); headers.put(MessageHeaders.REPLY_CHANNEL, replyChannel); MessageHeaders messageHeadersMock = new MessageHeaders(headers); @@ -224,45 +237,47 @@ public void sendNullAndReceiveMessage() { // should fail but it doesn't now @Test(expected = MessagingException.class) - public void validateErroMessageCanNotBeReplyMessage() { + public void validateErrorMessageCanNotBeReplyMessage() { DirectChannel reqChannel = new DirectChannel(); reqChannel.subscribe(message -> { throw new RuntimeException("ooops"); }); PublishSubscribeChannel errorChannel = new PublishSubscribeChannel(); - ServiceActivatingHandler handler = new ServiceActivatingHandler(new MyErrorService()); - handler.setBeanFactory(mock(BeanFactory.class)); + ServiceActivatingHandler handler = new ServiceActivatingHandler(new MyErrorService()); + handler.setBeanFactory(this.applicationContext); handler.afterPropertiesSet(); errorChannel.subscribe(handler); - this.messagingGateway = new MessagingGatewaySupport() { }; + this.messagingGateway = new MessagingGatewaySupport() { + + }; this.messagingGateway.setRequestChannel(reqChannel); this.messagingGateway.setErrorChannel(errorChannel); this.messagingGateway.setReplyChannel(null); - this.messagingGateway.setBeanFactory(mock(BeanFactory.class)); + this.messagingGateway.setBeanFactory(this.applicationContext); this.messagingGateway.afterPropertiesSet(); this.messagingGateway.start(); this.messagingGateway.sendAndReceiveMessage("hello"); } - // should not fail but it does now @Test - public void validateErrorChannelWithSuccessfulReply() { - TestUtils.TestApplicationContext testApplicationContext = TestUtils.createTestApplicationContext(); - testApplicationContext.refresh(); + public void validateErrorChannelWithSuccessfulReply() throws InterruptedException { DirectChannel reqChannel = new DirectChannel(); reqChannel.subscribe(message -> { throw new RuntimeException("ooops"); }); PublishSubscribeChannel errorChannel = new PublishSubscribeChannel(); - ServiceActivatingHandler handler = new ServiceActivatingHandler(new MyOneWayErrorService()); - handler.setBeanFactory(testApplicationContext); + MyOneWayErrorService myOneWayErrorService = new MyOneWayErrorService(); + ServiceActivatingHandler handler = new ServiceActivatingHandler(myOneWayErrorService); + handler.setBeanFactory(this.applicationContext); handler.afterPropertiesSet(); errorChannel.subscribe(handler); - this.messagingGateway = new MessagingGatewaySupport() { }; + this.messagingGateway = new MessagingGatewaySupport() { + + }; this.messagingGateway.setRequestChannel(reqChannel); this.messagingGateway.setErrorChannel(errorChannel); @@ -272,7 +287,8 @@ public void validateErrorChannelWithSuccessfulReply() { this.messagingGateway.start(); this.messagingGateway.send("hello"); - testApplicationContext.close(); + + assertTrue(myOneWayErrorService.errorReceived.await(10, TimeUnit.SECONDS)); } public static class MyErrorService { @@ -285,7 +301,10 @@ public Message handleErrorMessage(Message errorMessage) { public static class MyOneWayErrorService { + private final CountDownLatch errorReceived = new CountDownLatch(1); + public void handleErrorMessage(Message errorMessage) { + this.errorReceived.countDown(); } } 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 f213e1ef2d6..c2cf9c3668a 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -89,6 +89,8 @@ public class DelayHandlerTests { private final ResultHandler resultHandler = new ResultHandler(); + private TestApplicationContext context = TestUtils.createTestApplicationContext(); + @Before public void setup() { input.setBeanName("input"); @@ -104,7 +106,8 @@ public void setup() { @After public void tearDown() { - taskScheduler.destroy(); + this.context.close(); + this.taskScheduler.destroy(); } private void setDelayExpression() { @@ -113,10 +116,9 @@ private void setDelayExpression() { } private void startDelayerHandler() { - delayHandler.afterPropertiesSet(); - TestApplicationContext ac = TestUtils.createTestApplicationContext(); - delayHandler.setApplicationContext(ac); - delayHandler.onApplicationEvent(new ContextRefreshedEvent(ac)); + this.delayHandler.setApplicationContext(this.context); + this.delayHandler.afterPropertiesSet(); + this.delayHandler.onApplicationEvent(new ContextRefreshedEvent(this.context)); } @Test @@ -466,6 +468,7 @@ public void testDoubleOnApplicationEvent() { this.delayHandler.onApplicationEvent(contextRefreshedEvent); this.delayHandler.onApplicationEvent(contextRefreshedEvent); Mockito.verify(this.delayHandler, Mockito.times(1)).reschedulePersistedMessages(); + ac.close(); } @Test(expected = MessageHandlingException.class) @@ -473,7 +476,7 @@ public void testInt2243IgnoreExpressionFailuresAsFalse() { this.setDelayExpression(); this.delayHandler.setIgnoreExpressionFailures(false); startDelayerHandler(); - this.delayHandler.handleMessage(new GenericMessage("test")); + this.delayHandler.handleMessage(new GenericMessage<>("test")); } @Test //INT-3560 diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingHeaderEnricherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingHeaderEnricherTests.java index d4bf100052f..0e155bac95d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingHeaderEnricherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingHeaderEnricherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; import java.util.Collections; import java.util.HashMap; @@ -28,6 +29,7 @@ import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.transformer.HeaderEnricher; @@ -49,6 +51,7 @@ public class MethodInvokingHeaderEnricherTests { public void emptyHeadersOnRequest() { TestBean testBean = new TestBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testBean, "process"); + processor.setBeanFactory(mock(BeanFactory.class)); HeaderEnricher enricher = new HeaderEnricher(); enricher.setMessageProcessor(processor); enricher.setDefaultOverwrite(true); @@ -63,6 +66,7 @@ public void emptyHeadersOnRequest() { public void overwriteFalseByDefault() { TestBean testBean = new TestBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testBean, "process"); + processor.setBeanFactory(mock(BeanFactory.class)); HeaderEnricher enricher = new HeaderEnricher(); enricher.setMessageProcessor(processor); Message message = MessageBuilder.withPayload("test").setHeader("bar", "XYZ").build(); @@ -76,6 +80,7 @@ public void overwriteFalseByDefault() { public void overwriteFalseExplicit() { TestBean testBean = new TestBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testBean, "process"); + processor.setBeanFactory(mock(BeanFactory.class)); HeaderEnricher enricher = new HeaderEnricher(); enricher.setMessageProcessor(processor); enricher.setDefaultOverwrite(false); @@ -90,6 +95,7 @@ public void overwriteFalseExplicit() { public void overwriteTrue() { TestBean testBean = new TestBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testBean, "process"); + processor.setBeanFactory(mock(BeanFactory.class)); HeaderEnricher enricher = new HeaderEnricher(); enricher.setMessageProcessor(processor); enricher.setDefaultOverwrite(true); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorAnnotationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorAnnotationTests.java index 55d46a3d810..874bba8faf5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorAnnotationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorAnnotationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,6 +21,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; import java.lang.reflect.Method; import java.util.Collections; @@ -38,6 +39,7 @@ import org.junit.Assert; import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; @@ -69,13 +71,14 @@ public class MethodInvokingMessageProcessorAnnotationTests { public void multiThreadsUUIDToStringConversion() throws Exception { Method method = TestService.class.getMethod("headerId", String.class, String.class); final MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); ExecutorService exec = Executors.newFixedThreadPool(100); - processor.processMessage(new GenericMessage("foo")); + processor.processMessage(new GenericMessage<>("foo")); for (int i = 0; i < 100; i++) { exec.execute(new Runnable() { public void run() { - Object result = processor.processMessage(new GenericMessage("foo")); + Object result = processor.processMessage(new GenericMessage<>("foo")); assertNotNull(result); } }); @@ -89,7 +92,8 @@ public void run() { public void optionalHeader() throws Exception { Method method = TestService.class.getMethod("optionalHeader", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - Object result = processor.processMessage(new GenericMessage("foo")); + processor.setBeanFactory(mock(BeanFactory.class)); + Object result = processor.processMessage(new GenericMessage<>("foo")); assertNull(result); } @@ -97,16 +101,18 @@ public void optionalHeader() throws Exception { public void requiredHeaderNotProvided() throws Exception { Method method = TestService.class.getMethod("requiredHeader", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - processor.processMessage(new GenericMessage("foo")); + processor.setBeanFactory(mock(BeanFactory.class)); + processor.processMessage(new GenericMessage<>("foo")); } @Test(expected = MessageHandlingException.class) public void requiredHeaderNotProvidedOnSecondMessage() throws Exception { Method method = TestService.class.getMethod("requiredHeader", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message messageWithHeader = MessageBuilder.withPayload("foo") .setHeader("num", 123).build(); - GenericMessage messageWithoutHeader = new GenericMessage("foo"); + GenericMessage messageWithoutHeader = new GenericMessage<>("foo"); processor.processMessage(messageWithHeader); processor.processMessage(messageWithoutHeader); @@ -118,6 +124,7 @@ public void fromMessageWithRequiredHeaderProvided() throws Exception { Message message = MessageBuilder.withPayload("foo") .setHeader("num", 123).build(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(message); assertEquals(123, result); } @@ -126,6 +133,7 @@ public void fromMessageWithRequiredHeaderProvided() throws Exception { public void fromMessageWithOptionalAndRequiredHeaderAndOnlyOptionalHeaderProvided() throws Exception { Method method = TestService.class.getMethod("optionalAndRequiredHeader", String.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo") .setHeader("prop", "bar").build(); processor.processMessage(message); @@ -135,6 +143,7 @@ public void fromMessageWithOptionalAndRequiredHeaderAndOnlyOptionalHeaderProvide public void fromMessageWithOptionalAndRequiredHeaderAndOnlyRequiredHeaderProvided() throws Exception { Method method = TestService.class.getMethod("optionalAndRequiredHeader", String.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo") .setHeader("num", 123).build(); Object result = processor.processMessage(message); @@ -145,6 +154,7 @@ public void fromMessageWithOptionalAndRequiredHeaderAndOnlyRequiredHeaderProvide public void fromMessageWithOptionalAndRequiredHeaderAndBothHeadersProvided() throws Exception { Method method = TestService.class.getMethod("optionalAndRequiredHeader", String.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo") .setHeader("num", 123) .setHeader("prop", "bar") @@ -157,6 +167,7 @@ public void fromMessageWithOptionalAndRequiredHeaderAndBothHeadersProvided() thr public void fromMessageWithPropertiesMethodAndHeadersAnnotation() throws Exception { Method method = TestService.class.getMethod("propertiesHeaders", Properties.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("test") .setHeader("prop1", "foo").setHeader("prop2", "bar").build(); assertFalse(TestUtils.getPropertyValue(processor, "delegate.handlerMethod.spelOnly", Boolean.class)); @@ -180,6 +191,7 @@ public void fromMessageWithPropertiesMethodAndHeadersAnnotation() throws Excepti public void fromMessageWithPropertiesAndObjectMethod() throws Exception { Method method = TestService.class.getMethod("propertiesHeadersAndPayload", Properties.class, Object.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("test") .setHeader("prop1", "foo").setHeader("prop2", "bar").build(); Object result = processor.processMessage(message); @@ -193,6 +205,7 @@ public void fromMessageWithPropertiesAndObjectMethod() throws Exception { public void fromMessageWithMapAndObjectMethod() throws Exception { Method method = TestService.class.getMethod("mapHeadersAndPayload", Map.class, Object.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("test") .setHeader("prop1", "foo").setHeader("prop2", "bar").build(); Map result = (Map) processor.processMessage(message); @@ -208,6 +221,7 @@ public void fromMessageWithMapAndObjectMethod() throws Exception { public void fromMessageWithPropertiesMethodAndPropertiesPayload() throws Exception { Method method = TestService.class.getMethod("propertiesPayload", Properties.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Properties payload = new Properties(); payload.setProperty("prop1", "foo"); payload.setProperty("prop2", "bar"); @@ -223,6 +237,7 @@ public void fromMessageWithPropertiesMethodAndPropertiesPayload() throws Excepti public void fromMessageWithMapMethodAndHeadersAnnotation() throws Exception { Method method = TestService.class.getMethod("mapHeaders", Map.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("test") .setHeader("attrib1", 123) .setHeader("attrib2", 456).build(); @@ -235,7 +250,8 @@ public void fromMessageWithMapMethodAndHeadersAnnotation() throws Exception { public void fromMessageWithMapMethodAndMapPayload() throws Exception { Method method = TestService.class.getMethod("mapPayload", Map.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - Map payload = new HashMap(); + processor.setBeanFactory(mock(BeanFactory.class)); + Map payload = new HashMap<>(); payload.put("attrib1", 88); payload.put("attrib2", 99); Message> message = MessageBuilder.withPayload(payload) @@ -252,6 +268,7 @@ public void headerAnnotationWithExpression() throws Exception { Message message = this.getMessage(); Method method = TestService.class.getMethod("headerAnnotationWithExpression", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(message); Assert.assertEquals("monday", result); } @@ -261,6 +278,7 @@ public void irrelevantAnnotation() throws Exception { Message message = MessageBuilder.withPayload("foo").build(); Method method = TestService.class.getMethod("irrelevantAnnotation", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(message); assertEquals("foo", result); } @@ -275,20 +293,22 @@ public void multipleAnnotatedArgs() throws Exception { String.class, Map.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Object[] parameters = (Object[]) processor.processMessage(message); - Assert.assertNotNull(parameters); - Assert.assertTrue(parameters.length == 5); - Assert.assertTrue(parameters[0].equals("monday")); - Assert.assertTrue(parameters[1].equals("September")); - Assert.assertTrue(parameters[2].equals(employee)); - Assert.assertTrue(parameters[3].equals("oleg")); - Assert.assertTrue(parameters[4] instanceof Map); + assertNotNull(parameters); + assertEquals(5, parameters.length); + assertEquals("monday", parameters[0]); + assertEquals("September", parameters[1]); + assertEquals(parameters[2], employee); + assertEquals("oleg", parameters[3]); + assertTrue(parameters[4] instanceof Map); } @Test public void fromMessageToPayload() throws Exception { Method method = TestService.class.getMethod("mapOnly", Map.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload(employee).setHeader("number", "jkl").build(); Object result = processor.processMessage(message); Assert.assertTrue(result instanceof Map); @@ -299,6 +319,7 @@ public void fromMessageToPayload() throws Exception { public void fromMessageToPayloadArg() throws Exception { Method method = TestService.class.getMethod("payloadAnnotationFirstName", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload(employee).setHeader("number", "jkl").build(); Object result = processor.processMessage(message); Assert.assertTrue(result instanceof String); @@ -309,6 +330,7 @@ public void fromMessageToPayloadArg() throws Exception { public void fromMessageToPayloadArgs() throws Exception { Method method = TestService.class.getMethod("payloadAnnotationFullName", String.class, String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload(employee).setHeader("number", "jkl").build(); Object result = processor.processMessage(message); Assert.assertEquals("oleg zhurakousky", result); @@ -318,6 +340,7 @@ public void fromMessageToPayloadArgs() throws Exception { public void fromMessageToPayloadArgsHeaderArgs() throws Exception { Method method = TestService.class.getMethod("payloadArgAndHeaderArg", String.class, String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload(employee).setHeader("day", "monday").build(); Object result = processor.processMessage(message); Assert.assertEquals("olegmonday", result); @@ -327,6 +350,7 @@ public void fromMessageToPayloadArgsHeaderArgs() throws Exception { public void fromMessageInvalidMethodWithMultipleMappingAnnotations() throws Exception { Method method = MultipleMappingAnnotationTestBean.class.getMethod("test", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("payload").setHeader("foo", "bar").build(); processor.processMessage(message); } @@ -335,6 +359,7 @@ public void fromMessageInvalidMethodWithMultipleMappingAnnotations() throws Exce public void fromMessageToHeadersWithExpressions() throws Exception { Method method = TestService.class.getMethod("headersWithExpressions", String.class, String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Employee employee = new Employee("John", "Doe"); Message message = MessageBuilder.withPayload("payload").setHeader("emp", employee).build(); Object result = processor.processMessage(message); @@ -345,6 +370,7 @@ public void fromMessageToHeadersWithExpressions() throws Exception { public void fromMessageToHyphenatedHeaderName() throws Exception { Method method = TestService.class.getMethod("headerNameWithHyphen", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("payload").setHeader("foo-bar", "abc").build(); Object result = processor.processMessage(message); assertEquals("ABC", result); 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 4e51a923450..dc765e84da3 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 @@ -151,10 +151,11 @@ public boolean supportsParameter(MethodParameter parameter) { } @Override - public Object resolveArgument(MethodParameter parameter, Message message) throws Exception { + public Object resolveArgument(MethodParameter parameter, Message message) { String[] names = ((String) message.getPayload()).split(" "); return new Person(names[0], names[1]); } + }; f.setArgumentResolvers(Collections.singletonList(resolver)); f.afterPropertiesSet(); @@ -170,7 +171,7 @@ public Person(String fname, String lname) { } public String toString() { - return "Person: " + name; + return "Person: " + this.name; } } @@ -198,6 +199,7 @@ class C extends B { } MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new B(), "myMethod"); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = (Message) processor.processMessage(new GenericMessage<>("")); assertEquals("A", message.getHeaders().get("A")); } @@ -228,6 +230,7 @@ class C extends B { } MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new B(), "myMethod"); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = (Message) processor.processMessage(new GenericMessage<>("")); assertEquals("B", message.getHeaders().get("B")); } @@ -297,7 +300,8 @@ public Message myMethod(Message msg) { public void payloadAsMethodParameterAndObjectAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptPayloadAndReturnObject"); - Object result = processor.processMessage(new GenericMessage<>("testing")); + processor.setBeanFactory(mock(BeanFactory.class)); + Object result = processor.processMessage(new GenericMessage("testing")); assertEquals("testing-1", result); } @@ -305,7 +309,8 @@ public void payloadAsMethodParameterAndObjectAsReturnValue() { public void testPayloadCoercedToString() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptPayloadAndReturnObject"); - Object result = processor.processMessage(new GenericMessage<>(123456789)); + processor.setBeanFactory(mock(BeanFactory.class)); + Object result = processor.processMessage(new GenericMessage(123456789)); assertEquals("123456789-1", result); } @@ -313,6 +318,7 @@ public void testPayloadCoercedToString() { public void payloadAsMethodParameterAndMessageAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptPayloadAndReturnMessage"); + processor.setBeanFactory(mock(BeanFactory.class)); Message result = (Message) processor.processMessage(new GenericMessage<>("testing")); assertEquals("testing-2", result.getPayload()); } @@ -321,7 +327,8 @@ public void payloadAsMethodParameterAndMessageAsReturnValue() { public void messageAsMethodParameterAndObjectAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptMessageAndReturnObject"); - Object result = processor.processMessage(new GenericMessage<>("testing")); + processor.setBeanFactory(mock(BeanFactory.class)); + Object result = processor.processMessage(new GenericMessage("testing")); assertEquals("testing-3", result); } @@ -329,6 +336,7 @@ public void messageAsMethodParameterAndObjectAsReturnValue() { public void messageAsMethodParameterAndMessageAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptMessageAndReturnMessage"); + processor.setBeanFactory(mock(BeanFactory.class)); Message result = (Message) processor.processMessage(new GenericMessage<>("testing")); assertEquals("testing-4", result.getPayload()); } @@ -337,6 +345,7 @@ public void messageAsMethodParameterAndMessageAsReturnValue() { public void messageSubclassAsMethodParameterAndMessageAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptMessageSubclassAndReturnMessage"); + processor.setBeanFactory(mock(BeanFactory.class)); Message result = (Message) processor.processMessage(new GenericMessage<>("testing")); assertEquals("testing-5", result.getPayload()); } @@ -345,7 +354,8 @@ public void messageSubclassAsMethodParameterAndMessageAsReturnValue() { public void messageSubclassAsMethodParameterAndMessageSubclassAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptMessageSubclassAndReturnMessageSubclass"); - Message result = (Message) processor.processMessage(new GenericMessage<>("testing")); + processor.setBeanFactory(mock(BeanFactory.class)); + Message result = (Message) processor.processMessage(new GenericMessage("testing")); assertEquals("testing-6", result.getPayload()); } @@ -353,6 +363,7 @@ public void messageSubclassAsMethodParameterAndMessageSubclassAsReturnValue() { public void payloadAndHeaderAnnotationMethodParametersAndObjectAsReturnValue() { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), "acceptPayloadAndHeaderAndReturnObject"); + processor.setBeanFactory(mock(BeanFactory.class)); Message request = MessageBuilder.withPayload("testing").setHeader("number", 123).build(); Object result = processor.processMessage(request); assertEquals("testing-123", result); @@ -360,8 +371,9 @@ public void payloadAndHeaderAnnotationMethodParametersAndObjectAsReturnValue() { @Test public void testVoidMethodsIncludedByDefault() { - MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new TestBean(), - "testVoidReturningMethods"); + MethodInvokingMessageProcessor processor = + new MethodInvokingMessageProcessor(new TestBean(), "testVoidReturningMethods"); + processor.setBeanFactory(mock(BeanFactory.class)); assertNull(processor.processMessage(MessageBuilder.withPayload("Something").build())); assertEquals(12, processor.processMessage(MessageBuilder.withPayload(12).build())); } @@ -371,6 +383,7 @@ public void messageOnlyWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("messageOnly", Message.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); + processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(new GenericMessage<>("foo")); assertEquals("foo", result); } @@ -380,6 +393,7 @@ public void payloadWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("integerMethod", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); + processor.setBeanFactory(mock(BeanFactory.class)); Object result = processor.processMessage(new GenericMessage<>(123)); assertEquals(123, result); } @@ -389,7 +403,8 @@ public void convertedPayloadWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("integerMethod", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - Object result = processor.processMessage(new GenericMessage("456")); + processor.setBeanFactory(mock(BeanFactory.class)); + Object result = processor.processMessage(new GenericMessage<>("456")); assertEquals(456, result); } @@ -398,13 +413,15 @@ public void conversionFailureWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("integerMethod", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - processor.processMessage(new GenericMessage("foo")); + processor.setBeanFactory(mock(BeanFactory.class)); + processor.processMessage(new GenericMessage<>("foo")); } @Test public void filterSelectsAnnotationMethodsOnly() { OverloadedMethodBean bean = new OverloadedMethodBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(bean, ServiceActivator.class); + processor.setBeanFactory(mock(BeanFactory.class)); processor.processMessage(MessageBuilder.withPayload(123).build()); assertNotNull(bean.lastArg); assertEquals(String.class, bean.lastArg.getClass()); @@ -417,7 +434,8 @@ public void testProcessMessageBadExpression() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("integerMethod", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - assertEquals("foo", processor.processMessage(new GenericMessage("foo"))); + processor.setBeanFactory(mock(BeanFactory.class)); + assertEquals("foo", processor.processMessage(new GenericMessage<>("foo"))); } @Test @@ -426,7 +444,8 @@ public void testProcessMessageRuntimeException() throws Exception { TestErrorService service = new TestErrorService(); Method method = service.getClass().getMethod("error", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - assertEquals("foo", processor.processMessage(new GenericMessage("foo"))); + processor.setBeanFactory(mock(BeanFactory.class)); + assertEquals("foo", processor.processMessage(new GenericMessage<>("foo"))); } @Test @@ -435,7 +454,8 @@ public void testProcessMessageCheckedException() throws Exception { TestErrorService service = new TestErrorService(); Method method = service.getClass().getMethod("checked", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - assertEquals("foo", processor.processMessage(new GenericMessage("foo"))); + processor.setBeanFactory(mock(BeanFactory.class)); + assertEquals("foo", processor.processMessage(new GenericMessage<>("foo"))); } @Test @@ -445,7 +465,8 @@ public void testProcessMessageMethodNotFound() throws Exception { Method method = TestErrorService.class.getMethod("checked", String.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); - processor.processMessage(new GenericMessage("foo")); + processor.setBeanFactory(mock(BeanFactory.class)); + processor.processMessage(new GenericMessage<>("foo")); } @Test @@ -453,6 +474,7 @@ public void messageAndHeaderWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("messageAndHeader", Message.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo").setHeader("number", 42).build(); Object result = processor.processMessage(message); assertEquals("foo-42", result); @@ -463,8 +485,12 @@ public void multipleHeadersWithAnnotatedMethod() throws Exception { AnnotatedTestService service = new AnnotatedTestService(); Method method = service.getClass().getMethod("twoHeaders", String.class, Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); - Message message = MessageBuilder.withPayload("foo").setHeader("prop", "bar").setHeader("number", 42) - .build(); + processor.setBeanFactory(mock(BeanFactory.class)); + Message message = + MessageBuilder.withPayload("foo") + .setHeader("prop", "bar") + .setHeader("number", 42) + .build(); Object result = processor.processMessage(message); assertEquals("bar-42", result); } @@ -493,6 +519,8 @@ public void compiledOptionalAndRequiredWithAnnotatedMethod() throws Exception { private void optionalAndRequiredWithAnnotatedMethodGuts(MethodInvokingMessageProcessor processor, boolean compiled) { + + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo") .setHeader("num", 42) .build(); @@ -545,6 +573,8 @@ public void compiledOptionalAndRequiredDottedWithAnnotatedMethod() throws Except private void optionalAndRequiredDottedWithAnnotatedMethodGuts(MethodInvokingMessageProcessor processor, boolean compiled) { + + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("hello") .setHeader("dot2", new DotBean()) .build(); @@ -577,6 +607,7 @@ private void optionalAndRequiredDottedWithAnnotatedMethodGuts(MethodInvokingMess public void testOverloadedNonVoidReturningMethodsWithExactMatchForType() { AmbiguousMethodBean bean = new AmbiguousMethodBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(bean, "foo"); + processor.setBeanFactory(mock(BeanFactory.class)); processor.processMessage(MessageBuilder.withPayload("true").build()); assertNotNull(bean.lastArg); assertEquals(String.class, bean.lastArg.getClass()); @@ -621,13 +652,14 @@ public String voidMethod() { } MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(new Foo(), (String) null, false); + helper.setBeanFactory(mock(BeanFactory.class)); assertEquals("4", helper.process(new GenericMessage(2L))); assertEquals("1", helper.process(new GenericMessage(1))); assertEquals("foo", helper.process(new GenericMessage(new Date()))); } @Test - public void testInt3199GettersAmbiguity() throws Exception { + public void testInt3199GettersAmbiguity() { class Foo { @@ -678,6 +710,7 @@ public Object m3(Message message) { Foo targetObject = new Foo(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(targetObject, (String) null, false); + helper.setBeanFactory(mock(BeanFactory.class)); assertEquals("foo", helper.process(new GenericMessage("foo"))); assertEquals(1, helper.process(new GenericMessage(1))); assertEquals(targetObject, helper.process(new GenericMessage(targetObject))); @@ -708,6 +741,7 @@ public Object m3(Object payload) { Foo targetObject = new Foo(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(targetObject, (String) null, false); + helper.setBeanFactory(mock(BeanFactory.class)); assertEquals("foo", helper.process(new GenericMessage("foo"))); assertEquals(1, helper.process(new GenericMessage(1))); assertEquals(targetObject, helper.process(new GenericMessage(targetObject))); @@ -739,6 +773,7 @@ public Object m3() { Foo targetObject = new Foo(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(targetObject, (String) null, false); + helper.setBeanFactory(mock(BeanFactory.class)); assertEquals("foo", helper.process(new GenericMessage("foo"))); assertEquals("FOO", helper.process(new GenericMessage(targetObject))); } @@ -747,6 +782,7 @@ public Object m3() { public void testIneligible() { IneligibleMethodBean bean = new IneligibleMethodBean(); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(bean, "foo"); + processor.setBeanFactory(mock(BeanFactory.class)); processor.processMessage(MessageBuilder.withPayload("true").build()); assertNotNull(bean.lastArg); assertEquals(String.class, bean.lastArg.getClass()); @@ -757,7 +793,7 @@ public void testIneligible() { public void testOptionalArgs() throws Exception { class Foo { - private final Map arguments = new LinkedHashMap(); + private final Map arguments = new LinkedHashMap<>(); @SuppressWarnings("unused") public void optionalHeaders(Optional foo, @Header(value = "foo", required = false) String foo1, @@ -772,6 +808,7 @@ public void optionalHeaders(Optional foo, @Header(value = "foo", require Foo targetObject = new Foo(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(targetObject, (String) null, false); + helper.setBeanFactory(mock(BeanFactory.class)); helper.process(new GenericMessage<>(Optional.empty())); assertNull(targetObject.arguments.get("foo")); @@ -795,8 +832,9 @@ private String service(String payload) { } - MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper(new Foo(), ServiceActivator.class, - false); + MessagingMethodInvokerHelper helper = + new MessagingMethodInvokerHelper(new Foo(), ServiceActivator.class, false); + helper.setBeanFactory(mock(BeanFactory.class)); assertEquals("FOO", helper.process(new GenericMessage<>("foo"))); assertEquals("BAR", helper.process(new GenericMessage<>("bar"))); @@ -809,6 +847,7 @@ public void testPerformanceSpelVersusInvocable() throws Exception { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); + processor.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload(42).build(); @@ -823,6 +862,7 @@ public void testPerformanceSpelVersusInvocable() throws Exception { stopWatch.stop(); processor = new MethodInvokingMessageProcessor(service, method); + processor.setBeanFactory(mock(BeanFactory.class)); stopWatch.start("Invocable"); for (int i = 0; i < count; i++) { @@ -834,6 +874,7 @@ public void testPerformanceSpelVersusInvocable() throws Exception { processor = new MethodInvokingMessageProcessor(service, method); processor.setUseSpelInvoker(true); + processor.setBeanFactory(mock(BeanFactory.class)); stopWatch.start("Compiled SpEL"); for (int i = 0; i < count; i++) { @@ -858,7 +899,7 @@ public void myMethod(Object payload) { } MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(new A(), "myMethod"); - + processor.setBeanFactory(mock(BeanFactory.class)); try { processor.processMessage(new GenericMessage<>("foo")); } @@ -896,6 +937,7 @@ public void handleMessage(Message message) throws MessagingException { service = (MessageHandler) proxyFactory.getProxy(getClass().getClassLoader()); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, "handleMessage"); + processor.setBeanFactory(mock(BeanFactory.class)); processor.processMessage(new GenericMessage<>("foo")); @@ -931,6 +973,7 @@ public void handle(@Header(MessageHeaders.ID) UUID id, @Payload Object payload) GenericMessage testMessage = new GenericMessage<>("foo"); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(service, "handle"); + processor.setBeanFactory(mock(BeanFactory.class)); processor.processMessage(testMessage); @@ -942,8 +985,10 @@ public void handle(@Header(MessageHeaders.ID) UUID id, @Payload Object payload) @Test public void testUseSpelInvoker() throws Exception { UseSpelInvokerBean bean = new UseSpelInvokerBean(); - MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper<>(bean, - UseSpelInvokerBean.class.getDeclaredMethod("foo", String.class), false); + MessagingMethodInvokerHelper helper = + new MessagingMethodInvokerHelper<>(bean, + UseSpelInvokerBean.class.getDeclaredMethod("foo", String.class), false); + helper.setBeanFactory(mock(BeanFactory.class)); Message message = new GenericMessage<>("Test"); helper.process(message); assertEquals(SpelCompilerMode.OFF, @@ -951,24 +996,28 @@ public void testUseSpelInvoker() throws Exception { helper = new MessagingMethodInvokerHelper<>(bean, UseSpelInvokerBean.class.getDeclaredMethod("bar", String.class), false); + helper.setBeanFactory(mock(BeanFactory.class)); helper.process(message); assertEquals(SpelCompilerMode.IMMEDIATE, TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")); helper = new MessagingMethodInvokerHelper<>(bean, UseSpelInvokerBean.class.getDeclaredMethod("baz", String.class), false); + helper.setBeanFactory(mock(BeanFactory.class)); helper.process(message); assertEquals(SpelCompilerMode.MIXED, TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")); helper = new MessagingMethodInvokerHelper<>(bean, UseSpelInvokerBean.class.getDeclaredMethod("qux", String.class), false); + helper.setBeanFactory(mock(BeanFactory.class)); helper.process(message); assertEquals(SpelCompilerMode.OFF, TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")); helper = new MessagingMethodInvokerHelper<>(bean, UseSpelInvokerBean.class.getDeclaredMethod("fiz", String.class), false); + helper.setBeanFactory(mock(BeanFactory.class)); try { helper.process(message); } @@ -993,11 +1042,13 @@ public void testUseSpelInvoker() throws Exception { // Check other CTORs helper = new MessagingMethodInvokerHelper<>(bean, "bar", false); + helper.setBeanFactory(mock(BeanFactory.class)); helper.process(message); assertEquals(SpelCompilerMode.IMMEDIATE, TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")); helper = new MessagingMethodInvokerHelper<>(bean, ServiceActivator.class, false); + helper.setBeanFactory(mock(BeanFactory.class)); helper.process(message); assertEquals(SpelCompilerMode.MIXED, TestUtils.getPropertyValue(helper, "handlerMethod.expression.configuration.compilerMode")); @@ -1006,10 +1057,13 @@ public void testUseSpelInvoker() throws Exception { @Test public void testSingleMethodJson() throws Exception { SingleMethodJsonWithSpELBean bean = new SingleMethodJsonWithSpELBean(); - MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper<>(bean, - SingleMethodJsonWithSpELBean.class.getDeclaredMethod("foo", - SingleMethodJsonWithSpELBean.Foo.class), - false); + MessagingMethodInvokerHelper helper = + new MessagingMethodInvokerHelper<>(bean, + SingleMethodJsonWithSpELBean.class.getDeclaredMethod("foo", + SingleMethodJsonWithSpELBean.Foo.class), + false); + helper.setBeanFactory(mock(BeanFactory.class)); + Message message = new GenericMessage<>("{\"bar\":\"bar\"}", Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "application/json")); helper.process(message); @@ -1021,6 +1075,7 @@ public void testSingleMethodBadJson() throws Exception { SingleMethodJsonWithSpELMessageWildBean bean = new SingleMethodJsonWithSpELMessageWildBean(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper<>(bean, SingleMethodJsonWithSpELMessageWildBean.class.getDeclaredMethod("foo", Message.class), false); + helper.setBeanFactory(mock(BeanFactory.class)); Message message = new GenericMessage<>("baz", Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "application/json")); helper.process(message); @@ -1032,6 +1087,8 @@ public void testSingleMethodJsonMessageFoo() throws Exception { SingleMethodJsonWithSpELMessageFooBean bean = new SingleMethodJsonWithSpELMessageFooBean(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper<>(bean, SingleMethodJsonWithSpELMessageFooBean.class.getDeclaredMethod("foo", Message.class), false); + helper.setBeanFactory(mock(BeanFactory.class)); + Message message = new GenericMessage<>("{\"bar\":\"bar\"}", Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "application/json")); helper.process(message); @@ -1043,6 +1100,8 @@ public void testSingleMethodJsonMessageWild() throws Exception { SingleMethodJsonWithSpELMessageWildBean bean = new SingleMethodJsonWithSpELMessageWildBean(); MessagingMethodInvokerHelper helper = new MessagingMethodInvokerHelper<>(bean, SingleMethodJsonWithSpELMessageWildBean.class.getDeclaredMethod("foo", Message.class), false); + helper.setBeanFactory(mock(BeanFactory.class)); + Message message = new GenericMessage<>("{\"bar\":\"baz\"}", Collections.singletonMap(MessageHeaders.CONTENT_TYPE, "application/json")); helper.process(message); 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 c837c9c4ca8..939ab974dd3 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; import java.util.concurrent.BlockingQueue; import java.util.concurrent.SynchronousQueue; @@ -26,6 +27,7 @@ import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.endpoint.PollingConsumer; import org.springframework.integration.handler.MethodInvokingMessageHandler; @@ -39,13 +41,15 @@ /** * @author Mark Fisher * @author Oleg Zhurakousky + * @author Artem Bilan */ public class MethodInvokingMessageHandlerTests { @Test public void validMethod() { MethodInvokingMessageHandler handler = new MethodInvokingMessageHandler(new TestSink(), "validMethod"); - handler.handleMessage(new GenericMessage("test")); + handler.setBeanFactory(mock(BeanFactory.class)); + handler.handleMessage(new GenericMessage<>("test")); } @Test @@ -55,9 +59,10 @@ public void validMethodWithNoArgs() { @Test(expected = MessagingException.class) public void methodWithReturnValue() { - Message message = new GenericMessage("test"); + Message message = new GenericMessage<>("test"); try { - MethodInvokingMessageHandler handler = new MethodInvokingMessageHandler(new TestSink(), "methodWithReturnValue"); + MethodInvokingMessageHandler handler = new MethodInvokingMessageHandler(new TestSink(), + "methodWithReturnValue"); handler.handleMessage(message); } catch (MessagingException e) { @@ -74,14 +79,15 @@ public void noMatchingMethodName() { @Test public void subscription() throws Exception { TestApplicationContext context = TestUtils.createTestApplicationContext(); - SynchronousQueue queue = new SynchronousQueue(); + SynchronousQueue queue = new SynchronousQueue<>(); TestBean testBean = new TestBean(queue); QueueChannel channel = new QueueChannel(); context.registerChannel("channel", channel); - Message message = new GenericMessage("testing"); + Message message = new GenericMessage<>("testing"); channel.send(message); assertNull(queue.poll()); MethodInvokingMessageHandler handler = new MethodInvokingMessageHandler(testBean, "foo"); + handler.setBeanFactory(context); PollingConsumer endpoint = new PollingConsumer(channel, handler); endpoint.setTrigger(new PeriodicTrigger(10)); context.registerEndpoint("testEndpoint", endpoint); @@ -89,7 +95,7 @@ public void subscription() throws Exception { String result = queue.poll(2000, TimeUnit.MILLISECONDS); assertNotNull(result); assertEquals("testing", result); - context.stop(); + context.close(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/ErrorMessageExceptionTypeRouterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/ErrorMessageExceptionTypeRouterTests.java index 6ad4dadcd42..05c7f70bacd 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/ErrorMessageExceptionTypeRouterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/ErrorMessageExceptionTypeRouterTests.java @@ -23,10 +23,10 @@ import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; +import org.junit.After; import org.junit.Before; import org.junit.Test; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.integration.MessageRejectedException; @@ -46,7 +46,7 @@ */ public class ErrorMessageExceptionTypeRouterTests { - private final DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); + private final TestUtils.TestApplicationContext context = TestUtils.createTestApplicationContext(); private final QueueChannel illegalArgumentChannel = new QueueChannel(); @@ -60,28 +60,33 @@ public class ErrorMessageExceptionTypeRouterTests { @Before public void prepare() { - beanFactory.registerSingleton("illegalArgumentChannel", illegalArgumentChannel); - beanFactory.registerSingleton("runtimeExceptionChannel", runtimeExceptionChannel); - beanFactory.registerSingleton("messageHandlingExceptionChannel", messageHandlingExceptionChannel); - beanFactory.registerSingleton("messageDeliveryExceptionChannel", messageDeliveryExceptionChannel); - beanFactory.registerSingleton("defaultChannel", defaultChannel); + this.context.registerBean("illegalArgumentChannel", this.illegalArgumentChannel); + this.context.registerBean("runtimeExceptionChannel", this.runtimeExceptionChannel); + this.context.registerBean("messageHandlingExceptionChannel", this.messageHandlingExceptionChannel); + this.context.registerBean("messageDeliveryExceptionChannel", this.messageDeliveryExceptionChannel); + this.context.registerBean("defaultChannel", this.defaultChannel); + this.context.refresh(); } + @After + public void terDown() { + this.context.close(); + } @Test public void mostSpecificCause() { - Message failedMessage = new GenericMessage("foo"); + Message failedMessage = new GenericMessage<>("foo"); IllegalArgumentException rootCause = new IllegalArgumentException("bad argument"); RuntimeException middleCause = new RuntimeException(rootCause); MessageHandlingException error = new MessageHandlingException(failedMessage, "failed", middleCause); ErrorMessage message = new ErrorMessage(error); ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter(); - router.setBeanFactory(beanFactory); - router.setApplicationContext(TestUtils.createTestApplicationContext()); + router.setBeanFactory(this.context); + router.setApplicationContext(this.context); router.setChannelMapping(IllegalArgumentException.class.getName(), "illegalArgumentChannel"); router.setChannelMapping(RuntimeException.class.getName(), "runtimeExceptionChannel"); router.setChannelMapping(MessageHandlingException.class.getName(), "messageHandlingExceptionChannel"); - router.setDefaultOutputChannel(defaultChannel); + router.setDefaultOutputChannel(this.defaultChannel); router.afterPropertiesSet(); router.handleMessage(message); @@ -94,17 +99,17 @@ public void mostSpecificCause() { @Test public void fallbackToNextMostSpecificCause() { - Message failedMessage = new GenericMessage("foo"); + Message failedMessage = new GenericMessage<>("foo"); IllegalArgumentException rootCause = new IllegalArgumentException("bad argument"); RuntimeException middleCause = new RuntimeException(rootCause); MessageHandlingException error = new MessageHandlingException(failedMessage, "failed", middleCause); ErrorMessage message = new ErrorMessage(error); ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter(); - router.setBeanFactory(beanFactory); - router.setApplicationContext(TestUtils.createTestApplicationContext()); + router.setBeanFactory(this.context); + router.setApplicationContext(this.context); router.setChannelMapping(RuntimeException.class.getName(), "runtimeExceptionChannel"); router.setChannelMapping(MessageHandlingException.class.getName(), "runtimeExceptionChannel"); - router.setDefaultOutputChannel(defaultChannel); + router.setDefaultOutputChannel(this.defaultChannel); router.afterPropertiesSet(); router.handleMessage(message); @@ -117,16 +122,16 @@ public void fallbackToNextMostSpecificCause() { @Test public void fallbackToErrorMessageType() { - Message failedMessage = new GenericMessage("foo"); + Message failedMessage = new GenericMessage<>("foo"); IllegalArgumentException rootCause = new IllegalArgumentException("bad argument"); RuntimeException middleCause = new RuntimeException(rootCause); MessageHandlingException error = new MessageHandlingException(failedMessage, "failed", middleCause); ErrorMessage message = new ErrorMessage(error); ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter(); - router.setBeanFactory(beanFactory); - router.setApplicationContext(TestUtils.createTestApplicationContext()); + router.setBeanFactory(this.context); + router.setApplicationContext(this.context); router.setChannelMapping(MessageHandlingException.class.getName(), "messageHandlingExceptionChannel"); - router.setDefaultOutputChannel(defaultChannel); + router.setDefaultOutputChannel(this.defaultChannel); router.afterPropertiesSet(); router.handleMessage(message); @@ -139,13 +144,13 @@ public void fallbackToErrorMessageType() { @Test public void fallbackToDefaultChannel() { - Message failedMessage = new GenericMessage("foo"); + Message failedMessage = new GenericMessage<>("foo"); IllegalArgumentException rootCause = new IllegalArgumentException("bad argument"); RuntimeException middleCause = new RuntimeException(rootCause); MessageHandlingException error = new MessageHandlingException(failedMessage, "failed", middleCause); ErrorMessage message = new ErrorMessage(error); ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter(); - router.setApplicationContext(TestUtils.createTestApplicationContext()); + router.setApplicationContext(this.context); router.setDefaultOutputChannel(defaultChannel); router.afterPropertiesSet(); @@ -159,14 +164,13 @@ public void fallbackToDefaultChannel() { @Test public void noMatchAndNoDefaultChannel() { - Message failedMessage = new GenericMessage("foo"); + Message failedMessage = new GenericMessage<>("foo"); IllegalArgumentException rootCause = new IllegalArgumentException("bad argument"); RuntimeException middleCause = new RuntimeException(rootCause); MessageHandlingException error = new MessageHandlingException(failedMessage, "failed", middleCause); ErrorMessage message = new ErrorMessage(error); ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter(); - router.setBeanFactory(beanFactory); - router.setApplicationContext(TestUtils.createTestApplicationContext()); + router.setApplicationContext(this.context); router.setChannelMapping(MessageDeliveryException.class.getName(), "messageDeliveryExceptionChannel"); router.setResolutionRequired(true); router.setBeanName("fooRouter"); @@ -184,18 +188,18 @@ public void noMatchAndNoDefaultChannel() { @Test public void exceptionPayloadButNotErrorMessage() { - Message failedMessage = new GenericMessage("foo"); + Message failedMessage = new GenericMessage<>("foo"); IllegalArgumentException rootCause = new IllegalArgumentException("bad argument"); RuntimeException middleCause = new RuntimeException(rootCause); MessageHandlingException error = new MessageHandlingException(failedMessage, "failed", middleCause); Message message = new GenericMessage(error); ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter(); - router.setBeanFactory(beanFactory); - router.setApplicationContext(TestUtils.createTestApplicationContext()); + router.setBeanFactory(this.context); + router.setApplicationContext(this.context); router.setChannelMapping(IllegalArgumentException.class.getName(), "illegalArgumentChannel"); router.setChannelMapping(RuntimeException.class.getName(), "runtimeExceptionChannel"); router.setChannelMapping(MessageHandlingException.class.getName(), "messageHandlingExceptionChannel"); - router.setDefaultOutputChannel(defaultChannel); + router.setDefaultOutputChannel(this.defaultChannel); router.afterPropertiesSet(); router.handleMessage(message); @@ -208,14 +212,14 @@ public void exceptionPayloadButNotErrorMessage() { @Test public void intermediateCauseHasNoMappingButMostSpecificCauseDoes() { - Message failedMessage = new GenericMessage("foo"); + Message failedMessage = new GenericMessage<>("foo"); IllegalArgumentException rootCause = new IllegalArgumentException("bad argument"); RuntimeException middleCause = new RuntimeException(rootCause); MessageHandlingException error = new MessageHandlingException(failedMessage, "failed", middleCause); ErrorMessage message = new ErrorMessage(error); ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter(); - router.setBeanFactory(beanFactory); - router.setApplicationContext(TestUtils.createTestApplicationContext()); + router.setBeanFactory(this.context); + router.setApplicationContext(this.context); router.setChannelMapping(IllegalArgumentException.class.getName(), "illegalArgumentChannel"); router.setChannelMapping(MessageHandlingException.class.getName(), "messageHandlingExceptionChannel"); router.setDefaultOutputChannel(defaultChannel); @@ -232,11 +236,12 @@ public void intermediateCauseHasNoMappingButMostSpecificCauseDoes() { @Test public void testHierarchicalMapping() { IllegalArgumentException rootCause = new IllegalArgumentException("bad argument"); - MessageHandlingException error = new MessageRejectedException(new GenericMessage("foo"), "failed", rootCause); + MessageHandlingException error = + new MessageRejectedException(new GenericMessage("foo"), "failed", rootCause); ErrorMessage message = new ErrorMessage(error); ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter(); - router.setBeanFactory(beanFactory); - router.setApplicationContext(TestUtils.createTestApplicationContext()); + router.setBeanFactory(this.context); + router.setApplicationContext(this.context); router.setChannelMapping(MessageHandlingException.class.getName(), "messageHandlingExceptionChannel"); router.setDefaultOutputChannel(defaultChannel); router.afterPropertiesSet(); @@ -250,8 +255,7 @@ public void testHierarchicalMapping() { @Test public void testInvalidMapping() { ErrorMessageExceptionTypeRouter router = new ErrorMessageExceptionTypeRouter(); - router.setBeanFactory(beanFactory); - router.setApplicationContext(TestUtils.createTestApplicationContext()); + router.setApplicationContext(this.context); router.afterPropertiesSet(); try { router.setChannelMapping("foo", "fooChannel"); @@ -266,7 +270,8 @@ public void testInvalidMapping() { @Test public void testLateClassBinding() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class); - ctx.getBean(ErrorMessageExceptionTypeRouter.class).handleMessage(new GenericMessage<>(new NullPointerException())); + ctx.getBean(ErrorMessageExceptionTypeRouter.class) + .handleMessage(new GenericMessage<>(new NullPointerException())); assertNotNull(ctx.getBean("channel", PollableChannel.class).receive(0)); ctx.close(); } 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 93a16d0c597..77b4704c950 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; import java.lang.reflect.Method; import java.util.ArrayList; @@ -27,6 +28,7 @@ import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.channel.TestChannelResolver; import org.springframework.integration.support.MessageBuilder; @@ -52,8 +54,10 @@ public void channelNameResolutionByPayloadConfiguredByMethodReference() throws E SingleChannelNameRoutingTestBean testBean = new SingleChannelNameRoutingTestBean(); Method routingMethod = testBean.getClass().getMethod("routePayload", String.class); MethodInvokingRouter router = new MethodInvokingRouter(testBean, routingMethod); + router.setBeanFactory(mock(BeanFactory.class)); + router.afterPropertiesSet(); router.setChannelResolver(channelResolver); - Message message = new GenericMessage("bar"); + Message message = new GenericMessage<>("bar"); router.handleMessage(message); Message replyMessage = barChannel.receive(); assertNotNull(replyMessage); @@ -68,7 +72,9 @@ public void channelNameResolutionByPayloadConfiguredByMethodName() { SingleChannelNameRoutingTestBean testBean = new SingleChannelNameRoutingTestBean(); MethodInvokingRouter router = new MethodInvokingRouter(testBean, "routePayload"); router.setChannelResolver(channelResolver); - Message message = new GenericMessage("bar"); + router.setBeanFactory(mock(BeanFactory.class)); + router.afterPropertiesSet(); + Message message = new GenericMessage<>("bar"); router.handleMessage(message); Message replyMessage = barChannel.receive(); assertNotNull(replyMessage); @@ -86,6 +92,8 @@ public void channelNameResolutionByHeader() throws Exception { Method routingMethod = testBean.getClass().getMethod("routeByHeader", String.class); MethodInvokingRouter router = new MethodInvokingRouter(testBean, routingMethod); router.setChannelResolver(channelResolver); + router.setBeanFactory(mock(BeanFactory.class)); + router.afterPropertiesSet(); Message message = MessageBuilder.withPayload("bar") .setHeader("targetChannel", "foo").build(); router.handleMessage(message); @@ -109,26 +117,28 @@ public void channelNameResolutionByMessageConfiguredByMethodReference() throws E SingleChannelNameRoutingTestBean testBean = new SingleChannelNameRoutingTestBean(); Method routingMethod = testBean.getClass().getMethod("routeMessage", Message.class); MethodInvokingRouter router = new MethodInvokingRouter(testBean, routingMethod); - this.doTestChannelNameResolutionByMessage(router); + doTestChannelNameResolutionByMessage(router); } @Test public void channelNameResolutionByMessageConfiguredByMethodName() { SingleChannelNameRoutingTestBean testBean = new SingleChannelNameRoutingTestBean(); MethodInvokingRouter router = new MethodInvokingRouter(testBean, "routeMessage"); - this.doTestChannelNameResolutionByMessage(router); + doTestChannelNameResolutionByMessage(router); } private void doTestChannelNameResolutionByMessage(MethodInvokingRouter router) { + router.setBeanFactory(mock(BeanFactory.class)); + router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); TestChannelResolver channelResolver = new TestChannelResolver(); channelResolver.addChannel("foo-channel", fooChannel); channelResolver.addChannel("bar-channel", barChannel); router.setChannelResolver(channelResolver); - Message fooMessage = new GenericMessage("foo"); - Message barMessage = new GenericMessage("bar"); - Message badMessage = new GenericMessage("bad"); + Message fooMessage = new GenericMessage<>("foo"); + Message barMessage = new GenericMessage<>("bar"); + Message badMessage = new GenericMessage<>("bad"); router.handleMessage(fooMessage); Message result1 = fooChannel.receive(0); assertNotNull(result1); @@ -154,7 +164,7 @@ public void channelInstanceResolutionByPayloadConfiguredByMethodReference() thro SingleChannelInstanceRoutingTestBean testBean = new SingleChannelInstanceRoutingTestBean(channelResolver); Method routingMethod = testBean.getClass().getMethod("routePayload", String.class); MethodInvokingRouter router = new MethodInvokingRouter(testBean, routingMethod); - this.doTestChannelInstanceResolutionByPayload(router, channelResolver); + doTestChannelInstanceResolutionByPayload(router, channelResolver); } @Test @@ -162,14 +172,17 @@ public void channelInstanceResolutionByPayloadConfiguredByMethodName() { TestChannelResolver channelResolver = new TestChannelResolver(); SingleChannelInstanceRoutingTestBean testBean = new SingleChannelInstanceRoutingTestBean(channelResolver); MethodInvokingRouter router = new MethodInvokingRouter(testBean, "routePayload"); - this.doTestChannelInstanceResolutionByPayload(router, channelResolver); + doTestChannelInstanceResolutionByPayload(router, channelResolver); } private void doTestChannelInstanceResolutionByPayload(MethodInvokingRouter router, TestChannelResolver channelResolver) { - Message fooMessage = new GenericMessage("foo"); - Message barMessage = new GenericMessage("bar"); - Message badMessage = new GenericMessage("bad"); + + router.setBeanFactory(mock(BeanFactory.class)); + router.afterPropertiesSet(); + Message fooMessage = new GenericMessage<>("foo"); + Message barMessage = new GenericMessage<>("bar"); + Message badMessage = new GenericMessage<>("bad"); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); channelResolver.addChannel("foo-channel", fooChannel); @@ -200,7 +213,7 @@ public void channelInstanceResolutionByMessageConfiguredByMethodReference() thro SingleChannelInstanceRoutingTestBean testBean = new SingleChannelInstanceRoutingTestBean(channelResolver); Method routingMethod = testBean.getClass().getMethod("routeMessage", Message.class); MethodInvokingRouter router = new MethodInvokingRouter(testBean, routingMethod); - this.doTestChannelInstanceResolutionByMessage(router, channelResolver); + doTestChannelInstanceResolutionByMessage(router, channelResolver); } @Test @@ -208,19 +221,22 @@ public void channelInstanceResolutionByMessageConfiguredByMethodName() { TestChannelResolver channelResolver = new TestChannelResolver(); SingleChannelInstanceRoutingTestBean testBean = new SingleChannelInstanceRoutingTestBean(channelResolver); MethodInvokingRouter router = new MethodInvokingRouter(testBean, "routeMessage"); - this.doTestChannelInstanceResolutionByMessage(router, channelResolver); + doTestChannelInstanceResolutionByMessage(router, channelResolver); } private void doTestChannelInstanceResolutionByMessage(MethodInvokingRouter router, TestChannelResolver channelResolver) { + + router.setBeanFactory(mock(BeanFactory.class)); + router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); channelResolver.addChannel("foo-channel", fooChannel); channelResolver.addChannel("bar-channel", barChannel); router.setChannelResolver(channelResolver); - Message fooMessage = new GenericMessage("foo"); - Message barMessage = new GenericMessage("bar"); - Message badMessage = new GenericMessage("bad"); + Message fooMessage = new GenericMessage<>("foo"); + Message barMessage = new GenericMessage<>("bar"); + Message badMessage = new GenericMessage<>("bad"); router.handleMessage(fooMessage); Message result1 = fooChannel.receive(0); assertNotNull(result1); @@ -246,7 +262,7 @@ public void multiChannelNameResolutionByPayloadConfiguredByMethodReference() thr MultiChannelNameRoutingTestBean testBean = new MultiChannelNameRoutingTestBean(); Method routingMethod = testBean.getClass().getMethod("routePayload", String.class); MethodInvokingRouter router = new MethodInvokingRouter(testBean, routingMethod); - this.doTestMultiChannelNameResolutionByPayload(router, channelResolver); + doTestMultiChannelNameResolutionByPayload(router, channelResolver); } @Test @@ -254,19 +270,22 @@ public void multiChannelNameResolutionByPayloadConfiguredByMethodName() { TestChannelResolver channelResolver = new TestChannelResolver(); MultiChannelNameRoutingTestBean testBean = new MultiChannelNameRoutingTestBean(); MethodInvokingRouter router = new MethodInvokingRouter(testBean, "routePayload"); - this.doTestMultiChannelNameResolutionByPayload(router, channelResolver); + doTestMultiChannelNameResolutionByPayload(router, channelResolver); } private void doTestMultiChannelNameResolutionByPayload(MethodInvokingRouter router, TestChannelResolver channelResolver) { + + router.setBeanFactory(mock(BeanFactory.class)); + router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); channelResolver.addChannel("foo-channel", fooChannel); channelResolver.addChannel("bar-channel", barChannel); router.setChannelResolver(channelResolver); - Message fooMessage = new GenericMessage("foo"); - Message barMessage = new GenericMessage("bar"); - Message badMessage = new GenericMessage("bad"); + Message fooMessage = new GenericMessage<>("foo"); + Message barMessage = new GenericMessage<>("bar"); + Message badMessage = new GenericMessage<>("bad"); router.handleMessage(fooMessage); Message result1a = fooChannel.receive(0); Message result1b = barChannel.receive(0); @@ -297,11 +316,11 @@ public void multiChannelNameResolutionByMessageConfiguredByMethodReference() thr MultiChannelNameRoutingTestBean testBean = new MultiChannelNameRoutingTestBean(); Method routingMethod = testBean.getClass().getMethod("routeMessage", Message.class); MethodInvokingRouter router = new MethodInvokingRouter(testBean, routingMethod); - this.doTestMultiChannelNameResolutionByMessage(router, channelResolver); + doTestMultiChannelNameResolutionByMessage(router, channelResolver); } @Test - public void multiChannelNameResolutionByMessageConfiguredByMethodName() throws Exception { + public void multiChannelNameResolutionByMessageConfiguredByMethodName() { TestChannelResolver channelResolver = new TestChannelResolver(); MultiChannelNameRoutingTestBean testBean = new MultiChannelNameRoutingTestBean(); MethodInvokingRouter router = new MethodInvokingRouter(testBean, "routeMessage"); @@ -310,14 +329,17 @@ public void multiChannelNameResolutionByMessageConfiguredByMethodName() throws E private void doTestMultiChannelNameResolutionByMessage(MethodInvokingRouter router, TestChannelResolver channelResolver) { + + router.setBeanFactory(mock(BeanFactory.class)); + router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); channelResolver.addChannel("foo-channel", fooChannel); channelResolver.addChannel("bar-channel", barChannel); router.setChannelResolver(channelResolver); - Message fooMessage = new GenericMessage("foo"); - Message barMessage = new GenericMessage("bar"); - Message badMessage = new GenericMessage("bad"); + Message fooMessage = new GenericMessage<>("foo"); + Message barMessage = new GenericMessage<>("bar"); + Message badMessage = new GenericMessage<>("bad"); router.handleMessage(fooMessage); Message result1a = fooChannel.receive(0); assertNotNull(result1a); @@ -348,7 +370,7 @@ public void multiChannelNameArrayResolutionByMessageConfiguredByMethodReference( MultiChannelNameRoutingTestBean testBean = new MultiChannelNameRoutingTestBean(); Method routingMethod = testBean.getClass().getMethod("routeMessageToArray", Message.class); MethodInvokingRouter router = new MethodInvokingRouter(testBean, routingMethod); - this.doTestMultiChannelNameArrayResolutionByMessage(router, channelResolver); + doTestMultiChannelNameArrayResolutionByMessage(router, channelResolver); } @Test @@ -356,19 +378,22 @@ public void multiChannelNameArrayResolutionByMessageConfiguredByMethodName() { TestChannelResolver channelResolver = new TestChannelResolver(); MultiChannelNameRoutingTestBean testBean = new MultiChannelNameRoutingTestBean(); MethodInvokingRouter router = new MethodInvokingRouter(testBean, "routeMessageToArray"); - this.doTestMultiChannelNameArrayResolutionByMessage(router, channelResolver); + doTestMultiChannelNameArrayResolutionByMessage(router, channelResolver); } private void doTestMultiChannelNameArrayResolutionByMessage(MethodInvokingRouter router, TestChannelResolver channelResolver) { + + router.setBeanFactory(mock(BeanFactory.class)); + router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); channelResolver.addChannel("foo-channel", fooChannel); channelResolver.addChannel("bar-channel", barChannel); router.setChannelResolver(channelResolver); - Message fooMessage = new GenericMessage("foo"); - Message barMessage = new GenericMessage("bar"); - Message badMessage = new GenericMessage("bad"); + Message fooMessage = new GenericMessage<>("foo"); + Message barMessage = new GenericMessage<>("bar"); + Message badMessage = new GenericMessage<>("bad"); router.handleMessage(fooMessage); Message result1a = fooChannel.receive(0); assertNotNull(result1a); @@ -399,7 +424,7 @@ public void multiChannelListResolutionByPayloadConfiguredByMethodReference() thr MultiChannelInstanceRoutingTestBean testBean = new MultiChannelInstanceRoutingTestBean(channelResolver); Method routingMethod = testBean.getClass().getMethod("routePayload", String.class); MethodInvokingRouter router = new MethodInvokingRouter(testBean, routingMethod); - this.doTestMultiChannelListResolutionByPayload(router, channelResolver); + doTestMultiChannelListResolutionByPayload(router, channelResolver); } @Test @@ -407,11 +432,14 @@ public void multiChannelListResolutionByPayloadConfiguredByMethodName() { TestChannelResolver channelResolver = new TestChannelResolver(); MultiChannelInstanceRoutingTestBean testBean = new MultiChannelInstanceRoutingTestBean(channelResolver); MethodInvokingRouter router = new MethodInvokingRouter(testBean, "routePayload"); - this.doTestMultiChannelListResolutionByPayload(router, channelResolver); + doTestMultiChannelListResolutionByPayload(router, channelResolver); } private void doTestMultiChannelListResolutionByPayload(MethodInvokingRouter router, TestChannelResolver channelResolver) { + + router.setBeanFactory(mock(BeanFactory.class)); + router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); channelResolver.addChannel("foo-channel", fooChannel); @@ -459,11 +487,14 @@ public void multiChannelListResolutionByMessageConfiguredByMethodName() { TestChannelResolver channelResolver = new TestChannelResolver(); MultiChannelInstanceRoutingTestBean testBean = new MultiChannelInstanceRoutingTestBean(channelResolver); MethodInvokingRouter router = new MethodInvokingRouter(testBean, "routeMessage"); - this.doTestMultiChannelListResolutionByMessage(router, channelResolver); + doTestMultiChannelListResolutionByMessage(router, channelResolver); } private void doTestMultiChannelListResolutionByMessage(MethodInvokingRouter router, TestChannelResolver channelResolver) { + + router.setBeanFactory(mock(BeanFactory.class)); + router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); channelResolver.addChannel("foo-channel", fooChannel); @@ -503,7 +534,7 @@ public void multiChannelArrayResolutionByMessageConfiguredByMethodReference() th MultiChannelInstanceRoutingTestBean testBean = new MultiChannelInstanceRoutingTestBean(channelResolver); Method routingMethod = testBean.getClass().getMethod("routeMessageToArray", Message.class); MethodInvokingRouter router = new MethodInvokingRouter(testBean, routingMethod); - this.doTestMultiChannelArrayResolutionByMessage(router, channelResolver); + doTestMultiChannelArrayResolutionByMessage(router, channelResolver); } @Test @@ -511,19 +542,22 @@ public void multiChannelArrayResolutionByMessageConfiguredByMethodName() { TestChannelResolver channelResolver = new TestChannelResolver(); MultiChannelInstanceRoutingTestBean testBean = new MultiChannelInstanceRoutingTestBean(channelResolver); MethodInvokingRouter router = new MethodInvokingRouter(testBean, "routeMessageToArray"); - this.doTestMultiChannelArrayResolutionByMessage(router, channelResolver); + doTestMultiChannelArrayResolutionByMessage(router, channelResolver); } private void doTestMultiChannelArrayResolutionByMessage(MethodInvokingRouter router, TestChannelResolver channelResolver) { + + router.setBeanFactory(mock(BeanFactory.class)); + router.afterPropertiesSet(); QueueChannel fooChannel = new QueueChannel(); QueueChannel barChannel = new QueueChannel(); channelResolver.addChannel("foo-channel", fooChannel); channelResolver.addChannel("bar-channel", barChannel); router.setChannelResolver(channelResolver); - Message fooMessage = new GenericMessage("foo"); - Message barMessage = new GenericMessage("bar"); - Message badMessage = new GenericMessage("bad"); + Message fooMessage = new GenericMessage<>("foo"); + Message barMessage = new GenericMessage<>("bar"); + Message badMessage = new GenericMessage<>("bad"); router.handleMessage(fooMessage); Message result1a = fooChannel.receive(0); Message result1b = barChannel.receive(0); @@ -561,7 +595,8 @@ public void testClassAsKeyResolution() { router.setChannelResolver(channelResolver); router.setChannelMapping(String.class.getName(), "stringsChannel"); router.setChannelMapping(Integer.class.getName(), "numbersChannel"); - + router.setBeanFactory(mock(BeanFactory.class)); + router.afterPropertiesSet(); Message message = new GenericMessage<>("bar"); router.handleMessage(message); Message replyMessage = stringsChannel.receive(10000); 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 19dcee5f57b..4b4f1667b71 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,6 +19,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; import java.lang.reflect.Method; import java.util.ArrayList; @@ -32,6 +33,7 @@ import org.junit.Test; import org.springframework.aop.framework.ProxyFactory; +import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.annotation.Splitter; import org.springframework.integration.channel.QueueChannel; @@ -53,7 +55,7 @@ public class MethodInvokingSplitterTests { @Test public void splitStringToStringArray() throws Exception { GenericMessage message = new GenericMessage<>("foo.bar"); - MethodInvokingSplitter splitter = this.getSplitter("stringToStringArray"); + MethodInvokingSplitter splitter = getSplitter("stringToStringArray"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); @@ -69,7 +71,7 @@ public void splitStringToStringArray() throws Exception { @Test public void splitStringToStringList() throws Exception { GenericMessage message = new GenericMessage<>("foo.bar"); - MethodInvokingSplitter splitter = this.getSplitter("stringToStringList"); + MethodInvokingSplitter splitter = getSplitter("stringToStringList"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); @@ -85,7 +87,7 @@ public void splitStringToStringList() throws Exception { @Test public void splitMessageToStringArray() throws Exception { GenericMessage message = new GenericMessage<>("foo.bar"); - MethodInvokingSplitter splitter = this.getSplitter("messageToStringArray"); + MethodInvokingSplitter splitter = getSplitter("messageToStringArray"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); @@ -101,7 +103,7 @@ public void splitMessageToStringArray() throws Exception { @Test public void splitMessageToStringList() throws Exception { GenericMessage message = new GenericMessage<>("foo.bar"); - MethodInvokingSplitter splitter = this.getSplitter("messageToStringList"); + MethodInvokingSplitter splitter = getSplitter("messageToStringList"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); @@ -117,7 +119,7 @@ public void splitMessageToStringList() throws Exception { @Test public void splitMessageToMessageArray() throws Exception { GenericMessage message = new GenericMessage<>("foo.bar"); - MethodInvokingSplitter splitter = this.getSplitter("messageToMessageArray"); + MethodInvokingSplitter splitter = getSplitter("messageToMessageArray"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); @@ -154,6 +156,8 @@ public void splitMessageToMessageBuilderList() { MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, "messageToMessageBuilderList"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); + splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); @@ -202,9 +206,9 @@ public void splitStringToMessageList() throws Exception { } @Test - public void splitStringToStringArrayConfiguredByMethodName() { + public void splitStringToStringArrayConfiguredByMethodName() throws Exception { GenericMessage message = new GenericMessage<>("foo.bar"); - MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, "stringToStringArray"); + MethodInvokingSplitter splitter = getSplitter("stringToStringArray"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); @@ -218,9 +222,9 @@ public void splitStringToStringArrayConfiguredByMethodName() { } @Test - public void splitStringToStringListConfiguredByMethodName() { + public void splitStringToStringListConfiguredByMethodName() throws Exception { GenericMessage message = new GenericMessage<>("foo.bar"); - MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, "stringToStringList"); + MethodInvokingSplitter splitter = getSplitter("stringToStringList"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); @@ -239,6 +243,8 @@ public void splitMessageToStringArrayConfiguredByMethodName() { MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, "messageToStringArray"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); + splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); @@ -250,9 +256,9 @@ public void splitMessageToStringArrayConfiguredByMethodName() { } @Test - public void splitMessageToStringListConfiguredByMethodName() { + public void splitMessageToStringListConfiguredByMethodName() throws Exception { GenericMessage message = new GenericMessage<>("foo.bar"); - MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, "messageToStringList"); + MethodInvokingSplitter splitter = getSplitter("messageToStringList"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); @@ -266,9 +272,9 @@ public void splitMessageToStringListConfiguredByMethodName() { } @Test - public void splitMessageToMessageArrayConfiguredByMethodName() { + public void splitMessageToMessageArrayConfiguredByMethodName() throws Exception { GenericMessage message = new GenericMessage<>("foo.bar"); - MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, "messageToMessageArray"); + MethodInvokingSplitter splitter = getSplitter("messageToMessageArray"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); @@ -282,9 +288,9 @@ public void splitMessageToMessageArrayConfiguredByMethodName() { } @Test - public void splitMessageToMessageListConfiguredByMethodName() { + public void splitMessageToMessageListConfiguredByMethodName() throws Exception { GenericMessage message = new GenericMessage<>("foo.bar"); - MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, "messageToMessageList"); + MethodInvokingSplitter splitter = getSplitter("messageToMessageList"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); @@ -298,9 +304,9 @@ public void splitMessageToMessageListConfiguredByMethodName() { } @Test - public void splitStringToMessageArrayConfiguredByMethodName() { + public void splitStringToMessageArrayConfiguredByMethodName() throws Exception { GenericMessage message = new GenericMessage<>("foo.bar"); - MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, "stringToMessageArray"); + MethodInvokingSplitter splitter = getSplitter("stringToMessageArray"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); splitter.handleMessage(message); @@ -319,6 +325,8 @@ public void splitStringToMessageListConfiguredByMethodName() { MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, "stringToMessageList"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); + splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); @@ -337,11 +345,14 @@ class ListSplitter { public List split(List list) { return list; } + } GenericMessage> message = new GenericMessage<>(Arrays.asList("foo", "bar")); MethodInvokingSplitter splitter = new MethodInvokingSplitter(new ListSplitter(), "split"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); + splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); @@ -378,6 +389,8 @@ public Stream split(Stream stream) { MethodInvokingSplitter splitter = new MethodInvokingSplitter(new StreamSplitter(), "split"); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); + splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); @@ -453,6 +466,8 @@ public void splitPayloadAndHeader() throws Exception { MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean, splittingMethod); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); + splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); @@ -476,6 +491,8 @@ public void singleAnnotation() { MethodInvokingSplitter splitter = new MethodInvokingSplitter(annotatedBean); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); + splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); @@ -498,6 +515,8 @@ public void singlePublicMethod() { MethodInvokingSplitter splitter = new MethodInvokingSplitter(testBean); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); + splitter.setBeanFactory(mock(BeanFactory.class)); + splitter.afterPropertiesSet(); splitter.handleMessage(message); List> replies = replyChannel.clear(); Message reply1 = replies.get(0); @@ -516,7 +535,10 @@ public void multiplePublicMethods() { private MethodInvokingSplitter getSplitter(String methodName) throws Exception { Class paramType = methodName.startsWith("message") ? Message.class : String.class; Method splittingMethod = this.testBean.getClass().getMethod(methodName, paramType); - return new MethodInvokingSplitter(testBean, splittingMethod); + MethodInvokingSplitter methodInvokingSplitter = new MethodInvokingSplitter(this.testBean, splittingMethod); + methodInvokingSplitter.setBeanFactory(mock(BeanFactory.class)); + methodInvokingSplitter.afterPropertiesSet(); + return methodInvokingSplitter; } public static class SplitterTestBean { 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 17b8498cac6..389cab0cf39 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,8 +20,9 @@ import static org.hamcrest.Matchers.notNullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; -import java.util.Collections; +import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.UUID; @@ -30,6 +31,7 @@ import org.junit.Before; import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.annotation.Splitter; import org.springframework.integration.channel.DirectChannel; @@ -44,6 +46,7 @@ * @author Alex Peters * @author Artem Bilan * @author Gary Russell + * * @since 4.1 */ public class StreamingSplitterTests { @@ -52,24 +55,22 @@ public class StreamingSplitterTests { @Before public void setUp() { - message = new GenericMessage("foo.bar"); + this.message = new GenericMessage<>("foo.bar"); } @Test - public void splitToIterator_sequenceSizeInLastMessageHeader() - throws Exception { + public void splitToIterator_sequenceSizeInLastMessageHeader() { int messageQuantity = 5; - MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean( - messageQuantity)); + MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean(messageQuantity)); + splitter.setBeanFactory(mock(BeanFactory.class)); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); - - splitter.handleMessage(message); + splitter.afterPropertiesSet(); + splitter.handleMessage(this.message); List> receivedMessages = replyChannel.clear(); - Collections.sort(receivedMessages, (o1, o2) -> - o1.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class) - .compareTo(o2.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class))); + receivedMessages.sort(Comparator.comparing(o -> + o.getHeaders().get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class))); assertThat(receivedMessages.get(4) .getHeaders() .get(IntegrationMessageHeaderAccessor.SEQUENCE_NUMBER, Integer.class), @@ -77,22 +78,24 @@ public void splitToIterator_sequenceSizeInLastMessageHeader() } @Test - public void splitToIterator_sourceMessageHeadersIncluded() throws Exception { + public void splitToIterator_sourceMessageHeadersIncluded() { String anyHeaderKey = "anyProperty1"; String anyHeaderValue = "anyValue1"; - message = MessageBuilder.fromMessage(message) - .setHeader(anyHeaderKey, anyHeaderValue) - .build(); + this.message = + MessageBuilder.fromMessage(this.message) + .setHeader(anyHeaderKey, anyHeaderValue) + .build(); int messageQuantity = 5; - MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean( - messageQuantity)); + MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean(messageQuantity)); + splitter.setBeanFactory(mock(BeanFactory.class)); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); - splitter.handleMessage(message); + splitter.afterPropertiesSet(); + splitter.handleMessage(this.message); List> receivedMessages = replyChannel.clear(); assertThat(receivedMessages.size(), is(messageQuantity)); - for (Message reveivedMessage : receivedMessages) { - MessageHeaders headers = reveivedMessage.getHeaders(); + for (Message receivedMessage : receivedMessages) { + MessageHeaders headers = receivedMessage.getHeaders(); assertTrue("Unexpected result with: " + headers, headers.containsKey(anyHeaderKey)); assertThat("Unexpected result with: " + headers, headers.get(anyHeaderKey, String.class), @@ -104,53 +107,52 @@ public void splitToIterator_sourceMessageHeadersIncluded() throws Exception { } @Test - public void splitToIterator_allMessagesSent() throws Exception { + public void splitToIterator_allMessagesSent() { int messageQuantity = 5; - MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean( - messageQuantity)); + MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean(messageQuantity)); + splitter.setBeanFactory(mock(BeanFactory.class)); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); - - splitter.handleMessage(message); + splitter.afterPropertiesSet(); + splitter.handleMessage(this.message); assertThat(replyChannel.getQueueSize(), is(messageQuantity)); } @Test - public void splitToIterable_allMessagesSent() throws Exception { + public void splitToIterable_allMessagesSent() { int messageQuantity = 5; - MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IterableTestBean( - messageQuantity)); + MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IterableTestBean(messageQuantity)); + splitter.setBeanFactory(mock(BeanFactory.class)); QueueChannel replyChannel = new QueueChannel(); splitter.setOutputChannel(replyChannel); - - splitter.handleMessage(message); + splitter.afterPropertiesSet(); + splitter.handleMessage(this.message); assertThat(replyChannel.getQueueSize(), is(messageQuantity)); } @Test - public void splitToIterator_allMessagesContainSequenceNumber() - throws Exception { + public void splitToIterator_allMessagesContainSequenceNumber() { final int messageQuantity = 5; - MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean( - messageQuantity)); + MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean(messageQuantity)); + splitter.setBeanFactory(mock(BeanFactory.class)); DirectChannel replyChannel = new DirectChannel(); splitter.setOutputChannel(replyChannel); + splitter.afterPropertiesSet(); 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); + splitter.handleMessage(this.message); } @Test - public void splitWithMassiveReplyMessages_allMessagesSent() - throws Exception { + public void splitWithMassiveReplyMessages_allMessagesSent() { final int messageQuantity = 100000; - MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean( - messageQuantity)); + MethodInvokingSplitter splitter = new MethodInvokingSplitter(new IteratorTestBean(messageQuantity)); + splitter.setBeanFactory(mock(BeanFactory.class)); DirectChannel replyChannel = new DirectChannel(); splitter.setOutputChannel(replyChannel); - + splitter.afterPropertiesSet(); final AtomicInteger receivedMessageCounter = new AtomicInteger(0); new EventDrivenConsumer(replyChannel, message -> { assertThat("Failure with msg: " + message, message.getPayload(), is(notNullValue())); @@ -158,7 +160,7 @@ public void splitWithMassiveReplyMessages_allMessagesSent() }).start(); - splitter.handleMessage(message); + splitter.handleMessage(this.message); assertThat(receivedMessageCounter.get(), is(messageQuantity)); } @@ -197,6 +199,7 @@ public void remove() { }; } + } static class IterableTestBean { @@ -242,6 +245,7 @@ public void remove() { } }; } + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MapToObjectTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MapToObjectTransformerTests.java index d6bd6855617..5f775c468ec 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MapToObjectTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MapToObjectTransformerTests.java @@ -23,9 +23,10 @@ import java.util.HashMap; import java.util.Map; +import org.junit.After; +import org.junit.Before; import org.junit.Test; -import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.support.GenericApplicationContext; import org.springframework.context.support.StaticApplicationContext; @@ -45,9 +46,23 @@ */ public class MapToObjectTransformerTests { + private GenericApplicationContext context = TestUtils.createTestApplicationContext(); + + @Before + public void prepare() { + this.context.registerBeanDefinition(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME, + new RootBeanDefinition("org.springframework.integration.context.CustomConversionServiceFactoryBean")); + this.context.refresh(); + } + + @After + public void terDown() { + this.context.close(); + } + @Test public void testMapToObjectTransformation() { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("fname", "Justin"); map.put("lname", "Case"); Address address = new Address(); @@ -57,7 +72,7 @@ public void testMapToObjectTransformation() { Message message = MessageBuilder.withPayload(map).build(); MapToObjectTransformer transformer = new MapToObjectTransformer(Person.class); - transformer.setBeanFactory(this.getBeanFactory()); + transformer.setBeanFactory(this.context); Message newMessage = transformer.transform(message); Person person = (Person) newMessage.getPayload(); assertNotNull(person); @@ -70,7 +85,7 @@ public void testMapToObjectTransformation() { @Test public void testMapToObjectTransformationWithPrototype() { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("fname", "Justin"); map.put("lname", "Case"); Address address = new Address(); @@ -95,7 +110,7 @@ public void testMapToObjectTransformationWithPrototype() { @Test public void testMapToObjectTransformationWithConversionService() { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("fname", "Justin"); map.put("lname", "Case"); map.put("address", "1123 Main st"); @@ -103,11 +118,11 @@ public void testMapToObjectTransformationWithConversionService() { Message message = MessageBuilder.withPayload(map).build(); MapToObjectTransformer transformer = new MapToObjectTransformer(Person.class); - BeanFactory beanFactory = this.getBeanFactory(); ConverterRegistry conversionService = - beanFactory.getBean(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME, ConverterRegistry.class); + this.context.getBean(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME, + ConverterRegistry.class); conversionService.addConverter(new StringToAddressConverter()); - transformer.setBeanFactory(beanFactory); + transformer.setBeanFactory(this.context); Message newMessage = transformer.transform(message); Person person = (Person) newMessage.getPayload(); @@ -118,14 +133,6 @@ public void testMapToObjectTransformationWithConversionService() { assertEquals("1123 Main st", person.getAddress().getStreet()); } - private BeanFactory getBeanFactory() { - GenericApplicationContext ctx = TestUtils.createTestApplicationContext(); - ctx.registerBeanDefinition(IntegrationUtils.INTEGRATION_CONVERSION_SERVICE_BEAN_NAME, - new RootBeanDefinition("org.springframework.integration.context.CustomConversionServiceFactoryBean")); - ctx.refresh(); - return ctx; - } - public static class Person { private String fname; 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 a54eab23d0b..22442307b03 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,12 +18,14 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; import java.lang.reflect.Method; import java.util.Properties; import org.junit.Test; +import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.annotation.Transformer; import org.springframework.integration.handler.MethodInvokingMessageProcessor; import org.springframework.integration.support.MessageBuilder; @@ -34,6 +36,7 @@ /** * @author Mark Fisher + * @author Artem Bilan */ public class MethodInvokingTransformerTests { @@ -42,15 +45,17 @@ public void simplePayloadConfiguredWithMethodReference() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("exclaim", String.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); - Message message = new GenericMessage("foo"); + transformer.setBeanFactory(mock(BeanFactory.class)); + Message message = new GenericMessage<>("foo"); Message result = transformer.transform(message); assertEquals("FOO!", result.getPayload()); } @Test - public void simplePayloadConfiguredWithMethodName() throws Exception { + public void simplePayloadConfiguredWithMethodName() { TestBean testBean = new TestBean(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, "exclaim"); + transformer.setBeanFactory(mock(BeanFactory.class)); Message message = new GenericMessage("foo"); Message result = transformer.transform(message); assertEquals("FOO!", result.getPayload()); @@ -61,16 +66,18 @@ public void typeConversionConfiguredWithMethodReference() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("exclaim", String.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); - Message message = new GenericMessage(123); + transformer.setBeanFactory(mock(BeanFactory.class)); + Message message = new GenericMessage<>(123); Message result = transformer.transform(message); assertEquals("123!", result.getPayload()); } @Test - public void typeConversionConfiguredWithMethodName() throws Exception { + public void typeConversionConfiguredWithMethodName() { TestBean testBean = new TestBean(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, "exclaim"); - Message message = new GenericMessage(123); + transformer.setBeanFactory(mock(BeanFactory.class)); + Message message = new GenericMessage<>(123); Message result = transformer.transform(message); assertEquals("123!", result.getPayload()); } @@ -85,10 +92,10 @@ public void typeConversionFailureConfiguredWithMethodReference() throws Exceptio } @Test(expected = MessageHandlingException.class) - public void typeConversionFailureConfiguredWithMethodName() throws Exception { + public void typeConversionFailureConfiguredWithMethodName() { TestBean testBean = new TestBean(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, "exclaim"); - Message message = new GenericMessage(new TestBean()); + Message message = new GenericMessage<>(new TestBean()); transformer.transform(message); } @@ -97,6 +104,7 @@ public void headerAnnotationConfiguredWithMethodReference() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("headerTest", String.class, Integer.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); + transformer.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo") .setHeader("number", 123).build(); Message result = transformer.transform(message); @@ -104,9 +112,10 @@ public void headerAnnotationConfiguredWithMethodReference() throws Exception { } @Test - public void headerAnnotationConfiguredWithMethodName() throws Exception { + public void headerAnnotationConfiguredWithMethodName() { TestBean testBean = new TestBean(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, "headerTest"); + transformer.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo") .setHeader("number", 123).build(); Message result = transformer.transform(message); @@ -128,6 +137,7 @@ public void optionalHeaderAnnotation() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("optionalHeaderTest", String.class, Integer.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); + transformer.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo").setHeader("number", 99).build(); Message result = transformer.transform(message); assertEquals("foo99", result.getPayload()); @@ -138,6 +148,7 @@ public void optionalHeaderValueNotProvided() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("optionalHeaderTest", String.class, Integer.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); + transformer.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("foo").build(); Message result = transformer.transform(message); assertEquals("foonull", result.getPayload()); @@ -148,15 +159,17 @@ public void messageReturnValueConfiguredWithMethodReference() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("messageReturnValueTest", Message.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); + transformer.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("test").build(); Message result = transformer.transform(message); assertEquals("test", result.getPayload()); } @Test - public void messageReturnValueConfiguredWithMethodName() throws Exception { + public void messageReturnValueConfiguredWithMethodName() { TestBean testBean = new TestBean(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, "messageReturnValueTest"); + transformer.setBeanFactory(mock(BeanFactory.class)); Message message = MessageBuilder.withPayload("test").build(); Message result = transformer.transform(message); assertEquals("test", result.getPayload()); @@ -168,10 +181,11 @@ public void propertiesPayloadConfiguredWithMethodReference() throws Exception { TestBean testBean = new TestBean(); Method testMethod = testBean.getClass().getMethod("propertyPayloadTest", Properties.class); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, testMethod); + transformer.setBeanFactory(mock(BeanFactory.class)); Properties props = new Properties(); props.setProperty("prop1", "bad"); props.setProperty("prop3", "baz"); - Message message = new GenericMessage(props); + Message message = new GenericMessage<>(props); Message result = (Message) transformer.transform(message); assertEquals(Properties.class, result.getPayload().getClass()); Properties payload = result.getPayload(); @@ -185,13 +199,14 @@ public void propertiesPayloadConfiguredWithMethodReference() throws Exception { @Test @SuppressWarnings("unchecked") - public void propertiesPayloadConfiguredWithMethodName() throws Exception { + public void propertiesPayloadConfiguredWithMethodName() { TestBean testBean = new TestBean(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, "propertyPayloadTest"); + transformer.setBeanFactory(mock(BeanFactory.class)); Properties props = new Properties(); props.setProperty("prop1", "bad"); props.setProperty("prop3", "baz"); - Message message = new GenericMessage(props); + Message message = new GenericMessage<>(props); Message result = (Message) transformer.transform(message); assertEquals(Properties.class, result.getPayload().getClass()); Properties payload = result.getPayload(); @@ -207,12 +222,13 @@ public void propertiesPayloadConfiguredWithMethodName() throws Exception { public void nullReturningMethod() { TestBean testBean = new TestBean(); MethodInvokingTransformer transformer = new MethodInvokingTransformer(testBean, "nullReturnValueTest"); - GenericMessage message = new GenericMessage("test"); + transformer.setBeanFactory(mock(BeanFactory.class)); + GenericMessage message = new GenericMessage<>("test"); Message result = transformer.transform(message); assertNull(result); } - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) @Test // this changed in 2.0 see INT-785 and INT-1130 public void headerEnricherConfiguredWithMethodReference() throws Exception { TestBean testBean = new TestBean(); @@ -220,6 +236,7 @@ public void headerEnricherConfiguredWithMethodReference() throws Exception { HeaderEnricher transformer = new HeaderEnricher(); transformer.setDefaultOverwrite(true); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testBean, testMethod); + processor.setBeanFactory(mock(BeanFactory.class)); transformer.setMessageProcessor(processor); Message message = MessageBuilder.withPayload("test") .setHeader("prop1", "bad") @@ -231,12 +248,14 @@ public void headerEnricherConfiguredWithMethodReference() throws Exception { assertEquals("baz", result.getHeaders().get("prop3")); } - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) @Test // this changed in 2.0 see INT-785 and INT-1130 - public void headerEnricherConfiguredWithMethodName() throws Exception { + public void headerEnricherConfiguredWithMethodName() { TestBean testBean = new TestBean(); HeaderEnricher transformer = new HeaderEnricher(); - MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testBean, "propertyEnricherTest"); + MethodInvokingMessageProcessor processor = + new MethodInvokingMessageProcessor(testBean, "propertyEnricherTest"); + processor.setBeanFactory(mock(BeanFactory.class)); transformer.setMessageProcessor(processor); transformer.setDefaultOverwrite(true); Message message = MessageBuilder.withPayload("test") 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 3aeb5e7d72b..dd896e981d5 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 @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -103,7 +103,7 @@ public void testToNonStringConversionNotSupportedByGenericConversionService() { Collection converted = (Collection) typeConverter.convertValue(1234, TypeDescriptor.valueOf(Integer.class), TypeDescriptor.forObject(new ArrayList<>(Arrays.asList(1)))); - assertEquals(Arrays.asList(1234), converted); + assertEquals(Collections.singletonList(1234), converted); } @Test @@ -192,7 +192,7 @@ public Bar convert(Foo source) { Set fooSet = new HashSet<>(); fooSet.add(new Foo()); - Map> fooMap = new HashMap>(); + Map> fooMap = new HashMap<>(); fooMap.put("foo", fooSet); foos = new HashMap<>(); foos.put("foo", fooMap); @@ -204,6 +204,7 @@ public Bar convert(Foo source) { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor<>(service, "handle"); processor.setConversionService(conversionService); processor.setUseSpelInvoker(true); + processor.setBeanFactory(beanFactory); ServiceActivatingHandler handler = new ServiceActivatingHandler(processor); QueueChannel replyChannel = new QueueChannel(); handler.setOutputChannel(replyChannel); @@ -231,6 +232,7 @@ public Bar convert(Foo source) { MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor<>(service, "handle"); processor.setConversionService(conversionService); processor.setUseSpelInvoker(true); + processor.setBeanFactory(beanFactory); ServiceActivatingHandler handler = new ServiceActivatingHandler(processor); QueueChannel replyChannel = new QueueChannel(); handler.setOutputChannel(replyChannel); diff --git a/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/ApplicationEventListeningMessageProducerTests.java b/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/ApplicationEventListeningMessageProducerTests.java index 237c23a35bf..4aaeb783f3e 100644 --- a/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/ApplicationEventListeningMessageProducerTests.java +++ b/spring-integration-event/src/test/java/org/springframework/integration/event/inbound/ApplicationEventListeningMessageProducerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -170,6 +170,8 @@ public void payloadExpressionEvaluatedAgainstApplicationEvent() { Message message3 = channel.receive(20); assertNotNull(message3); assertEquals("received: event2", message3.getPayload()); + + ctx.close(); } @Test @@ -180,7 +182,7 @@ public void messagingEventReceived() { adapter.start(); Message message1 = channel.receive(0); assertNull(message1); - adapter.onApplicationEvent(new MessagingEvent(new GenericMessage("test"))); + adapter.onApplicationEvent(new MessagingEvent(new GenericMessage<>("test"))); Message message2 = channel.receive(20); assertNotNull(message2); assertEquals("test", message2.getPayload()); @@ -194,7 +196,7 @@ public void messageAsSourceOrCustomEventType() { adapter.start(); Message message1 = channel.receive(0); assertNull(message1); - adapter.onApplicationEvent(new TestMessagingEvent(new GenericMessage("test"))); + adapter.onApplicationEvent(new TestMessagingEvent(new GenericMessage<>("test"))); Message message2 = channel.receive(20); assertNotNull(message2); assertEquals("test", message2.getPayload()); @@ -204,6 +206,7 @@ public void messageAsSourceOrCustomEventType() { public void anyApplicationEventCausesExceptionWithErrorHandling() { DirectChannel channel = new DirectChannel(); channel.subscribe(new AbstractReplyProducingMessageHandler() { + @Override protected Object handleRequestMessage(Message requestMessage) { throw new RuntimeException("Failed"); @@ -223,7 +226,7 @@ protected Object handleRequestMessage(Message requestMessage) { } @Test - @SuppressWarnings({"unchecked", "serial"}) + @SuppressWarnings({ "unchecked", "serial" }) public void testInt2935CheckRetrieverCache() { GenericApplicationContext ctx = TestUtils.createTestApplicationContext(); ConfigurableListableBeanFactory beanFactory = ctx.getBeanFactory(); @@ -278,6 +281,7 @@ public void testInt2935CheckRetrieverCache() { } ctx.publishEvent(new ApplicationEvent("Some event") { + }); assertEquals(4, listenerCounter.get()); diff --git a/spring-integration-http/src/test/java/org/springframework/integration/http/outbound/UriVariableExpressionTests.java b/spring-integration-http/src/test/java/org/springframework/integration/http/outbound/UriVariableExpressionTests.java index 06a3fe9f45e..60cbe1ca16f 100644 --- a/spring-integration-http/src/test/java/org/springframework/integration/http/outbound/UriVariableExpressionTests.java +++ b/spring-integration-http/src/test/java/org/springframework/integration/http/outbound/UriVariableExpressionTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,9 +35,6 @@ import org.springframework.context.support.AbstractApplicationContext; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; -import org.springframework.http.HttpMethod; -import org.springframework.http.client.ClientHttpRequest; -import org.springframework.http.client.SimpleClientHttpRequestFactory; import org.springframework.integration.config.IntegrationRegistrar; import org.springframework.integration.expression.ExpressionEvalMap; import org.springframework.integration.support.MessageBuilder; @@ -62,15 +59,11 @@ public void testFromMessageWithExpressions() { HttpRequestExecutingMessageHandler handler = new HttpRequestExecutingMessageHandler("http://test/{foo}"); SpelExpressionParser parser = new SpelExpressionParser(); handler.setUriVariableExpressions(Collections.singletonMap("foo", parser.parseExpression("payload"))); - handler.setRequestFactory(new SimpleClientHttpRequestFactory() { - - @Override - public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) { - uriHolder.set(uri); - throw new RuntimeException("intentional"); - } - - }); + handler.setRequestFactory( + (uri, httpMethod) -> { + uriHolder.set(uri); + throw new RuntimeException("intentional"); + }); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet(); Message message = new GenericMessage<>("bar"); @@ -96,15 +89,11 @@ public void testFromMessageWithSuperfluousExpressionsInt3054() { multipleExpressions.put("foo", parser.parseExpression("payload")); multipleExpressions.put("extra-to-be-ignored", parser.parseExpression("headers.extra")); handler.setUriVariableExpressions(multipleExpressions); - handler.setRequestFactory(new SimpleClientHttpRequestFactory() { - - @Override - public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) { - uriHolder.set(uri); - throw new RuntimeException("intentional"); - } - - }); + handler.setRequestFactory( + (uri, httpMethod) -> { + uriHolder.set(uri); + throw new RuntimeException("intentional"); + }); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet(); try { @@ -122,15 +111,11 @@ public void testInt3055UriVariablesExpression() { final AtomicReference uriHolder = new AtomicReference<>(); HttpRequestExecutingMessageHandler handler = new HttpRequestExecutingMessageHandler("http://test/{foo}"); - handler.setRequestFactory(new SimpleClientHttpRequestFactory() { - - @Override - public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) { - uriHolder.set(uri); - throw new RuntimeException("intentional"); - } - - }); + handler.setRequestFactory( + (uri, httpMethod) -> { + uriHolder.set(uri); + throw new RuntimeException("intentional"); + }); AbstractApplicationContext context = TestUtils.createTestApplicationContext(); IntegrationRegistrar registrar = new IntegrationRegistrar(); @@ -192,6 +177,8 @@ public ClientHttpRequest createRequest(URI uri, HttpMethod httpMethod) { assertEquals("intentional", e.getCause().getMessage()); } assertEquals("http://test/42", uriHolder.get().toString()); + + context.close(); } } diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpInboundGatewayTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpInboundGatewayTests.java index a39b2a18d78..652e9ca5529 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpInboundGatewayTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpInboundGatewayTests.java @@ -28,6 +28,8 @@ import java.util.HashSet; import java.util.Set; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; @@ -38,7 +40,6 @@ import org.junit.Test; import org.springframework.beans.factory.BeanFactory; -import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.handler.ServiceActivatingHandler; @@ -76,6 +77,8 @@ public void testNetSingle() throws Exception { gateway.setRequestChannel(channel); ServiceActivatingHandler handler = new ServiceActivatingHandler(new Service()); handler.setChannelResolver(channelName -> channel); + handler.setBeanFactory(mock(BeanFactory.class)); + handler.afterPropertiesSet(); Socket socket1 = SocketFactory.getDefault().createSocket("localhost", port); socket1.getOutputStream().write("Test1\r\n".getBytes()); Socket socket2 = SocketFactory.getDefault().createSocket("localhost", port); @@ -87,6 +90,8 @@ public void testNetSingle() throws Exception { assertEquals("Echo:Test1\r\n", new String(bytes)); readFully(socket2.getInputStream(), bytes); assertEquals("Echo:Test2\r\n", new String(bytes)); + gateway.stop(); + scf.stop(); } @Test @@ -102,6 +107,8 @@ public void testNetNotSingle() throws Exception { gateway.setRequestChannel(channel); gateway.setBeanFactory(mock(BeanFactory.class)); ServiceActivatingHandler handler = new ServiceActivatingHandler(new Service()); + handler.setBeanFactory(mock(BeanFactory.class)); + handler.afterPropertiesSet(); Socket socket = SocketFactory.getDefault().createSocket("localhost", port); socket.getOutputStream().write("Test1\r\n".getBytes()); socket.getOutputStream().write("Test2\r\n".getBytes()); @@ -112,6 +119,8 @@ public void testNetNotSingle() throws Exception { assertEquals("Echo:Test1\r\n", new String(bytes)); readFully(socket.getInputStream(), bytes); assertEquals("Echo:Test2\r\n", new String(bytes)); + gateway.stop(); + scf.stop(); } @Test @@ -121,7 +130,9 @@ public void testNetClientMode() throws Exception { final CountDownLatch latch2 = new CountDownLatch(1); final CountDownLatch latch3 = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); - new SimpleAsyncTaskExecutor() + + ExecutorService executorService = Executors.newSingleThreadExecutor(); + executorService .execute(() -> { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0, 10); @@ -158,6 +169,8 @@ public void testNetClientMode() throws Exception { gateway.setBeanFactory(mock(BeanFactory.class)); gateway.afterPropertiesSet(); ServiceActivatingHandler handler = new ServiceActivatingHandler(new Service()); + handler.setBeanFactory(mock(BeanFactory.class)); + handler.afterPropertiesSet(); ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); taskScheduler.setPoolSize(1); taskScheduler.initialize(); @@ -173,6 +186,7 @@ public void testNetClientMode() throws Exception { assertTrue(latch3.await(10, TimeUnit.SECONDS)); assertTrue(done.get()); gateway.stop(); + executorService.shutdown(); } @Test @@ -189,6 +203,8 @@ public void testNioSingle() throws Exception { gateway.setBeanFactory(mock(BeanFactory.class)); ServiceActivatingHandler handler = new ServiceActivatingHandler(new Service()); handler.setChannelResolver(channelName -> channel); + handler.setBeanFactory(mock(BeanFactory.class)); + handler.afterPropertiesSet(); Socket socket1 = SocketFactory.getDefault().createSocket("localhost", port); socket1.getOutputStream().write("Test1\r\n".getBytes()); Socket socket2 = SocketFactory.getDefault().createSocket("localhost", port); @@ -200,6 +216,8 @@ public void testNioSingle() throws Exception { assertEquals("Echo:Test1\r\n", new String(bytes)); readFully(socket2.getInputStream(), bytes); assertEquals("Echo:Test2\r\n", new String(bytes)); + gateway.stop(); + scf.stop(); } @Test @@ -215,6 +233,8 @@ public void testNioNotSingle() throws Exception { gateway.setRequestChannel(channel); gateway.setBeanFactory(mock(BeanFactory.class)); ServiceActivatingHandler handler = new ServiceActivatingHandler(new Service()); + handler.setBeanFactory(mock(BeanFactory.class)); + handler.afterPropertiesSet(); Socket socket = SocketFactory.getDefault().createSocket("localhost", port); socket.getOutputStream().write("Test1\r\n".getBytes()); socket.getOutputStream().write("Test2\r\n".getBytes()); @@ -228,6 +248,8 @@ public void testNioNotSingle() throws Exception { results.add(new String(bytes)); assertTrue(results.remove("Echo:Test1\r\n")); assertTrue(results.remove("Echo:Test2\r\n")); + gateway.stop(); + scf.stop(); } @Test @@ -240,7 +262,7 @@ public void testErrorFlow() throws Exception { final String errorMessage = "An error occurred"; errorChannel.subscribe(message -> { MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); - replyChannel.send(new GenericMessage(errorMessage)); + replyChannel.send(new GenericMessage<>(errorMessage)); }); gateway.setErrorChannel(errorChannel); scf.start(); @@ -260,6 +282,8 @@ public void testErrorFlow() throws Exception { assertEquals(errorMessage + "\r\n", new String(bytes)); readFully(socket2.getInputStream(), bytes); assertEquals(errorMessage + "\r\n", new String(bytes)); + gateway.stop(); + scf.stop(); } diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpReceivingChannelAdapterTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpReceivingChannelAdapterTests.java index 890908f00a5..c798e1b6479 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpReceivingChannelAdapterTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpReceivingChannelAdapterTests.java @@ -632,6 +632,8 @@ public void testException() throws Exception { SubscribableChannel channel = new DirectChannel(); adapter.setOutputChannel(channel); ServiceActivatingHandler handler = new ServiceActivatingHandler(new FailingService()); + handler.setBeanFactory(mock(BeanFactory.class)); + handler.afterPropertiesSet(); channel.subscribe(handler); QueueChannel errorChannel = new QueueChannel(); adapter.setErrorChannel(errorChannel); diff --git a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/AbstractMongoDbMessageGroupStoreTests.java b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/AbstractMongoDbMessageGroupStoreTests.java index 99fbf9bb5f3..d90a67ded95 100644 --- a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/AbstractMongoDbMessageGroupStoreTests.java +++ b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/AbstractMongoDbMessageGroupStoreTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,9 +31,12 @@ import java.util.Properties; import java.util.UUID; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.context.support.GenericApplicationContext; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; @@ -45,6 +48,7 @@ import org.springframework.integration.store.MessageGroupStore; import org.springframework.integration.store.MessageStore; import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.GenericMessage; @@ -59,6 +63,18 @@ */ public abstract class AbstractMongoDbMessageGroupStoreTests extends MongoDbAvailableTests { + protected final GenericApplicationContext testApplicationContext = TestUtils.createTestApplicationContext(); + + @Before + public void setup() { + this.testApplicationContext.refresh(); + } + + @After + public void tearDown() { + this.testApplicationContext.close(); + } + @Test @MongoDbAvailable public void testNonExistingEmptyMessageGroup() throws Exception { diff --git a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/AbstractMongoDbMessageStoreTests.java b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/AbstractMongoDbMessageStoreTests.java index be7ffdee7d8..59996aead31 100644 --- a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/AbstractMongoDbMessageStoreTests.java +++ b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/AbstractMongoDbMessageStoreTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2018 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,8 +29,11 @@ import java.util.UUID; import org.hamcrest.Matchers; +import org.junit.After; +import org.junit.Before; import org.junit.Test; +import org.springframework.context.support.GenericApplicationContext; import org.springframework.data.annotation.PersistenceConstructor; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import org.springframework.integration.channel.DirectChannel; @@ -42,6 +45,7 @@ import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.MutableMessage; import org.springframework.integration.support.MutableMessageBuilder; +import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.ErrorMessage; @@ -59,6 +63,17 @@ */ public abstract class AbstractMongoDbMessageStoreTests extends MongoDbAvailableTests { + protected final GenericApplicationContext testApplicationContext = TestUtils.createTestApplicationContext(); + + @Before + public void setup() { + this.testApplicationContext.refresh(); + } + + @After + public void tearDown() { + this.testApplicationContext.close(); + } @Test @MongoDbAvailable diff --git a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/ConfigurableMongoDbMessageGroupStoreTests.java b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/ConfigurableMongoDbMessageGroupStoreTests.java index 1a27b1e3032..3d7b7bcb3d3 100644 --- a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/ConfigurableMongoDbMessageGroupStoreTests.java +++ b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/ConfigurableMongoDbMessageGroupStoreTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,6 @@ import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.context.support.GenericApplicationContext; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.ReadingConverter; import org.springframework.data.mongodb.MongoDbFactory; @@ -40,7 +39,6 @@ import org.springframework.integration.store.AbstractMessageGroupStore; import org.springframework.integration.store.MessageStore; import org.springframework.integration.support.MessageBuilder; -import org.springframework.integration.test.util.TestUtils; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.util.StopWatch; @@ -58,9 +56,7 @@ public class ConfigurableMongoDbMessageGroupStoreTests extends AbstractMongoDbMe protected ConfigurableMongoDbMessageStore getMessageGroupStore() throws Exception { MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(new MongoClient(), "test"); ConfigurableMongoDbMessageStore mongoDbMessageStore = new ConfigurableMongoDbMessageStore(mongoDbFactory); - GenericApplicationContext testApplicationContext = TestUtils.createTestApplicationContext(); - testApplicationContext.refresh(); - mongoDbMessageStore.setApplicationContext(testApplicationContext); + mongoDbMessageStore.setApplicationContext(this.testApplicationContext); mongoDbMessageStore.afterPropertiesSet(); return mongoDbMessageStore; } @@ -79,7 +75,7 @@ public void testWithAggregatorWithShutdown() throws Exception { @Test @Ignore("The performance test. Enough slow. Also needs the release strategy changed to size() == 1000") @MongoDbAvailable - public void messageGroupStoreLazyLoadPerformance() throws Exception { + public void messageGroupStoreLazyLoadPerformance() { cleanupCollections(new SimpleMongoDbFactory(new MongoClient(), "test")); StopWatch watch = new StopWatch("Lazy-Load Performance"); diff --git a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/ConfigurableMongoDbMessageStoreTests.java b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/ConfigurableMongoDbMessageStoreTests.java index 26c9c32fd7d..d65e416b364 100644 --- a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/ConfigurableMongoDbMessageStoreTests.java +++ b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/ConfigurableMongoDbMessageStoreTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2017 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,11 +17,9 @@ package org.springframework.integration.mongodb.store; -import org.springframework.context.support.GenericApplicationContext; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; import org.springframework.integration.store.MessageStore; -import org.springframework.integration.test.util.TestUtils; import com.mongodb.MongoClient; @@ -35,9 +33,7 @@ public class ConfigurableMongoDbMessageStoreTests extends AbstractMongoDbMessage protected MessageStore getMessageStore() throws Exception { MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(new MongoClient(), "test"); ConfigurableMongoDbMessageStore mongoDbMessageStore = new ConfigurableMongoDbMessageStore(mongoDbFactory); - GenericApplicationContext testApplicationContext = TestUtils.createTestApplicationContext(); - testApplicationContext.refresh(); - mongoDbMessageStore.setApplicationContext(testApplicationContext); + mongoDbMessageStore.setApplicationContext(this.testApplicationContext); mongoDbMessageStore.afterPropertiesSet(); return mongoDbMessageStore; } diff --git a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/MongoDbMessageStoreClaimCheckIntegrationTests.java b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/MongoDbMessageStoreClaimCheckIntegrationTests.java index 1e1f30bcf3c..d793f5e1a93 100644 --- a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/MongoDbMessageStoreClaimCheckIntegrationTests.java +++ b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/MongoDbMessageStoreClaimCheckIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,6 +20,8 @@ import java.io.Serializable; +import org.junit.After; +import org.junit.Before; import org.junit.Test; import org.springframework.context.support.GenericApplicationContext; @@ -41,6 +43,18 @@ */ public class MongoDbMessageStoreClaimCheckIntegrationTests extends MongoDbAvailableTests { + private final GenericApplicationContext testApplicationContext = TestUtils.createTestApplicationContext(); + + @Before + public void setup() { + this.testApplicationContext.refresh(); + } + + @After + public void tearDown() { + this.testApplicationContext.close(); + } + @Test @MongoDbAvailable public void stringPayload() throws Exception { @@ -84,9 +98,7 @@ public void objectPayload() throws Exception { public void stringPayloadConfigurable() throws Exception { MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(new MongoClient(), "test"); ConfigurableMongoDbMessageStore messageStore = new ConfigurableMongoDbMessageStore(mongoDbFactory); - GenericApplicationContext testApplicationContext = TestUtils.createTestApplicationContext(); - testApplicationContext.refresh(); - messageStore.setApplicationContext(testApplicationContext); + messageStore.setApplicationContext(this.testApplicationContext); messageStore.afterPropertiesSet(); ClaimCheckInTransformer checkin = new ClaimCheckInTransformer(messageStore); ClaimCheckOutTransformer checkout = new ClaimCheckOutTransformer(messageStore); @@ -104,9 +116,7 @@ public void stringPayloadConfigurable() throws Exception { public void objectPayloadConfigurable() throws Exception { MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(new MongoClient(), "test"); ConfigurableMongoDbMessageStore messageStore = new ConfigurableMongoDbMessageStore(mongoDbFactory); - GenericApplicationContext testApplicationContext = TestUtils.createTestApplicationContext(); - testApplicationContext.refresh(); - messageStore.setApplicationContext(testApplicationContext); + messageStore.setApplicationContext(this.testApplicationContext); messageStore.afterPropertiesSet(); ClaimCheckInTransformer checkin = new ClaimCheckInTransformer(messageStore); ClaimCheckOutTransformer checkout = new ClaimCheckOutTransformer(messageStore); @@ -127,7 +137,9 @@ public void objectPayloadConfigurable() throws Exception { static class Beverage implements Serializable { private String name; + private int shots; + private boolean iced; @SuppressWarnings("unused") diff --git a/spring-integration-test-support/src/main/java/org/springframework/integration/test/util/TestUtils.java b/spring-integration-test-support/src/main/java/org/springframework/integration/test/util/TestUtils.java index d4127bfdb35..72b0d243600 100644 --- a/spring-integration-test-support/src/main/java/org/springframework/integration/test/util/TestUtils.java +++ b/spring-integration-test-support/src/main/java/org/springframework/integration/test/util/TestUtils.java @@ -52,6 +52,8 @@ */ public abstract class TestUtils { + private static final Log LOGGER = LogFactory.getLog(TestUtils.class); + /** * Obtain a value for the property from the provide object. * Supports nested properties via period delimiter. @@ -114,6 +116,11 @@ public static TestApplicationContext createTestApplicationContext() { scheduler.setErrorHandler(errorHandler); registerBean("taskScheduler", scheduler, context); registerBean("integrationConversionService", new DefaultFormattingConversionService(), context); + registerBean("errorChannel", + (MessageChannel) (message, timeout) -> { + LOGGER.error(message); + return true; + }, context); return context; } diff --git a/spring-integration-xml/src/main/java/org/springframework/integration/xml/xpath/XPathUtils.java b/spring-integration-xml/src/main/java/org/springframework/integration/xml/xpath/XPathUtils.java index 5b8a902b1f6..c9e39fbc6cc 100644 --- a/spring-integration-xml/src/main/java/org/springframework/integration/xml/xpath/XPathUtils.java +++ b/spring-integration-xml/src/main/java/org/springframework/integration/xml/xpath/XPathUtils.java @@ -62,12 +62,12 @@ public final class XPathUtils { private static final List RESULT_TYPES = Arrays.asList(STRING, BOOLEAN, NUMBER, NODE, NODE_LIST, DOCUMENT_LIST); - private static final XmlPayloadConverter converter = new DefaultXmlPayloadConverter(); + private static final XmlPayloadConverter CONVERTER = new DefaultXmlPayloadConverter(); - private static final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactoryUtils.newInstance(); + private static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactoryUtils.newInstance(); static { - documentBuilderFactory.setNamespaceAware(true); + DOCUMENT_BUILDER_FACTORY.setNamespaceAware(true); } /** @@ -97,7 +97,7 @@ public static T evaluate(Object object, String xpath, Object... resultArg) { } XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpath); - Node node = converter.convertToNode(object); + Node node = CONVERTER.convertToNode(object); if (resultType == null) { return (T) expression.evaluateAsString(node); @@ -111,7 +111,7 @@ else if (resultType instanceof String && RESULT_TYPES.contains(resultType)) { List nodeList = (List) XPathEvaluationType.NODE_LIST_RESULT.evaluateXPath(expression, node); try { - DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); + DocumentBuilder documentBuilder = DOCUMENT_BUILDER_FACTORY.newDocumentBuilder(); List documents = new ArrayList<>(nodeList.size()); for (Node n : nodeList) { Document document = documentBuilder.newDocument(); From ab94a686e428618e8c9fa4828cf2906797a636d2 Mon Sep 17 00:00:00 2001 From: Artem Bilan Date: Tue, 15 Jan 2019 14:40:07 -0500 Subject: [PATCH 2/2] * Restore NPE check for the `BeanFactory` in the `MessagingMethodInvokerHelper` to avoid breaking changes in the current point release * Some other polishing and optimizations in the `MessagingMethodInvokerHelper` --- .../support/MessagingMethodInvokerHelper.java | 41 ++++++++++--------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/spring-integration-core/src/main/java/org/springframework/integration/handler/support/MessagingMethodInvokerHelper.java b/spring-integration-core/src/main/java/org/springframework/integration/handler/support/MessagingMethodInvokerHelper.java index 6f900479d4b..80d74ad6839 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/handler/support/MessagingMethodInvokerHelper.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/handler/support/MessagingMethodInvokerHelper.java @@ -398,7 +398,9 @@ private MessagingMethodInvokerHelper(Object targetObject, Class "Cannot convert to expected type (" + this.expectedType + ") from " + this.method); } } else { AnnotatedMethodFilter filter = new AnnotatedMethodFilter(this.annotationType, this.methodName, this.requiresReply); Assert.state(canReturnExpectedType(filter, targetType, context.getTypeConverter()), - "Cannot convert to expected type (" + this.expectedType + ") from " + this.method); + () -> "Cannot convert to expected type (" + this.expectedType + ") from " + this.method); context.registerMethodFilter(targetType, filter); } context.setVariable("target", this.targetObject); @@ -703,9 +705,7 @@ && contentTypeIsJson(parameters.message)) { } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Failed to convert from JSON", e); - } + logger.debug("Failed to convert from JSON", e); } } } @@ -899,13 +899,14 @@ else if (!Modifier.isPublic(method1.getModifiers())) { } Assert.state(!fallbackMethods.isEmpty() || !fallbackMessageMethods.isEmpty(), - "Target object of type [" + this.targetObject.getClass() + + () -> "Target object of type [" + this.targetObject.getClass() + "] has no eligible methods for handling Messages."); - Assert.isNull(ambiguousFallbackType.get(), "Found ambiguous parameter type [" + ambiguousFallbackType - + "] for method match: " + fallbackMethods.values()); + Assert.isNull(ambiguousFallbackType.get(), + () -> "Found ambiguous parameter type [" + ambiguousFallbackType + + "] for method match: " + fallbackMethods.values()); Assert.isNull(ambiguousFallbackMessageGenericType.get(), - "Found ambiguous parameter type [" + () -> "Found ambiguous parameter type [" + ambiguousFallbackMessageGenericType + "] for method match: " + fallbackMethods.values()); @@ -967,8 +968,9 @@ private void findSingleSpecifMethodOnInterfacesIfProxy(final Object targetObject } private void checkSpelInvokerRequired(final Class targetClass, Method methodArg, HandlerMethod handlerMethod) { - UseSpelInvoker useSpel = AnnotationUtils.findAnnotation(AopUtils.getMostSpecificMethod(methodArg, targetClass), - UseSpelInvoker.class); + UseSpelInvoker useSpel = + AnnotationUtils.findAnnotation(AopUtils.getMostSpecificMethod(methodArg, targetClass), + UseSpelInvoker.class); if (useSpel == null) { useSpel = AnnotationUtils.findAnnotation(targetClass, UseSpelInvoker.class); } @@ -1005,14 +1007,12 @@ private Class getTargetClass(Object targetObject) { try { // Maybe a proxy with no target - e.g. gateway Class[] interfaces = ((Advised) targetObject).getProxiedInterfaces(); - if (interfaces != null && interfaces.length == 1) { + if (interfaces.length == 1) { targetClass = interfaces[0]; } } catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Exception trying to extract interface", e); - } + logger.debug("Exception trying to extract interface", e); } } } @@ -1133,7 +1133,10 @@ public String toString() { } private String generateExpression(Method method) { - StringBuilder sb = new StringBuilder("#target." + method.getName() + "("); + StringBuilder sb = + new StringBuilder("#target.") + .append(method.getName()) + .append('('); Class[] parameterTypes = method.getParameterTypes(); Annotation[][] parameterAnnotations = method.getParameterAnnotations(); boolean hasUnqualifiedMapParameter = false; @@ -1347,9 +1350,7 @@ public static class ParametersWrapper { */ public static Object getHeader(Map headers, String header) { Object object = headers.get(header); - if (object == null) { - throw new IllegalArgumentException("required header not available: " + header); - } + Assert.notNull(object, () -> "required header not available: " + header); return object; }