From 3f5aba2cb9ee326795491e8e444dc90cac71a3dc Mon Sep 17 00:00:00 2001 From: Artem Bilan Date: Wed, 17 Jun 2020 14:00:06 -0400 Subject: [PATCH] Support Java 14 (#3310) * Support Java 14 * Provide changes to avoid deprecated Java API and have a compatibility back to Java 8 * Change affected test classes to JUnit 5 whenever it is possible * Ignore/Disable some TCP/IP tests which don't pass on Java 14 * Fix (some) TCP tests on JRE 14 * Fix SSL Handshake test - client side handshake is successful with java 14 - change the badClient cert to a badServer cert to force an error on the client side Co-authored-by: artembilan Co-authored-by: Gary Russell --- build.gradle | 14 ++ .../support/DefaultAmqpHeaderMapperTests.java | 2 +- .../integration/dsl/EndpointSpec.java | 14 +- .../dsl/IntegrationFlowAdapter.java | 8 +- .../integration/dsl/IntegrationFlows.java | 6 +- .../integration/handler/BridgeHandler.java | 4 +- .../integration/metadata/MetadataStore.java | 6 +- .../integration/dsl/IntegrationFlowDsl.kt | 2 +- .../config/xml/DelayerParserTests.java | 6 +- .../xml/HeaderEnricherOverwriteTests.java | 6 +- .../config/xml/HeaderEnricherTests.java | 13 +- .../dsl/flows/IntegrationFlowTests.java | 5 +- .../dsl/flowservices/FlowServiceTests.java | 11 +- .../dsl/manualflow/ManualFlowTests.java | 9 +- .../ProducerAndConsumerAutoStartupTests.java | 8 +- ...namicExpressionFilterIntegrationTests.java | 30 ++- .../filter/SpelFilterIntegrationTests.java | 45 ++-- .../gateway/GatewayProxyFactoryBeanTests.java | 2 +- ...vokingMessageProcessorAnnotationTests.java | 6 +- .../message/MessageBuilderTests.java | 8 +- .../message/MessageHeadersTests.java | 39 ++-- .../message/PayloadAndHeaderMappingTests.java | 211 +++++++++--------- .../router/config/RouterParserTests.java | 59 ++--- .../SpelSplitterIntegrationTests.java | 23 +- .../integration/dsl/KotlinDslTests.kt | 4 +- .../file/DefaultFileNameGeneratorTests.java | 9 +- ...GroovyScriptExecutingMessageProcessor.java | 41 ++-- .../HttpOutboundGatewayParserTests.java | 4 +- .../http/inbound/CrossOriginTests.java | 6 +- .../tcp/connection/TcpNioSSLConnection.java | 7 + .../udp/MulticastReceivingChannelAdapter.java | 8 +- .../udp/MulticastSendingMessageHandler.java | 21 +- .../CachingClientConnectionFactoryTests.java | 103 +++------ .../ip/tcp/connection/SocketSupportTests.java | 15 +- .../tcp/connection/TcpNioConnectionTests.java | 64 +++--- ...ramPacketMulticastSendingHandlerTests.java | 18 +- .../integration/ip/udp/MulticastRule.java | 38 ++-- .../ip/udp/UdpChannelAdapterTests.java | 27 ++- .../integration/ip/util/SocketTestUtils.java | 124 ++-------- .../jms/config/JmsChannelFactoryBean.java | 11 +- .../jms/dsl/JmsListenerContainerSpec.java | 15 +- .../jms/DefaultJmsHeaderMapperTests.java | 59 ++--- .../jms/config/TestJmsHeaderMapper.java | 7 +- .../integration/jms/dsl/JmsTests.java | 4 +- .../jmx/NamedFieldsMBeanAttributeFilter.java | 9 +- .../NotNamedFieldsMBeanAttributeFilter.java | 9 +- .../jmx/MBeanAttributeFilterTests.java | 14 +- .../jmx/configuration/DslMBeanTests.java | 4 +- .../IntegrationRSocketMessageHandler.java | 21 +- .../jsr223/Jsr223ServiceActivatorTests.java | 56 +++-- .../WebFluxOutboundGatewayParserTests.java | 13 +- .../config/XPathTransformerParserTests.java | 6 +- .../transformer/XPathTransformerTests.java | 30 +-- 53 files changed, 613 insertions(+), 671 deletions(-) diff --git a/build.gradle b/build.gradle index 58af78f2dd..b10d9ae97c 100644 --- a/build.gradle +++ b/build.gradle @@ -67,7 +67,9 @@ ext { h2Version = '1.4.200' jacksonVersion = '2.11.0' javaxActivationVersion = '1.2.0' + javaxAnnotationVersion= '1.3.2' javaxMailVersion = '1.6.2' + jaxbVersion = '2.3.3' jmsApiVersion = '2.0.1' jpa21ApiVersion = '1.0.2.Final' jpaApiVersion = '2.2.1' @@ -90,8 +92,10 @@ ext { resilience4jVersion = '1.4.0' romeToolsVersion = '1.12.2' rsocketVersion = '1.0.0' + saajVersion = '1.5.2' servletApiVersion = '4.0.1' smackVersion = '4.3.4' + soapVersion = '1.4.0' springAmqpVersion = project.hasProperty('springAmqpVersion') ? project.springAmqpVersion : '2.3.0-SNAPSHOT' springDataVersion = project.hasProperty('springDataVersion') ? project.springDataVersion : '2020.0.0-SNAPSHOT' springSecurityVersion = project.hasProperty('springSecurityVersion') ? project.springSecurityVersion : '5.4.0-SNAPSHOT' @@ -231,6 +235,7 @@ configure(javaProjects) { subproject -> testImplementation 'io.projectreactor:reactor-test' testImplementation "com.jayway.jsonpath:json-path:$jsonpathVersion" testImplementation 'com.fasterxml.jackson.core:jackson-databind' + testImplementation "javax.annotation:javax.annotation-api:$javaxAnnotationVersion" // To avoid compiler warnings about @API annotations in JUnit code testCompileOnly 'org.apiguardian:apiguardian-api:1.0.0' @@ -314,6 +319,8 @@ configure(javaProjects) { subproject -> environment 'SI_FATAL_WHEN_NO_BEANFACTORY', 'true' useJUnitPlatform() + + enableAssertions = false } checkstyle { @@ -774,6 +781,11 @@ project('spring-integration-ws') { exclude group: 'org.springframework' } + optionalApi "javax.activation:javax.activation-api:$javaxActivationVersion" + providedImplementation "javax.xml.soap:javax.xml.soap-api:$soapVersion" + providedImplementation "com.sun.xml.bind:jaxb-impl:$jaxbVersion" + providedImplementation "com.sun.xml.messaging.saaj:saaj-impl:$saajVersion" + testImplementation "com.thoughtworks.xstream:xstream:$xstreamVersion" testImplementation ("org.springframework.ws:spring-ws-support:$springWsVersion") { exclude group: 'org.springframework' @@ -801,6 +813,8 @@ project('spring-integration-xml') { optionalApi ("org.springframework.ws:spring-ws-core:$springWsVersion") { exclude group: 'org.springframework' } + + testImplementation "com.sun.xml.bind:jaxb-impl:$jaxbVersion" } } diff --git a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/DefaultAmqpHeaderMapperTests.java b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/DefaultAmqpHeaderMapperTests.java index 2a6b5f9376..50fe29b56f 100644 --- a/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/DefaultAmqpHeaderMapperTests.java +++ b/spring-integration-amqp/src/test/java/org/springframework/integration/amqp/support/DefaultAmqpHeaderMapperTests.java @@ -115,7 +115,7 @@ public class DefaultAmqpHeaderMapperTests { assertThat(amqpProperties.getDeliveryMode()).isEqualTo(MessageDeliveryMode.NON_PERSISTENT); assertThat(amqpProperties.getDeliveryTag()).isEqualTo(1234L); assertThat(amqpProperties.getExpiration()).isEqualTo("test.expiration"); - assertThat(amqpProperties.getMessageCount()).isEqualTo(new Integer(42)); + assertThat(amqpProperties.getMessageCount()).isEqualTo(42); assertThat(amqpProperties.getMessageId()).isEqualTo("test.messageId"); assertThat(amqpProperties.getReceivedExchange()).isEqualTo("test.receivedExchange"); assertThat(amqpProperties.getReceivedRoutingKey()).isEqualTo("test.receivedRoutingKey"); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/dsl/EndpointSpec.java b/spring-integration-core/src/main/java/org/springframework/integration/dsl/EndpointSpec.java index cc0a799879..176c53f5b0 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/dsl/EndpointSpec.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/dsl/EndpointSpec.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2019 the original author or authors. + * Copyright 2016-2020 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 java.util.LinkedHashMap; import java.util.Map; import java.util.function.Function; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.BeanNameAware; import org.springframework.core.ResolvableType; import org.springframework.integration.channel.DirectChannel; @@ -55,14 +56,9 @@ public abstract class EndpointSpec, F extends Be @SuppressWarnings("unchecked") protected EndpointSpec(H handler) { - try { - Class fClass = ResolvableType.forClass(this.getClass()).as(EndpointSpec.class).resolveGenerics()[1]; - this.endpointFactoryBean = (F) fClass.newInstance(); - this.handler = handler; - } - catch (Exception e) { - throw new IllegalStateException(e); - } + Class fClass = ResolvableType.forClass(this.getClass()).as(EndpointSpec.class).resolveGenerics()[1]; + this.endpointFactoryBean = (F) BeanUtils.instantiateClass(fClass); + this.handler = handler; } @Override diff --git a/spring-integration-core/src/main/java/org/springframework/integration/dsl/IntegrationFlowAdapter.java b/spring-integration-core/src/main/java/org/springframework/integration/dsl/IntegrationFlowAdapter.java index 66d24c9815..22865db52a 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/dsl/IntegrationFlowAdapter.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/dsl/IntegrationFlowAdapter.java @@ -179,14 +179,14 @@ public abstract class IntegrationFlowAdapter implements IntegrationFlow, SmartLi return IntegrationFlows.from(inboundGatewaySpec); } - protected IntegrationFlowBuilder from(Supplier messageSource) { - return IntegrationFlows.from(messageSource); + protected IntegrationFlowBuilder fromSupplier(Supplier messageSource) { + return IntegrationFlows.fromSupplier(messageSource); } - protected IntegrationFlowBuilder from(Supplier messageSource, + protected IntegrationFlowBuilder fromSupplier(Supplier messageSource, Consumer endpointConfigurer) { - return IntegrationFlows.from(messageSource, endpointConfigurer); + return IntegrationFlows.fromSupplier(messageSource, endpointConfigurer); } protected IntegrationFlowBuilder from(Class serviceInterface) { diff --git a/spring-integration-core/src/main/java/org/springframework/integration/dsl/IntegrationFlows.java b/spring-integration-core/src/main/java/org/springframework/integration/dsl/IntegrationFlows.java index ec1b260c45..9f328d71ff 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/dsl/IntegrationFlows.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/dsl/IntegrationFlows.java @@ -141,8 +141,8 @@ public final class IntegrationFlows { * @return new {@link IntegrationFlowBuilder}. * @see Supplier */ - public static IntegrationFlowBuilder from(Supplier messageSource) { - return from(messageSource, null); + public static IntegrationFlowBuilder fromSupplier(Supplier messageSource) { + return fromSupplier(messageSource, null); } /** @@ -156,7 +156,7 @@ public final class IntegrationFlows { * @return new {@link IntegrationFlowBuilder}. * @see Supplier */ - public static IntegrationFlowBuilder from(Supplier messageSource, + public static IntegrationFlowBuilder fromSupplier(Supplier messageSource, Consumer endpointConfigurer) { Assert.notNull(messageSource, "'messageSource' must not be null"); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/handler/BridgeHandler.java b/spring-integration-core/src/main/java/org/springframework/integration/handler/BridgeHandler.java index 66fac1a705..92df472ccd 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/handler/BridgeHandler.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/handler/BridgeHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ import org.springframework.messaging.Message; *

* The BridgeHandler can be used as a stopper at the end of an assembly line of * channels. In this setup the output channel doesn't have to be set, but if the - * output channel is omitted the REPLY_CHANNEL MUST be set on the + * output channel is omitted the {@code REPLY_CHANNEL} MUST be set on the * message. Otherwise, a MessagingException will be thrown at runtime. * * @author Mark Fisher diff --git a/spring-integration-core/src/main/java/org/springframework/integration/metadata/MetadataStore.java b/spring-integration-core/src/main/java/org/springframework/integration/metadata/MetadataStore.java index 41edd8102f..0980bceedb 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/metadata/MetadataStore.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/metadata/MetadataStore.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -52,8 +52,8 @@ public interface MetadataStore { /** * Remove a value for the given key from this MetadataStore. * @param key The key. - * @return The previous value associated with key, or - * null if there was no mapping for key. + * @return The previous value associated with key, or + * null if there was no mapping for key. */ @ManagedAttribute String remove(String key); diff --git a/spring-integration-core/src/main/kotlin/org/springframework/integration/dsl/IntegrationFlowDsl.kt b/spring-integration-core/src/main/kotlin/org/springframework/integration/dsl/IntegrationFlowDsl.kt index 4fb241eeba..923341eb2f 100644 --- a/spring-integration-core/src/main/kotlin/org/springframework/integration/dsl/IntegrationFlowDsl.kt +++ b/spring-integration-core/src/main/kotlin/org/springframework/integration/dsl/IntegrationFlowDsl.kt @@ -106,7 +106,7 @@ fun integrationFlow(messageSource: MessageSourceSpec<*, out MessageSource<*>>, fun integrationFlow(source: () -> Any, options: SourcePollingChannelAdapterSpec.() -> Unit = {}, flow: KotlinIntegrationFlowDefinition.() -> Unit) = - buildIntegrationFlow(IntegrationFlows.from(source, options), flow) + buildIntegrationFlow(IntegrationFlows.fromSupplier(source, options), flow) /** * Functional [IntegrationFlow] definition in Kotlin DSL for [IntegrationFlows.from] - diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelayerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelayerParserTests.java index d1172998c5..77ff5be58d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelayerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/DelayerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -63,13 +63,13 @@ public class DelayerParserTests { DelayHandler delayHandler = context.getBean("delayerWithDefaultScheduler.handler", DelayHandler.class); assertThat(delayHandler.getOrder()).isEqualTo(99); assertThat(delayHandler.getOutputChannel()).isSameAs(this.context.getBean("output")); - assertThat(TestUtils.getPropertyValue(delayHandler, "defaultDelay", Long.class)).isEqualTo(new Long(1234)); + assertThat(TestUtils.getPropertyValue(delayHandler, "defaultDelay", Long.class)).isEqualTo(1234L); //INT-2243 assertThat(TestUtils.getPropertyValue(delayHandler, "delayExpression")).isNotNull(); assertThat(TestUtils.getPropertyValue(delayHandler, "delayExpression", Expression.class).getExpressionString()) .isEqualTo("headers.foo"); assertThat(TestUtils.getPropertyValue(delayHandler, "messagingTemplate.sendTimeout", Long.class)) - .isEqualTo(new Long(987)); + .isEqualTo(987L); assertThat(TestUtils.getPropertyValue(delayHandler, "taskScheduler")).isNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherOverwriteTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherOverwriteTests.java index 019b0dfd85..45d162b853 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherOverwriteTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherOverwriteTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -159,7 +159,7 @@ public class HeaderEnricherOverwriteTests { template.setDefaultDestination(channel); Message result = template.sendAndReceive(new GenericMessage("test")); assertThat(result).isNotNull(); - assertThat(new IntegrationMessageHeaderAccessor(result).getPriority()).isEqualTo(new Integer(42)); + assertThat(new IntegrationMessageHeaderAccessor(result).getPriority()).isEqualTo(42); } @Test @@ -173,7 +173,7 @@ public class HeaderEnricherOverwriteTests { input.send(message); Message result = replyChannel.receive(0); assertThat(result).isNotNull(); - assertThat(new IntegrationMessageHeaderAccessor(result).getPriority()).isEqualTo(new Integer(77)); + assertThat(new IntegrationMessageHeaderAccessor(result).getPriority()).isEqualTo(77); } @Test diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherTests.java index 62c17a55cc..86114aa697 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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 java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; +import java.util.Objects; import org.junit.Test; import org.junit.runner.RunWith; @@ -137,7 +138,7 @@ public class HeaderEnricherTests { MessageChannel channel = context.getBean("expirationDateValueInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); - assertThat(new IntegrationMessageHeaderAccessor(result).getExpirationDate()).isEqualTo(new Long(1111)); + assertThat(new IntegrationMessageHeaderAccessor(result).getExpirationDate()).isEqualTo(1111L); } @Test @@ -146,7 +147,7 @@ public class HeaderEnricherTests { MessageChannel channel = context.getBean("expirationDateRefInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); - assertThat(new IntegrationMessageHeaderAccessor(result).getExpirationDate()).isEqualTo(new Long(9999)); + assertThat(new IntegrationMessageHeaderAccessor(result).getExpirationDate()).isEqualTo(9999); } @Test @@ -155,7 +156,7 @@ public class HeaderEnricherTests { MessageChannel channel = context.getBean("priorityInput", MessageChannel.class); Message result = template.sendAndReceive(channel, new GenericMessage<>("test")); assertThat(result).isNotNull(); - assertThat(new IntegrationMessageHeaderAccessor(result).getPriority()).isEqualTo(new Integer(42)); + assertThat(new IntegrationMessageHeaderAccessor(result).getPriority()).isEqualTo(42); } @Test @@ -165,7 +166,7 @@ public class HeaderEnricherTests { Message result = template.sendAndReceive(channel, new GenericMessage<>(Collections.singletonMap("priority", "-10"))); assertThat(result).isNotNull(); - assertThat(new IntegrationMessageHeaderAccessor(result).getPriority()).isEqualTo(new Integer(-10)); + assertThat(new IntegrationMessageHeaderAccessor(result).getPriority()).isEqualTo(-10); } @Test @@ -300,7 +301,7 @@ public class HeaderEnricherTests { TestBean testBean = (TestBean) o; - return !(name != null ? !name.equals(testBean.name) : testBean.name != null); + return Objects.equals(name, testBean.name); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/flows/IntegrationFlowTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/flows/IntegrationFlowTests.java index a9880d2710..a412cd9498 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/flows/IntegrationFlowTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/flows/IntegrationFlowTests.java @@ -540,7 +540,7 @@ public class IntegrationFlowTests { @Bean public IntegrationFlow supplierFlow() { - return IntegrationFlows.from(stringSupplier()) + return IntegrationFlows.fromSupplier(stringSupplier()) .transform(toUpperCaseFunction()) .channel("suppliedChannel") .get(); @@ -572,7 +572,8 @@ public class IntegrationFlowTests { @Bean public IntegrationFlow supplierFlow2() { - return IntegrationFlows.from(() -> "foo", c -> c.poller(Pollers.fixedDelay(100).maxMessagesPerPoll(1))) + return IntegrationFlows.fromSupplier(() -> "foo", + c -> c.poller(Pollers.fixedDelay(100).maxMessagesPerPoll(1))) .transform(String::toUpperCase) .channel("suppliedChannel2") .get(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/flowservices/FlowServiceTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/flowservices/FlowServiceTests.java index afb348734d..68ab2b657a 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/flowservices/FlowServiceTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/flowservices/FlowServiceTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2016-2019 the original author or authors. + * Copyright 2016-2020 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. @@ -25,8 +25,7 @@ import java.util.List; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.aop.framework.Advised; import org.springframework.aop.support.AopUtils; @@ -60,7 +59,7 @@ import org.springframework.messaging.handler.annotation.Header; import org.springframework.scheduling.TriggerContext; import org.springframework.stereotype.Component; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.util.StringUtils; /** @@ -68,7 +67,7 @@ import org.springframework.util.StringUtils; * * @since 5.0 */ -@RunWith(SpringRunner.class) +@SpringJUnitConfig @DirtiesContext public class FlowServiceTests { @@ -174,7 +173,7 @@ public class FlowServiceTests { @Override protected IntegrationFlowDefinition buildFlow() { - return from(this::messageSource, e -> e.poller(p -> p.trigger(this::nextExecutionTime))) + return fromSupplier(this::messageSource, e -> e.poller(p -> p.trigger(this::nextExecutionTime))) .split(this, null, e -> e.applySequence(false)) .transform(this) .aggregate(a -> a.processor(this, null)) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/dsl/manualflow/ManualFlowTests.java b/spring-integration-core/src/test/java/org/springframework/integration/dsl/manualflow/ManualFlowTests.java index 1fd66fc397..b728aa3f16 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/dsl/manualflow/ManualFlowTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/dsl/manualflow/ManualFlowTests.java @@ -34,8 +34,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanCreationException; import org.springframework.beans.factory.BeanCreationNotAllowedException; @@ -87,7 +86,7 @@ import org.springframework.messaging.support.GenericMessage; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import org.springframework.util.ReflectionUtils; import reactor.core.publisher.Flux; @@ -100,7 +99,7 @@ import reactor.core.publisher.Flux; */ @ContextConfiguration(loader = NoBeansOverrideAnnotationConfigContextLoader.class, classes = ManualFlowTests.RootConfiguration.class) -@RunWith(SpringRunner.class) +@SpringJUnitConfig @DirtiesContext public class ManualFlowTests { @@ -537,7 +536,7 @@ public class ManualFlowTests { .withCauseExactlyInstanceOf(IllegalStateException.class) .withRootCauseInstanceOf(ClassCastException.class) .withMessageContaining("from source: '" + source + "'") - .withStackTraceContaining("java.util.Date cannot be cast to java.lang.String"); + .withStackTraceContaining("java.util.Date cannot be cast to"); flowRegistration.destroy(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ProducerAndConsumerAutoStartupTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ProducerAndConsumerAutoStartupTests.java index e320b8e254..9128df244d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ProducerAndConsumerAutoStartupTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ProducerAndConsumerAutoStartupTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -58,9 +58,9 @@ public class ProducerAndConsumerAutoStartupTests { received.add(this.consumer.poll(10000)); } this.context.stop(); - assertThat(received.get(0)).isEqualTo(new Integer(1)); - assertThat(received.get(1)).isEqualTo(new Integer(2)); - assertThat(received.get(2)).isEqualTo(new Integer(3)); + assertThat(received.get(0)).isEqualTo(1); + assertThat(received.get(1)).isEqualTo(2); + assertThat(received.get(2)).isEqualTo(3); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/filter/DynamicExpressionFilterIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/filter/DynamicExpressionFilterIntegrationTests.java index c482fbe4e5..dac797ccea 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/filter/DynamicExpressionFilterIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/filter/DynamicExpressionFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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,21 +18,19 @@ package org.springframework.integration.filter; import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.support.GenericMessage; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Mark Fisher + * @author Artem Bilan */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class DynamicExpressionFilterIntegrationTests { @Autowired @@ -46,15 +44,15 @@ public class DynamicExpressionFilterIntegrationTests { @Test - public void simpleExpressionBasedFilter() { - this.input.send(new GenericMessage(1)); - this.input.send(new GenericMessage(0)); - this.input.send(new GenericMessage(99)); - this.input.send(new GenericMessage(-99)); - assertThat(positives.receive(0).getPayload()).isEqualTo(new Integer(1)); - assertThat(positives.receive(0).getPayload()).isEqualTo(new Integer(99)); - assertThat(negatives.receive(0).getPayload()).isEqualTo(new Integer(0)); - assertThat(negatives.receive(0).getPayload()).isEqualTo(new Integer(-99)); + void simpleExpressionBasedFilter() { + this.input.send(new GenericMessage<>(1)); + this.input.send(new GenericMessage<>(0)); + this.input.send(new GenericMessage<>(99)); + this.input.send(new GenericMessage<>(-99)); + assertThat(positives.receive(0).getPayload()).isEqualTo(1); + assertThat(positives.receive(0).getPayload()).isEqualTo(99); + assertThat(negatives.receive(0).getPayload()).isEqualTo(0); + assertThat(negatives.receive(0).getPayload()).isEqualTo(-99); assertThat(positives.receive(0)).isNull(); assertThat(negatives.receive(0)).isNull(); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/filter/SpelFilterIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/filter/SpelFilterIntegrationTests.java index ea207df3b8..62b40616e2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/filter/SpelFilterIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/filter/SpelFilterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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,21 +18,19 @@ package org.springframework.integration.filter; import static org.assertj.core.api.Assertions.assertThat; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.support.GenericMessage; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Mark Fisher + * @author Artem Bilan */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class SpelFilterIntegrationTests { @Autowired @@ -56,28 +54,28 @@ public class SpelFilterIntegrationTests { @Test public void simpleExpressionBasedFilter() { - this.simpleInput.send(new GenericMessage(1)); - this.simpleInput.send(new GenericMessage(0)); - this.simpleInput.send(new GenericMessage(99)); - this.simpleInput.send(new GenericMessage(-99)); - assertThat(positives.receive(0).getPayload()).isEqualTo(new Integer(1)); - assertThat(positives.receive(0).getPayload()).isEqualTo(new Integer(99)); - assertThat(negatives.receive(0).getPayload()).isEqualTo(new Integer(0)); - assertThat(negatives.receive(0).getPayload()).isEqualTo(new Integer(-99)); + this.simpleInput.send(new GenericMessage<>(1)); + this.simpleInput.send(new GenericMessage<>(0)); + this.simpleInput.send(new GenericMessage<>(99)); + this.simpleInput.send(new GenericMessage<>(-99)); + assertThat(positives.receive(0).getPayload()).isEqualTo(1); + assertThat(positives.receive(0).getPayload()).isEqualTo(99); + assertThat(negatives.receive(0).getPayload()).isEqualTo(0); + assertThat(negatives.receive(0).getPayload()).isEqualTo(-99); assertThat(positives.receive(0)).isNull(); assertThat(negatives.receive(0)).isNull(); } @Test public void beanResolvingExpressionBasedFilter() { - this.beanResolvingInput.send(new GenericMessage(1)); - this.beanResolvingInput.send(new GenericMessage(2)); - this.beanResolvingInput.send(new GenericMessage(9)); - this.beanResolvingInput.send(new GenericMessage(22)); - assertThat(odds.receive(0).getPayload()).isEqualTo(new Integer(1)); - assertThat(odds.receive(0).getPayload()).isEqualTo(new Integer(9)); - assertThat(evens.receive(0).getPayload()).isEqualTo(new Integer(2)); - assertThat(evens.receive(0).getPayload()).isEqualTo(new Integer(22)); + this.beanResolvingInput.send(new GenericMessage<>(1)); + this.beanResolvingInput.send(new GenericMessage<>(2)); + this.beanResolvingInput.send(new GenericMessage<>(9)); + this.beanResolvingInput.send(new GenericMessage<>(22)); + assertThat(odds.receive(0).getPayload()).isEqualTo(1); + assertThat(odds.receive(0).getPayload()).isEqualTo(9); + assertThat(evens.receive(0).getPayload()).isEqualTo(2); + assertThat(evens.receive(0).getPayload()).isEqualTo(22); assertThat(odds.receive(0)).isNull(); assertThat(evens.receive(0)).isNull(); } @@ -89,6 +87,7 @@ public class SpelFilterIntegrationTests { public boolean isEven(int number) { return number % 2 == 0; } + } } 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 5094de2c78..dcf2335de5 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 @@ -209,7 +209,7 @@ public class GatewayProxyFactoryBeanTests { proxyFactory.afterPropertiesSet(); TestService service = (TestService) proxyFactory.getObject(); Integer result = service.requestReplyWithIntegers(123); - assertThat(result).isEqualTo(new Integer(123456)); + assertThat(result).isEqualTo(123456); } @Test 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 b719837138..a595ec7d66 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-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -255,8 +255,8 @@ public class MethodInvokingMessageProcessorAnnotationTests { .setHeader("attrib2", 456).build(); Map result = (Map) processor.processMessage(message); assertThat(result.size()).isEqualTo(2); - assertThat(result.get("attrib1")).isEqualTo(new Integer(88)); - assertThat(result.get("attrib2")).isEqualTo(new Integer(99)); + assertThat(result.get("attrib1")).isEqualTo(88); + assertThat(result.get("attrib2")).isEqualTo(99); } @Test diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderTests.java index 3571372f66..0a126d186d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageBuilderTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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 class MessageBuilderTests { .setHeader("count", 123) .build(); assertThat(message.getHeaders().get("foo", String.class)).isEqualTo("bar"); - assertThat(message.getHeaders().get("count", Integer.class)).isEqualTo(new Integer(123)); + assertThat(message.getHeaders().get("count", Integer.class)).isEqualTo(123); } @Test @@ -189,7 +189,7 @@ public class MessageBuilderTests { public void testPriority() { Message importantMessage = MessageBuilder.withPayload(1) .setPriority(123).build(); - assertThat(new IntegrationMessageHeaderAccessor(importantMessage).getPriority()).isEqualTo(new Integer(123)); + assertThat(new IntegrationMessageHeaderAccessor(importantMessage).getPriority()).isEqualTo(123); } @Test @@ -199,7 +199,7 @@ public class MessageBuilderTests { Message message2 = MessageBuilder.fromMessage(message1) .setHeaderIfAbsent(IntegrationMessageHeaderAccessor.PRIORITY, 13) .build(); - assertThat(new IntegrationMessageHeaderAccessor(message2).getPriority()).isEqualTo(new Integer(42)); + assertThat(new IntegrationMessageHeaderAccessor(message2).getPriority()).isEqualTo(42); } @Test diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageHeadersTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageHeadersTests.java index c1601b0bfa..593e114531 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MessageHeadersTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MessageHeadersTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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,6 +17,7 @@ package org.springframework.integration.message; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -26,12 +27,13 @@ import java.util.HashMap; import java.util.Map; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.messaging.MessageHeaders; /** * @author Mark Fisher + * @author Artem Bilan */ public class MessageHeadersTests { @@ -50,7 +52,7 @@ public class MessageHeadersTests { } @Test - public void testIdOverwritten() throws Exception { + public void testIdOverwritten() { MessageHeaders headers1 = new MessageHeaders(null); MessageHeaders headers2 = new MessageHeaders(headers1); assertThat(headers2.getId()).isNotSameAs(headers1.getId()); @@ -64,8 +66,8 @@ public class MessageHeadersTests { @Test public void testNonTypedAccessOfHeaderValue() { - Integer value = new Integer(123); - Map map = new HashMap(); + int value = 123; + Map map = new HashMap<>(); map.put("test", value); MessageHeaders headers = new MessageHeaders(map); assertThat(headers.get("test")).isEqualTo(value); @@ -73,41 +75,44 @@ public class MessageHeadersTests { @Test public void testTypedAccessOfHeaderValue() { - Integer value = new Integer(123); - Map map = new HashMap(); + int value = 123; + Map map = new HashMap<>(); map.put("test", value); MessageHeaders headers = new MessageHeaders(map); assertThat(headers.get("test", Integer.class)).isEqualTo(value); } - @Test(expected = IllegalArgumentException.class) + @Test public void testHeaderValueAccessWithIncorrectType() { - Integer value = new Integer(123); - Map map = new HashMap(); + int value = 123; + Map map = new HashMap<>(); map.put("test", value); MessageHeaders headers = new MessageHeaders(map); - assertThat(headers.get("test", String.class)).isEqualTo(value); + assertThatIllegalArgumentException() + .isThrownBy(() -> headers.get("test", String.class)) + .withMessageContaining( + "Expected [class java.lang.String] but actual type is [class java.lang.Integer]"); } @Test public void testNullHeaderValue() { - Map map = new HashMap(); + Map map = new HashMap<>(); MessageHeaders headers = new MessageHeaders(map); assertThat(headers.get("nosuchattribute")).isNull(); } @Test public void testNullHeaderValueWithTypedAccess() { - Map map = new HashMap(); + Map map = new HashMap<>(); MessageHeaders headers = new MessageHeaders(map); assertThat(headers.get("nosuchattribute", String.class)).isNull(); } @Test public void testHeaderKeys() { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("key1", "val1"); - map.put("key2", new Integer(123)); + map.put("key2", 123); MessageHeaders headers = new MessageHeaders(map); Set keys = headers.keySet(); assertThat(keys.contains("key1")).isTrue(); @@ -116,7 +121,7 @@ public class MessageHeadersTests { @Test public void serializeWithAllSerializableHeaders() throws Exception { - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("name", "joe"); map.put("age", 42); MessageHeaders input = new MessageHeaders(map); @@ -128,7 +133,7 @@ public class MessageHeadersTests { @Test public void serializeWithNonSerializableHeader() throws Exception { Object address = new Object(); - Map map = new HashMap(); + Map map = new HashMap<>(); map.put("name", "joe"); map.put("address", address); MessageHeaders input = new MessageHeaders(map); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java index 7f3eb2b6bc..9bcedb56ab 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/PayloadAndHeaderMappingTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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,16 +17,18 @@ package org.springframework.integration.message; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Properties; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.integration.handler.ServiceActivatingHandler; @@ -44,24 +46,24 @@ import org.springframework.messaging.handler.annotation.Payload; * * @since 1.0.3 */ -@SuppressWarnings({ "rawtypes", "unchecked" }) +@SuppressWarnings({"rawtypes", "unchecked"}) public class PayloadAndHeaderMappingTests { private static final ConfigurableApplicationContext applicationContext = TestUtils.createTestApplicationContext(); private TestBean bean; - @BeforeClass + @BeforeAll public static void start() { applicationContext.refresh(); } - @AfterClass + @AfterAll public static void stop() { applicationContext.close(); } - @Before + @BeforeEach public void setup() { bean = new TestBean(); } @@ -71,7 +73,7 @@ public class PayloadAndHeaderMappingTests { public void headerPropertiesAndObjectPayload() throws Exception { MessageHandler handler = this.getHandler("headerPropertiesAndObjectPayload", Properties.class, Object.class); Object payload = "test"; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -87,7 +89,7 @@ public class PayloadAndHeaderMappingTests { public void stringPayloadAndHeaderProperties() throws Exception { MessageHandler handler = this.getHandler("stringPayloadAndHeaderProperties", String.class, Properties.class); Object payload = "test"; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -103,7 +105,7 @@ public class PayloadAndHeaderMappingTests { public void headerMapAndObjectPayload() throws Exception { MessageHandler handler = this.getHandler("headerMapAndObjectPayload", Map.class, Object.class); Object payload = "test"; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -119,7 +121,7 @@ public class PayloadAndHeaderMappingTests { public void objectPayloadAndHeaderMap() throws Exception { MessageHandler handler = this.getHandler("objectPayloadAndHeaderMap", Object.class, Map.class); Object payload = "test"; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -134,10 +136,10 @@ public class PayloadAndHeaderMappingTests { @Test public void payloadMapAndHeaderString() throws Exception { MessageHandler handler = this.getHandler("payloadMapAndHeaderString", Map.class, String.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("abc", 1); payload.put("xyz", "test"); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); @@ -150,10 +152,10 @@ public class PayloadAndHeaderMappingTests { @Test public void payloadMapAndHeaderStrings() throws Exception { MessageHandler handler = this.getHandler("payloadMapAndHeaderStrings", Map.class, String.class, String.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("abc", 1); payload.put("xyz", "test"); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", "3"); @@ -170,7 +172,7 @@ public class PayloadAndHeaderMappingTests { MessageHandler handler = this.getHandler("objectPayloadHeaderMapAndStringHeaders", String.class, Map.class, String.class, Object.class); Object payload = "test"; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -191,10 +193,10 @@ public class PayloadAndHeaderMappingTests { @Test public void payloadMapAndHeaderMap() throws Exception { MessageHandler handler = this.getHandler("payloadMapAndHeaderMap", Map.class, Map.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("abc", 1); payload.put("xyz", "test"); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -209,10 +211,10 @@ public class PayloadAndHeaderMappingTests { @Test public void headerMapAndPayloadMap() throws Exception { MessageHandler handler = this.getHandler("headerMapAndPayloadMap", Map.class, Map.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("abc", 1); payload.put("xyz", "test"); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -228,7 +230,7 @@ public class PayloadAndHeaderMappingTests { public void headerMapOnlyWithStringPayload() throws Exception { MessageHandler handler = this.getHandler("headerMapOnly", Map.class); String payload = "test"; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -243,10 +245,10 @@ public class PayloadAndHeaderMappingTests { @Test public void headerMapOnlyWithMapPayload() throws Exception { MessageHandler handler = this.getHandler("headerMapOnly", Map.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("abc", 1); payload.put("xyz", "test"); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -261,9 +263,9 @@ public class PayloadAndHeaderMappingTests { @Test public void mapOnlyNoAnnotationsWithMapPayload() throws Exception { MessageHandler handler = this.getHandler("mapOnlyNoAnnotations", Map.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("payload", 1); - Map headers = new HashMap(); + Map headers = new HashMap<>(); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); assertThat(bean.lastPayload).isEqualTo(payload); @@ -274,7 +276,7 @@ public class PayloadAndHeaderMappingTests { public void mapOnlyNoAnnotationsWithStringPayload() throws Exception { MessageHandler handler = this.getHandler("mapOnlyNoAnnotations", Map.class); String payload = "test"; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -289,8 +291,8 @@ public class PayloadAndHeaderMappingTests { @Test public void mapOnlyNoAnnotationsWithIntegerPayload() throws Exception { MessageHandler handler = this.getHandler("mapOnlyNoAnnotations", Map.class); - Integer payload = new Integer(123); - Map headers = new HashMap(); + int payload = 123; + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -307,7 +309,7 @@ public class PayloadAndHeaderMappingTests { MessageHandler handler = this.getHandler("propertiesOnlyNoAnnotations", Properties.class); Properties payload = new Properties(); payload.setProperty("payload", "1"); - Map headers = new HashMap(); + Map headers = new HashMap<>(); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); assertThat(bean.lastPayload).isEqualTo(payload); @@ -317,9 +319,9 @@ public class PayloadAndHeaderMappingTests { @Test public void propertiesOnlyNoAnnotationsWithMapPayload() throws Exception { MessageHandler handler = this.getHandler("propertiesOnlyNoAnnotations", Properties.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("payload", 1); - Map headers = new HashMap(); + Map headers = new HashMap<>(); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); handler.handleMessage(message); assertThat(bean.lastPayload).isEqualTo(payload); @@ -330,7 +332,7 @@ public class PayloadAndHeaderMappingTests { public void propertiesOnlyNoAnnotationsWithStringPayload() throws Exception { MessageHandler handler = this.getHandler("propertiesOnlyNoAnnotations", Properties.class); String payload = "payload=abc"; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); @@ -347,8 +349,8 @@ public class PayloadAndHeaderMappingTests { @Test public void propertiesOnlyNoAnnotationsWithIntegerPayload() throws Exception { MessageHandler handler = this.getHandler("propertiesOnlyNoAnnotations", Properties.class); - Integer payload = new Integer(123); - Map headers = new HashMap(); + int payload = 123; + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); Message message = MessageBuilder.withPayload(payload).copyHeaders(headers).build(); @@ -362,7 +364,7 @@ public class PayloadAndHeaderMappingTests { public void headerPropertiesOnlyWithStringPayload() throws Exception { MessageHandler handler = this.getHandler("headerPropertiesOnly", Properties.class); String payload = "test"; - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -377,10 +379,10 @@ public class PayloadAndHeaderMappingTests { @Test public void headerPropertiesOnlyWithMapPayload() throws Exception { MessageHandler handler = this.getHandler("headerPropertiesOnly", Properties.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("abc", 1); payload.put("xyz", "test"); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -398,7 +400,7 @@ public class PayloadAndHeaderMappingTests { Properties payload = new Properties(); payload.setProperty("abc", "1"); payload.setProperty("xyz", "2"); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -413,10 +415,10 @@ public class PayloadAndHeaderMappingTests { @Test public void payloadMapAndHeaderProperties() throws Exception { MessageHandler handler = this.getHandler("payloadMapAndHeaderProperties", Map.class, Properties.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("abc", 1); payload.put("xyz", "test"); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -432,10 +434,10 @@ public class PayloadAndHeaderMappingTests { public void headerPropertiesPayloadMapAndStringHeader() throws Exception { MessageHandler handler = this.getHandler("headerPropertiesPayloadMapAndStringHeader", Properties.class, Map.class, String.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("abc", 1); payload.put("xyz", "test"); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); headers.put("baz", 99); @@ -450,15 +452,16 @@ public class PayloadAndHeaderMappingTests { //assertFalse(bean.lastHeaders.containsKey("baz")); } - @Test(expected = IllegalArgumentException.class) - public void twoMapsNoAnnotations() throws Exception { - this.getHandler("twoMapsNoAnnotations", Map.class, Map.class); + @Test + public void twoMapsNoAnnotations() { + assertThatIllegalArgumentException() + .isThrownBy(() -> getHandler("twoMapsNoAnnotations", Map.class, Map.class)); } @Test public void twoMapsWithAnnotationsWithStringPayload() throws Exception { MessageHandler handler = this.getHandler("twoMapsWithAnnotations", Map.class, Map.class); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); Message message = MessageBuilder.withPayload("test").copyHeaders(headers).build(); @@ -473,10 +476,10 @@ public class PayloadAndHeaderMappingTests { @Test public void twoMapsWithAnnotationsWithMapPayload() throws Exception { MessageHandler handler = this.getHandler("twoMapsWithAnnotations", Map.class, Map.class); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); - Map payloadMap = new HashMap(); + Map payloadMap = new HashMap<>(); payloadMap.put("baz", "99"); Message message = MessageBuilder.withPayload(payloadMap).copyHeaders(headers).build(); handler.handleMessage(message); @@ -487,33 +490,35 @@ public class PayloadAndHeaderMappingTests { assertThat(bean.lastHeaders.get("baz")).isEqualTo(null); } - @Test(expected = IllegalStateException.class) - public void twoStringsAmbiguousUsingMethodName() throws Exception { - SingleAmbiguousMethodTestBean bean = new SingleAmbiguousMethodTestBean(); - new ServiceActivatingHandler(bean, "twoStrings"); + @Test + public void twoStringsAmbiguousUsingMethodName() { + assertThatIllegalStateException() + .isThrownBy(() -> new ServiceActivatingHandler(new SingleAmbiguousMethodTestBean(), "twoStrings")); } - @Test(expected = IllegalStateException.class) - public void twoStringsAmbiguousWithoutMethodName() throws Exception { - SingleAmbiguousMethodTestBean bean = new SingleAmbiguousMethodTestBean(); - new ServiceActivatingHandler(bean); + @Test + public void twoStringsAmbiguousWithoutMethodName() { + assertThatIllegalStateException() + .isThrownBy(() -> new ServiceActivatingHandler(new SingleAmbiguousMethodTestBean())); } - @Test(expected = IllegalArgumentException.class) - public void twoStringsNoAnnotations() throws Exception { - this.getHandler("twoStringsNoAnnotations", String.class, String.class); + @Test + public void twoStringsNoAnnotations() { + assertThatIllegalArgumentException() + .isThrownBy(() -> getHandler("twoStringsNoAnnotations", String.class, String.class)); } - @Test(expected = IllegalArgumentException.class) - public void twoMapsNoAnnotationsAndObject() throws Exception { - this.getHandler("twoMapsNoAnnotationsAndObject", Map.class, Object.class, Map.class); + @Test + public void twoMapsNoAnnotationsAndObject() { + assertThatIllegalArgumentException() + .isThrownBy(() -> getHandler("twoMapsNoAnnotationsAndObject", Map.class, Object.class, Map.class)); } @Test public void mapAndAnnotatedStringHeaderWithStringPayload() throws Exception { MessageHandler handler = this.getHandler( "mapAndAnnotatedStringHeaderExpectingMapAsHeaders", Map.class, String.class); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); Message message = MessageBuilder.withPayload("test") @@ -529,9 +534,9 @@ public class PayloadAndHeaderMappingTests { public void mapAndAnnotatedStringHeaderWithMapPayload() throws Exception { MessageHandler handler = this.getHandler( "mapAndAnnotatedStringHeaderExpectingMapAsPayload", Map.class, String.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("test", "0"); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); Message message = MessageBuilder.withPayload(payload) @@ -546,7 +551,7 @@ public class PayloadAndHeaderMappingTests { @Test public void singleStringHeaderOnlyWithStringPayload() throws Exception { MessageHandler handler = this.getHandler("singleStringHeaderOnly", String.class); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); Message message = MessageBuilder.withPayload("test") @@ -560,10 +565,10 @@ public class PayloadAndHeaderMappingTests { @Test public void singleStringHeaderOnlyWithIntegerPayload() throws Exception { MessageHandler handler = this.getHandler("singleStringHeaderOnly", String.class); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); - Message message = MessageBuilder.withPayload(new Integer(123)) + Message message = MessageBuilder.withPayload(123) .copyHeaders(headers).build(); handler.handleMessage(message); assertThat(bean.lastPayload).isNull(); @@ -574,9 +579,9 @@ public class PayloadAndHeaderMappingTests { @Test public void singleStringHeaderOnlyWithMapPayload() throws Exception { MessageHandler handler = this.getHandler("singleStringHeaderOnly", String.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("foo", 99); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "1"); headers.put("bar", "2"); Message message = MessageBuilder.withPayload(payload) @@ -590,49 +595,49 @@ public class PayloadAndHeaderMappingTests { @Test public void singleIntegerHeaderOnlyWithIntegerPayload() throws Exception { MessageHandler handler = this.getHandler("singleIntegerHeaderOnly", Integer.class); - Map headers = new HashMap(); - headers.put("foo", new Integer(123)); - headers.put("bar", new Integer(456)); - Message message = MessageBuilder.withPayload(new Integer(789)) + Map headers = new HashMap<>(); + headers.put("foo", 123); + headers.put("bar", 456); + Message message = MessageBuilder.withPayload(789) .copyHeaders(headers).build(); handler.handleMessage(message); assertThat(bean.lastPayload).isNull(); - assertThat(bean.lastHeaders.get("foo")).isEqualTo(new Integer(123)); + assertThat(bean.lastHeaders.get("foo")).isEqualTo(123); assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test public void singleIntegerHeaderOnlyWithIntegerPayloadAndStringHeader() throws Exception { MessageHandler handler = this.getHandler("singleIntegerHeaderOnly", Integer.class); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "999"); - headers.put("bar", new Integer(456)); - Message message = MessageBuilder.withPayload(new Integer(789)) + headers.put("bar", 456); + Message message = MessageBuilder.withPayload(789) .copyHeaders(headers).build(); handler.handleMessage(message); assertThat(bean.lastPayload).isNull(); - assertThat(bean.lastHeaders.get("foo")).isEqualTo(new Integer(999)); + assertThat(bean.lastHeaders.get("foo")).isEqualTo(999); assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test public void singleIntegerHeaderOnlyWithStringPayload() throws Exception { MessageHandler handler = this.getHandler("singleIntegerHeaderOnly", Integer.class); - Map headers = new HashMap(); - headers.put("foo", new Integer(123)); - headers.put("bar", new Integer(456)); + Map headers = new HashMap<>(); + headers.put("foo", 123); + headers.put("bar", 456); Message message = MessageBuilder.withPayload("test") .copyHeaders(headers).build(); handler.handleMessage(message); assertThat(bean.lastPayload).isNull(); - assertThat(bean.lastHeaders.get("foo")).isEqualTo(new Integer(123)); + assertThat(bean.lastHeaders.get("foo")).isEqualTo(123); assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test public void singleObjectHeaderOnlyWithStringPayload() throws Exception { MessageHandler handler = this.getHandler("singleObjectHeaderOnly", Object.class); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "123"); headers.put("bar", "456"); Message message = MessageBuilder.withPayload("test") @@ -646,7 +651,7 @@ public class PayloadAndHeaderMappingTests { @Test public void singleObjectHeaderOnlyWithObjectPayload() throws Exception { MessageHandler handler = this.getHandler("singleObjectHeaderOnly", Object.class); - Map headers = new HashMap(); + Map headers = new HashMap<>(); headers.put("foo", "123"); headers.put("bar", "456"); Message message = MessageBuilder.withPayload(new Object()) @@ -660,37 +665,37 @@ public class PayloadAndHeaderMappingTests { @Test public void singleObjectHeaderOnlyWithIntegerPayload() throws Exception { MessageHandler handler = this.getHandler("singleObjectHeaderOnly", Object.class); - Map headers = new HashMap(); - headers.put("foo", new Integer(123)); - headers.put("bar", new Integer(456)); - Message message = MessageBuilder.withPayload(new Integer(789)) + Map headers = new HashMap<>(); + headers.put("foo", 123); + headers.put("bar", 456); + Message message = MessageBuilder.withPayload(789) .copyHeaders(headers).build(); handler.handleMessage(message); assertThat(bean.lastPayload).isNull(); - assertThat(bean.lastHeaders.get("foo")).isEqualTo(new Integer(123)); + assertThat(bean.lastHeaders.get("foo")).isEqualTo(123); assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test public void singleObjectHeaderOnlyWithMapPayload() throws Exception { MessageHandler handler = this.getHandler("singleObjectHeaderOnly", Object.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("foo", 99); - Map headers = new HashMap(); - headers.put("foo", new Integer(123)); - headers.put("bar", new Integer(456)); + Map headers = new HashMap<>(); + headers.put("foo", 123); + headers.put("bar", 456); Message message = MessageBuilder.withPayload(payload) .copyHeaders(headers).build(); handler.handleMessage(message); assertThat(bean.lastPayload).isNull(); - assertThat(bean.lastHeaders.get("foo")).isEqualTo(new Integer(123)); + assertThat(bean.lastHeaders.get("foo")).isEqualTo(123); assertThat(bean.lastHeaders.get("bar")).isNull(); } @Test public void twoPayloadExpressions() throws Exception { MessageHandler handler = this.getHandler("twoPayloadExpressions", String.class, String.class); - Map payload = new HashMap(); + Map payload = new HashMap<>(); payload.put("foo", 123); payload.put("bar", 456); Message message = MessageBuilder.withPayload(payload).build(); @@ -720,6 +725,7 @@ public class PayloadAndHeaderMappingTests { public String concat(String s1, String s2) { return "s1" + "s2"; } + } @SuppressWarnings("unused") @@ -775,7 +781,9 @@ public class PayloadAndHeaderMappingTests { this.lastPayload = payload; } - public void payloadMapAndHeaderStrings(Map payload, @Header("foo") String header1, @Header("bar") String header2) { + public void payloadMapAndHeaderStrings(Map payload, @Header("foo") String header1, + @Header("bar") String header2) { + this.lastHeaders = new HashMap(); this.lastHeaders.put("foo", header1); this.lastHeaders.put("bar", header2); @@ -797,7 +805,9 @@ public class PayloadAndHeaderMappingTests { this.lastPayload = payload; } - public void headerPropertiesPayloadMapAndStringHeader(@Headers Properties headers, Map payload, @Header("foo") String header) { + public void headerPropertiesPayloadMapAndStringHeader(@Headers Properties headers, Map payload, + @Header("foo") String header) { + this.lastHeaders = headers; this.lastHeaders.put("foo2", header); this.lastPayload = payload; @@ -881,6 +891,7 @@ public class PayloadAndHeaderMappingTests { public void twoPayloadExpressions(@Payload("foo") String foo, @Payload("bar") String bar) { this.lastPayload = foo + bar; } + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterParserTests.java index c33a66823a..850f66cd24 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/RouterParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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,6 +17,7 @@ package org.springframework.integration.router.config; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -24,8 +25,7 @@ import static org.mockito.Mockito.verify; import java.util.Collections; import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; @@ -46,8 +46,7 @@ import org.springframework.messaging.SubscribableChannel; import org.springframework.messaging.core.DestinationResolutionException; import org.springframework.messaging.core.DestinationResolver; import org.springframework.messaging.support.GenericMessage; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Mark Fisher @@ -55,8 +54,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * @author Gunnar Hillert * @author Artem Bilan */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class RouterParserTests { @Autowired @@ -64,6 +62,7 @@ public class RouterParserTests { @Autowired private PollableChannel output2; + @Autowired private MessageChannel input; @@ -121,11 +120,11 @@ public class RouterParserTests { @Test public void testRouter() { - this.input.send(new GenericMessage("1")); + this.input.send(new GenericMessage<>("1")); Message result1 = this.output1.receive(1000); assertThat(result1.getPayload()).isEqualTo("1"); assertThat(output2.receive(0)).isNull(); - input.send(new GenericMessage("2")); + input.send(new GenericMessage<>("2")); Message result2 = this.output2.receive(1000); assertThat(result2.getPayload()).isEqualTo("2"); assertThat(output1.receive(0)).isNull(); @@ -133,7 +132,7 @@ public class RouterParserTests { @Test public void testRouterWithDefaultOutputChannel() { - this.inputForRouterWithDefaultOutput.send(new GenericMessage("99")); + this.inputForRouterWithDefaultOutput.send(new GenericMessage<>("99")); assertThat(this.output1.receive(0)).isNull(); assertThat(this.output2.receive(0)).isNull(); Message result = this.defaultOutput.receive(0); @@ -142,7 +141,7 @@ public class RouterParserTests { @Test public void refOnlyForAbstractMessageRouterImplementation() { - this.inputForAbstractMessageRouterImplementation.send(new GenericMessage("test-implementation")); + this.inputForAbstractMessageRouterImplementation.send(new GenericMessage<>("test-implementation")); Message result = this.output3.receive(1000); assertThat(result).isNotNull(); assertThat(result.getPayload()).isEqualTo("test-implementation"); @@ -150,7 +149,7 @@ public class RouterParserTests { @Test public void refOnlyForAnnotatedObject() { - this.inputForAnnotatedRouter.send(new GenericMessage("test-annotation")); + this.inputForAnnotatedRouter.send(new GenericMessage<>("test-annotation")); Message result = this.output4.receive(1000); assertThat(result).isNotNull(); assertThat(result.getPayload()).isEqualTo("test-annotation"); @@ -158,30 +157,30 @@ public class RouterParserTests { @Test public void testResolutionRequired() { - try { - this.inputForRouterRequiringResolution.send(new GenericMessage(3)); - } - catch (Exception e) { - assertThat(e.getCause() instanceof DestinationResolutionException).isTrue(); - } + assertThatExceptionOfType(Exception.class) + .isThrownBy(() -> this.inputForRouterRequiringResolution.send(new GenericMessage<>(3))) + .withCauseInstanceOf(DestinationResolutionException.class); } - @Test(expected = MessageDeliveryException.class) + @Test public void testResolutionRequiredIsFalse() { - this.resolutionRequiredIsFalseInput.send(new GenericMessage("channelThatDoesNotExist")); + assertThatExceptionOfType(MessageDeliveryException.class) + .isThrownBy(() -> + this.resolutionRequiredIsFalseInput.send(new GenericMessage<>("channelThatDoesNotExist"))); } @Test public void timeoutValueConfigured() { assertThat(this.routerWithTimeout instanceof MethodInvokingRouter).isTrue(); - MessagingTemplate template = TestUtils.getPropertyValue(this.routerWithTimeout, "messagingTemplate", MessagingTemplate.class); + MessagingTemplate template = + TestUtils.getPropertyValue(this.routerWithTimeout, "messagingTemplate", MessagingTemplate.class); Long timeout = TestUtils.getPropertyValue(template, "sendTimeout", Long.class); - assertThat(timeout).isEqualTo(new Long(1234)); + assertThat(timeout).isEqualTo(1234L); } @Test public void sequence() { - Message originalMessage = new GenericMessage("test"); + Message originalMessage = new GenericMessage<>("test"); this.sequenceRouter.send(originalMessage); Message message1 = this.sequenceOut1.receive(1000); Message message2 = this.sequenceOut2.receive(1000); @@ -202,11 +201,11 @@ public class RouterParserTests { @Test public void testInt2893RouterNestedBean() { - this.routerNestedBeanChannel.send(new GenericMessage("1")); + this.routerNestedBeanChannel.send(new GenericMessage<>("1")); Message result1 = this.output1.receive(1000); assertThat(result1.getPayload()).isEqualTo("1"); assertThat(this.output2.receive(0)).isNull(); - this.routerNestedBeanChannel.send(new GenericMessage("2")); + this.routerNestedBeanChannel.send(new GenericMessage<>("2")); Message result2 = this.output2.receive(1000); assertThat(result2.getPayload()).isEqualTo("2"); assertThat(this.output1.receive(0)).isNull(); @@ -214,11 +213,11 @@ public class RouterParserTests { @Test public void testInt2893RouterNestedBeanWithinChain() { - this.chainRouterNestedBeanChannel.send(new GenericMessage("1")); + this.chainRouterNestedBeanChannel.send(new GenericMessage<>("1")); Message result1 = this.output1.receive(1000); assertThat(result1.getPayload()).isEqualTo("1"); assertThat(this.output2.receive(0)).isNull(); - this.chainRouterNestedBeanChannel.send(new GenericMessage("2")); + this.chainRouterNestedBeanChannel.send(new GenericMessage<>("2")); Message result2 = this.output2.receive(1000); assertThat(result2.getPayload()).isEqualTo("2"); assertThat(this.output1.receive(0)).isNull(); @@ -228,7 +227,7 @@ public class RouterParserTests { public void testErrorChannel() { MessageHandler handler = mock(MessageHandler.class); this.errorChannel.subscribe(handler); - this.routerAndErrorChannelInputChannel.send(new GenericMessage("fail")); + this.routerAndErrorChannelInputChannel.send(new GenericMessage<>("fail")); verify(handler, times(1)).handleMessage(Mockito.any(Message.class)); } @@ -239,9 +238,11 @@ public class RouterParserTests { public static class NonExistingChannelRouter { + public String route(String payload) { return "foo"; } + } public static class TestRouterImplementation extends AbstractMappingMessageRouter { @@ -257,6 +258,7 @@ public class RouterParserTests { protected List getChannelKeys(Message message) { return Collections.singletonList((Object) this.channel); } + } @@ -272,6 +274,7 @@ public class RouterParserTests { public MessageChannel test(String payload) { return this.channel; } + } public static class ReturnStringPassedInAsChannelNameRouter { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/splitter/SpelSplitterIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/splitter/SpelSplitterIntegrationTests.java index 2e63dc9f3b..15f50c76db 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/splitter/SpelSplitterIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/splitter/SpelSplitterIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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,8 +23,7 @@ import java.util.Arrays; import java.util.Iterator; import java.util.List; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.integration.IntegrationMessageHeaderAccessor; @@ -33,16 +32,14 @@ import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.support.GenericMessage; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Mark Fisher * @author Artem Bilan * @author Gary Russell */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class SpelSplitterIntegrationTests { @Autowired @@ -83,13 +80,13 @@ public class SpelSplitterIntegrationTests { Message two = output.receive(0); Message three = output.receive(0); Message four = output.receive(0); - assertThat(one.getPayload()).isEqualTo(new Integer(1)); + assertThat(one.getPayload()).isEqualTo(1); assertThat(one.getHeaders().get("foo")).isEqualTo("foo"); - assertThat(two.getPayload()).isEqualTo(new Integer(2)); + assertThat(two.getPayload()).isEqualTo(2); assertThat(two.getHeaders().get("foo")).isEqualTo("foo"); - assertThat(three.getPayload()).isEqualTo(new Integer(3)); + assertThat(three.getPayload()).isEqualTo(3); assertThat(three.getHeaders().get("foo")).isEqualTo("foo"); - assertThat(four.getPayload()).isEqualTo(new Integer(4)); + assertThat(four.getPayload()).isEqualTo(4); assertThat(four.getHeaders().get("foo")).isEqualTo("foo"); assertThat(output.receive(0)).isNull(); } @@ -111,7 +108,7 @@ public class SpelSplitterIntegrationTests { @Test public void iteratorSplitter() { - this.iteratorInput.send(new GenericMessage("a,b,c,d")); + this.iteratorInput.send(new GenericMessage<>("a,b,c,d")); Message a = output.receive(0); Message b = output.receive(0); Message c = output.receive(0); @@ -133,7 +130,7 @@ public class SpelSplitterIntegrationTests { @Test public void spelIteratorSplitter() { - this.spelIteratorInput.send(new GenericMessage("a,b,c,d")); + this.spelIteratorInput.send(new GenericMessage<>("a,b,c,d")); Message a = output.receive(0); Message b = output.receive(0); Message c = output.receive(0); diff --git a/spring-integration-core/src/test/kotlin/org/springframework/integration/dsl/KotlinDslTests.kt b/spring-integration-core/src/test/kotlin/org/springframework/integration/dsl/KotlinDslTests.kt index c68f78b323..91b1ed10c6 100644 --- a/spring-integration-core/src/test/kotlin/org/springframework/integration/dsl/KotlinDslTests.kt +++ b/spring-integration-core/src/test/kotlin/org/springframework/integration/dsl/KotlinDslTests.kt @@ -154,8 +154,8 @@ class KotlinDslTests { val verifyLater = StepVerifier - .create(Flux.from(fluxChannel).map { it.payload }.cast(Integer::class.java)) - .expectNext(Integer(4), Integer(6)) + .create(Flux.from(fluxChannel).map { it.payload }.map { it.toString().toInt() }) + .expectNext(4, 6) .thenCancel() .verifyLater() diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/DefaultFileNameGeneratorTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/DefaultFileNameGeneratorTests.java index 35c42f20a3..2fe62a6bec 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/DefaultFileNameGeneratorTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/DefaultFileNameGeneratorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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,7 +21,7 @@ import static org.mockito.Mockito.mock; import java.io.File; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.BeanFactory; import org.springframework.integration.support.MessageBuilder; @@ -30,6 +30,7 @@ import org.springframework.messaging.Message; /** * @author Mark Fisher * @author Gary Russell + * @author Artem Bilan */ public class DefaultFileNameGeneratorTests { @@ -55,7 +56,7 @@ public class DefaultFileNameGeneratorTests { public void defaultHeaderNameNotString() { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); generator.setBeanFactory(mock(BeanFactory.class)); - Message message = MessageBuilder.withPayload("test").setHeader(FileHeaders.FILENAME, new Integer(123)) + Message message = MessageBuilder.withPayload("test").setHeader(FileHeaders.FILENAME, 123) .build(); String filename = generator.generateFileName(message); assertThat(filename).isEqualTo(message.getHeaders().getId() + ".msg"); @@ -86,7 +87,7 @@ public class DefaultFileNameGeneratorTests { DefaultFileNameGenerator generator = new DefaultFileNameGenerator(); generator.setBeanFactory(mock(BeanFactory.class)); generator.setHeaderName("foo"); - Message message = MessageBuilder.withPayload("test").setHeader("foo", new Integer(123)).build(); + Message message = MessageBuilder.withPayload("test").setHeader("foo", 123).build(); String filename = generator.generateFileName(message); assertThat(filename).isEqualTo(message.getHeaders().getId() + ".msg"); } diff --git a/spring-integration-groovy/src/main/java/org/springframework/integration/groovy/GroovyScriptExecutingMessageProcessor.java b/spring-integration-groovy/src/main/java/org/springframework/integration/groovy/GroovyScriptExecutingMessageProcessor.java index 2711da17f3..2d6b2850a4 100644 --- a/spring-integration-groovy/src/main/java/org/springframework/integration/groovy/GroovyScriptExecutingMessageProcessor.java +++ b/spring-integration-groovy/src/main/java/org/springframework/integration/groovy/GroovyScriptExecutingMessageProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import java.util.concurrent.locks.ReentrantLock; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.customizers.ASTTransformationCustomizer; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.NoSuchBeanDefinitionException; @@ -118,8 +119,8 @@ public class GroovyScriptExecutingMessageProcessor extends AbstractScriptExecuti *

More compiler options can be provided via {@link #setCompilerConfiguration(CompilerConfiguration)} * overriding this flag. * @param compileStatic the compile static {@code boolean} flag. - * @since 4.3 * @see CompileStatic + * @since 4.3 */ public void setCompileStatic(boolean compileStatic) { this.compileStatic = compileStatic; @@ -130,9 +131,9 @@ public class GroovyScriptExecutingMessageProcessor extends AbstractScriptExecuti * For example the {@link CompileStatic} and {@link org.codehaus.groovy.control.customizers.ImportCustomizer} * are the most popular options. * @param compilerConfiguration the Groovy script compiler options to use. - * @since 4.3 * @see CompileStatic * @see GroovyClassLoader + * @since 4.3 */ public void setCompilerConfiguration(CompilerConfiguration compilerConfiguration) { this.compilerConfiguration = compilerConfiguration; @@ -201,31 +202,21 @@ public class GroovyScriptExecutingMessageProcessor extends AbstractScriptExecuti } private Object execute(Map variables) throws ScriptCompilationException { - try { - GroovyObject goo = (GroovyObject) this.scriptClass.newInstance(); + GroovyObject goo = (GroovyObject) BeanUtils.instantiateClass(this.scriptClass); - VariableBindingGroovyObjectCustomizerDecorator groovyObjectCustomizer = - new BindingOverwriteGroovyObjectCustomizerDecorator(new BeanFactoryFallbackBinding(variables)); - groovyObjectCustomizer.setCustomizer(this.customizerDecorator); + VariableBindingGroovyObjectCustomizerDecorator groovyObjectCustomizer = + new BindingOverwriteGroovyObjectCustomizerDecorator(new BeanFactoryFallbackBinding(variables)); + groovyObjectCustomizer.setCustomizer(this.customizerDecorator); - if (goo instanceof Script) { - // Allow metaclass and other customization. - groovyObjectCustomizer.customize(goo); - // A Groovy script, probably creating an instance: let's execute it. - return ((Script) goo).run(); - } - else { - // An instance of the scripted class: let's return it as-is. - return goo; - } + if (goo instanceof Script) { + // Allow metaclass and other customization. + groovyObjectCustomizer.customize(goo); + // A Groovy script, probably creating an instance: let's execute it. + return ((Script) goo).run(); } - catch (InstantiationException ex) { - throw new ScriptCompilationException( - this.scriptSource, "Could not instantiate Groovy script class: " + this.scriptClass.getName(), ex); - } - catch (IllegalAccessException ex) { - throw new ScriptCompilationException( - this.scriptSource, "Could not access Groovy script constructor: " + this.scriptClass.getName(), ex); + else { + // An instance of the scripted class: let's return it as-is. + return goo; } } diff --git a/spring-integration-http/src/test/java/org/springframework/integration/http/config/HttpOutboundGatewayParserTests.java b/spring-integration-http/src/test/java/org/springframework/integration/http/config/HttpOutboundGatewayParserTests.java index 8302093ba0..e82c3b742f 100644 --- a/spring-integration-http/src/test/java/org/springframework/integration/http/config/HttpOutboundGatewayParserTests.java +++ b/spring-integration-http/src/test/java/org/springframework/integration/http/config/HttpOutboundGatewayParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -147,7 +147,7 @@ public class HttpOutboundGatewayParserTests { assertThat(templateAccessor.getPropertyValue("errorHandler")).isEqualTo(errorHandlerBean); Object sendTimeout = new DirectFieldAccessor( handlerAccessor.getPropertyValue("messagingTemplate")).getPropertyValue("sendTimeout"); - assertThat(sendTimeout).isEqualTo(new Long("1234")); + assertThat(sendTimeout).isEqualTo(1234L); Map uriVariableExpressions = (Map) handlerAccessor.getPropertyValue("uriVariableExpressions"); assertThat(uriVariableExpressions.size()).isEqualTo(1); diff --git a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/CrossOriginTests.java b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/CrossOriginTests.java index 666a4ec1e8..f4404d5e0c 100644 --- a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/CrossOriginTests.java +++ b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/CrossOriginTests.java @@ -89,7 +89,7 @@ public class CrossOriginTests { assertThat(config.getAllowCredentials()).isTrue(); assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[] { "*" }); assertThat(config.getExposedHeaders()).isEmpty(); - assertThat(config.getMaxAge()).isEqualTo(new Long(1800)); + assertThat(config.getMaxAge()).isEqualTo(1800L); } @Test @@ -103,7 +103,7 @@ public class CrossOriginTests { .isEqualTo(new String[] { "https://site1.com", "https://site2.com" }); assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[] { "header1", "header2" }); assertThat(config.getExposedHeaders().toArray()).isEqualTo(new String[] { "header3", "header4" }); - assertThat(config.getMaxAge()).isEqualTo(new Long(123)); + assertThat(config.getMaxAge()).isEqualTo(123L); assertThat(config.getAllowCredentials()).isEqualTo(false); } @@ -120,7 +120,7 @@ public class CrossOriginTests { assertThat(config.getAllowCredentials()).isTrue(); assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[] { "*" }); assertThat(config.getExposedHeaders()).isEmpty(); - assertThat(config.getMaxAge()).isEqualTo(new Long(1800)); + assertThat(config.getMaxAge()).isEqualTo(1800L); } @Test diff --git a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNioSSLConnection.java b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNioSSLConnection.java index b3e481383f..e9d693597f 100644 --- a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNioSSLConnection.java +++ b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNioSSLConnection.java @@ -301,6 +301,7 @@ public class TcpNioSSLConnection extends TcpNioConnection { @Override public void close() { super.close(); + logger.trace("Resuming for close"); this.semaphore.release(); } @@ -364,6 +365,9 @@ public class TcpNioSSLConnection extends TcpNioConnection { TcpNioSSLConnection.this.semaphore.drainPermits(); HandshakeStatus status = TcpNioSSLConnection.this.sslEngine.getHandshakeStatus(); while (status != HandshakeStatus.FINISHED) { + if (logger.isTraceEnabled()) { + logger.trace("Handshake Status: " + status); + } writeEncodedIfAny(); status = runTasksIfNeeded(result); if (status == HandshakeStatus.NEED_UNWRAP) { @@ -383,6 +387,9 @@ public class TcpNioSSLConnection extends TcpNioConnection { logger.debug(status); } } + if (logger.isTraceEnabled()) { + logger.trace("Handshake Status: " + status); + } } private void writeEncodedIfAny() throws IOException { diff --git a/spring-integration-ip/src/main/java/org/springframework/integration/ip/udp/MulticastReceivingChannelAdapter.java b/spring-integration-ip/src/main/java/org/springframework/integration/ip/udp/MulticastReceivingChannelAdapter.java index b7aaef98de..e5fca6db88 100644 --- a/spring-integration-ip/src/main/java/org/springframework/integration/ip/udp/MulticastReceivingChannelAdapter.java +++ b/spring-integration-ip/src/main/java/org/springframework/integration/ip/udp/MulticastReceivingChannelAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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 java.io.IOException; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.MulticastSocket; +import java.net.NetworkInterface; import org.springframework.messaging.MessagingException; @@ -29,6 +30,8 @@ import org.springframework.messaging.MessagingException; * * @author Gary Russell * @author Marcin Pilaczynski + * @author Artem Bilan + * * @since 2.0 */ public class MulticastReceivingChannelAdapter extends UnicastReceivingChannelAdapter { @@ -68,8 +71,7 @@ public class MulticastReceivingChannelAdapter extends UnicastReceivingChannelAda MulticastSocket socket = port == 0 ? new MulticastSocket() : new MulticastSocket(port); String localAddress = this.getLocalAddress(); if (localAddress != null) { - InetAddress whichNic = InetAddress.getByName(localAddress); - socket.setInterface(whichNic); + socket.setNetworkInterface(NetworkInterface.getByName(localAddress)); } setSocketAttributes(socket); socket.joinGroup(InetAddress.getByName(this.group)); diff --git a/spring-integration-ip/src/main/java/org/springframework/integration/ip/udp/MulticastSendingMessageHandler.java b/spring-integration-ip/src/main/java/org/springframework/integration/ip/udp/MulticastSendingMessageHandler.java index 0624808569..e063e7f9c9 100644 --- a/spring-integration-ip/src/main/java/org/springframework/integration/ip/udp/MulticastSendingMessageHandler.java +++ b/spring-integration-ip/src/main/java/org/springframework/integration/ip/udp/MulticastSendingMessageHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2001-2019 the original author or authors. + * Copyright 2001-2020 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.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; +import java.net.NetworkInterface; import java.net.URISyntaxException; import org.springframework.expression.Expression; @@ -35,6 +36,8 @@ import org.springframework.messaging.Message; * acknowledgments are required to determine success. * * @author Gary Russell + * @author Artem Bilan + * * @since 2.0 */ public class MulticastSendingMessageHandler extends UnicastSendingMessageHandler { @@ -79,6 +82,7 @@ public class MulticastSendingMessageHandler extends UnicastSendingMessageHandler */ public MulticastSendingMessageHandler(String address, int port, boolean acknowledge, String ackHost, int ackPort, int ackTimeout) { + super(address, port, acknowledge, ackHost, ackPort, ackTimeout); } @@ -96,6 +100,7 @@ public class MulticastSendingMessageHandler extends UnicastSendingMessageHandler public MulticastSendingMessageHandler(String address, int port, boolean lengthCheck, boolean acknowledge, String ackHost, int ackPort, int ackTimeout) { + super(address, port, lengthCheck, acknowledge, ackHost, ackPort, ackTimeout); } @@ -134,8 +139,8 @@ public class MulticastSendingMessageHandler extends UnicastSendingMessageHandler private void createSocket() throws IOException { if (getTheSocket() == null) { MulticastSocket socket; - if (this.isAcknowledge()) { - int ackPort = this.getAckPort(); + if (isAcknowledge()) { + int ackPort = getAckPort(); if (this.localAddress == null) { socket = ackPort == 0 ? new MulticastSocket() : new MulticastSocket(ackPort); } @@ -143,8 +148,9 @@ public class MulticastSendingMessageHandler extends UnicastSendingMessageHandler InetAddress whichNic = InetAddress.getByName(this.localAddress); socket = new MulticastSocket(new InetSocketAddress(whichNic, ackPort)); } - if (getSoReceiveBufferSize() > 0) { - socket.setReceiveBufferSize(this.getSoReceiveBufferSize()); + int soReceiveBufferSize = getSoReceiveBufferSize(); + if (soReceiveBufferSize > 0) { + socket.setReceiveBufferSize(soReceiveBufferSize); } if (logger.isDebugEnabled()) { logger.debug("Listening for acks on port: " + socket.getLocalPort()); @@ -161,8 +167,7 @@ public class MulticastSendingMessageHandler extends UnicastSendingMessageHandler } setSocketAttributes(socket); if (this.localAddress != null) { - InetAddress whichNic = InetAddress.getByName(this.localAddress); - socket.setInterface(whichNic); + socket.setNetworkInterface(NetworkInterface.getByName(this.localAddress)); } this.multicastSocket = socket; } @@ -194,7 +199,7 @@ public class MulticastSendingMessageHandler extends UnicastSendingMessageHandler protected void convertAndSend(Message message) throws IOException, URISyntaxException { super.convertAndSend(message); if (logger.isDebugEnabled()) { - logger.debug("Sent packet to " + this.multicastSocket.getInterface()); + logger.debug("Sent packet to " + this.multicastSocket.getNetworkInterface()); } } diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/CachingClientConnectionFactoryTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/CachingClientConnectionFactoryTests.java index cc3703f6da..68eb6bff0c 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/CachingClientConnectionFactoryTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/CachingClientConnectionFactoryTests.java @@ -51,8 +51,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.logging.Log; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; @@ -62,7 +61,6 @@ import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.core.task.SimpleAsyncTaskExecutor; import org.springframework.integration.channel.QueueChannel; @@ -82,8 +80,7 @@ import org.springframework.messaging.SubscribableChannel; import org.springframework.messaging.support.ErrorMessage; import org.springframework.messaging.support.GenericMessage; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Gary Russell @@ -92,8 +89,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * @since 2.2 * */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig @DirtiesContext public class CachingClientConnectionFactoryTests { @@ -183,14 +179,7 @@ public class CachingClientConnectionFactoryTests { when(factory.isRunning()).thenReturn(true); TcpConnectionSupport mockConn1 = makeMockConnection("conn1"); TcpConnectionSupport mockConn2 = makeMockConnection("conn2"); - doAnswer(new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return null; - } - - }).when(mockConn1).close(); + doAnswer(invocation -> null).when(mockConn1).close(); when(factory.getConnection()).thenReturn(mockConn1) .thenReturn(mockConn2).thenReturn(mockConn1) .thenReturn(mockConn2); @@ -213,7 +202,7 @@ public class CachingClientConnectionFactoryTests { conn2a.close(); } - @Test(expected = PoolItemNotAvailableException.class) + @Test public void testLimit() throws Exception { AbstractClientConnectionFactory factory = mock(AbstractClientConnectionFactory.class); when(factory.isRunning()).thenReturn(true); @@ -230,7 +219,8 @@ public class CachingClientConnectionFactoryTests { assertThat(conn1.toString()).isEqualTo("Cached:" + mockConn1.toString()); TcpConnection conn2 = cachingFactory.getConnection(); assertThat(conn2.toString()).isEqualTo("Cached:" + mockConn2.toString()); - cachingFactory.getConnection(); + assertThatExceptionOfType(PoolItemNotAvailableException.class) + .isThrownBy(cachingFactory::getConnection); } @Test @@ -253,14 +243,7 @@ public class CachingClientConnectionFactoryTests { TcpConnection conn2 = cachingFactory.getConnection(); assertThat(conn2.toString()).isEqualTo("Cached:" + mockConn2.toString()); cachingFactory.stop(); - Answer answer = new Answer() { - - @Override - public Object answer(InvocationOnMock invocation) throws Throwable { - return null; - } - - }; + Answer answer = invocation -> null; doAnswer(answer).when(mockConn1).close(); doAnswer(answer).when(mockConn2).close(); when(factory.isRunning()).thenReturn(false); @@ -368,15 +351,16 @@ public class CachingClientConnectionFactoryTests { CachingClientConnectionFactory cccf) throws Exception { TcpConnection cached1 = cccf.getConnection(); assertThatExceptionOfType(MessagingException.class) - .isThrownBy(() -> cached1.send(new GenericMessage("foo"))); + .isThrownBy(() -> cached1.send(new GenericMessage<>("foo"))); // Before INT-3163 this failed with a timeout - connection not returned to pool after failure on send() TcpConnection cached2 = cccf.getConnection(); assertThat(cached1.getConnectionId().contains(conn1.getConnectionId())).isTrue(); assertThat(cached2.getConnectionId().contains(conn2.getConnectionId())).isTrue(); } - private CachingClientConnectionFactory createCCCFWith2Connections(TcpConnectionSupport conn1, TcpConnectionSupport conn2) - throws Exception { + private CachingClientConnectionFactory createCCCFWith2Connections(TcpConnectionSupport conn1, + TcpConnectionSupport conn2) throws Exception { + AbstractClientConnectionFactory factory = mock(AbstractClientConnectionFactory.class); when(factory.isRunning()).thenReturn(true); when(factory.getConnection()).thenReturn(conn1, conn2); @@ -392,17 +376,7 @@ public class CachingClientConnectionFactoryTests { OutputStream stream = mock(OutputStream.class); doThrow(new IOException("Foo")).when(stream).write(any(byte[].class), anyInt(), anyInt()); when(socket.getOutputStream()).thenReturn(stream); - TcpNetConnection conn = new TcpNetConnection(socket, false, false, new ApplicationEventPublisher() { - - @Override - public void publishEvent(ApplicationEvent event) { - } - - @Override - public void publishEvent(Object event) { - - } - + TcpNetConnection conn = new TcpNetConnection(socket, false, false, event -> { }, "foo"); conn.setMapper(new TcpMessageMapper()); conn.setSerializer(new ByteArrayCrLfSerializer()); @@ -411,20 +385,15 @@ public class CachingClientConnectionFactoryTests { private TcpConnectionSupport mockedTcpNioConnection() throws Exception { SocketChannel socketChannel = mock(SocketChannel.class); - new DirectFieldAccessor(socketChannel).setPropertyValue("open", false); + if (System.getProperty("java.version").startsWith("1.8")) { + new DirectFieldAccessor(socketChannel).setPropertyValue("open", false); + } + else { + new DirectFieldAccessor(socketChannel).setPropertyValue("closed", true); + } doThrow(new IOException("Foo")).when(socketChannel).write(Mockito.any(ByteBuffer.class)); when(socketChannel.socket()).thenReturn(mock(Socket.class)); - TcpNioConnection conn = new TcpNioConnection(socketChannel, false, false, new ApplicationEventPublisher() { - - @Override - public void publishEvent(ApplicationEvent event) { - } - - @Override - public void publishEvent(Object event) { - - } - + TcpNioConnection conn = new TcpNioConnection(socketChannel, false, false, event -> { }, "foo"); conn.setMapper(new TcpMessageMapper()); conn.setSerializer(new ByteArrayCrLfSerializer()); @@ -447,7 +416,7 @@ public class CachingClientConnectionFactoryTests { } @Test - public void integrationTest() throws Exception { + public void integrationTest() { TestingUtilities.waitListening(serverCf, null); new DirectFieldAccessor(this.clientAdapterCf).setPropertyValue("port", this.serverCf.getPort()); @@ -466,7 +435,7 @@ public class CachingClientConnectionFactoryTests { @Test // @Repeat(1000) // INT-3722 public void gatewayIntegrationTest() throws Exception { - final List connectionIds = new ArrayList(); + final List connectionIds = new ArrayList<>(); final AtomicBoolean okToRun = new AtomicBoolean(true); ExecutorService exec = Executors.newSingleThreadExecutor(); exec.execute(() -> { @@ -494,7 +463,7 @@ public class CachingClientConnectionFactoryTests { await().atMost(Duration.ofSeconds(10)).until(() -> connections.size() > 0); // assert we use the same connection from the pool - toGateway.send(new GenericMessage("Hello, world2!")); + toGateway.send(new GenericMessage<>("Hello, world2!")); m = fromGateway.receive(1000); assertThat(m).isNotNull(); assertThat(new String((byte[]) m.getPayload())).isEqualTo("foo:" + "Hello, world2!"); @@ -533,7 +502,7 @@ public class CachingClientConnectionFactoryTests { // Failover AbstractClientConnectionFactory factory1 = mock(AbstractClientConnectionFactory.class); AbstractClientConnectionFactory factory2 = mock(AbstractClientConnectionFactory.class); - List factories = new ArrayList(); + List factories = new ArrayList<>(); factories.add(factory1); factories.add(factory2); TcpConnectionSupport mockConn1 = makeMockConnection(); @@ -551,7 +520,7 @@ public class CachingClientConnectionFactoryTests { CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2); cachingFactory.start(); TcpConnection conn1 = cachingFactory.getConnection(); - GenericMessage message = new GenericMessage("foo"); + GenericMessage message = new GenericMessage<>("foo"); conn1 = cachingFactory.getConnection(); conn1.send(message); Mockito.verify(mockConn2).send(message); @@ -586,7 +555,7 @@ public class CachingClientConnectionFactoryTests { AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port2); factory2.setBeanName("client2"); factory2.registerListener(message -> false); - List factories = new ArrayList(); + List factories = new ArrayList<>(); factories.add(factory1); factories.add(factory2); FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories); @@ -595,7 +564,7 @@ public class CachingClientConnectionFactoryTests { CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2); cachingFactory.start(); TcpConnection conn1 = cachingFactory.getConnection(); - GenericMessage message = new GenericMessage("foo"); + GenericMessage message = new GenericMessage<>("foo"); conn1.send(message); conn1.close(); TcpConnection conn2 = cachingFactory.getConnection(); @@ -653,7 +622,7 @@ public class CachingClientConnectionFactoryTests { AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port2); factory2.setBeanName("client2"); factory2.registerListener(message -> false); - List factories = new ArrayList(); + List factories = new ArrayList<>(); factories.add(factory1); factories.add(factory2); FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories); @@ -662,7 +631,7 @@ public class CachingClientConnectionFactoryTests { CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(failoverFactory, 2); cachingFactory.start(); TcpConnection conn1 = cachingFactory.getConnection(); - GenericMessage message = new GenericMessage("foo"); + GenericMessage message = new GenericMessage<>("foo"); conn1.send(message); conn1.close(); TcpConnection conn2 = cachingFactory.getConnection(); @@ -686,7 +655,7 @@ public class CachingClientConnectionFactoryTests { TcpNetServerConnectionFactory in = new TcpNetServerConnectionFactory(0); final CountDownLatch latch1 = new CountDownLatch(2); final CountDownLatch latch2 = new CountDownLatch(102); - final List connectionIds = new ArrayList(); + final List connectionIds = new ArrayList<>(); in.registerListener(message -> { connectionIds.add((String) message.getHeaders().get(IpHeaders.CONNECTION_ID)); latch1.countDown(); @@ -702,16 +671,16 @@ public class CachingClientConnectionFactoryTests { cache.setConnectionWaitTimeout(100); cache.start(); TcpConnectionSupport connection1 = cache.getConnection(); - connection1.send(new GenericMessage("foo")); + connection1.send(new GenericMessage<>("foo")); connection1.close(); TcpConnectionSupport connection2 = cache.getConnection(); - connection2.send(new GenericMessage("foo")); + connection2.send(new GenericMessage<>("foo")); connection2.close(); assertThat(latch1.await(10, TimeUnit.SECONDS)).isTrue(); assertThat(connectionIds.get(1)).isSameAs(connectionIds.get(0)); for (int i = 0; i < 100; i++) { TcpConnectionSupport connection = cache.getConnection(); - connection.send(new GenericMessage("foo")); + connection.send(new GenericMessage<>("foo")); connection.close(); } assertThat(latch2.await(10, TimeUnit.SECONDS)).isTrue(); @@ -722,7 +691,7 @@ public class CachingClientConnectionFactoryTests { @SuppressWarnings("unchecked") @Test //INT-3722 - public void testGatewayRelease() throws Exception { + public void testGatewayRelease() { TcpNetServerConnectionFactory in = new TcpNetServerConnectionFactory(0); in.setApplicationEventPublisher(mock(ApplicationEventPublisher.class)); final TcpSendingMessageHandler handler = new TcpSendingMessageHandler(); @@ -780,7 +749,7 @@ public class CachingClientConnectionFactoryTests { } }).when(logger).debug(anyString()); gate.start(); - gate.handleMessage(new GenericMessage("foo")); + gate.handleMessage(new GenericMessage<>("foo")); Message result = (Message) outputChannel.receive(10000); assertThat(result).isNotNull(); assertThat(new String(result.getPayload())).isEqualTo("foo"); @@ -812,7 +781,7 @@ public class CachingClientConnectionFactoryTests { }; factory.setApplicationEventPublisher(mock(ApplicationEventPublisher.class)); final CachingClientConnectionFactory cachingFactory = new CachingClientConnectionFactory(factory, 1); - final AtomicReference> received = new AtomicReference>(); + final AtomicReference> received = new AtomicReference<>(); cachingFactory.registerListener(message -> { if (!(message instanceof ErrorMessage)) { received.set(message); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/SocketSupportTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/SocketSupportTests.java index 770ed74ff7..6ad716ab43 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/SocketSupportTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/SocketSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -49,7 +49,7 @@ import javax.net.SocketFactory; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLServerSocket; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.integration.ip.tcp.serializer.ByteArrayCrLfSerializer; @@ -520,14 +520,14 @@ public class SocketSupportTests { testNioClientAndServerSSLDifferentContexts(false); assertThatExceptionOfType(MessagingException.class) .isThrownBy(() -> testNioClientAndServerSSLDifferentContexts(true)) - .withMessageMatching(".*(Socket closed during SSL Handshake|Broken pipe" - + "|Connection reset by peer|AsynchronousCloseException|ClosedChannelException).*"); + .withMessageMatching(".*javax.net.ssl.SSLHandshakeException.*"); } - private void testNioClientAndServerSSLDifferentContexts(boolean badClient) throws Exception { + private void testNioClientAndServerSSLDifferentContexts(boolean badServer) throws Exception { System.setProperty("javax.net.debug", "all"); // SSL activity in the console TcpNioServerConnectionFactory server = new TcpNioServerConnectionFactory(0); - TcpSSLContextSupport serverSslContextSupport = new DefaultTcpSSLContextSupport("server.ks", + TcpSSLContextSupport serverSslContextSupport = new DefaultTcpSSLContextSupport( + badServer ? "client.ks" : "server.ks", "server.truststore.ks", "secret", "secret"); DefaultTcpNioSSLConnectionSupport tcpNioConnectionSupport = new DefaultTcpNioSSLConnectionSupport(serverSslContextSupport, false) { @@ -550,8 +550,7 @@ public class SocketSupportTests { TestingUtilities.waitListening(server, null); TcpNioClientConnectionFactory client = new TcpNioClientConnectionFactory("localhost", server.getPort()); - TcpSSLContextSupport clientSslContextSupport = new DefaultTcpSSLContextSupport( - badClient ? "server.ks" : "client.ks", + TcpSSLContextSupport clientSslContextSupport = new DefaultTcpSSLContextSupport("client.ks", "client.truststore.ks", "secret", "secret"); DefaultTcpNioSSLConnectionSupport clientTcpNioConnectionSupport = new DefaultTcpNioSSLConnectionSupport(clientSslContextSupport, false); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionTests.java index ff0b9f8d73..a31c6c0a6c 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionTests.java @@ -63,10 +63,9 @@ import javax.net.SocketFactory; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TestName; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInfo; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @@ -84,7 +83,7 @@ import org.springframework.integration.ip.tcp.serializer.MapJsonSerializer; import org.springframework.integration.ip.util.TestingUtilities; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.support.converter.MapMessageConverter; -import org.springframework.integration.test.rule.Log4j2LevelAdjuster; +import org.springframework.integration.test.condition.LogLevels; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.util.CompositeExecutor; import org.springframework.messaging.Message; @@ -103,31 +102,25 @@ import org.springframework.util.StopWatch; * @since 2.0 * */ +@LogLevels(level = "trace", categories = "org.springframework.integration.ip.tcp") public class TcpNioConnectionTests { private static final Log logger = LogFactory.getLog(TcpNioConnectionTests.class); - @Rule - public Log4j2LevelAdjuster adjuster = - Log4j2LevelAdjuster.trace() - .categories("org.springframework.integration.ip.tcp"); - - @Rule - public TestName testName = new TestName(); - private final ApplicationEventPublisher nullPublisher = mock(ApplicationEventPublisher.class); private final AsyncTaskExecutor executor = new SimpleAsyncTaskExecutor(); @Test - public void testWriteTimeout() throws Exception { + public void testWriteTimeout(TestInfo testInfo) throws Exception { final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); final AtomicReference serverSocket = new AtomicReference<>(); this.executor.execute(() -> { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0); - logger.debug(testName.getMethodName() + " starting server for " + server.getLocalPort()); + logger.debug(testInfo.getTestMethod().get().getName() + + " starting server for " + server.getLocalPort()); serverSocket.set(server); latch.countDown(); Socket s = server.accept(); @@ -166,14 +159,15 @@ public class TcpNioConnectionTests { } @Test - public void testReadTimeout() throws Exception { + public void testReadTimeout(TestInfo testInfo) throws Exception { final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(1); final AtomicReference serverSocket = new AtomicReference<>(); this.executor.execute(() -> { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0); - logger.debug(testName.getMethodName() + " starting server for " + server.getLocalPort()); + logger.debug(testInfo.getTestMethod().get().getName() + + " starting server for " + server.getLocalPort()); serverSocket.set(server); latch.countDown(); Socket socket = server.accept(); @@ -209,13 +203,14 @@ public class TcpNioConnectionTests { } @Test - public void testMemoryLeak() throws Exception { + public void testMemoryLeak(TestInfo testInfo) throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference serverSocket = new AtomicReference<>(); this.executor.execute(() -> { try { ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(0); - logger.debug(testName.getMethodName() + " starting server for " + server.getLocalPort()); + logger.debug(testInfo.getTestMethod().get().getName() + + " starting server for " + server.getLocalPort()); serverSocket.set(server); latch.countDown(); Socket socket = server.accept(); @@ -264,37 +259,46 @@ public class TcpNioConnectionTests { connections.put(chan1, conn1); connections.put(chan2, conn2); connections.put(chan3, conn3); + boolean java8 = System.getProperty("java.version").startsWith("1.8"); final List fields = new ArrayList<>(); - ReflectionUtils.doWithFields(SocketChannel.class, field -> { - field.setAccessible(true); - fields.add(field); - }, field -> field.getName().equals("open")); + if (java8) { + ReflectionUtils.doWithFields(SocketChannel.class, field -> { + field.setAccessible(true); + fields.add(field); + }, field -> field.getName().equals("open")); + } + else { + ReflectionUtils.doWithFields(SocketChannel.class, field -> { + field.setAccessible(true); + fields.add(field); + }, field -> field.getName().equals("closed")); + } Field field = fields.get(0); // Can't use Mockito because isOpen() is final - ReflectionUtils.setField(field, chan1, true); - ReflectionUtils.setField(field, chan2, true); - ReflectionUtils.setField(field, chan3, true); + ReflectionUtils.setField(field, chan1, java8); + ReflectionUtils.setField(field, chan2, java8); + ReflectionUtils.setField(field, chan3, java8); Selector selector = mock(Selector.class); HashSet keys = new HashSet<>(); when(selector.selectedKeys()).thenReturn(keys); factory.processNioSelections(1, selector, null, connections); assertThat(connections.size()).isEqualTo(3); // all open - ReflectionUtils.setField(field, chan1, false); + ReflectionUtils.setField(field, chan1, !java8); factory.processNioSelections(1, selector, null, connections); assertThat(connections.size()).isEqualTo(3); // interval didn't pass Thread.sleep(110); factory.processNioSelections(1, selector, null, connections); assertThat(connections.size()).isEqualTo(2); // first is closed - ReflectionUtils.setField(field, chan2, false); + ReflectionUtils.setField(field, chan2, !java8); factory.processNioSelections(1, selector, null, connections); assertThat(connections.size()).isEqualTo(2); // interval didn't pass Thread.sleep(110); factory.processNioSelections(1, selector, null, connections); assertThat(connections.size()).isEqualTo(1); // second is closed - ReflectionUtils.setField(field, chan3, false); + ReflectionUtils.setField(field, chan3, !java8); factory.processNioSelections(1, selector, null, connections); assertThat(connections.size()).isEqualTo(1); // interval didn't pass Thread.sleep(110); @@ -812,7 +816,7 @@ public class TcpNioConnectionTests { } @Test - @Ignore // Timing is too short for CI/Travis + @Disabled("Timing is too short for CI/Travis") public void testNoDelayOnClose() throws Exception { TcpNioServerConnectionFactory cf = new TcpNioServerConnectionFactory(0); final CountDownLatch reading = new CountDownLatch(1); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketMulticastSendingHandlerTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketMulticastSendingHandlerTests.java index 8cccbf648e..a80204b91f 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketMulticastSendingHandlerTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketMulticastSendingHandlerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,11 +24,13 @@ import java.net.DatagramSocket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; +import java.net.NetworkInterface; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; @@ -69,7 +71,7 @@ public class DatagramPacketMulticastSendingHandlerTests { byte[] buffer = new byte[8]; DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket socket1 = new MulticastSocket(testPort); - socket1.setInterface(InetAddress.getByName(multicastRule.getNic())); + socket1.setNetworkInterface(multicastRule.getNic()); InetAddress group = InetAddress.getByName(multicastAddress); socket1.joinGroup(group); listening.countDown(); @@ -94,7 +96,10 @@ public class DatagramPacketMulticastSendingHandlerTests { assertThat(listening.await(10000, TimeUnit.MILLISECONDS)).isTrue(); MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort); handler.setBeanFactory(mock(BeanFactory.class)); - handler.setLocalAddress(this.multicastRule.getNic()); + NetworkInterface nic = this.multicastRule.getNic(); + if (nic != null) { + handler.setLocalAddress(nic.getName()); + } handler.afterPropertiesSet(); handler.handleMessage(MessageBuilder.withPayload(payload).build()); assertThat(received.await(10000, TimeUnit.MILLISECONDS)).isTrue(); @@ -103,6 +108,7 @@ public class DatagramPacketMulticastSendingHandlerTests { } @Test + @Ignore("Doesn't work on Java 14") public void verifySendMulticastWithAcks() throws Exception { MulticastSocket socket; @@ -125,7 +131,7 @@ public class DatagramPacketMulticastSendingHandlerTests { byte[] buffer = new byte[1000]; DatagramPacket receivedPacket = new DatagramPacket(buffer, buffer.length); MulticastSocket socket1 = new MulticastSocket(testPort); - socket1.setInterface(InetAddress.getByName(multicastRule.getNic())); + socket1.setNetworkInterface(multicastRule.getNic()); socket1.setSoTimeout(8000); InetAddress group = InetAddress.getByName(multicastAddress); socket1.joinGroup(group); @@ -146,7 +152,7 @@ public class DatagramPacketMulticastSendingHandlerTests { Object id = message.getHeaders().get(IpHeaders.ACK_ID); byte[] ack = id.toString().getBytes(); DatagramPacket ackPack = new DatagramPacket(ack, ack.length, - new InetSocketAddress(multicastRule.getNic(), ackPort.get())); + new InetSocketAddress(multicastRule.getNic().getInetAddresses().nextElement(), ackPort.get())); DatagramSocket out = new DatagramSocket(); out.send(ackPack); out.close(); @@ -164,7 +170,7 @@ public class DatagramPacketMulticastSendingHandlerTests { assertThat(listening.await(10000, TimeUnit.MILLISECONDS)).isTrue(); MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(multicastAddress, testPort, true, true, "localhost", 0, 10000); - handler.setLocalAddress(this.multicastRule.getNic()); + handler.setLocalAddress(this.multicastRule.getNic().getName()); handler.setMinAcksForSuccess(2); handler.setBeanFactory(mock(BeanFactory.class)); handler.afterPropertiesSet(); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/MulticastRule.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/MulticastRule.java index 0b177e0837..750aee88e1 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/MulticastRule.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/MulticastRule.java @@ -1,5 +1,5 @@ /* - * Copyright 2015-2019 the original author or authors. + * Copyright 2015-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,8 +16,9 @@ package org.springframework.integration.ip.udp; -import java.net.InetAddress; +import java.net.InetSocketAddress; import java.net.MulticastSocket; +import java.net.NetworkInterface; import org.apache.commons.logging.LogFactory; import org.junit.Assume; @@ -26,10 +27,12 @@ import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.springframework.integration.ip.util.SocketTestUtils; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * @author Artem Bilan + * * @since 4.3 */ public class MulticastRule extends TestWatcher { @@ -38,7 +41,8 @@ public class MulticastRule extends TestWatcher { private final String group; - private final String nic; + @Nullable + private final NetworkInterface nic; private boolean skip; @@ -58,19 +62,20 @@ public class MulticastRule extends TestWatcher { throw new IllegalStateException(e); } if (this.nic != null) { - System.setProperty("multicast.local.address", this.nic); + System.setProperty("multicast.local.address", this.nic.getName()); } } - private String checkMulticast() throws Exception { - String nic = SocketTestUtils.chooseANic(true); - if (nic == null) { // no multicast support + @Nullable + private NetworkInterface checkMulticast() throws Exception { + NetworkInterface nic = SocketTestUtils.chooseANic(true); + if (nic == null) { // no multicast support this.skip = true; return null; } try { MulticastSocket socket = new MulticastSocket(); - socket.joinGroup(InetAddress.getByName(this.group)); + socket.joinGroup(new InetSocketAddress(this.group, 161), nic); socket.close(); } catch (Exception e) { @@ -84,25 +89,18 @@ public class MulticastRule extends TestWatcher { return group; } - public String getNic() { + @Nullable + public NetworkInterface getNic() { return nic; } @Override public Statement apply(Statement base, Description description) { if (this.skip) { - LogFactory.getLog(this.getClass()).info("No Multicast support; test skipped"); - return new Statement() { - - @Override - public void evaluate() throws Throwable { - Assume.assumeTrue(false); - } - }; - } - else { - return super.apply(base, description); + LogFactory.getLog(getClass()).info("No Multicast support; test skipped"); } + Assume.assumeFalse(this.skip); + return super.apply(base, description); } } diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/UdpChannelAdapterTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/UdpChannelAdapterTests.java index 63060842de..99754373bd 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/UdpChannelAdapterTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/UdpChannelAdapterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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,8 +23,8 @@ import static org.mockito.Mockito.mock; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; -import java.net.Inet4Address; import java.net.InetSocketAddress; +import java.net.NetworkInterface; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; @@ -34,6 +34,8 @@ import java.util.concurrent.atomic.AtomicReference; import org.junit.Rule; import org.junit.Test; +import org.junit.jupiter.api.condition.EnabledOnJre; +import org.junit.jupiter.api.condition.JRE; import org.springframework.beans.factory.BeanFactory; import org.springframework.context.ConfigurableApplicationContext; @@ -244,13 +246,16 @@ public class UdpChannelAdapterTests { @SuppressWarnings("unchecked") @Test + @EnabledOnJre(JRE.JAVA_8) public void testMulticastReceiver() throws Exception { QueueChannel channel = new QueueChannel(2); MulticastReceivingChannelAdapter adapter = new MulticastReceivingChannelAdapter(this.multicastRule.getGroup(), 0); adapter.setOutputChannel(channel); - String nic = this.multicastRule.getNic(); - adapter.setLocalAddress(nic); + NetworkInterface nic = this.multicastRule.getNic(); + if (nic != null) { + adapter.setLocalAddress(nic.getName()); + } adapter.start(); SocketTestUtils.waitListening(adapter); int port = adapter.getPort(); @@ -259,7 +264,7 @@ public class UdpChannelAdapterTests { DatagramPacketMessageMapper mapper = new DatagramPacketMessageMapper(); DatagramPacket packet = mapper.fromMessage(message); packet.setSocketAddress(new InetSocketAddress(this.multicastRule.getGroup(), port)); - DatagramSocket datagramSocket = new DatagramSocket(0, Inet4Address.getByName(nic)); + DatagramSocket datagramSocket = new DatagramSocket(0, nic.getInetAddresses().nextElement()); datagramSocket.send(packet); datagramSocket.close(); @@ -271,19 +276,23 @@ public class UdpChannelAdapterTests { @SuppressWarnings("unchecked") @Test - public void testMulticastSender() throws Exception { + public void testMulticastSender() { QueueChannel channel = new QueueChannel(2); UnicastReceivingChannelAdapter adapter = new MulticastReceivingChannelAdapter(this.multicastRule.getGroup(), 0); adapter.setOutputChannel(channel); - String nic = this.multicastRule.getNic(); - adapter.setLocalAddress(nic); + NetworkInterface nic = this.multicastRule.getNic(); + if (nic != null) { + adapter.setLocalAddress(nic.getName()); + } adapter.start(); SocketTestUtils.waitListening(adapter); MulticastSendingMessageHandler handler = new MulticastSendingMessageHandler(this.multicastRule.getGroup(), adapter.getPort()); - handler.setLocalAddress(nic); + if (nic != null) { + handler.setLocalAddress(nic.getName()); + } Message message = MessageBuilder.withPayload("ABCD".getBytes()).build(); handler.handleMessage(message); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/util/SocketTestUtils.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/util/SocketTestUtils.java index 6390bc688e..463e67bb45 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/util/SocketTestUtils.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/util/SocketTestUtils.java @@ -21,7 +21,6 @@ import static org.awaitility.Awaitility.await; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; -import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.Socket; @@ -36,6 +35,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.integration.ip.AbstractInternetProtocolReceivingChannelAdapter; +import org.springframework.lang.Nullable; /** * TCP/IP Test utilities. @@ -62,9 +62,7 @@ public class SocketTestUtils { public static CountDownLatch testSendLength(final int port, final CountDownLatch latch) { final CountDownLatch testCompleteLatch = new CountDownLatch(1); Thread thread = new Thread(() -> { - Socket socket = null; - try { - socket = new Socket(InetAddress.getByName("localhost"), port); + try (Socket socket = new Socket(InetAddress.getByName("localhost"), port)) { for (int i = 0; i < 2; i++) { byte[] len = new byte[4]; ByteBuffer.wrap(len).putInt(TEST_STRING.length() * 2); @@ -84,16 +82,6 @@ public class SocketTestUtils { catch (Exception e1) { logger.error(e1); } - finally { - if (socket != null) { - try { - socket.close(); - } - catch (IOException e2) { - - } - } - } }); thread.setDaemon(true); thread.start(); @@ -106,9 +94,7 @@ public class SocketTestUtils { public static CountDownLatch testSendLengthOverflow(final int port) { final CountDownLatch testCompleteLatch = new CountDownLatch(1); Thread thread = new Thread(() -> { - Socket socket = null; - try { - socket = new Socket(InetAddress.getByName("localhost"), port); + try (Socket socket = new Socket(InetAddress.getByName("localhost"), port)) { byte[] len = new byte[4]; ByteBuffer.wrap(len).putInt(Integer.MAX_VALUE); socket.getOutputStream().write(len); @@ -118,16 +104,6 @@ public class SocketTestUtils { catch (Exception e1) { logger.error(e1); } - finally { - if (socket != null) { - try { - socket.close(); - } - catch (IOException e2) { - - } - } - } }); thread.setDaemon(true); thread.start(); @@ -191,9 +167,7 @@ public class SocketTestUtils { public static CountDownLatch testSendStxEtx(final int port, final CountDownLatch latch) { final CountDownLatch testCompleteLatch = new CountDownLatch(1); Thread thread = new Thread(() -> { - Socket socket = null; - try { - socket = new Socket(InetAddress.getByName("localhost"), port); + try (Socket socket = new Socket(InetAddress.getByName("localhost"), port)) { OutputStream outputStream = socket.getOutputStream(); for (int i = 0; i < 2; i++) { writeByte(outputStream, 0x02, true); @@ -213,16 +187,6 @@ public class SocketTestUtils { catch (Exception e1) { logger.error(e1); } - finally { - if (socket != null) { - try { - socket.close(); - } - catch (IOException e2) { - - } - } - } }); thread.setDaemon(true); thread.start(); @@ -235,9 +199,7 @@ public class SocketTestUtils { public static CountDownLatch testSendStxEtxOverflow(final int port) { final CountDownLatch testCompleteLatch = new CountDownLatch(1); Thread thread = new Thread(() -> { - Socket socket = null; - try { - socket = new Socket(InetAddress.getByName("localhost"), port); + try (Socket socket = new Socket(InetAddress.getByName("localhost"), port)) { OutputStream outputStream = socket.getOutputStream(); writeByte(outputStream, 0x02, true); for (int i = 0; i < 1500; i++) { @@ -248,16 +210,6 @@ public class SocketTestUtils { catch (Exception e1) { logger.debug("write failed", e1); } - finally { - if (socket != null) { - try { - socket.close(); - } - catch (IOException e2) { - - } - } - } }); thread.setDaemon(true); thread.start(); @@ -271,9 +223,7 @@ public class SocketTestUtils { public static CountDownLatch testSendCrLf(final int port, final CountDownLatch latch) { final CountDownLatch testCompleteLatch = new CountDownLatch(1); Thread thread = new Thread(() -> { - Socket socket = null; - try { - socket = new Socket(InetAddress.getByName("localhost"), port); + try (Socket socket = new Socket(InetAddress.getByName("localhost"), port)) { OutputStream outputStream = socket.getOutputStream(); for (int i = 0; i < 2; i++) { outputStream.write(TEST_STRING.getBytes()); @@ -293,16 +243,6 @@ public class SocketTestUtils { catch (Exception e1) { logger.error(e1); } - finally { - if (socket != null) { - try { - socket.close(); - } - catch (IOException e2) { - - } - } - } }); thread.setDaemon(true); thread.start(); @@ -315,8 +255,7 @@ public class SocketTestUtils { */ public static void testSendCrLfSingle(final int port, final CountDownLatch latch) { Thread thread = new Thread(() -> { - try { - Socket socket = new Socket(InetAddress.getByName("localhost"), port); + try (Socket socket = new Socket(InetAddress.getByName("localhost"), port)) { OutputStream outputStream = socket.getOutputStream(); outputStream.write(TEST_STRING.getBytes()); outputStream.write(TEST_STRING.getBytes()); @@ -325,7 +264,6 @@ public class SocketTestUtils { if (latch != null) { latch.await(); } - socket.close(); } catch (Exception ex) { logger.error(ex); @@ -340,12 +278,10 @@ public class SocketTestUtils { */ public static void testSendRaw(final int port) { Thread thread = new Thread(() -> { - try { - Socket socket = new Socket(InetAddress.getByName("localhost"), port); + try (Socket socket = new Socket(InetAddress.getByName("localhost"), port)) { OutputStream outputStream = socket.getOutputStream(); outputStream.write(TEST_STRING.getBytes()); outputStream.write(TEST_STRING.getBytes()); - socket.close(); } catch (Exception ex) { logger.error(ex); @@ -354,16 +290,15 @@ public class SocketTestUtils { thread.setDaemon(true); thread.start(); } + /** * Sends two serialized objects over the same socket. - * @param port + * @param port the port for socket */ public static CountDownLatch testSendSerialized(final int port) { final CountDownLatch testCompleteLatch = new CountDownLatch(1); Thread thread = new Thread(() -> { - Socket socket = null; - try { - socket = new Socket(InetAddress.getByName("localhost"), port); + try (Socket socket = new Socket(InetAddress.getByName("localhost"), port)) { OutputStream outputStream = socket.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(outputStream); oos.writeObject(TEST_STRING); @@ -376,16 +311,6 @@ public class SocketTestUtils { catch (Exception e1) { logger.error(e1); } - finally { - if (socket != null) { - try { - socket.close(); - } - catch (IOException e2) { - - } - } - } }); thread.setDaemon(true); thread.start(); @@ -398,14 +323,12 @@ public class SocketTestUtils { public static CountDownLatch testSendCrLfOverflow(final int port) { final CountDownLatch testCompleteLatch = new CountDownLatch(1); Thread thread = new Thread(() -> { - try { - Socket socket = new Socket(InetAddress.getByName("localhost"), port); + try (Socket socket = new Socket(InetAddress.getByName("localhost"), port)) { OutputStream outputStream = socket.getOutputStream(); for (int i = 0; i < 1500; i++) { writeByte(outputStream, 'x', true); } testCompleteLatch.await(10, TimeUnit.SECONDS); - socket.close(); } catch (Exception e) { @@ -427,26 +350,23 @@ public class SocketTestUtils { } } - public static String chooseANic(boolean multicast) throws Exception { + @Nullable + public static NetworkInterface chooseANic(boolean multicast) throws Exception { Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { - NetworkInterface intface = interfaces.nextElement(); - if (intface.isLoopback() || (multicast && !intface.supportsMulticast()) - || intface.getName().contains("vboxnet")) { - continue; - } - for (Enumeration inetAddr = intface.getInetAddresses(); inetAddr.hasMoreElements(); ) { - InetAddress nextElement = inetAddr.nextElement(); - if (nextElement instanceof Inet4Address) { - return nextElement.getHostAddress(); - } + NetworkInterface networkInterface = interfaces.nextElement(); + if (!networkInterface.isLoopback() + && (!multicast || networkInterface.supportsMulticast()) + && !networkInterface.getName().contains("vboxnet") + && networkInterface.getInetAddresses().hasMoreElements()) { + return networkInterface; } } return null; } - public static void waitListening(AbstractInternetProtocolReceivingChannelAdapter adapter) throws Exception { - await("Adapter not listening").atMost(Duration.ofSeconds(10)).until(() -> adapter.isListening()); + public static void waitListening(AbstractInternetProtocolReceivingChannelAdapter adapter) { + await("Adapter not listening").atMost(Duration.ofSeconds(10)).until(adapter::isListening); } } diff --git a/spring-integration-jms/src/main/java/org/springframework/integration/jms/config/JmsChannelFactoryBean.java b/spring-integration-jms/src/main/java/org/springframework/integration/jms/config/JmsChannelFactoryBean.java index e231ddb0c3..1e36f994ef 100644 --- a/spring-integration-jms/src/main/java/org/springframework/integration/jms/config/JmsChannelFactoryBean.java +++ b/spring-integration-jms/src/main/java/org/springframework/integration/jms/config/JmsChannelFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,6 +24,7 @@ import javax.jms.Destination; import javax.jms.ExceptionListener; import javax.jms.Session; +import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.config.AbstractFactoryBean; @@ -412,13 +413,7 @@ public class JmsChannelFactoryBean extends AbstractFactoryBean, C extends AbstractMessageListenerContainer> +public class JmsListenerContainerSpec, + C extends AbstractMessageListenerContainer> extends JmsDestinationAccessorSpec { protected JmsListenerContainerSpec(Class aClass) { - super(newInstance(aClass)); + super(BeanUtils.instantiateClass(aClass)); if (DefaultMessageListenerContainer.class.isAssignableFrom(aClass)) { this.target.setSessionTransacted(true); } } - private static C newInstance(Class aClass) { - try { - return aClass.newInstance(); - } - catch (InstantiationException | IllegalAccessException e) { - throw new IllegalStateException(e); - } - } - /** * @param destination the destination. * @return the spec. diff --git a/spring-integration-jms/src/test/java/org/springframework/integration/jms/DefaultJmsHeaderMapperTests.java b/spring-integration-jms/src/test/java/org/springframework/integration/jms/DefaultJmsHeaderMapperTests.java index 015806edd7..6cbb1f8f50 100644 --- a/spring-integration-jms/src/test/java/org/springframework/integration/jms/DefaultJmsHeaderMapperTests.java +++ b/spring-integration-jms/src/test/java/org/springframework/integration/jms/DefaultJmsHeaderMapperTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -25,7 +25,7 @@ import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Session; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.integration.IntegrationMessageHeaderAccessor; @@ -41,6 +41,7 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; /** * @author Mark Fisher * @author Gary Russell + * @author Artem Bilan */ public class DefaultJmsHeaderMapperTests { @@ -83,7 +84,7 @@ public class DefaultJmsHeaderMapperTests { @Test public void testJmsCorrelationIdNumberConvertsToString() throws JMSException { Message message = MessageBuilder.withPayload("test") - .setHeader(JmsHeaders.CORRELATION_ID, new Integer(123)).build(); + .setHeader(JmsHeaders.CORRELATION_ID, 123).build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); @@ -103,8 +104,10 @@ public class DefaultJmsHeaderMapperTests { @Test public void testJmsTypeMappedFromHeader() throws JMSException { String jmsType = "testing"; - Message message = MessageBuilder.withPayload("test") - .setHeader(JmsHeaders.TYPE, jmsType).build(); + Message message = + MessageBuilder.withPayload("test") + .setHeader(JmsHeaders.TYPE, jmsType) + .build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); @@ -114,8 +117,10 @@ public class DefaultJmsHeaderMapperTests { @Test public void testJmsTypeIgnoredIfIncorrectType() throws JMSException { - Message message = MessageBuilder.withPayload("test") - .setHeader(JmsHeaders.TYPE, new Integer(123)).build(); + Message message = + MessageBuilder.withPayload("test") + .setHeader(JmsHeaders.TYPE, 123) + .build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); @@ -137,9 +142,10 @@ public class DefaultJmsHeaderMapperTests { @Test public void testUserDefinedPropertyMappedFromHeader() throws JMSException { - Message message = MessageBuilder.withPayload("test") - .setHeader("foo", new Integer(123)) - .build(); + Message message = + MessageBuilder.withPayload("test") + .setHeader("foo", 123) + .build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage(); mapper.fromHeaders(message.getHeaders(), jmsMessage); @@ -151,9 +157,10 @@ public class DefaultJmsHeaderMapperTests { @Test public void testUserDefinedPropertyMappedFromHeaderWithCustomPrefix() throws JMSException { - Message message = MessageBuilder.withPayload("test") - .setHeader("foo", new Integer(123)) - .build(); + Message message = + MessageBuilder.withPayload("test") + .setHeader("foo", 123) + .build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); mapper.setOutboundPrefix("custom_"); javax.jms.Message jmsMessage = new StubTextMessage(); @@ -301,11 +308,12 @@ public class DefaultJmsHeaderMapperTests { @Test public void testPropertyMappingExceptionIsNotFatal() throws JMSException { - Message message = MessageBuilder.withPayload("test") - .setHeader("foo", new Integer(123)) - .setHeader("bad", new Integer(456)) - .setHeader("bar", new Integer(789)) - .build(); + Message message = + MessageBuilder.withPayload("test") + .setHeader("foo", 123) + .setHeader("bad", 456) + .setHeader("bar", 789) + .build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage() { @@ -328,11 +336,12 @@ public class DefaultJmsHeaderMapperTests { @Test public void testIllegalArgumentExceptionIsNotFatal() throws JMSException { - Message message = MessageBuilder.withPayload("test") - .setHeader("foo", new Integer(123)) - .setHeader("bad", new Integer(456)) - .setHeader("bar", new Integer(789)) - .build(); + Message message = + MessageBuilder.withPayload("test") + .setHeader("foo", 123) + .setHeader("bad", 456) + .setHeader("bar", 789) + .build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage() { @@ -416,7 +425,7 @@ public class DefaultJmsHeaderMapperTests { @Test public void attemptToWriteDisallowedCorrelationIdNumberPropertyIsNotFatal() throws JMSException { Message message = MessageBuilder.withPayload("test") - .setHeader(JmsHeaders.CORRELATION_ID, new Integer(123)) + .setHeader(JmsHeaders.CORRELATION_ID, 123) .setHeader("foo", "bar") .build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); @@ -544,7 +553,7 @@ public class DefaultJmsHeaderMapperTests { } - @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "javatype") + @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "javatype") private static class Foo { } diff --git a/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/TestJmsHeaderMapper.java b/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/TestJmsHeaderMapper.java index 47f2e9cf8a..a75f3ad0dc 100644 --- a/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/TestJmsHeaderMapper.java +++ b/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/TestJmsHeaderMapper.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,6 +27,7 @@ import org.springframework.messaging.MessageHeaders; /** * @author Mark Fisher * @author Gary Russell + * @author Artem Bilan */ public class TestJmsHeaderMapper extends JmsHeaderMapper { @@ -36,9 +37,9 @@ public class TestJmsHeaderMapper extends JmsHeaderMapper { @Override public Map toHeaders(Message source) { - Map headerMap = new HashMap(); + Map headerMap = new HashMap<>(); headerMap.put("testProperty", "foo"); - headerMap.put("testAttribute", new Integer(123)); + headerMap.put("testAttribute", 123); return headerMap; } diff --git a/spring-integration-jms/src/test/java/org/springframework/integration/jms/dsl/JmsTests.java b/spring-integration-jms/src/test/java/org/springframework/integration/jms/dsl/JmsTests.java index b5a656260c..13f2badfeb 100644 --- a/spring-integration-jms/src/test/java/org/springframework/integration/jms/dsl/JmsTests.java +++ b/spring-integration-jms/src/test/java/org/springframework/integration/jms/dsl/JmsTests.java @@ -88,7 +88,7 @@ import org.springframework.transaction.PlatformTransactionManager; */ @SpringJUnitConfig @LogLevels(level = "debug", - categories = { "org.springframework", "org.springframework.integration", "org.apache" }) + categories = {"org.springframework", "org.springframework.integration", "org.apache"}) @DirtiesContext public class JmsTests extends ActiveMQMultiContextTests { @@ -215,7 +215,7 @@ public class JmsTests extends ActiveMQMultiContextTests { @Test public void testJmsPipelineFlow() { assertThat(TestUtils.getPropertyValue(this.jmsOutboundGatewayHandler, "idleReplyContainerTimeout", Long.class)) - .isEqualTo(new Long(10000)); + .isEqualTo(10000L); PollableChannel replyChannel = new QueueChannel(); Message message = MessageBuilder.withPayload("hello through the jms pipeline") .setReplyChannel(replyChannel) diff --git a/spring-integration-jmx/src/main/java/org/springframework/integration/jmx/NamedFieldsMBeanAttributeFilter.java b/spring-integration-jmx/src/main/java/org/springframework/integration/jmx/NamedFieldsMBeanAttributeFilter.java index 1551f1615e..47d74152fb 100644 --- a/spring-integration-jmx/src/main/java/org/springframework/integration/jmx/NamedFieldsMBeanAttributeFilter.java +++ b/spring-integration-jmx/src/main/java/org/springframework/integration/jmx/NamedFieldsMBeanAttributeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 the original author or authors. + * Copyright 2013-2020 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,12 @@ import java.util.Arrays; import javax.management.ObjectName; +import org.springframework.util.Assert; + /** * @author Stuart Williams + * @author Artem Bilan + * * @since 3.0 * */ @@ -33,7 +37,8 @@ public class NamedFieldsMBeanAttributeFilter implements MBeanAttributeFilter { * @param namedFields The named fields that should pass the filter. */ public NamedFieldsMBeanAttributeFilter(String... namedFields) { - this.namedFields = (String[]) Arrays.asList(namedFields).toArray(); + Assert.notNull(namedFields, "'namedFields' must not be null"); + this.namedFields = Arrays.copyOf(namedFields, namedFields.length); } @Override diff --git a/spring-integration-jmx/src/main/java/org/springframework/integration/jmx/NotNamedFieldsMBeanAttributeFilter.java b/spring-integration-jmx/src/main/java/org/springframework/integration/jmx/NotNamedFieldsMBeanAttributeFilter.java index 97ccb5f427..e66a49b7fc 100644 --- a/spring-integration-jmx/src/main/java/org/springframework/integration/jmx/NotNamedFieldsMBeanAttributeFilter.java +++ b/spring-integration-jmx/src/main/java/org/springframework/integration/jmx/NotNamedFieldsMBeanAttributeFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 the original author or authors. + * Copyright 2013-2020 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,12 @@ import java.util.Arrays; import javax.management.ObjectName; +import org.springframework.util.Assert; + /** * @author Stuart Williams + * @author Artem Bilan + * * @since 3.0 * */ @@ -33,7 +37,8 @@ public class NotNamedFieldsMBeanAttributeFilter implements MBeanAttributeFilter * @param namedFields The named fields that should be filtered. */ public NotNamedFieldsMBeanAttributeFilter(String... namedFields) { - this.namedFields = (String[]) Arrays.asList(namedFields).toArray(); + Assert.notNull(namedFields, "'namedFields' must not be null"); + this.namedFields = Arrays.copyOf(namedFields, namedFields.length); } @Override diff --git a/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/MBeanAttributeFilterTests.java b/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/MBeanAttributeFilterTests.java index 350528ea29..b56b5c265e 100644 --- a/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/MBeanAttributeFilterTests.java +++ b/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/MBeanAttributeFilterTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2019 the original author or authors. + * Copyright 2013-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -33,16 +32,15 @@ import org.springframework.integration.endpoint.SourcePollingChannelAdapter; import org.springframework.messaging.Message; import org.springframework.messaging.PollableChannel; import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Stuart Williams * @author Gary Russell + * @author Artem Bilan * */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration +@SpringJUnitConfig @DirtiesContext public class MBeanAttributeFilterTests { @@ -106,7 +104,7 @@ public class MBeanAttributeFilterTests { Map bean = (Map) payload .get(domain + ":name=in,type=MessageChannel"); - List keys = new ArrayList(bean.keySet()); + List keys = new ArrayList<>(bean.keySet()); Collections.sort(keys); assertThat(keys) .containsExactly("LoggingEnabled", "MaxSendDuration", "MeanErrorRate", "MeanErrorRatio", diff --git a/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/configuration/DslMBeanTests.java b/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/configuration/DslMBeanTests.java index 257fa93324..f1411817b2 100644 --- a/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/configuration/DslMBeanTests.java +++ b/spring-integration-jmx/src/test/java/org/springframework/integration/jmx/configuration/DslMBeanTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2018-2019 the original author or authors. + * Copyright 2018-2020 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. @@ -63,7 +63,7 @@ public class DslMBeanTests { assertThat(query).hasSize(0); IntegrationFlow dynamicFlow = - IntegrationFlows.from(() -> "foo", e -> e.poller(p -> p.fixedDelay(1000))) + IntegrationFlows.fromSupplier(() -> "foo", e -> e.poller(p -> p.fixedDelay(1000))) .channel("channelTwo") .nullChannel(); diff --git a/spring-integration-rsocket/src/main/java/org/springframework/integration/rsocket/IntegrationRSocketMessageHandler.java b/spring-integration-rsocket/src/main/java/org/springframework/integration/rsocket/IntegrationRSocketMessageHandler.java index eb3984dd8b..c730068850 100644 --- a/spring-integration-rsocket/src/main/java/org/springframework/integration/rsocket/IntegrationRSocketMessageHandler.java +++ b/spring-integration-rsocket/src/main/java/org/springframework/integration/rsocket/IntegrationRSocketMessageHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2019 the original author or authors. + * Copyright 2019-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,6 +18,7 @@ package org.springframework.integration.rsocket; import java.lang.reflect.Method; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.List; @@ -66,17 +67,17 @@ class IntegrationRSocketMessageHandler extends RSocketMessageHandler { public boolean detectEndpoints() { ApplicationContext applicationContext = getApplicationContext(); + boolean endpointsDetected = false; if (applicationContext != null && getHandlerMethods().isEmpty()) { - return applicationContext - .getBeansOfType(IntegrationRSocketEndpoint.class) - .values() - .stream() - .peek(this::addEndpoint) - .count() > 0; - } - else { - return false; + Collection endpoints = + applicationContext.getBeansOfType(IntegrationRSocketEndpoint.class) + .values(); + for (IntegrationRSocketEndpoint endpoint : endpoints) { + addEndpoint(endpoint); + endpointsDetected = true; + } } + return endpointsDetected; } public void addEndpoint(IntegrationRSocketEndpoint endpoint) { diff --git a/spring-integration-scripting/src/test/java/org/springframework/integration/scripting/config/jsr223/Jsr223ServiceActivatorTests.java b/spring-integration-scripting/src/test/java/org/springframework/integration/scripting/config/jsr223/Jsr223ServiceActivatorTests.java index 7076aa0072..3de32d33a5 100644 --- a/spring-integration-scripting/src/test/java/org/springframework/integration/scripting/config/jsr223/Jsr223ServiceActivatorTests.java +++ b/spring-integration-scripting/src/test/java/org/springframework/integration/scripting/config/jsr223/Jsr223ServiceActivatorTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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,14 +17,13 @@ package org.springframework.integration.scripting.config.jsr223; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import java.util.Date; import java.util.HashMap; import java.util.Map; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; @@ -34,18 +33,18 @@ import org.springframework.integration.scripting.ScriptVariableGenerator; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; /** * @author Mark Fisher * @author Oleg Zhurakousky * @author David Turanski * @author Gunnar Hillert + * @author Artem Bilan + * * @since 2.0 */ -@ContextConfiguration -@RunWith(SpringJUnit4ClassRunner.class) +@SpringJUnitConfig public class Jsr223ServiceActivatorTests { @Autowired @@ -118,8 +117,7 @@ public class Jsr223ServiceActivatorTests { } @Test - public void inlineScript() throws Exception { - + public void inlineScript() { QueueChannel replyChannel = new QueueChannel(); replyChannel.setBeanName("returnAddress"); for (int i = 1; i <= 3; i++) { @@ -142,34 +140,31 @@ public class Jsr223ServiceActivatorTests { } @Test - public void variablesAndScriptVariableGenerator() throws Exception { - try { - new ClassPathXmlApplicationContext("Jsr223ServiceActivatorTests-fail-withgenerator-context.xml", - this.getClass()).close(); - fail("BeansException expected."); - } - catch (BeansException e) { - assertThat(e.getMessage()) - .contains("'script-variable-generator' and 'variable' sub-elements are mutually exclusive."); - } + public void variablesAndScriptVariableGenerator() { + assertThatExceptionOfType(BeansException.class) + .isThrownBy(() -> + new ClassPathXmlApplicationContext( + "Jsr223ServiceActivatorTests-fail-withgenerator-context.xml", + getClass())) + .withMessageContaining( + "'script-variable-generator' and 'variable' sub-elements are mutually exclusive."); } @Test - public void testDuplicateVariable() throws Exception { - try { - new ClassPathXmlApplicationContext("Jsr223ServiceActivatorTests-fail-duplicated-variable-context.xml", - this.getClass()).close(); - fail("BeansException expected."); - } - catch (BeansException e) { - assertThat(e.getMessage()).contains("Duplicated variable: foo"); - } + public void testDuplicateVariable() { + assertThatExceptionOfType(BeansException.class) + .isThrownBy(() -> + new ClassPathXmlApplicationContext( + "Jsr223ServiceActivatorTests-fail-duplicated-variable-context.xml", + getClass())) + .withMessageContaining("Duplicated variable: foo"); } public static class SampleScriptVariSource implements ScriptVariableGenerator { + @Override public Map generateScriptVariables(Message message) { - Map variables = new HashMap(); + Map variables = new HashMap<>(); variables.put("foo", "foo"); variables.put("bar", "bar"); variables.put("date", new Date()); @@ -177,6 +172,7 @@ public class Jsr223ServiceActivatorTests { variables.put("headers", message.getHeaders()); return variables; } + } } diff --git a/spring-integration-webflux/src/test/java/org/springframework/integration/webflux/config/WebFluxOutboundGatewayParserTests.java b/spring-integration-webflux/src/test/java/org/springframework/integration/webflux/config/WebFluxOutboundGatewayParserTests.java index cee78adc06..326fd42a80 100644 --- a/spring-integration-webflux/src/test/java/org/springframework/integration/webflux/config/WebFluxOutboundGatewayParserTests.java +++ b/spring-integration-webflux/src/test/java/org/springframework/integration/webflux/config/WebFluxOutboundGatewayParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2017-2019 the original author or authors. + * Copyright 2017-2020 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 @@ package org.springframework.integration.webflux.config; import static org.assertj.core.api.Assertions.assertThat; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.Map; import org.junit.Test; @@ -106,20 +107,20 @@ public class WebFluxOutboundGatewayParserTests { assertThat(uriExpression.getValue()).isEqualTo("http://localhost/test2"); assertThat(TestUtils.getPropertyValue(handler, "httpMethodExpression", Expression.class).getExpressionString()) .isEqualTo(HttpMethod.PUT.name()); - assertThat(handlerAccessor.getPropertyValue("charset")).isEqualTo(Charset.forName("UTF-8")); + assertThat(handlerAccessor.getPropertyValue("charset")).isEqualTo(StandardCharsets.UTF_8); assertThat(handlerAccessor.getPropertyValue("extractPayload")).isEqualTo(false); Object sendTimeout = new DirectFieldAccessor( handlerAccessor.getPropertyValue("messagingTemplate")).getPropertyValue("sendTimeout"); - assertThat(sendTimeout).isEqualTo(new Long("1234")); + assertThat(sendTimeout).isEqualTo(1234L); Map uriVariableExpressions = (Map) handlerAccessor.getPropertyValue("uriVariableExpressions"); - assertThat(uriVariableExpressions.size()).isEqualTo(1); + assertThat(uriVariableExpressions).hasSize(1); assertThat(uriVariableExpressions.get("foo").getExpressionString()).isEqualTo("headers.bar"); DirectFieldAccessor mapperAccessor = new DirectFieldAccessor(handlerAccessor.getPropertyValue("headerMapper")); String[] mappedRequestHeaders = (String[]) mapperAccessor.getPropertyValue("outboundHeaderNames"); String[] mappedResponseHeaders = (String[]) mapperAccessor.getPropertyValue("inboundHeaderNames"); - assertThat(mappedRequestHeaders.length).isEqualTo(2); - assertThat(mappedResponseHeaders.length).isEqualTo(1); + assertThat(mappedRequestHeaders).hasSize(2); + assertThat(mappedResponseHeaders).hasSize(1); assertThat(ObjectUtils.containsElement(mappedRequestHeaders, "requestHeader1")).isTrue(); assertThat(ObjectUtils.containsElement(mappedRequestHeaders, "requestHeader2")).isTrue(); assertThat(mappedResponseHeaders[0]).isEqualTo("responseHeader"); diff --git a/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/XPathTransformerParserTests.java b/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/XPathTransformerParserTests.java index 10742334e4..0dc16e7265 100644 --- a/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/XPathTransformerParserTests.java +++ b/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/XPathTransformerParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 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. @@ -113,7 +113,7 @@ public class XPathTransformerParserTests { @Test public void numberResult() { this.numberInput.send(message); - assertThat(output.receive(0).getPayload()).isEqualTo(new Double(42)); + assertThat(output.receive(0).getPayload()).isEqualTo(42d); } @Test @@ -156,7 +156,7 @@ public class XPathTransformerParserTests { @Test public void expressionRef() { this.expressionRefInput.send(message); - assertThat(output.receive(0).getPayload()).isEqualTo(new Double(84)); + assertThat(output.receive(0).getPayload()).isEqualTo(84d); } diff --git a/spring-integration-xml/src/test/java/org/springframework/integration/xml/transformer/XPathTransformerTests.java b/spring-integration-xml/src/test/java/org/springframework/integration/xml/transformer/XPathTransformerTests.java index 28dca21e1d..aaff6fbe18 100644 --- a/spring-integration-xml/src/test/java/org/springframework/integration/xml/transformer/XPathTransformerTests.java +++ b/spring-integration-xml/src/test/java/org/springframework/integration/xml/transformer/XPathTransformerTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2019 the original author or authors. + * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -24,8 +24,8 @@ import java.util.List; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Source; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Node; @@ -41,6 +41,8 @@ import org.springframework.xml.xpath.XPathExpressionFactory; /** * @author Mark Fisher + * @author Artem Bilan + * * @since 2.0 */ public class XPathTransformerTests { @@ -50,21 +52,21 @@ public class XPathTransformerTests { private volatile Message message; - @Before + @BeforeEach public void createMessage() { this.message = MessageBuilder.withPayload(XML).build(); } @Test - public void stringResultTypeByDefault() throws Exception { + public void stringResultTypeByDefault() { XPathTransformer transformer = new XPathTransformer("/parent/child/@name"); Object result = transformer.doTransform(message); assertThat(result).isEqualTo("test"); } @Test - public void xpathExpressionReferenceConstructorInsteadOfString() throws Exception { + public void xpathExpressionReferenceConstructorInsteadOfString() { XPathExpression expression = XPathExpressionFactory.createXPathExpression("/parent/child/@name"); XPathTransformer transformer = new XPathTransformer(expression); Object result = transformer.doTransform(message); @@ -72,15 +74,15 @@ public class XPathTransformerTests { } @Test - public void numberResult() throws Exception { + public void numberResult() { XPathTransformer transformer = new XPathTransformer("/parent/child/@age"); transformer.setEvaluationType(XPathEvaluationType.NUMBER_RESULT); Object result = transformer.doTransform(message); - assertThat(result).isEqualTo(new Double(42)); + assertThat(result).isEqualTo(42d); } @Test - public void booleanResult() throws Exception { + public void booleanResult() { XPathTransformer transformer = new XPathTransformer("/parent/child/@married = 'true'"); transformer.setEvaluationType(XPathEvaluationType.BOOLEAN_RESULT); Object result = transformer.doTransform(message); @@ -88,7 +90,7 @@ public class XPathTransformerTests { } @Test - public void nodeResult() throws Exception { + public void nodeResult() { XPathTransformer transformer = new XPathTransformer("/parent/child"); transformer.setEvaluationType(XPathEvaluationType.NODE_RESULT); Object result = transformer.doTransform(message); @@ -102,7 +104,7 @@ public class XPathTransformerTests { @Test @SuppressWarnings("unchecked") - public void nodeListResult() throws Exception { + public void nodeListResult() { XPathTransformer transformer = new XPathTransformer("/parent/child"); transformer.setEvaluationType(XPathEvaluationType.NODE_LIST_RESULT); Message message = MessageBuilder.withPayload( @@ -120,7 +122,7 @@ public class XPathTransformerTests { } @Test - public void nodeMapper() throws Exception { + public void nodeMapper() { XPathTransformer transformer = new XPathTransformer("/parent/child/@name"); transformer.setNodeMapper(new TestNodeMapper()); Object result = transformer.doTransform(message); @@ -128,7 +130,7 @@ public class XPathTransformerTests { } @Test - public void customConverter() throws Exception { + public void customConverter() { XPathTransformer transformer = new XPathTransformer("/test/@type"); transformer.setConverter(new TestXmlPayloadConverter()); Object result = transformer.doTransform(message); @@ -146,6 +148,7 @@ public class XPathTransformerTests { public Object mapNode(Node node, int nodeNum) throws DOMException { return node.getTextContent() + "-mapped"; } + } @@ -175,6 +178,7 @@ public class XPathTransformerTests { public Document convertToDocument(Object object) { throw new UnsupportedOperationException(); } + } }