From 12fb590b95fc65e0aef7f75971cd510b9e9e000d Mon Sep 17 00:00:00 2001 From: Artem Bilan Date: Thu, 1 Sep 2016 17:23:55 -0400 Subject: [PATCH] Mainly Checkstyle Violation Fixes * Upgrade to Checkstyle `7.1` * Relax `RequireThis` rule a bit. Right now it does the effort only in case of overlapping. See https://github.com/checkstyle/checkstyle/issues/2362 for more info * Enable some annotation rules and provide fixes for violations * Enable `tabs indents` rule. This was the biggest fix in this PR * Resolve `TODO` in the `MessagingMethodInvokerHelper` and fix tests to meet `IllegalStateException` now Remain Checkstyle version `6.16.1` and reinstate `RequireThis` rule The latest Checkstyle has a bug with local scope variables if they have the same names as property. Revert some literals splitting Fix some line length exceeding and code style --- build.gradle | 5 +- .../amqp/channel/PollableAmqpChannel.java | 4 +- .../amqp/inbound/AmqpInboundGateway.java | 114 ++++----- .../aggregator/BarrierMessageHandler.java | 2 +- .../HeaderAttributeCorrelationStrategy.java | 14 +- ...eadStatePropagationChannelInterceptor.java | 2 +- .../config/EnableMessageHistory.java | 2 +- .../config/GlobalChannelInterceptor.java | 2 +- .../config/SplitterFactoryBean.java | 16 +- ...stractCorrelatingMessageHandlerParser.java | 8 +- .../integration/config/xml/ChainParser.java | 4 +- .../DefaultInboundChannelAdapterParser.java | 13 +- .../config/xml/IntegrationNamespaceUtils.java | 45 ++-- .../xml/ObjectToMapTransformerParser.java | 5 +- .../integration/endpoint/PollingConsumer.java | 2 +- ...oadableResourceBundleExpressionSource.java | 4 +- .../integration/store/SimpleMessageGroup.java | 4 +- .../store/SimpleMessageGroupFactory.java | 8 +- .../ExponentialMovingAverageRate.java | 4 +- .../support/utils/IntegrationUtils.java | 12 +- .../util/MessagingMethodInvokerHelper.java | 228 ++++++++---------- .../BarrierMessageHandlerTests.java | 4 +- .../aggregator/ConcurrentAggregatorTests.java | 6 +- ...aderAttributeCorrelationStrategyTests.java | 23 +- ...hodInvokingMessageGroupProcessorTests.java | 2 +- .../MethodInvokingReleaseStrategyTests.java | 4 +- ...dDispatcherConfigurationScenarioTests.java | 26 +- .../GlobalChannelInterceptorTests.java | 3 +- ...AggregatorWithMessageStoreParserTests.java | 79 +++--- ...tionStrategyInvalidConfigurationTests.java | 18 +- .../ReleaseStrategyFactoryBeanTests.java | 4 +- ...esequencerWithMessageStoreParserTests.java | 39 +-- .../config/TestCorrelationStrategy.java | 8 +- .../integration/config/TestTrigger.java | 10 +- ...otatedEndpointWithCorrelationStrategy.java | 37 ++- .../config/xml/BridgeParserTests.java | 11 +- .../config/xml/CronTriggerParserTests.java | 26 +- .../config/xml/HeaderEnricherParserTests.java | 39 +-- .../xml/IntervalTriggerParserTests.java | 28 +-- .../ObjectToMapTransformerParserTests.java | 79 ++++-- .../config/xml/PollerParserTests.java | 10 +- .../configuration/EnableIntegrationTests.java | 2 +- .../core/AsyncMessagingTemplateTests.java | 5 +- .../ServiceActivatorEndpointTests.java | 5 +- .../handler/BridgeHandlerTests.java | 9 +- ...vokingMessageProcessorAnnotationTests.java | 29 ++- .../MethodInvokingMessageProcessorTests.java | 2 +- .../integration/history/AnnotatedAdapter.java | 9 +- .../integration/json/JsonPathTests.java | 4 +- .../MethodInvokingMessageHandlerTests.java | 2 +- .../message/PayloadAndHeaderMappingTests.java | 4 +- .../config/PayloadTypeRouterParserTests.java | 49 ++-- .../support/MessageScenariosTests.java | 49 ++-- .../support/MutableMessageTests.java | 54 ++--- .../MessageHistoryParameterTests.java | 13 +- .../transformer/SysLogTransformerTests.java | 20 +- .../file/DefaultDirectoryScanner.java | 41 ++-- .../integration/file/FileLocker.java | 29 ++- .../file/FileWritingMessageHandler.java | 6 +- .../config/FileOutboundGatewayParser.java | 4 +- ...eTailInboundChannelAdapterFactoryBean.java | 2 +- .../file/filters/AbstractFileListFilter.java | 40 ++- .../file/filters/FileListFilter.java | 15 +- .../locking/AbstractFileLockerFilter.java | 8 +- .../file/locking/NioFileLocker.java | 83 ++++--- .../file/remote/RemoteFileTemplate.java | 18 +- .../AbstractRemoteFileOutboundGateway.java | 71 +++--- .../AbstractFilePayloadTransformer.java | 20 +- ...eReadingMessageSourceIntegrationTests.java | 10 +- ...ourcePersistentFilterIntegrationTests.java | 6 +- .../AutoCreateDirectoryIntegrationTests.java | 161 +++++++------ .../file/config/CustomFileNameGenerator.java | 12 +- ...dChannelAdapterWithPatternParserTests.java | 138 +++++------ .../file/config/FileMessageHistoryTests.java | 18 +- .../FileToStringTransformerParserTests.java | 28 +-- .../file/locking/NioFileLockerTests.java | 41 ++-- .../RemoteFileOutboundGatewayTests.java | 39 +-- .../session/AbstractFtpSessionFactory.java | 6 +- .../session/DefaultFtpsSessionFactory.java | 4 +- .../integration/ftp/session/FtpSession.java | 6 +- ...GroovyScriptExecutingMessageProcessor.java | 2 +- ...gMessagingGatewayWithPathMappingTests.java | 59 ++--- ...Int2312RequestMappingIntegrationTests.java | 20 +- ...tpHeaderMapperFromMessageInboundTests.java | 98 ++++---- .../ip/config/IpAdapterParserUtils.java | 7 +- .../connection/AbstractConnectionFactory.java | 21 +- .../tcp/connection/TcpConnectionSupport.java | 2 +- .../ip/tcp/connection/TcpNetConnection.java | 25 +- .../ip/tcp/connection/TcpNioConnection.java | 34 +-- .../ByteArrayLengthHeaderSerializer.java | 83 +++---- .../ip/udp/UnicastSendingMessageHandler.java | 28 ++- .../ip/config/ParserUnitTests.java | 32 +-- .../tcp/InterceptedSharedConnectionTests.java | 2 +- .../ip/tcp/SharedConnectionTests.java | 2 +- .../ip/tcp/TcpConfigInboundGatewayTests.java | 48 ++-- .../ip/tcp/TcpConfigOutboundGatewayTests.java | 18 +- .../ip/tcp/TcpOutboundGatewayTests.java | 6 +- .../tcp/connection/HelloWorldInterceptor.java | 4 +- .../connection/TcpNioConnectionReadTests.java | 15 +- .../tcp/connection/TcpNioConnectionTests.java | 20 +- .../tcp/serializer/DeserializationTests.java | 24 +- .../udp/DatagramPacketMessageMapperTests.java | 4 +- .../DatagramPacketSendingHandlerTests.java | 2 +- .../integration/jdbc/StoredProcExecutor.java | 22 +- .../jdbc/StoredProcOutboundGateway.java | 2 +- .../jdbc/StoredProcPollingChannelAdapter.java | 2 +- .../jdbc/StoredProcExecutorTests.java | 25 +- ...ewayWithSpringContextIntegrationTests.java | 76 +++--- .../jdbc/config/JdbcTypesEnumTests.java | 5 +- .../StoredProcOutboundGatewayParserTests.java | 42 ++-- .../storedproc/ProcedureParameterTests.java | 4 +- .../jdbc/storedproc/derby/DerbyFunctions.java | 4 +- .../jms/JmsMessageDrivenEndpoint.java | 2 +- .../integration/jms/JmsOutboundGateway.java | 12 +- .../jms/DefaultJmsHeaderMapperTests.java | 123 ++++++---- .../jms/config/ActiveMqTestUtils.java | 6 +- .../jms/config/JmsChannelHistoryTests.java | 3 +- .../NotificationListeningMessageProducer.java | 4 +- .../jpa/config/xml/JpaParserUtils.java | 21 +- .../jpa/core/AbstractJpaOperations.java | 8 +- .../integration/jpa/core/JpaExecutor.java | 45 ++-- .../jpa/inbound/JpaPollingChannelAdapter.java | 4 +- .../jpa/core/AbstractJpaOperationsTests.java | 38 +-- .../integration/mail/MailTransportUtils.java | 172 ++++++------- .../integration/mail/Pop3MailReceiver.java | 2 +- .../mail/ImapMailReceiverTests.java | 69 ++++-- ...MailSendingMessageHandlerContextTests.java | 4 +- .../mail/Pop3MailReceiverTests.java | 99 +++----- .../integration/mail/StubJavaMailSender.java | 2 +- .../mongodb/store/MongoDbMessageStore.java | 6 +- ...AbstractMongoDbMessageGroupStoreTests.java | 2 +- .../xml/MqttOutboundChannelAdapterParser.java | 2 +- .../inbound/RedisStoreMessageSource.java | 7 +- .../redis/util/RedisLockRegistry.java | 20 +- .../RedisQueueMessageDrivenEndpointTests.java | 18 +- .../config/AbstractScriptParser.java | 3 +- .../jsr223/PythonScriptExecutorTests.java | 22 +- .../ChannelSecurityMetadataSource.java | 14 +- ...yContextPropagationChannelInterceptor.java | 2 +- .../session/DefaultSftpSessionFactory.java | 2 +- .../stomp/AbstractStompSessionManager.java | 2 +- .../stomp/outbound/StompMessageHandler.java | 2 +- ...ssageHandlerWebSocketIntegrationTests.java | 2 +- ...soleOutboundChannelAdapterParserTests.java | 2 +- ...logReceivingChannelAdapterFactoryBean.java | 8 +- .../test/matcher/TypeSafeMatcher.java | 84 +++---- .../support/AbstractResponseValidator.java | 37 +-- .../test/support/MessageValidator.java | 23 +- .../test/support/PayloadValidator.java | 10 +- .../test/support/RequestResponseScenario.java | 204 ++++++++-------- .../inbound/AbstractTwitterMessageSource.java | 2 +- .../TimelineReceivingMessageSource.java | 2 +- .../ignored/TestSendingDMsUsingNamespace.java | 5 +- ...ectMessageReceivingMessageSourceTests.java | 11 +- .../SearchReceivingMessageSourceTests.java | 11 +- .../TimelineReceivingMessageSourceTests.java | 11 +- ...rectMessageSendingMessageHandlerTests.java | 11 +- .../StatusUpdatingMessageHandlerTests.java | 11 +- .../client/StompIntegrationTests.java | 6 +- .../ws/DefaultSoapHeaderMapper.java | 6 +- .../WebServiceInboundGatewayParser.java | 11 +- .../ws/config/StubMessageFactory.java | 14 +- .../config/StubWebServiceMessageCallback.java | 4 +- .../WebServiceInboundGatewayParserTests.java | 2 +- ...eOutboundGatewayWithHeaderMapperTests.java | 47 ++-- .../xml/DefaultXmlPayloadConverterTests.java | 8 +- .../TestXmlApplicationContextHelper.java | 4 +- .../config/XPathExpressionParserTests.java | 31 ++- .../XPathMessageSplitterParserTests.java | 6 +- .../XmlValidatingMessageSelectorTests.java | 2 +- .../transformer/CustomTestResultFactory.java | 45 ++-- src/checkstyle/checkstyle.xml | 33 ++- 172 files changed, 2116 insertions(+), 2007 deletions(-) diff --git a/build.gradle b/build.gradle index 1f5a223a96..524d04e22c 100644 --- a/build.gradle +++ b/build.gradle @@ -151,7 +151,7 @@ subprojects { subproject -> } jacoco { - toolVersion = "0.7.2.201409121644" + toolVersion = "0.7.7.201606060606" } // dependencies that are common across all java projects @@ -229,7 +229,7 @@ subprojects { subproject -> } checkstyle { - configFile = file("${rootDir}/src/checkstyle/checkstyle.xml") + configFile = file("$rootDir/src/checkstyle/checkstyle.xml") toolVersion = "6.16.1" } @@ -355,6 +355,7 @@ project('spring-integration-gemfire') { exclude group: 'org.springframework', module: 'spring-context-support' exclude group: 'org.springframework', module: 'spring-core' exclude group: 'org.springframework', module: 'spring-tx' + exclude group: 'org.springframework', module: 'spring-oxm' } compile "commons-io:commons-io:$commonsIoVersion" testCompile project(":spring-integration-stream") diff --git a/spring-integration-amqp/src/main/java/org/springframework/integration/amqp/channel/PollableAmqpChannel.java b/spring-integration-amqp/src/main/java/org/springframework/integration/amqp/channel/PollableAmqpChannel.java index 1324bd7e2e..f655f34f7d 100644 --- a/spring-integration-amqp/src/main/java/org/springframework/integration/amqp/channel/PollableAmqpChannel.java +++ b/spring-integration-amqp/src/main/java/org/springframework/integration/amqp/channel/PollableAmqpChannel.java @@ -143,7 +143,7 @@ public class PollableAmqpChannel extends AbstractAmqpChannel } Assert.notNull(this.amqpAdmin, "If no queueName is configured explicitly, an AmqpAdmin instance must be provided, " + - "or the AmqpTemplate must be a RabbitTemplate since the Queue needs to be declared."); + "or the AmqpTemplate must be a RabbitTemplate since the Queue needs to be declared."); this.queueName = this.channelName; this.amqpAdmin.declareQueue(new Queue(this.queueName)); } @@ -163,7 +163,7 @@ public class PollableAmqpChannel extends AbstractAmqpChannel interceptorStack = new ArrayDeque(); if (!interceptorList.preReceive(this, interceptorStack)) { - return null; + return null; } } Object object = doReceive(); diff --git a/spring-integration-amqp/src/main/java/org/springframework/integration/amqp/inbound/AmqpInboundGateway.java b/spring-integration-amqp/src/main/java/org/springframework/integration/amqp/inbound/AmqpInboundGateway.java index d755f757a1..043bf1c615 100644 --- a/spring-integration-amqp/src/main/java/org/springframework/integration/amqp/inbound/AmqpInboundGateway.java +++ b/spring-integration-amqp/src/main/java/org/springframework/integration/amqp/inbound/AmqpInboundGateway.java @@ -18,7 +18,6 @@ package org.springframework.integration.amqp.inbound; import java.util.Map; -import org.springframework.amqp.AmqpException; import org.springframework.amqp.core.AcknowledgeMode; import org.springframework.amqp.core.Address; import org.springframework.amqp.core.AmqpTemplate; @@ -37,8 +36,6 @@ import org.springframework.integration.gateway.MessagingGatewaySupport; import org.springframework.util.Assert; import org.springframework.util.StringUtils; -import com.rabbitmq.client.Channel; - /** * Adapter that receives Messages from an AMQP Queue, converts them into * Spring Integration Messages, and sends the results to a Message Channel. @@ -79,7 +76,7 @@ public class AmqpInboundGateway extends MessagingGatewaySupport { } private AmqpInboundGateway(AbstractMessageListenerContainer listenerContainer, AmqpTemplate amqpTemplate, - boolean amqpTemplateExplicitlySet) { + boolean amqpTemplateExplicitlySet) { Assert.notNull(listenerContainer, "listenerContainer must not be null"); Assert.notNull(amqpTemplate, "'amqpTemplate' must not be null"); Assert.isNull(listenerContainer.getMessageListener(), @@ -139,71 +136,62 @@ public class AmqpInboundGateway extends MessagingGatewaySupport { @Override protected void onInit() throws Exception { - this.messageListenerContainer.setMessageListener(new ChannelAwareMessageListener() { - @Override - public void onMessage(Message message, Channel channel) { - Object payload = AmqpInboundGateway.this.amqpMessageConverter.fromMessage(message); - Map headers = - AmqpInboundGateway.this.headerMapper.toHeadersFromRequest(message.getMessageProperties()); - if (AmqpInboundGateway.this.messageListenerContainer.getAcknowledgeMode() == AcknowledgeMode.MANUAL) { - headers.put(AmqpHeaders.DELIVERY_TAG, message.getMessageProperties().getDeliveryTag()); - headers.put(AmqpHeaders.CHANNEL, channel); + this.messageListenerContainer.setMessageListener((ChannelAwareMessageListener) (message, channel) -> { + Object payload = this.amqpMessageConverter.fromMessage(message); + Map headers = + this.headerMapper.toHeadersFromRequest(message.getMessageProperties()); + if (this.messageListenerContainer.getAcknowledgeMode() == AcknowledgeMode.MANUAL) { + headers.put(AmqpHeaders.DELIVERY_TAG, message.getMessageProperties().getDeliveryTag()); + headers.put(AmqpHeaders.CHANNEL, channel); + } + org.springframework.messaging.Message request = getMessageBuilderFactory() + .withPayload(payload) + .copyHeaders(headers) + .build(); + final org.springframework.messaging.Message reply = sendAndReceiveMessage(request); + if (reply != null) { + Address replyTo; + String replyToProperty = message.getMessageProperties().getReplyTo(); + if (replyToProperty != null) { + replyTo = new Address(replyToProperty); } - org.springframework.messaging.Message request = - getMessageBuilderFactory().withPayload(payload).copyHeaders(headers).build(); - final org.springframework.messaging.Message reply = sendAndReceiveMessage(request); - if (reply != null) { - Address replyTo; - String replyToProperty = message.getMessageProperties().getReplyTo(); - if (replyToProperty != null) { - replyTo = new Address(replyToProperty); + else { + replyTo = AmqpInboundGateway.this.defaultReplyTo; + } + + MessagePostProcessor messagePostProcessor = message1 -> { + MessageProperties messageProperties = message1.getMessageProperties(); + String contentEncoding = messageProperties.getContentEncoding(); + long contentLength = messageProperties.getContentLength(); + String contentType = messageProperties.getContentType(); + this.headerMapper.fromHeadersToReply(reply.getHeaders(), messageProperties); + // clear the replyTo from the original message since we are using it now + messageProperties.setReplyTo(null); + // reset the content-* properties as determined by the MessageConverter + if (StringUtils.hasText(contentEncoding)) { + messageProperties.setContentEncoding(contentEncoding); + } + messageProperties.setContentLength(contentLength); + if (contentType != null) { + messageProperties.setContentType(contentType); + } + return message1; + }; + + if (replyTo != null) { + this.amqpTemplate.convertAndSend(replyTo.getExchangeName(), + replyTo.getRoutingKey(), reply.getPayload(), messagePostProcessor); + } + else { + if (!this.amqpTemplateExplicitlySet) { + throw new IllegalStateException("There is no 'replyTo' message property " + + "and the `defaultReplyTo` hasn't been configured."); } else { - replyTo = AmqpInboundGateway.this.defaultReplyTo; - } - - MessagePostProcessor messagePostProcessor = new MessagePostProcessor() { - - @Override - public Message postProcessMessage(Message message) throws AmqpException { - MessageProperties messageProperties = message.getMessageProperties(); - String contentEncoding = messageProperties.getContentEncoding(); - long contentLength = messageProperties.getContentLength(); - String contentType = messageProperties.getContentType(); - AmqpInboundGateway.this.headerMapper.fromHeadersToReply(reply.getHeaders(), - messageProperties); - // clear the replyTo from the original message since we are using it now - messageProperties.setReplyTo(null); - // reset the content-* properties as determined by the MessageConverter - if (StringUtils.hasText(contentEncoding)) { - messageProperties.setContentEncoding(contentEncoding); - } - messageProperties.setContentLength(contentLength); - if (contentType != null) { - messageProperties.setContentType(contentType); - } - return message; - } - - }; - - if (replyTo != null) { - AmqpInboundGateway.this.amqpTemplate.convertAndSend(replyTo.getExchangeName(), - replyTo.getRoutingKey(), reply.getPayload(), messagePostProcessor); - } - else { - if (!AmqpInboundGateway.this.amqpTemplateExplicitlySet) { - throw new IllegalStateException("There is no 'replyTo' message property " + - "and the `defaultReplyTo` hasn't been configured."); - } - else { - AmqpInboundGateway.this.amqpTemplate.convertAndSend(reply.getPayload(), - messagePostProcessor); - } + this.amqpTemplate.convertAndSend(reply.getPayload(), messagePostProcessor); } } } - }); this.messageListenerContainer.afterPropertiesSet(); if (!this.amqpTemplateExplicitlySet) { diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/BarrierMessageHandler.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/BarrierMessageHandler.java index 96d5464886..3065c34ac2 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/BarrierMessageHandler.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/BarrierMessageHandler.java @@ -98,7 +98,7 @@ public class BarrierMessageHandler extends AbstractReplyProducingMessageHandler * @param correlationStrategy the correlation strategy. */ public BarrierMessageHandler(long timeout, MessageGroupProcessor outputProcessor, - CorrelationStrategy correlationStrategy) { + CorrelationStrategy correlationStrategy) { Assert.notNull(outputProcessor, "'messageGroupProcessor' cannot be null"); Assert.notNull(correlationStrategy, "'correlationStrategy' cannot be null"); this.messageGroupProcessor = outputProcessor; diff --git a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategy.java b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategy.java index 1110944707..ae14ab25ba 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategy.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategy.java @@ -26,16 +26,16 @@ import org.springframework.messaging.Message; */ public class HeaderAttributeCorrelationStrategy implements CorrelationStrategy { - private String attributeName; + private String attributeName; - public HeaderAttributeCorrelationStrategy(String attributeName) { - this.attributeName = attributeName; - } + public HeaderAttributeCorrelationStrategy(String attributeName) { + this.attributeName = attributeName; + } - public Object getCorrelationKey(Message message) { - return message.getHeaders().get(this.attributeName); - } + public Object getCorrelationKey(Message message) { + return message.getHeaders().get(this.attributeName); + } } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/channel/interceptor/ThreadStatePropagationChannelInterceptor.java b/spring-integration-core/src/main/java/org/springframework/integration/channel/interceptor/ThreadStatePropagationChannelInterceptor.java index ebfa6e1780..5e7212b6c7 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/channel/interceptor/ThreadStatePropagationChannelInterceptor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/channel/interceptor/ThreadStatePropagationChannelInterceptor.java @@ -83,7 +83,7 @@ public abstract class ThreadStatePropagationChannelInterceptor @Override public void afterMessageHandled(Message message, MessageChannel channel, MessageHandler handler, - Exception ex) { + Exception ex) { // No-op } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/config/EnableMessageHistory.java b/spring-integration-core/src/main/java/org/springframework/integration/config/EnableMessageHistory.java index f922946a96..41fe6036d0 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/config/EnableMessageHistory.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/config/EnableMessageHistory.java @@ -36,6 +36,6 @@ import org.springframework.context.annotation.Import; @Import(MessageHistoryRegistrar.class) public @interface EnableMessageHistory { - String[] value() default "*"; + String[] value() default "*"; } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/config/GlobalChannelInterceptor.java b/spring-integration-core/src/main/java/org/springframework/integration/config/GlobalChannelInterceptor.java index 323a8c0cf4..47340fc76d 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/config/GlobalChannelInterceptor.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/config/GlobalChannelInterceptor.java @@ -35,7 +35,7 @@ import java.lang.annotation.Target; * @author Artem Bilan * @since 4.0 */ -@Target({ElementType.TYPE, ElementType.METHOD}) +@Target({ ElementType.TYPE, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface GlobalChannelInterceptor { diff --git a/spring-integration-core/src/main/java/org/springframework/integration/config/SplitterFactoryBean.java b/spring-integration-core/src/main/java/org/springframework/integration/config/SplitterFactoryBean.java index 8d6bd7176b..5fb5856ec6 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/config/SplitterFactoryBean.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/config/SplitterFactoryBean.java @@ -76,8 +76,9 @@ public class SplitterFactoryBean extends AbstractStandardMessageHandlerFactoryBe this.configureSplitter(splitter); } else { - Assert.isTrue(!StringUtils.hasText(targetMethodName), "target method should not be provided when the target " - + "object is an implementation of AbstractMessageSplitter"); + Assert.isTrue(!StringUtils.hasText(targetMethodName), + "target method should not be provided when the target " + + "object is an implementation of AbstractMessageSplitter"); this.configureSplitter(splitter); if (targetObject instanceof MessageHandler) { return (MessageHandler) targetObject; @@ -123,9 +124,9 @@ public class SplitterFactoryBean extends AbstractStandardMessageHandlerFactoryBe ((AbstractReplyProducingMessageHandler) handler).setRequiresReply(this.requiresReply); } else if (this.requiresReply && logger.isDebugEnabled()) { - logger.debug("requires-reply can only be set to AbstractReplyProducingMessageHandler or its subclass, " - + handler.getComponentName() + " doesn't support it."); - } + logger.debug("requires-reply can only be set to AbstractReplyProducingMessageHandler or its subclass, " + + handler.getComponentName() + " doesn't support it."); + } } if (!(handler instanceof AbstractMessageSplitter)) { Assert.isNull(this.applySequence, "Cannot set applySequence if the referenced bean is " @@ -136,8 +137,9 @@ public class SplitterFactoryBean extends AbstractStandardMessageHandlerFactoryBe else { AbstractMessageSplitter splitter = (AbstractMessageSplitter) handler; if (this.delimiters != null) { - Assert.isTrue(splitter instanceof DefaultMessageSplitter, "The 'delimiters' property is only available" + - " for a Splitter definition where no 'ref', 'expression', or inner bean has been provided."); + Assert.isInstanceOf(DefaultMessageSplitter.class, splitter, + "The 'delimiters' property is only available for a Splitter definition where no 'ref', " + + "'expression', or inner bean has been provided."); ((DefaultMessageSplitter) splitter).setDelimiters(this.delimiters); } if (this.applySequence != null) { diff --git a/spring-integration-core/src/main/java/org/springframework/integration/config/xml/AbstractCorrelatingMessageHandlerParser.java b/spring-integration-core/src/main/java/org/springframework/integration/config/xml/AbstractCorrelatingMessageHandlerParser.java index f55818392d..babeeb42d0 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/config/xml/AbstractCorrelatingMessageHandlerParser.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/config/xml/AbstractCorrelatingMessageHandlerParser.java @@ -64,11 +64,13 @@ public abstract class AbstractCorrelatingMessageHandlerParser extends AbstractCo private static final String EXPIRE_GROUPS_UPON_TIMEOUT = "expire-groups-upon-timeout"; protected void doParse(BeanDefinitionBuilder builder, Element element, BeanMetadataElement processor, - ParserContext parserContext) { - IntegrationNamespaceUtils.injectPropertyWithAdapter(CORRELATION_STRATEGY_REF_ATTRIBUTE, CORRELATION_STRATEGY_METHOD_ATTRIBUTE, + ParserContext parserContext) { + IntegrationNamespaceUtils.injectPropertyWithAdapter(CORRELATION_STRATEGY_REF_ATTRIBUTE, + CORRELATION_STRATEGY_METHOD_ATTRIBUTE, CORRELATION_STRATEGY_EXPRESSION_ATTRIBUTE, CORRELATION_STRATEGY_PROPERTY, "CorrelationStrategy", element, builder, processor, parserContext); - IntegrationNamespaceUtils.injectPropertyWithAdapter(RELEASE_STRATEGY_REF_ATTRIBUTE, RELEASE_STRATEGY_METHOD_ATTRIBUTE, + IntegrationNamespaceUtils.injectPropertyWithAdapter(RELEASE_STRATEGY_REF_ATTRIBUTE, + RELEASE_STRATEGY_METHOD_ATTRIBUTE, RELEASE_STRATEGY_EXPRESSION_ATTRIBUTE, RELEASE_STRATEGY_PROPERTY, "ReleaseStrategy", element, builder, processor, parserContext); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/config/xml/ChainParser.java b/spring-integration-core/src/main/java/org/springframework/integration/config/xml/ChainParser.java index df057294f3..21c128a723 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/config/xml/ChainParser.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/config/xml/ChainParser.java @@ -85,7 +85,7 @@ public class ChainParser extends AbstractConsumerEndpointParser { String handlerBeanName = ((RuntimeBeanReference) childBeanMetadata).getBeanName(); if (!handlerBeanNameSet.add(handlerBeanName)) { parserContext.getReaderContext().error("A bean definition is already registered for " + - "beanName: '" + handlerBeanName + "' within the current .", + "beanName: '" + handlerBeanName + "' within the current .", element); return null; } @@ -121,7 +121,7 @@ public class ChainParser extends AbstractConsumerEndpointParser { } private BeanMetadataElement parseChild(String chainHandlerId, Element element, int order, ParserContext parserContext, - BeanDefinition parentDefinition) { + BeanDefinition parentDefinition) { BeanDefinitionHolder holder = null; diff --git a/spring-integration-core/src/main/java/org/springframework/integration/config/xml/DefaultInboundChannelAdapterParser.java b/spring-integration-core/src/main/java/org/springframework/integration/config/xml/DefaultInboundChannelAdapterParser.java index 3d719c3fef..8255970d18 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/config/xml/DefaultInboundChannelAdapterParser.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/config/xml/DefaultInboundChannelAdapterParser.java @@ -50,14 +50,15 @@ public class DefaultInboundChannelAdapterParser extends AbstractPollingInboundCh protected BeanMetadataElement parseSource(Element element, ParserContext parserContext) { Object source = parserContext.extractSource(element); BeanMetadataElement result = null; - BeanComponentDefinition innnerBeanDef = IntegrationNamespaceUtils.parseInnerHandlerDefinition(element, parserContext); + BeanComponentDefinition innerBeanDef = + IntegrationNamespaceUtils.parseInnerHandlerDefinition(element, parserContext); String sourceRef = element.getAttribute(IntegrationNamespaceUtils.REF_ATTRIBUTE); String methodName = element.getAttribute(IntegrationNamespaceUtils.METHOD_ATTRIBUTE); String expressionString = element.getAttribute(IntegrationNamespaceUtils.EXPRESSION_ATTRIBUTE); Element scriptElement = DomUtils.getChildElementByTagName(element, "script"); Element expressionElement = DomUtils.getChildElementByTagName(element, "expression"); - boolean hasInnerDef = innnerBeanDef != null; + boolean hasInnerDef = innerBeanDef != null; boolean hasRef = StringUtils.hasText(sourceRef); boolean hasExpression = StringUtils.hasText(expressionString); boolean hasScriptElement = scriptElement != null; @@ -77,10 +78,10 @@ public class DefaultInboundChannelAdapterParser extends AbstractPollingInboundCh return null; } if (hasMethod) { - result = this.parseMethodInvokingSource(innnerBeanDef, methodName, element, parserContext); + result = this.parseMethodInvokingSource(innerBeanDef, methodName, element, parserContext); } else { - result = innnerBeanDef.getBeanDefinition(); + result = innerBeanDef.getBeanDefinition(); } } else if (hasScriptElement) { @@ -124,7 +125,7 @@ public class DefaultInboundChannelAdapterParser extends AbstractPollingInboundCh } private BeanMetadataElement parseMethodInvokingSource(BeanMetadataElement targetObject, String methodName, Element element, - ParserContext parserContext) { + ParserContext parserContext) { BeanDefinitionBuilder sourceBuilder = BeanDefinitionBuilder.genericBeanDefinition(MethodInvokingMessageSource.class); sourceBuilder.addPropertyValue("object", targetObject); sourceBuilder.addPropertyValue("methodName", methodName); @@ -133,7 +134,7 @@ public class DefaultInboundChannelAdapterParser extends AbstractPollingInboundCh } private BeanMetadataElement parseExpression(String expressionString, Element expressionElement, Element element, - ParserContext parserContext) { + ParserContext parserContext) { BeanDefinitionBuilder sourceBuilder = BeanDefinitionBuilder.genericBeanDefinition(ExpressionEvaluatingMessageSource.class); BeanDefinition expressionDef = null; diff --git a/spring-integration-core/src/main/java/org/springframework/integration/config/xml/IntegrationNamespaceUtils.java b/spring-integration-core/src/main/java/org/springframework/integration/config/xml/IntegrationNamespaceUtils.java index 46b756b5b0..1eb167d7b3 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/config/xml/IntegrationNamespaceUtils.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/config/xml/IntegrationNamespaceUtils.java @@ -70,12 +70,19 @@ import org.springframework.util.xml.DomUtils; public abstract class IntegrationNamespaceUtils { public static final String REF_ATTRIBUTE = "ref"; + public static final String METHOD_ATTRIBUTE = "method"; + public static final String ORDER = "order"; + public static final String EXPRESSION_ATTRIBUTE = "expression"; + public static final String REQUEST_HANDLER_ADVICE_CHAIN = "request-handler-advice-chain"; + public static final String AUTO_STARTUP = "auto-startup"; + public static final String PHASE = "phase"; + public static final String ROLE = "role"; /** @@ -277,7 +284,7 @@ public abstract class IntegrationNamespaceUtils { * @return the text from the attribute or element or null */ public static String getTextFromAttributeOrNestedElement(Element element, String name, - ParserContext parserContext) { + ParserContext parserContext) { String attr = element.getAttribute(name); Element childElement = DomUtils.getChildElementByTagName(element, name); if (StringUtils.hasText(attr) && childElement != null) { @@ -306,9 +313,10 @@ public abstract class IntegrationNamespaceUtils { String ref = element.getAttribute(REF_ATTRIBUTE); if (StringUtils.hasText(ref) && innerComponentDefinition != null) { parserContext.getReaderContext().error( - "Ambiguous definition. Inner bean " + (innerComponentDefinition.getBeanDefinition().getBeanClassName()) - + " declaration and \"ref\" " + ref + " are not allowed together on element " + - IntegrationNamespaceUtils.createElementDescription(element) + ".", + "Ambiguous definition. Inner bean " + + (innerComponentDefinition.getBeanDefinition().getBeanClassName()) + + " declaration and \"ref\" " + ref + " are not allowed together on element " + + IntegrationNamespaceUtils.createElementDescription(element) + ".", parserContext.extractSource(element)); } return innerComponentDefinition; @@ -324,7 +332,7 @@ public abstract class IntegrationNamespaceUtils { * @param replyHeaderValue The reply header value. */ public static void configureHeaderMapper(Element element, BeanDefinitionBuilder rootBuilder, - ParserContext parserContext, Class headerMapperClass, String replyHeaderValue) { + ParserContext parserContext, Class headerMapperClass, String replyHeaderValue) { configureHeaderMapper(element, rootBuilder, parserContext, BeanDefinitionBuilder.genericBeanDefinition(headerMapperClass), replyHeaderValue); } @@ -339,7 +347,7 @@ public abstract class IntegrationNamespaceUtils { * @param replyHeaderValue The reply header value. */ public static void configureHeaderMapper(Element element, BeanDefinitionBuilder rootBuilder, - ParserContext parserContext, BeanDefinitionBuilder headerMapperBuilder, String replyHeaderValue) { + ParserContext parserContext, BeanDefinitionBuilder headerMapperBuilder, String replyHeaderValue) { String defaultMappedReplyHeadersAttributeName = "mapped-reply-headers"; if (!StringUtils.hasText(replyHeaderValue)) { replyHeaderValue = defaultMappedReplyHeadersAttributeName; @@ -368,6 +376,7 @@ public abstract class IntegrationNamespaceUtils { rootBuilder.addPropertyValue("headerMapper", headerMapperBuilder.getBeanDefinition()); } } + /** * Parse a "transactional" element and configure a {@link TransactionInterceptor} * with "transactionManager" and other "transactionDefinition" properties. @@ -380,9 +389,11 @@ public abstract class IntegrationNamespaceUtils { */ public static BeanDefinition configureTransactionAttributes(Element txElement) { BeanDefinition txDefinition = configureTransactionDefinition(txElement); - BeanDefinitionBuilder attributeSourceBuilder = BeanDefinitionBuilder.genericBeanDefinition(MatchAlwaysTransactionAttributeSource.class); + BeanDefinitionBuilder attributeSourceBuilder = + BeanDefinitionBuilder.genericBeanDefinition(MatchAlwaysTransactionAttributeSource.class); attributeSourceBuilder.addPropertyValue("transactionAttribute", txDefinition); - BeanDefinitionBuilder txInterceptorBuilder = BeanDefinitionBuilder.genericBeanDefinition(TransactionInterceptor.class); + BeanDefinitionBuilder txInterceptorBuilder = + BeanDefinitionBuilder.genericBeanDefinition(TransactionInterceptor.class); txInterceptorBuilder.addPropertyReference("transactionManager", txElement.getAttribute("transaction-manager")); txInterceptorBuilder.addPropertyValue("transactionAttributeSource", attributeSourceBuilder.getBeanDefinition()); return txInterceptorBuilder.getBeanDefinition(); @@ -408,20 +419,22 @@ public abstract class IntegrationNamespaceUtils { String[] handlerAlias = null; String id = element.getAttribute(AbstractBeanDefinitionParser.ID_ATTRIBUTE); if (StringUtils.hasText(id)) { - handlerAlias = new String[] {id + IntegrationConfigUtils.HANDLER_ALIAS_SUFFIX}; + handlerAlias = new String[] { id + IntegrationConfigUtils.HANDLER_ALIAS_SUFFIX }; } return handlerAlias; } public static void configureAndSetAdviceChainIfPresent(Element adviceChainElement, Element txElement, BeanDefinition parentBeanDefinition, ParserContext parserContext) { - configureAndSetAdviceChainIfPresent(adviceChainElement, txElement, parentBeanDefinition, parserContext, "adviceChain"); + configureAndSetAdviceChainIfPresent(adviceChainElement, txElement, parentBeanDefinition, parserContext, + "adviceChain"); } @SuppressWarnings({ "rawtypes" }) public static void configureAndSetAdviceChainIfPresent(Element adviceChainElement, Element txElement, BeanDefinition parentBeanDefinition, ParserContext parserContext, String propertyName) { - ManagedList adviceChain = configureAdviceChain(adviceChainElement, txElement, parentBeanDefinition, parserContext); + ManagedList adviceChain = configureAdviceChain(adviceChainElement, txElement, parentBeanDefinition, + parserContext); if (adviceChain != null) { parentBeanDefinition.getPropertyValues().add(propertyName, adviceChain); } @@ -483,14 +496,14 @@ public abstract class IntegrationNamespaceUtils { if (hasAttributeValue && hasAttributeExpression) { parserContext.getReaderContext().error("Only one of '" + valueElementName + "' or '" - + expressionElementName + "' is allowed", element); + + expressionElementName + "' is allowed", element); } if (oneRequired && (!hasAttributeValue && !hasAttributeExpression)) { parserContext.getReaderContext().error("One of '" + valueElementName + "' or '" + expressionElementName + "' is required", element); } - BeanDefinition expressionDef = null; + BeanDefinition expressionDef; if (hasAttributeValue) { expressionDef = new RootBeanDefinition(LiteralExpression.class); expressionDef.getConstructorArgumentValues().addGenericArgumentValue(valueElementValue); @@ -540,8 +553,8 @@ public abstract class IntegrationNamespaceUtils { constructorArgumentValues.addGenericArgumentValue(new RuntimeBeanReference(handlerBeanName)); } else { - parserContext.getReaderContext().error("Only one subscriber is allowed for a FixedSubscriberChannel.", - element); + parserContext.getReaderContext() + .error("Only one subscriber is allowed for a FixedSubscriberChannel.", element); } } } @@ -634,7 +647,7 @@ public abstract class IntegrationNamespaceUtils { } private static BeanMetadataElement createAdapter(BeanMetadataElement ref, String method, - String unqualifiedClassName) { + String unqualifiedClassName) { BeanDefinitionBuilder builder = BeanDefinitionBuilder .genericBeanDefinition(IntegrationConfigUtils.BASE_PACKAGE + ".config." + unqualifiedClassName + "FactoryBean"); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/config/xml/ObjectToMapTransformerParser.java b/spring-integration-core/src/main/java/org/springframework/integration/config/xml/ObjectToMapTransformerParser.java index 5a372a04b4..bd2dc3d8ac 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/config/xml/ObjectToMapTransformerParser.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/config/xml/ObjectToMapTransformerParser.java @@ -16,10 +16,11 @@ package org.springframework.integration.config.xml; +import org.w3c.dom.Element; + import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.integration.transformer.ObjectToMapTransformer; -import org.w3c.dom.Element; /** * @author Oleg Zhurakousky @@ -35,6 +36,6 @@ public class ObjectToMapTransformerParser extends AbstractTransformerParser { @Override protected void parseTransformer(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { - IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "flatten", "shouldFlattenKeys"); + IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "flatten", "shouldFlattenKeys"); } } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/endpoint/PollingConsumer.java b/spring-integration-core/src/main/java/org/springframework/integration/endpoint/PollingConsumer.java index 1f7ce78595..b72855f9d2 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/endpoint/PollingConsumer.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/endpoint/PollingConsumer.java @@ -173,7 +173,7 @@ public class PollingConsumer extends AbstractPollingEndpoint implements Integrat } private void triggerAfterMessageHandled(Message message, Exception ex, - Deque interceptorStack) { + Deque interceptorStack) { Iterator iterator = interceptorStack.descendingIterator(); while (iterator.hasNext()) { ExecutorChannelInterceptor interceptor = iterator.next(); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/expression/ReloadableResourceBundleExpressionSource.java b/spring-integration-core/src/main/java/org/springframework/integration/expression/ReloadableResourceBundleExpressionSource.java index 574e3c9ce7..03ac013c8e 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/expression/ReloadableResourceBundleExpressionSource.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/expression/ReloadableResourceBundleExpressionSource.java @@ -111,7 +111,7 @@ public class ReloadableResourceBundleExpressionSource implements ExpressionSourc * @see java.util.ResourceBundle */ public void setBasename(String basename) { - setBasenames(new String[] {basename}); + setBasenames(new String[] { basename }); } /** @@ -393,7 +393,7 @@ public class ReloadableResourceBundleExpressionSource implements ExpressionSourc PropertiesHolder propHolder = this.cachedProperties.get(filename); if (propHolder != null && (propHolder.getRefreshTimestamp() < 0 || - propHolder.getRefreshTimestamp() > System.currentTimeMillis() - this.cacheMillis)) { + propHolder.getRefreshTimestamp() > System.currentTimeMillis() - this.cacheMillis)) { return propHolder; } return refreshProperties(filename, propHolder); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/store/SimpleMessageGroup.java b/spring-integration-core/src/main/java/org/springframework/integration/store/SimpleMessageGroup.java index 7d86ad941b..29ca08f94e 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/store/SimpleMessageGroup.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/store/SimpleMessageGroup.java @@ -66,12 +66,12 @@ public class SimpleMessageGroup implements MessageGroup { } public SimpleMessageGroup(Collection> messages, Object groupId, long timestamp, - boolean complete) { + boolean complete) { this(new LinkedHashSet>(), messages, groupId, timestamp, complete); } SimpleMessageGroup(Collection> internalStore, Collection> messages, Object groupId, - long timestamp, boolean complete) { + long timestamp, boolean complete) { Assert.notNull(internalStore, "'internalStore' must not be null"); Assert.notNull(messages, "'messages' must not be null"); this.messages = internalStore; diff --git a/spring-integration-core/src/main/java/org/springframework/integration/store/SimpleMessageGroupFactory.java b/spring-integration-core/src/main/java/org/springframework/integration/store/SimpleMessageGroupFactory.java index c805c58dd7..37d04b32d4 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/store/SimpleMessageGroupFactory.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/store/SimpleMessageGroupFactory.java @@ -55,7 +55,7 @@ public class SimpleMessageGroupFactory implements MessageGroupFactory { @Override public MessageGroup create(Collection> messages, Object groupId, long timestamp, - boolean complete) { + boolean complete) { return new SimpleMessageGroup(this.type.get(), messages, groupId, timestamp, complete); } @@ -84,7 +84,6 @@ public class SimpleMessageGroupFactory implements MessageGroupFactory { public enum GroupType { BLOCKING_QUEUE { - @Override Collection> get() { return new LinkedBlockingQueue>(); @@ -92,7 +91,6 @@ public class SimpleMessageGroupFactory implements MessageGroupFactory { }, HASH_SET { - @Override Collection> get() { return new LinkedHashSet>(); @@ -100,15 +98,13 @@ public class SimpleMessageGroupFactory implements MessageGroupFactory { }, SYNCHRONISED_SET { - @Override Collection> get() { - return Collections.>synchronizedSet(new LinkedHashSet>()); + return Collections.synchronizedSet(new LinkedHashSet<>()); } }, PERSISTENT { - @Override Collection> get() { return HASH_SET.get(); diff --git a/spring-integration-core/src/main/java/org/springframework/integration/support/management/ExponentialMovingAverageRate.java b/spring-integration-core/src/main/java/org/springframework/integration/support/management/ExponentialMovingAverageRate.java index 8f9eed8938..036c40d75a 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/support/management/ExponentialMovingAverageRate.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/support/management/ExponentialMovingAverageRate.java @@ -22,7 +22,6 @@ import java.util.Deque; import java.util.List; - /** * Cumulative statistics for an event rate with higher weight given to recent data. * Clients call {@link #increment()} when a new event occurs, and then use convenience methods (e.g. {@link #getMean()}) @@ -66,7 +65,6 @@ public class ExponentialMovingAverageRate { private final double factor; - /** * @param period the period to base the rate measurement (in seconds) * @param lapsePeriod the exponential lapse rate for the rate average (in seconds) @@ -215,7 +213,7 @@ public class ExponentialMovingAverageRate { return this.times.peekLast() / this.factor; } else { - return this.t0; + return this.t0; } } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/support/utils/IntegrationUtils.java b/spring-integration-core/src/main/java/org/springframework/integration/support/utils/IntegrationUtils.java index 69538d5d65..417f339fa1 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/support/utils/IntegrationUtils.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/support/utils/IntegrationUtils.java @@ -71,22 +71,21 @@ public final class IntegrationUtils { MessageBuilderFactory messageBuilderFactory = null; if (beanFactory != null) { try { - messageBuilderFactory = beanFactory.getBean( + messageBuilderFactory = beanFactory.getBean( INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME, MessageBuilderFactory.class); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("No MessageBuilderFactory with name '" - + INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME - + "' found: " + e.getMessage() - + ", using default."); + + INTEGRATION_MESSAGE_BUILDER_FACTORY_BEAN_NAME + + "' found: " + e.getMessage() + + ", using default."); } } } else { if (logger.isDebugEnabled()) { - logger.debug("No 'beanFactory' supplied; cannot find MessageBuilderFactory" - + ", using default."); + logger.debug("No 'beanFactory' supplied; cannot find MessageBuilderFactory, using default."); } if (fatalWhenNoBeanFactory) { throw new RuntimeException("All Message creators need a BeanFactory"); @@ -139,4 +138,5 @@ public final class IntegrationUtils { throw new IllegalArgumentException(e); } } + } diff --git a/spring-integration-core/src/main/java/org/springframework/integration/util/MessagingMethodInvokerHelper.java b/spring-integration-core/src/main/java/org/springframework/integration/util/MessagingMethodInvokerHelper.java index 8ba2949461..0b5d6056de 100644 --- a/spring-integration-core/src/main/java/org/springframework/integration/util/MessagingMethodInvokerHelper.java +++ b/spring-integration-core/src/main/java/org/springframework/integration/util/MessagingMethodInvokerHelper.java @@ -63,7 +63,6 @@ import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.ObjectUtils; import org.springframework.util.ReflectionUtils; -import org.springframework.util.ReflectionUtils.MethodCallback; import org.springframework.util.ReflectionUtils.MethodFilter; import org.springframework.util.StringUtils; @@ -203,7 +202,7 @@ public class MessagingMethodInvokerHelper extends AbstractExpressionEvaluator Assert.notNull(targetObject, "targetObject must not be null"); this.targetObject = targetObject; try { - this.handlerMethod = new HandlerMethod(method, canProcessMessageList); + this.handlerMethod = new HandlerMethod(method, canProcessMessageList); } catch (IneligibleMethodException e) { throw new IllegalArgumentException(e); @@ -273,11 +272,11 @@ public class MessagingMethodInvokerHelper extends AbstractExpressionEvaluator if (this.expectedType != null) { Assert.state(context.getTypeConverter() .canConvert(TypeDescriptor.valueOf((this.method).getReturnType()), - TypeDescriptor.valueOf(this.expectedType)), + TypeDescriptor.valueOf(this.expectedType)), "Cannot convert to expected type (" + this.expectedType + ") from " + this.method); } } - else { + else { AnnotatedMethodFilter filter = new AnnotatedMethodFilter(this.annotationType, this.methodName, this.requiresReply); Assert.state(canReturnExpectedType(filter, targetType, context.getTypeConverter()), @@ -351,94 +350,91 @@ public class MessagingMethodInvokerHelper extends AbstractExpressionEvaluator final AtomicReference> ambiguousFallbackMessageGenericType = new AtomicReference>(); final Class targetClass = this.getTargetClass(targetObject); MethodFilter methodFilter = new UniqueMethodFilter(targetClass); - ReflectionUtils.doWithMethods(targetClass, new MethodCallback() { - @Override - public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { - boolean matchesAnnotation = false; - if (method.isBridge()) { - return; + ReflectionUtils.doWithMethods(targetClass, method1 -> { + boolean matchesAnnotation = false; + if (method1.isBridge()) { + return; + } + if (isMethodDefinedOnObjectClass(method1)) { + return; + } + if (method1.getDeclaringClass().equals(Proxy.class)) { + return; + } + if (!Modifier.isPublic(method1.getModifiers())) { + return; + } + if (requiresReply && void.class.equals(method1.getReturnType())) { + return; + } + if (methodName != null && !methodName.equals(method1.getName())) { + return; + } + if (methodName == null + && ObjectUtils.containsElement(new String[] { "start", "stop", "isRunning" }, method1.getName())) { + return; + } + if (annotationType != null && AnnotationUtils.findAnnotation(method1, annotationType) != null) { + matchesAnnotation = true; + } + HandlerMethod handlerMethod1 = null; + try { + handlerMethod1 = new HandlerMethod(method1, this.canProcessMessageList); + } + catch (IneligibleMethodException e) { + if (logger.isDebugEnabled()) { + logger.debug("Method [" + method1 + "] is not eligible for Message handling " + + e.getMessage() + "."); } - if (isMethodDefinedOnObjectClass(method)) { - return; + return; + } + catch (Exception e) { + if (logger.isDebugEnabled()) { + logger.debug("Method [" + method1 + "] is not eligible for Message handling.", e); } - if (method.getDeclaringClass().equals(Proxy.class)) { - return; - } - if (!Modifier.isPublic(method.getModifiers())) { - return; - } - if (requiresReply && void.class.equals(method.getReturnType())) { - return; - } - if (methodName != null && !methodName.equals(method.getName())) { - return; - } - if (methodName == null - && ObjectUtils.containsElement(new String[] {"start", "stop", "isRunning"}, method.getName())) { - return; - } - if (annotationType != null && AnnotationUtils.findAnnotation(method, annotationType) != null) { - matchesAnnotation = true; - } - HandlerMethod handlerMethod = null; - try { - handlerMethod = new HandlerMethod(method, MessagingMethodInvokerHelper.this.canProcessMessageList); - } - catch (IneligibleMethodException e) { - if (logger.isDebugEnabled()) { - logger.debug("Method [" + method + "] is not eligible for Message handling " - + e.getMessage() + "."); - } - return; - } - catch (Exception e) { - if (logger.isDebugEnabled()) { - logger.debug("Method [" + method + "] is not eligible for Message handling.", e); - } - return; - } - Class targetParameterType = handlerMethod.getTargetParameterType(); - if (matchesAnnotation || annotationType == null) { - if (handlerMethod.isMessageMethod()) { - if (candidateMessageMethods.containsKey(targetParameterType)) { - throw new IllegalArgumentException("Found more than one method match for type " + - "[Message<" + targetParameterType + ">]"); - } - candidateMessageMethods.put(targetParameterType, handlerMethod); - } - else { - if (candidateMethods.containsKey(targetParameterType)) { - String exceptionMessage = "Found more than one method match for "; - if (Void.class.equals(targetParameterType)) { - exceptionMessage += "empty parameter for 'payload'"; - } - else { - exceptionMessage += "type [" + targetParameterType + "]"; - } - throw new IllegalArgumentException(exceptionMessage); - } - candidateMethods.put(targetParameterType, handlerMethod); + return; + } + Class targetParameterType = handlerMethod1.getTargetParameterType(); + if (matchesAnnotation || annotationType == null) { + if (handlerMethod1.isMessageMethod()) { + if (candidateMessageMethods.containsKey(targetParameterType)) { + throw new IllegalArgumentException("Found more than one method match for type " + + "[Message<" + targetParameterType + ">]"); } + candidateMessageMethods.put(targetParameterType, handlerMethod1); } else { - if (handlerMethod.isMessageMethod()) { - if (fallbackMessageMethods.containsKey(targetParameterType)) { - // we need to check for duplicate type matches, - // but only if we end up falling back - // and we'll only keep track of the first one - ambiguousFallbackMessageGenericType.compareAndSet(null, targetParameterType); + if (candidateMethods.containsKey(targetParameterType)) { + String exceptionMessage = "Found more than one method match for "; + if (Void.class.equals(targetParameterType)) { + exceptionMessage += "empty parameter for 'payload'"; } - fallbackMessageMethods.put(targetParameterType, handlerMethod); - } - else { - if (fallbackMethods.containsKey(targetParameterType)) { - // we need to check for duplicate type matches, - // but only if we end up falling back - // and we'll only keep track of the first one - ambiguousFallbackType.compareAndSet(null, targetParameterType); + else { + exceptionMessage += "type [" + targetParameterType + "]"; } - fallbackMethods.put(targetParameterType, handlerMethod); + throw new IllegalArgumentException(exceptionMessage); } + candidateMethods.put(targetParameterType, handlerMethod1); + } + } + else { + if (handlerMethod1.isMessageMethod()) { + if (fallbackMessageMethods.containsKey(targetParameterType)) { + // we need to check for duplicate type matches, + // but only if we end up falling back + // and we'll only keep track of the first one + ambiguousFallbackMessageGenericType.compareAndSet(null, targetParameterType); + } + fallbackMessageMethods.put(targetParameterType, handlerMethod1); + } + else { + if (fallbackMethods.containsKey(targetParameterType)) { + // we need to check for duplicate type matches, + // but only if we end up falling back + // and we'll only keep track of the first one + ambiguousFallbackType.compareAndSet(null, targetParameterType); + } + fallbackMethods.put(targetParameterType, handlerMethod1); } } }, methodFilter); @@ -455,7 +451,7 @@ public class MessagingMethodInvokerHelper extends AbstractExpressionEvaluator return handlerMethods; } if ((ambiguousFallbackType.get() != null - || ambiguousFallbackMessageGenericType.get() != null) + || ambiguousFallbackMessageGenericType.get() != null) && ServiceActivator.class.equals(annotationType)) { /* * When there are ambiguous fallback methods, @@ -487,15 +483,9 @@ public class MessagingMethodInvokerHelper extends AbstractExpressionEvaluator } } - try { - Assert.state(!fallbackMethods.isEmpty() || !fallbackMessageMethods.isEmpty(), - "Target object of type [" + this.targetObject.getClass() + - "] has no eligible methods for handling Messages."); - } - catch (Exception e) { - //TODO backward compatibility. Remove in 5.0 - throw new IllegalArgumentException(e.getMessage()); - } + Assert.state(!fallbackMethods.isEmpty() || !fallbackMessageMethods.isEmpty(), + "Target object of type [" + this.targetObject.getClass() + + "] has no eligible methods for handling Messages."); Assert.isNull(ambiguousFallbackType.get(), "Found ambiguous parameter type [" + ambiguousFallbackType + "] for method match: " + fallbackMethods.values()); @@ -509,32 +499,20 @@ public class MessagingMethodInvokerHelper extends AbstractExpressionEvaluator } private void findSingleSpecifMethodOnInterfacesIfProxy(final Object targetObject, final String methodName, - Map, HandlerMethod> candidateMessageMethods, - Map, HandlerMethod> candidateMethods) { + Map, HandlerMethod> candidateMessageMethods, + Map, HandlerMethod> candidateMethods) { if (AopUtils.isAopProxy(targetObject)) { final AtomicReference targetMethod = new AtomicReference(); Class[] interfaces = ((Advised) targetObject).getProxiedInterfaces(); for (Class clazz : interfaces) { - ReflectionUtils.doWithMethods(clazz, new MethodCallback() { - - @Override - public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { - if (targetMethod.get() != null) { - throw new IllegalStateException("Ambiguous method " + methodName + " on " + targetObject); - } - else { - targetMethod.set(method); - } + ReflectionUtils.doWithMethods(clazz, method1 -> { + if (targetMethod.get() != null) { + throw new IllegalStateException("Ambiguous method " + methodName + " on " + targetObject); } - - }, new MethodFilter() { - - @Override - public boolean matches(Method method) { - return method.getName().equals(methodName); + else { + targetMethod.set(method1); } - - }); + }, method12 -> method12.getName().equals(methodName)); } Method method = targetMethod.get(); if (method != null) { @@ -629,17 +607,11 @@ public class MessagingMethodInvokerHelper extends AbstractExpressionEvaluator } private static boolean isMethodDefinedOnObjectClass(Method method) { - if (method == null) { - return false; - } - if (method.getDeclaringClass().equals(Object.class)) { - return true; - } - if (ReflectionUtils.isEqualsMethod(method) || ReflectionUtils.isHashCodeMethod(method) - || ReflectionUtils.isToStringMethod(method) || AopUtils.isFinalizeMethod(method)) { - return true; - } - return (method.getName().equals("clone") && method.getParameterTypes().length == 0); + return method != null && + (method.getDeclaringClass().equals(Object.class) || ReflectionUtils.isEqualsMethod(method) || + ReflectionUtils.isHashCodeMethod(method) || ReflectionUtils.isToStringMethod(method) || + AopUtils.isFinalizeMethod(method) || (method.getName().equals("clone") + && method.getParameterTypes().length == 0)); } /** @@ -769,7 +741,7 @@ public class MessagingMethodInvokerHelper extends AbstractExpressionEvaluator } else if (Iterator.class.isAssignableFrom(parameterType)) { if (this.canProcessMessageList) { - Type type = method.getGenericParameterTypes()[i]; + Type type = method.getGenericParameterTypes()[i]; Type parameterizedType = null; if (type instanceof ParameterizedType) { parameterizedType = ((ParameterizedType) type).getActualTypeArguments()[0]; @@ -856,8 +828,8 @@ public class MessagingMethodInvokerHelper extends AbstractExpressionEvaluator private synchronized void setExclusiveTargetParameterType(TypeDescriptor targetParameterType, MethodParameter methodParameter) { if (this.targetParameterTypeDescriptor != null) { - throw new IneligibleMethodException("Found more than one parameter type candidate: [" - + this.targetParameterTypeDescriptor + "] and [" + targetParameterType + "]"); + throw new IneligibleMethodException("Found more than one parameter type candidate: [" + + this.targetParameterTypeDescriptor + "] and [" + targetParameterType + "]"); } this.targetParameterTypeDescriptor = targetParameterType; if (Message.class.isAssignableFrom(targetParameterType.getObjectType())) { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/BarrierMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/BarrierMessageHandlerTests.java index df3cfc5d85..e1b8efaa41 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/BarrierMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/BarrierMessageHandlerTests.java @@ -300,7 +300,7 @@ public class BarrierMessageHandlerTests { return barrier; } - @ServiceActivator (inputChannel = "release", poller = @Poller(fixedDelay = "0")) + @ServiceActivator(inputChannel = "release", poller = @Poller(fixedDelay = "0")) @Bean public MessageHandler releaser() { return new MessageHandler() { @@ -315,6 +315,6 @@ public class BarrierMessageHandlerTests { }; } - } + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ConcurrentAggregatorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ConcurrentAggregatorTests.java index ca9242c1d1..6178d6e881 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ConcurrentAggregatorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/ConcurrentAggregatorTests.java @@ -127,7 +127,7 @@ public class ConcurrentAggregatorTests { .getCount()); Message reply = replyChannel.receive(1000); assertNull("No message should have been sent normally", reply); - this.store.expireMessageGroups(-10000); + this.store.expireMessageGroups(-10000); Message discardedMessage = discardChannel.receive(1000); assertNotNull("A message should have been discarded", discardedMessage); assertEquals(message, discardedMessage); @@ -152,7 +152,7 @@ public class ConcurrentAggregatorTests { assertEquals("handlers should have been invoked within time limit", 0, latch.getCount()); - this.store.expireMessageGroups(-10000); + this.store.expireMessageGroups(-10000); Message reply = replyChannel.receive(1000); assertNotNull("A reply message should have been received", reply); assertEquals(15, reply.getPayload()); @@ -336,6 +336,7 @@ public class ConcurrentAggregatorTests { private class MultiplyingProcessor implements MessageGroupProcessor { + @Override public Object processMessageGroup(MessageGroup group) { Integer product = 1; @@ -349,6 +350,7 @@ public class ConcurrentAggregatorTests { @SuppressWarnings("unused") private class NullReturningMessageProcessor implements MessageGroupProcessor { + @Override public Object processMessageGroup(MessageGroup group) { return null; diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategyTests.java index 4c5d62bde5..e1e9b2f70c 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/HeaderAttributeCorrelationStrategyTests.java @@ -18,25 +18,24 @@ package org.springframework.integration.aggregator; import static org.junit.Assert.assertEquals; -import org.springframework.messaging.Message; -import org.springframework.integration.support.MessageBuilder; - import org.junit.Test; +import org.springframework.integration.support.MessageBuilder; +import org.springframework.messaging.Message; + /** * @author Marius Bogoevici */ public class HeaderAttributeCorrelationStrategyTests { - @Test - public void testHeaderAttributeCorrelationStrategy() { - String testedHeaderValue = "@!arbitraryTestValue!@"; - String testHeaderName = "header.for.test"; - Message message = MessageBuilder.withPayload("irrelevantData").setHeader(testHeaderName, testedHeaderValue).build(); - HeaderAttributeCorrelationStrategy correlationStrategy = new HeaderAttributeCorrelationStrategy(testHeaderName); - assertEquals(testedHeaderValue, correlationStrategy.getCorrelationKey(message)); - } - + @Test + public void testHeaderAttributeCorrelationStrategy() { + String testedHeaderValue = "@!arbitraryTestValue!@"; + String testHeaderName = "header.for.test"; + Message message = MessageBuilder.withPayload("irrelevantData").setHeader(testHeaderName, testedHeaderValue).build(); + HeaderAttributeCorrelationStrategy correlationStrategy = new HeaderAttributeCorrelationStrategy(testHeaderName); + assertEquals(testedHeaderValue, correlationStrategy.getCorrelationKey(message)); + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java index 8bda6c2c21..1849cc4af5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingMessageGroupProcessorTests.java @@ -486,7 +486,7 @@ public class MethodInvokingMessageGroupProcessorTests { new MethodInvokingMessageGroupProcessor(bean); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = IllegalStateException.class) public void noPublicMethods() { @SuppressWarnings("unused") diff --git a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java index 09987e1998..72cdc217c8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/aggregator/MethodInvokingReleaseStrategyTests.java @@ -139,7 +139,7 @@ public class MethodInvokingReleaseStrategyTests { Assert.assertTrue(adapter.canRelease(messages)); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = IllegalStateException.class) public void testAdapterWithWrongMethodName() { class TestReleaseStrategy { } @@ -159,7 +159,7 @@ public class MethodInvokingReleaseStrategyTests { Assert.assertTrue(adapter.canRelease(messages)); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = IllegalStateException.class) public void testTooManyParametersUsingMethodName() { class TestReleaseStrategy { @SuppressWarnings("unused") diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/MixedDispatcherConfigurationScenarioTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/MixedDispatcherConfigurationScenarioTests.java index 09c0077e94..152583ee06 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/MixedDispatcherConfigurationScenarioTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/MixedDispatcherConfigurationScenarioTests.java @@ -62,12 +62,14 @@ public class MixedDispatcherConfigurationScenarioTests { private ExecutorService executor; - private CountDownLatch allDone; - private CountDownLatch start; - private AtomicBoolean failed; + private CountDownLatch allDone; + + private CountDownLatch start; + + private AtomicBoolean failed; @Mock - private List exceptionRegistry; + private List exceptionRegistry; private ApplicationContext ac; @@ -92,7 +94,7 @@ public class MixedDispatcherConfigurationScenarioTests { Mockito.reset(handlerC); ac = new ClassPathXmlApplicationContext("MixedDispatcherConfigurationScenarioTests-context.xml", - MixedDispatcherConfigurationScenarioTests.class); + MixedDispatcherConfigurationScenarioTests.class); executor = ac.getBean("taskExecutor", ExecutorService.class); allDone = new CountDownLatch(TOTAL_EXECUTIONS); start = new CountDownLatch(1); @@ -129,6 +131,7 @@ public class MixedDispatcherConfigurationScenarioTests { dispatcher.addHandler(handlerB); Runnable messageSenderTask = new Runnable() { + @Override public void run() { try { @@ -174,6 +177,7 @@ public class MixedDispatcherConfigurationScenarioTests { dispatcher.addHandler(handlerB); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) { RuntimeException e = new RuntimeException(); @@ -185,6 +189,7 @@ public class MixedDispatcherConfigurationScenarioTests { }).when(handlerA).handleMessage(message); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) { allDone.countDown(); @@ -193,6 +198,7 @@ public class MixedDispatcherConfigurationScenarioTests { }).when(handlerB).handleMessage(message); Runnable messageSenderTask = new Runnable() { + @Override public void run() { try { @@ -267,6 +273,7 @@ public class MixedDispatcherConfigurationScenarioTests { final Message message = this.message; final AtomicBoolean failed = new AtomicBoolean(false); Runnable messageSenderTask = new Runnable() { + @Override public void run() { try { @@ -317,6 +324,7 @@ public class MixedDispatcherConfigurationScenarioTests { final Message message = this.message; final AtomicBoolean failed = new AtomicBoolean(false); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) { failed.set(true); @@ -327,6 +335,7 @@ public class MixedDispatcherConfigurationScenarioTests { } }).when(handlerA).handleMessage(message); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) { allDone.countDown(); @@ -334,6 +343,7 @@ public class MixedDispatcherConfigurationScenarioTests { } }).when(handlerB).handleMessage(message); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) { allDone.countDown(); @@ -342,6 +352,7 @@ public class MixedDispatcherConfigurationScenarioTests { }).when(handlerC).handleMessage(message); Runnable messageSenderTask = new Runnable() { + @Override public void run() { try { @@ -416,6 +427,7 @@ public class MixedDispatcherConfigurationScenarioTests { final Message message = this.message; final AtomicBoolean failed = new AtomicBoolean(false); Runnable messageSenderTask = new Runnable() { + @Override public void run() { try { @@ -462,6 +474,7 @@ public class MixedDispatcherConfigurationScenarioTests { dispatcher.addHandler(handlerC); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) { RuntimeException e = new RuntimeException(); @@ -470,6 +483,7 @@ public class MixedDispatcherConfigurationScenarioTests { } }).when(handlerA).handleMessage(message); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) { allDone.countDown(); @@ -477,6 +491,7 @@ public class MixedDispatcherConfigurationScenarioTests { } }).when(handlerB).handleMessage(message); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) { return null; @@ -484,6 +499,7 @@ public class MixedDispatcherConfigurationScenarioTests { }).when(handlerC).handleMessage(message); Runnable messageSenderTask = new Runnable() { + @Override public void run() { try { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalChannelInterceptorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalChannelInterceptorTests.java index 42c253a668..f382ea89d9 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalChannelInterceptorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/channel/interceptor/GlobalChannelInterceptorTests.java @@ -58,7 +58,7 @@ public class GlobalChannelInterceptorTests { @Test public void validateGlobalInterceptor() throws Exception { - Map channels = applicationContext.getBeansOfType(ChannelInterceptorAware.class); + Map channels = applicationContext.getBeansOfType(ChannelInterceptorAware.class); for (String channelName : channels.keySet()) { ChannelInterceptorAware channel = channels.get(channelName); if (channelName.equals("nullChannel")) { @@ -114,6 +114,7 @@ public class GlobalChannelInterceptorTests { } } } + @Test public void testWildCardPatternMatch() { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorWithMessageStoreParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorWithMessageStoreParserTests.java index 0fd26b82f4..1bbfcf68e7 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorWithMessageStoreParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/AggregatorWithMessageStoreParserTests.java @@ -20,12 +20,13 @@ import static org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.messaging.Message; -import org.springframework.messaging.MessageChannel; import org.springframework.integration.store.MessageGroupStore; import org.springframework.integration.support.MessageBuilder; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.GenericMessage; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; @@ -50,48 +51,48 @@ public class AggregatorWithMessageStoreParserTests { @Autowired private MessageGroupStore messageGroupStore; - @Autowired + @Autowired private MessageChannel controlBusChannel; - @Test - @DirtiesContext - public void testAggregation() { - input.send(createMessage("123", "id1", 3, 1, null)); - assertEquals(1, messageGroupStore.getMessageGroup("id1").size()); - input.send(createMessage("789", "id1", 3, 3, null)); - assertEquals(2, messageGroupStore.getMessageGroup("id1").size()); - input.send(createMessage("456", "id1", 3, 2, null)); - assertEquals("One and only one message should have been aggregated", 1, aggregatorBean - .getAggregatedMessages().size()); - Message aggregatedMessage = aggregatorBean.getAggregatedMessages().get("id1"); - assertEquals("The aggregated message payload is not correct", "123456789", aggregatedMessage - .getPayload()); - } + @Test + @DirtiesContext + public void testAggregation() { + input.send(createMessage("123", "id1", 3, 1, null)); + assertEquals(1, messageGroupStore.getMessageGroup("id1").size()); + input.send(createMessage("789", "id1", 3, 3, null)); + assertEquals(2, messageGroupStore.getMessageGroup("id1").size()); + input.send(createMessage("456", "id1", 3, 2, null)); + assertEquals("One and only one message should have been aggregated", 1, aggregatorBean + .getAggregatedMessages().size()); + Message aggregatedMessage = aggregatorBean.getAggregatedMessages().get("id1"); + assertEquals("The aggregated message payload is not correct", "123456789", aggregatedMessage + .getPayload()); + } - @Test - @DirtiesContext - public void testExpiry() { - input.send(createMessage("123", "id1", 3, 1, null)); - assertEquals(1, messageGroupStore.getMessageGroup("id1").size()); - input.send(createMessage("456", "id1", 3, 2, null)); - assertEquals(2, messageGroupStore.getMessageGroup("id1").size()); - this.controlBusChannel.send(new GenericMessage("@messageStore.expireMessageGroups(-10000)")); - assertEquals("One and only one message should have been aggregated", 1, aggregatorBean - .getAggregatedMessages().size()); - Message aggregatedMessage = aggregatorBean.getAggregatedMessages().get("id1"); - assertEquals("The aggregated message payload is not correct", "123456", aggregatedMessage - .getPayload()); - } + @Test + @DirtiesContext + public void testExpiry() { + input.send(createMessage("123", "id1", 3, 1, null)); + assertEquals(1, messageGroupStore.getMessageGroup("id1").size()); + input.send(createMessage("456", "id1", 3, 2, null)); + assertEquals(2, messageGroupStore.getMessageGroup("id1").size()); + this.controlBusChannel.send(new GenericMessage("@messageStore.expireMessageGroups(-10000)")); + assertEquals("One and only one message should have been aggregated", 1, aggregatorBean + .getAggregatedMessages().size()); + Message aggregatedMessage = aggregatorBean.getAggregatedMessages().get("id1"); + assertEquals("The aggregated message payload is not correct", "123456", aggregatedMessage + .getPayload()); + } - private static Message createMessage(T payload, Object correlationId, int sequenceSize, int sequenceNumber, - MessageChannel outputChannel) { - return MessageBuilder.withPayload(payload) - .setCorrelationId(correlationId) - .setSequenceSize(sequenceSize) - .setSequenceNumber(sequenceNumber) - .setReplyChannel(outputChannel).build(); - } + private static Message createMessage(T payload, Object correlationId, int sequenceSize, int sequenceNumber, + MessageChannel outputChannel) { + return MessageBuilder.withPayload(payload) + .setCorrelationId(correlationId) + .setSequenceSize(sequenceSize) + .setSequenceNumber(sequenceNumber) + .setReplyChannel(outputChannel).build(); + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/CorrelationStrategyInvalidConfigurationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/CorrelationStrategyInvalidConfigurationTests.java index 2db8017f89..9f2f0ad362 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/CorrelationStrategyInvalidConfigurationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/CorrelationStrategyInvalidConfigurationTests.java @@ -30,23 +30,23 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; */ public class CorrelationStrategyInvalidConfigurationTests { - @Test - public void testCorrelationStrategyWithVoidReturningMethods() throws Exception { + @Test + public void testCorrelationStrategyWithVoidReturningMethods() throws Exception { try { new ClassPathXmlApplicationContext("correlationStrategyWithVoidMethods.xml", - CorrelationStrategyInvalidConfigurationTests.class).close(); + CorrelationStrategyInvalidConfigurationTests.class).close(); } catch (BeanCreationException e) { assertThat(e.getMessage(), containsString("MessageCountReleaseStrategy] has no eligible methods")); } - } + } - public static class VoidReturningCorrelationStrategy { + public static class VoidReturningCorrelationStrategy { - public void invalidCorrelationMethod(String string) { - //do nothing - } + public void invalidCorrelationMethod(String string) { + //do nothing + } - } + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/ReleaseStrategyFactoryBeanTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/ReleaseStrategyFactoryBeanTests.java index ca01b81fce..263787c9ed 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/ReleaseStrategyFactoryBeanTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/ReleaseStrategyFactoryBeanTests.java @@ -48,10 +48,10 @@ public class ReleaseStrategyFactoryBeanTests { factory.setMethodName("doRelease"); try { factory.afterPropertiesSet(); - fail("IllegalArgumentException expected"); + fail("IllegalStateException expected"); } catch (Exception e) { - assertThat(e, instanceOf(IllegalArgumentException.class)); + assertThat(e, instanceOf(IllegalStateException.class)); assertThat(e.getMessage(), containsString("Target object of type " + "[class org.springframework.integration.config.ReleaseStrategyFactoryBeanTests$Foo] " + "has no eligible methods for handling Messages.")); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/ResequencerWithMessageStoreParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/ResequencerWithMessageStoreParserTests.java index cb23cc627d..5edd64c130 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/ResequencerWithMessageStoreParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/ResequencerWithMessageStoreParserTests.java @@ -21,14 +21,15 @@ import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.messaging.Message; -import org.springframework.messaging.MessageChannel; -import org.springframework.messaging.PollableChannel; import org.springframework.integration.IntegrationMessageHeaderAccessor; import org.springframework.integration.store.MessageGroupStore; import org.springframework.integration.support.MessageBuilder; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.PollableChannel; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -50,14 +51,14 @@ public class ResequencerWithMessageStoreParserTests { @Autowired private MessageGroupStore messageGroupStore; - @Test - public void testResequence() { + @Test + public void testResequence() { - input.send(createMessage("123", "id1", 3, 1, null)); - assertEquals(1, messageGroupStore.getMessageGroup("id1").size()); - input.send(createMessage("789", "id1", 3, 3, null)); - assertEquals(2, messageGroupStore.getMessageGroup("id1").size()); - input.send(createMessage("456", "id1", 3, 2, null)); + input.send(createMessage("123", "id1", 3, 1, null)); + assertEquals(1, messageGroupStore.getMessageGroup("id1").size()); + input.send(createMessage("789", "id1", 3, 3, null)); + assertEquals(2, messageGroupStore.getMessageGroup("id1").size()); + input.send(createMessage("456", "id1", 3, 2, null)); Message message1 = output.receive(500); Message message2 = output.receive(500); @@ -70,16 +71,16 @@ public class ResequencerWithMessageStoreParserTests { assertNotNull(message3); assertEquals(new Integer(3), new IntegrationMessageHeaderAccessor(message3).getSequenceNumber()); - } + } - private static Message createMessage(T payload, Object correlationId, int sequenceSize, int sequenceNumber, - MessageChannel outputChannel) { - return MessageBuilder.withPayload(payload) - .setCorrelationId(correlationId) - .setSequenceSize(sequenceSize) - .setSequenceNumber(sequenceNumber) - .setReplyChannel(outputChannel).build(); - } + private static Message createMessage(T payload, Object correlationId, int sequenceSize, int sequenceNumber, + MessageChannel outputChannel) { + return MessageBuilder.withPayload(payload) + .setCorrelationId(correlationId) + .setSequenceSize(sequenceSize) + .setSequenceNumber(sequenceNumber) + .setReplyChannel(outputChannel).build(); + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/TestCorrelationStrategy.java b/spring-integration-core/src/test/java/org/springframework/integration/config/TestCorrelationStrategy.java index 097ca8996d..ffa4043574 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/TestCorrelationStrategy.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/TestCorrelationStrategy.java @@ -16,16 +16,16 @@ package org.springframework.integration.config; -import org.springframework.messaging.Message; import org.springframework.integration.aggregator.CorrelationStrategy; +import org.springframework.messaging.Message; /** * @author Marius Bogoevici */ public class TestCorrelationStrategy implements CorrelationStrategy { - public Object getCorrelationKey(Message message) { - throw new UnsupportedOperationException("for configuration test only"); - } + public Object getCorrelationKey(Message message) { + throw new UnsupportedOperationException("for configuration test only"); + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/TestTrigger.java b/spring-integration-core/src/test/java/org/springframework/integration/config/TestTrigger.java index a3d17ce874..dc4fef7239 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/TestTrigger.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/TestTrigger.java @@ -16,18 +16,18 @@ package org.springframework.integration.config; +import java.util.Date; + import org.springframework.scheduling.Trigger; import org.springframework.scheduling.TriggerContext; -import java.util.Date; - /** * @author Marius Bogoevici */ public class TestTrigger implements Trigger { - public Date nextExecutionTime(TriggerContext triggerContext) { - throw new UnsupportedOperationException(); - } + public Date nextExecutionTime(TriggerContext triggerContext) { + throw new UnsupportedOperationException(); + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/TestAnnotatedEndpointWithCorrelationStrategy.java b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/TestAnnotatedEndpointWithCorrelationStrategy.java index 569041ca26..9d8e5434b2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/TestAnnotatedEndpointWithCorrelationStrategy.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/annotation/TestAnnotatedEndpointWithCorrelationStrategy.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2016 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,35 +17,34 @@ package org.springframework.integration.config.annotation; import java.util.List; +import java.util.stream.Collectors; -import org.springframework.integration.annotation.MessageEndpoint; import org.springframework.integration.annotation.Aggregator; -import org.springframework.integration.annotation.ReleaseStrategy; import org.springframework.integration.annotation.CorrelationStrategy; +import org.springframework.integration.annotation.MessageEndpoint; +import org.springframework.integration.annotation.ReleaseStrategy; /** * @author Marius Bogoevici + * @author Artem Bilan */ @MessageEndpoint("endpointWithCorrelationStrategy") public class TestAnnotatedEndpointWithCorrelationStrategy { - @Aggregator(inputChannel = "inputChannel") - public String aggregatingMethod(List payloads) { - StringBuffer buffer = new StringBuffer(); - for (String s: payloads) { - buffer.append(s); - } - return buffer.toString(); - } + @Aggregator(inputChannel = "inputChannel") + public String aggregatingMethod(List payloads) { + return payloads.stream() + .collect(Collectors.joining()); + } - @ReleaseStrategy - public boolean isComplete(List payloads) { - return payloads.size() == 3; - } + @ReleaseStrategy + public boolean isComplete(List payloads) { + return payloads.size() == 3; + } - @CorrelationStrategy - public String correlate(String payload) { - return payload.substring(0, 1); - } + @CorrelationStrategy + public String correlate(String payload) { + return payload.substring(0, 1); + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/BridgeParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/BridgeParserTests.java index 1acb41ca9d..e76ad2a0cc 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/BridgeParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/BridgeParserTests.java @@ -22,20 +22,21 @@ import static org.junit.Assert.assertThat; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.junit.Test; + import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.integration.channel.QueueChannel; +import org.springframework.integration.core.MessagingTemplate; import org.springframework.integration.endpoint.EventDrivenConsumer; import org.springframework.integration.handler.BridgeHandler; -import org.springframework.messaging.support.GenericMessage; import org.springframework.integration.message.MessageMatcher; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessagingException; import org.springframework.messaging.PollableChannel; -import org.springframework.integration.core.MessagingTemplate; +import org.springframework.messaging.support.GenericMessage; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; @@ -71,9 +72,9 @@ public class BridgeParserTests extends AbstractJUnit4SpringContextTests { @Factory - public static Matcher> sameExceptImmutableHeaders(Message expected) { - return new MessageMatcher(expected); - } + public static Matcher> sameExceptImmutableHeaders(Message expected) { + return new MessageMatcher(expected); + } @Test public void pollableChannel() { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/CronTriggerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/CronTriggerParserTests.java index b3d3e4a579..73bde8cfab 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/CronTriggerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/CronTriggerParserTests.java @@ -40,19 +40,19 @@ public class CronTriggerParserTests { @Autowired private ApplicationContext context; - @Test - public void checkConfigWithAttribute() { - Object poller = context.getBean("pollerWithAttribute"); - assertEquals(PollerMetadata.class, poller.getClass()); - PollerMetadata metadata = (PollerMetadata) poller; - Trigger trigger = metadata.getTrigger(); - assertEquals(CronTrigger.class, trigger.getClass()); - DirectFieldAccessor accessor = new DirectFieldAccessor(trigger); - String expression = (String) new DirectFieldAccessor( - accessor.getPropertyValue("sequenceGenerator")) - .getPropertyValue("expression"); - assertEquals("*/10 * 9-17 * * MON-FRI", expression); - } + @Test + public void checkConfigWithAttribute() { + Object poller = context.getBean("pollerWithAttribute"); + assertEquals(PollerMetadata.class, poller.getClass()); + PollerMetadata metadata = (PollerMetadata) poller; + Trigger trigger = metadata.getTrigger(); + assertEquals(CronTrigger.class, trigger.getClass()); + DirectFieldAccessor accessor = new DirectFieldAccessor(trigger); + String expression = (String) new DirectFieldAccessor( + accessor.getPropertyValue("sequenceGenerator")) + .getPropertyValue("expression"); + assertEquals("*/10 * 9-17 * * MON-FRI", expression); + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherParserTests.java index 14ac2dece6..684709864e 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/HeaderEnricherParserTests.java @@ -16,25 +16,25 @@ package org.springframework.integration.config.xml; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import org.springframework.messaging.Message; import org.springframework.integration.channel.QueueChannel; -import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.support.GenericMessage; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.test.util.TestUtils; import org.springframework.integration.transformer.MessageTransformationException; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageHandler; +import org.springframework.messaging.support.GenericMessage; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - /** * @author Mark Fisher * @since 2.0 @@ -50,14 +50,14 @@ public class HeaderEnricherParserTests { @Test // INT-1154 public void sendTimeoutDefault() { Object endpoint = context.getBean("headerEnricherWithDefaults"); - long sendTimeout = TestUtils.getPropertyValue(endpoint, "handler.messagingTemplate.sendTimeout", Long.class).longValue(); + long sendTimeout = TestUtils.getPropertyValue(endpoint, "handler.messagingTemplate.sendTimeout", Long.class); assertEquals(-1L, sendTimeout); } @Test // INT-1154 public void sendTimeoutConfigured() { Object endpoint = context.getBean("headerEnricherWithSendTimeout"); - long sendTimeout = TestUtils.getPropertyValue(endpoint, "handler.messagingTemplate.sendTimeout", Long.class).longValue(); + long sendTimeout = TestUtils.getPropertyValue(endpoint, "handler.messagingTemplate.sendTimeout", Long.class); assertEquals(1234L, sendTimeout); } @@ -89,18 +89,19 @@ public class HeaderEnricherParserTests { Message message = new GenericMessage("hello"); messageHandler.handleMessage(message); } + @Test public void testStringPriorityHeaderWithType() { - MessageHandler messageHandler = - TestUtils.getPropertyValue(context.getBean("headerEnricherWithPriorityAsStringAndType"), "handler", MessageHandler.class); - QueueChannel replyChannel = new QueueChannel(); - Message message = MessageBuilder.withPayload("foo").setReplyChannel(replyChannel).build(); - messageHandler.handleMessage(message); - Message transformed = replyChannel.receive(1000); - assertNotNull(transformed); - Object priority = transformed.getHeaders().get("priority"); - assertNotNull(priority); - assertTrue(priority instanceof Integer); + MessageHandler messageHandler = + TestUtils.getPropertyValue(context.getBean("headerEnricherWithPriorityAsStringAndType"), "handler", MessageHandler.class); + QueueChannel replyChannel = new QueueChannel(); + Message message = MessageBuilder.withPayload("foo").setReplyChannel(replyChannel).build(); + messageHandler.handleMessage(message); + Message transformed = replyChannel.receive(1000); + assertNotNull(transformed); + Object priority = transformed.getHeaders().get("priority"); + assertNotNull(priority); + assertTrue(priority instanceof Integer); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/IntervalTriggerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/IntervalTriggerParserTests.java index 706183df4b..8b2eda98af 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/IntervalTriggerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/IntervalTriggerParserTests.java @@ -37,34 +37,34 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) public class IntervalTriggerParserTests { - @Autowired - ApplicationContext context; + @Autowired + ApplicationContext context; - @Test - public void testFixedRateTrigger() { - Object poller = context.getBean("pollerWithFixedRateAttribute"); + @Test + public void testFixedRateTrigger() { + Object poller = context.getBean("pollerWithFixedRateAttribute"); assertEquals(PollerMetadata.class, poller.getClass()); PollerMetadata metadata = (PollerMetadata) poller; Trigger trigger = metadata.getTrigger(); assertEquals(PeriodicTrigger.class, trigger.getClass()); DirectFieldAccessor accessor = new DirectFieldAccessor(trigger); Boolean fixedRate = (Boolean) accessor.getPropertyValue("fixedRate"); - Long period = (Long) accessor.getPropertyValue("period"); - assertEquals(fixedRate, true); + Long period = (Long) accessor.getPropertyValue("period"); + assertEquals(fixedRate, true); assertEquals(36L, period.longValue()); - } + } - @Test - public void testFixedDelayTrigger() { - Object poller = context.getBean("pollerWithFixedDelayAttribute"); + @Test + public void testFixedDelayTrigger() { + Object poller = context.getBean("pollerWithFixedDelayAttribute"); assertEquals(PollerMetadata.class, poller.getClass()); PollerMetadata metadata = (PollerMetadata) poller; Trigger trigger = metadata.getTrigger(); assertEquals(PeriodicTrigger.class, trigger.getClass()); DirectFieldAccessor accessor = new DirectFieldAccessor(trigger); Boolean fixedRate = (Boolean) accessor.getPropertyValue("fixedRate"); - Long period = (Long) accessor.getPropertyValue("period"); - assertEquals(fixedRate, false); + Long period = (Long) accessor.getPropertyValue("period"); + assertEquals(fixedRate, false); assertEquals(37L, period.longValue()); - } + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToMapTransformerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToMapTransformerParserTests.java index a25e0d210b..20bf2942ef 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToMapTransformerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/ObjectToMapTransformerParserTests.java @@ -16,6 +16,10 @@ package org.springframework.integration.config.xml; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -24,6 +28,7 @@ import java.util.Map; import org.hamcrest.Matchers; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.expression.MapAccessor; @@ -31,18 +36,14 @@ import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; +import org.springframework.integration.support.MessageBuilder; +import org.springframework.integration.transformer.MessageTransformationException; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.PollableChannel; -import org.springframework.integration.support.MessageBuilder; -import org.springframework.integration.transformer.MessageTransformationException; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertThat; - /** * @author Oleg Zhurakousky * @author Gunnar Hillert @@ -60,13 +61,13 @@ public class ObjectToMapTransformerParserTests { @Qualifier("output") private PollableChannel output; - @Autowired - @Qualifier("nestedInput") - private MessageChannel nestedInput; + @Autowired + @Qualifier("nestedInput") + private MessageChannel nestedInput; - @Autowired - @Qualifier("nestedOutput") - private PollableChannel nestedOutput; + @Autowired + @Qualifier("nestedOutput") + private PollableChannel nestedOutput; @SuppressWarnings("unchecked") @@ -90,6 +91,7 @@ public class ObjectToMapTransformerParserTests { assertEquals(valueFromTheMap, valueFromExpression); } } + @Test(expected = MessageTransformationException.class) public void testObjectToSpelMapTransformerWithCycle() { Employee employee = this.buildEmployee(); @@ -126,8 +128,8 @@ public class ObjectToMapTransformerParserTests { companyAddress.setZip("12345"); Map coordinates = new HashMap(); - coordinates.put("latitude", new Integer[]{1, 5, 13}); - coordinates.put("longitude", new Integer[]{156}); + coordinates.put("latitude", new Integer[] { 1, 5, 13 }); + coordinates.put("longitude", new Integer[] { 156 }); companyAddress.setCoordinates(coordinates); Employee employee = new Employee(); @@ -180,128 +182,177 @@ public class ObjectToMapTransformerParserTests { } public static class Employee { + private List departments; + private String companyName; + private Person person; + private Address companyAddress; + private Map> testMapInMapData; + public Map> getTestMapInMapData() { return testMapInMapData; } + public void setTestMapInMapData( Map> testMapInMapData) { this.testMapInMapData = testMapInMapData; } + public String getCompanyName() { return companyName; } + public void setCompanyName(String companyName) { this.companyName = companyName; } + public Person getPerson() { return person; } + public void setPerson(Person person) { this.person = person; } + public Address getCompanyAddress() { return companyAddress; } + public void setCompanyAddress(Address companyAddress) { this.companyAddress = companyAddress; } + public List getDepartments() { return departments; } + public void setDepartments(List departments) { this.departments = departments; } } public static class Person { + private String fname; + private String lname; + private String[] akaNames; + private List> remarks; + private Child child; + public Child getChild() { return child; } + public void setChild(Child child) { this.child = child; } + public List> getRemarks() { return remarks; } + public void setRemarks(List> remarks) { this.remarks = remarks; } + private Address address; + public String[] getAkaNames() { return akaNames; } + public void setAkaNames(String... akaNames) { this.akaNames = akaNames; } + public String getFname() { return fname; } + public void setFname(String fname) { this.fname = fname; } + public String getLname() { return lname; } + public void setLname(String lname) { this.lname = lname; } + public Address getAddress() { return address; } + public void setAddress(Address address) { this.address = address; } } public static class Address { + private String street; + private String city; + private String zip; + private Map> mapWithListData; + private Map coordinates; + public Map> getMapWithListData() { return mapWithListData; } + public void setMapWithListData(Map> mapWithListData) { this.mapWithListData = mapWithListData; } + public String getStreet() { return street; } + public void setStreet(String street) { this.street = street; } + public String getCity() { return city; } + public void setCity(String city) { this.city = city; } + public String getZip() { return zip; } + public void setZip(String zip) { this.zip = zip; } + public Map getCoordinates() { return coordinates; } + public void setCoordinates(Map coordinates) { this.coordinates = coordinates; } } public static class Child { + private Person parent; public Person getParent() { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PollerParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PollerParserTests.java index eb9610effe..deef30622d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PollerParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/config/xml/PollerParserTests.java @@ -115,9 +115,9 @@ public class PollerParserTests { context.close(); } - @Test + @Test public void pollerWithTriggerReference() { - ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( + ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( "pollerWithTriggerReference.xml", PollerParserTests.class); Object poller = context.getBean("poller"); assertNotNull(poller); @@ -126,19 +126,19 @@ public class PollerParserTests { context.close(); } - @Test(expected = BeanDefinitionParsingException.class) + @Test(expected = BeanDefinitionParsingException.class) public void pollerWithCronTriggerAndTimeUnit() { new ClassPathXmlApplicationContext( "cronTriggerWithTimeUnit-fail.xml", PollerParserTests.class).close(); } - @Test(expected = BeanDefinitionParsingException.class) + @Test(expected = BeanDefinitionParsingException.class) public void topLevelPollerWithRef() { new ClassPathXmlApplicationContext( "defaultPollerWithRef.xml", PollerParserTests.class).close(); } - @Test(expected = BeanDefinitionParsingException.class) + @Test(expected = BeanDefinitionParsingException.class) public void pollerWithCronAndFixedDelay() { new ClassPathXmlApplicationContext( "pollerWithCronAndFixedDelay.xml", PollerParserTests.class).close(); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java b/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java index 7208aeac08..aa96bd50b2 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/configuration/EnableIntegrationTests.java @@ -1268,7 +1268,7 @@ public class EnableIntegrationTests { } @Override - @MyServiceActivatorNoLocalAtts() + @MyServiceActivatorNoLocalAtts public Integer annCount2() { return 0; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java b/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java index 1f999aac0a..40c16a1370 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/core/AsyncMessagingTemplateTests.java @@ -30,16 +30,17 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.Test; + import org.springframework.context.support.StaticApplicationContext; import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.channel.QueueChannel; import org.springframework.integration.handler.AbstractReplyProducingMessageHandler; -import org.springframework.messaging.support.GenericMessage; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessagingException; import org.springframework.messaging.core.MessagePostProcessor; +import org.springframework.messaging.support.GenericMessage; import org.springframework.util.Assert; /** @@ -436,7 +437,7 @@ public class AsyncMessagingTemplateTests { private static void sendMessageAfterDelay(final MessageChannel channel, final GenericMessage message, - final int delay) { + final int delay) { Executors.newSingleThreadExecutor().execute(new Runnable() { public void run() { diff --git a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java index eacba3898b..ca330912b8 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/endpoint/ServiceActivatorEndpointTests.java @@ -106,6 +106,7 @@ public class ServiceActivatorEndpointTests { final QueueChannel replyChannel2 = new QueueChannel(); replyChannel2.setBeanName("replyChannel2"); Object handler = new Object() { + @SuppressWarnings("unused") public Message handle(Message message) { return new GenericMessage("foo" + message.getPayload()); @@ -179,6 +180,7 @@ public class ServiceActivatorEndpointTests { public void correlationIdNotSetIfMessageIsReturnedUnaltered() { QueueChannel replyChannel = new QueueChannel(1); ServiceActivatingHandler endpoint = new ServiceActivatingHandler(new Object() { + @SuppressWarnings("unused") public Message handle(Message message) { return message; @@ -195,6 +197,7 @@ public class ServiceActivatorEndpointTests { public void correlationIdSetByHandlerTakesPrecedence() { QueueChannel replyChannel = new QueueChannel(1); ServiceActivatingHandler endpoint = new ServiceActivatingHandler(new Object() { + @SuppressWarnings("unused") public Message handle(Message message) { return MessageBuilder.fromMessage(message) @@ -223,7 +226,7 @@ public class ServiceActivatorEndpointTests { private ServiceActivatingHandler createEndpoint() { - return new ServiceActivatingHandler(new TestBean(), "handle"); + return new ServiceActivatingHandler(new TestBean(), "handle"); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/BridgeHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/BridgeHandlerTests.java index 83c493e585..45878cf6d1 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/BridgeHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/BridgeHandlerTests.java @@ -22,13 +22,14 @@ import static org.junit.Assert.assertThat; import org.hamcrest.Factory; import org.hamcrest.Matcher; import org.junit.Test; + import org.springframework.integration.channel.QueueChannel; -import org.springframework.messaging.support.GenericMessage; import org.springframework.integration.message.MessageMatcher; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.PollableChannel; import org.springframework.messaging.core.DestinationResolutionException; +import org.springframework.messaging.support.GenericMessage; /** * @author Mark Fisher @@ -39,9 +40,9 @@ public class BridgeHandlerTests { private BridgeHandler handler = new BridgeHandler(); @Factory - public static Matcher> sameExceptImmutableHeaders(Message expected) { - return new MessageMatcher(expected); - } + public static Matcher> sameExceptImmutableHeaders(Message expected) { + return new MessageMatcher(expected); + } @Test public void simpleBridge() { 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 0b3685008c..5a45cd1c74 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 @@ -36,6 +36,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Assert; import org.junit.Test; + +import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandlingException; import org.springframework.messaging.MessageHeaders; @@ -44,7 +46,6 @@ import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.Headers; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.support.GenericMessage; -import org.springframework.integration.support.MessageBuilder; /** * @author Mark Fisher @@ -69,6 +70,7 @@ public class MethodInvokingMessageProcessorAnnotationTests { processor.processMessage(new GenericMessage("foo")); for (int i = 0; i < 100; i++) { exec.execute(new Runnable() { + public void run() { Object result = processor.processMessage(new GenericMessage("foo")); assertNotNull(result); @@ -99,7 +101,7 @@ public class MethodInvokingMessageProcessorAnnotationTests { public void requiredHeaderNotProvidedOnSecondMessage() throws Exception { Method method = TestService.class.getMethod("requiredHeader", Integer.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); - Message messageWithHeader = MessageBuilder.withPayload("foo") + Message messageWithHeader = MessageBuilder.withPayload("foo") .setHeader("num", new Integer(123)).build(); GenericMessage messageWithoutHeader = new GenericMessage("foo"); @@ -253,11 +255,11 @@ public class MethodInvokingMessageProcessorAnnotationTests { public void multipleAnnotatedArgs() throws Exception { Message message = this.getMessage(); Method method = TestService.class.getMethod("multipleAnnotatedArguments", - String.class, - String.class, - Employee.class, - String.class, - Map.class); + String.class, + String.class, + Employee.class, + String.class, + Map.class); MethodInvokingMessageProcessor processor = new MethodInvokingMessageProcessor(testService, method); Object[] parameters = (Object[]) processor.processMessage(message); Assert.assertNotNull(parameters); @@ -337,7 +339,8 @@ public class MethodInvokingMessageProcessorAnnotationTests { @SuppressWarnings("unused") private static class MultipleMappingAnnotationTestBean { - public void test(@Payload("payload") @Header("foo") String s) { + + public void test(@Payload("payload") @Header("foo") String s) { } } @@ -416,14 +419,14 @@ public class MethodInvokingMessageProcessorAnnotationTests { } public Object[] multipleAnnotatedArguments(@Header("day") String argA, - @Header("month") String argB, - @Payload Employee payloadArg, - @Payload("fname") String value, - @Headers Map headers) { + @Header("month") String argB, + @Payload Employee payloadArg, + @Payload("fname") String value, + @Headers Map headers) { return new Object[] { argA, argB, payloadArg, value, headers }; } - public String irrelevantAnnotation(@BogusAnnotation() String value) { + public String irrelevantAnnotation(@BogusAnnotation String value) { return value; } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java index 549b5e5da2..f24dc7d7da 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/handler/MethodInvokingMessageProcessorTests.java @@ -527,7 +527,7 @@ public class MethodInvokingMessageProcessorTests { @SuppressWarnings("unused") public void optionalHeaders(Optional foo, @Header(value = "foo", required = false) String foo1, - @Header(value = "foo") Optional foo2) { + @Header("foo") Optional foo2) { this.arguments.put("foo", (foo.isPresent() ? foo.get() : null)); this.arguments.put("foo1", foo1); this.arguments.put("foo2", (foo2.isPresent() ? foo2.get() : null)); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/history/AnnotatedAdapter.java b/spring-integration-core/src/test/java/org/springframework/integration/history/AnnotatedAdapter.java index 8142ad96a6..74be373723 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/history/AnnotatedAdapter.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/history/AnnotatedAdapter.java @@ -20,20 +20,23 @@ import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationEvent; -import org.springframework.messaging.Message; import org.springframework.integration.annotation.MessageEndpoint; +import org.springframework.messaging.Message; /** * @author Oleg Zhurakousky * */ -@MessageEndpoint(value = "outputAdapter") +@MessageEndpoint("outputAdapter") public class AnnotatedAdapter implements ApplicationContextAware { + private volatile ApplicationContext applicationContext; @SuppressWarnings("serial") public void handle(Message message) { - applicationContext.publishEvent(new ApplicationEvent(message) { }); + applicationContext.publishEvent(new ApplicationEvent(message) { + + }); } public void setApplicationContext(ApplicationContext applicationContext) diff --git a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonPathTests.java b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonPathTests.java index 73babbaf36..2598a901eb 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/json/JsonPathTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/json/JsonPathTests.java @@ -178,7 +178,7 @@ public class JsonPathTests { @Test public void testInt3139JsonPathSplitter() { - this.splitterInput.send(testMessage); + this.splitterInput.send(testMessage); for (int i = 0; i < 4; i++) { Message receive = this.splitterOutput.receive(10000); assertNotNull(receive); @@ -214,7 +214,7 @@ public class JsonPathTests { @Bean public Predicate jsonPathFilter() { - return Filter.filter(Criteria.where("isbn").exists(true).and("category").ne("fiction")); + return Filter.filter(Criteria.where("isbn").exists(true).and("category").ne("fiction")); } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java index e32e45ea44..9a9419afe5 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/message/MethodInvokingMessageHandlerTests.java @@ -66,7 +66,7 @@ public class MethodInvokingMessageHandlerTests { } } - @Test(expected = IllegalArgumentException.class) + @Test(expected = IllegalStateException.class) public void noMatchingMethodName() { new MethodInvokingMessageHandler(new TestSink(), "noSuchMethod"); } 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 501e547117..7b457cb3ed 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 @@ -474,13 +474,13 @@ public class PayloadAndHeaderMappingTests { assertEquals(null, bean.lastHeaders.get("baz")); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = IllegalStateException.class) public void twoStringsAmbiguousUsingMethodName() throws Exception { SingleAmbiguousMethodTestBean bean = new SingleAmbiguousMethodTestBean(); new ServiceActivatingHandler(bean, "twoStrings"); } - @Test(expected = IllegalArgumentException.class) + @Test(expected = IllegalStateException.class) public void twoStringsAmbiguousWithoutMethodName() throws Exception { SingleAmbiguousMethodTestBean bean = new SingleAmbiguousMethodTestBean(); new ServiceActivatingHandler(bean); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/router/config/PayloadTypeRouterParserTests.java b/spring-integration-core/src/test/java/org/springframework/integration/router/config/PayloadTypeRouterParserTests.java index 6c00ef1197..4191eff139 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/router/config/PayloadTypeRouterParserTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/router/config/PayloadTypeRouterParserTests.java @@ -53,8 +53,8 @@ public class PayloadTypeRouterParserTests { context.start(); Message message1 = MessageBuilder.withPayload("Hello").build(); Message message2 = MessageBuilder.withPayload(25).build(); - Message message3 = MessageBuilder.withPayload(new Integer[]{23, 24, 34}).build(); - Message message4 = MessageBuilder.withPayload(new Long[]{23L, 24L, 34L}).build(); + Message message3 = MessageBuilder.withPayload(new Integer[] { 23, 24, 34 }).build(); + Message message4 = MessageBuilder.withPayload(new Long[] { 23L, 24L, 34L }).build(); testService.foo(message1); testService.foo(message2); testService.foo(message3); @@ -80,33 +80,34 @@ public class PayloadTypeRouterParserTests { @SuppressWarnings("unused") private final String routerConfigFakeType = - "" + - "" + - " " + - " " + - " " + - " " + - ""; + "" + + "" + + " " + + " " + + " " + + " " + + ""; private final String routerConfigNoMaping = - "" + - "" + - " " + - " " + - ""; + "" + + "" + + " " + + " " + + ""; public interface TestService { + void foo(Message message); } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/MessageScenariosTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/MessageScenariosTests.java index a73730fc4c..a00afbc236 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/MessageScenariosTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/MessageScenariosTests.java @@ -40,39 +40,42 @@ public class MessageScenariosTests extends AbstractRequestResponseScenarioTests List scenarios = new ArrayList(); RequestResponseScenario scenario1 = new RequestResponseScenario( "inputChannel", "outputChannel") - .setPayload("hello") - .setResponseValidator(new PayloadValidator() { - @Override - protected void validateResponse(String response) { - assertEquals("HELLO", response); - } - }); + .setPayload("hello") + .setResponseValidator(new PayloadValidator() { + + @Override + protected void validateResponse(String response) { + assertEquals("HELLO", response); + } + }); scenarios.add(scenario1); RequestResponseScenario scenario2 = new RequestResponseScenario( "inputChannel", "outputChannel") - .setMessage(MessageBuilder.withPayload("hello").setHeader("foo", "bar").build()) - .setResponseValidator(new MessageValidator() { - @Override - protected void validateMessage(Message message) { - assertThat(message, hasPayload("HELLO")); - assertThat(message, hasHeader("foo", "bar")); - } - }); + .setMessage(MessageBuilder.withPayload("hello").setHeader("foo", "bar").build()) + .setResponseValidator(new MessageValidator() { + + @Override + protected void validateMessage(Message message) { + assertThat(message, hasPayload("HELLO")); + assertThat(message, hasHeader("foo", "bar")); + } + }); scenarios.add(scenario2); RequestResponseScenario scenario3 = new RequestResponseScenario( "inputChannel2", "outputChannel2") - .setMessage(MessageBuilder.withPayload("hello").setHeader("foo", "bar").build()) - .setResponseValidator(new MessageValidator() { - @Override - protected void validateMessage(Message message) { - assertThat(message, hasPayload("HELLO")); - assertThat(message, hasHeader("foo", "bar")); - } - }); + .setMessage(MessageBuilder.withPayload("hello").setHeader("foo", "bar").build()) + .setResponseValidator(new MessageValidator() { + + @Override + protected void validateMessage(Message message) { + assertThat(message, hasPayload("HELLO")); + assertThat(message, hasHeader("foo", "bar")); + } + }); scenarios.add(scenario3); diff --git a/spring-integration-core/src/test/java/org/springframework/integration/support/MutableMessageTests.java b/spring-integration-core/src/test/java/org/springframework/integration/support/MutableMessageTests.java index 7094e676fc..432a8c3c8d 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/support/MutableMessageTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/support/MutableMessageTests.java @@ -34,42 +34,42 @@ import org.springframework.messaging.MessageHeaders; */ public class MutableMessageTests { - @Test - public void testMessageIdTimestampRemains() { + @Test + public void testMessageIdTimestampRemains() { - UUID uuid = UUID.randomUUID(); - long timestamp = System.currentTimeMillis(); + UUID uuid = UUID.randomUUID(); + long timestamp = System.currentTimeMillis(); - Object payload = new Object(); - Map headerMap = new HashMap<>(); + Object payload = new Object(); + Map headerMap = new HashMap<>(); - headerMap.put(MessageHeaders.ID, uuid); - headerMap.put(MessageHeaders.TIMESTAMP, timestamp); + headerMap.put(MessageHeaders.ID, uuid); + headerMap.put(MessageHeaders.TIMESTAMP, timestamp); - MutableMessage mutableMessage = new MutableMessage<>(payload, headerMap); - MutableMessageHeaders headers = mutableMessage.getHeaders(); + MutableMessage mutableMessage = new MutableMessage<>(payload, headerMap); + MutableMessageHeaders headers = mutableMessage.getHeaders(); - assertThat(headers.getRawHeaders(), hasEntry(MessageHeaders.ID, (Object) uuid)); - assertThat(headers.getRawHeaders(), hasEntry(MessageHeaders.TIMESTAMP, (Object) timestamp)); - } + assertThat(headers.getRawHeaders(), hasEntry(MessageHeaders.ID, (Object) uuid)); + assertThat(headers.getRawHeaders(), hasEntry(MessageHeaders.TIMESTAMP, (Object) timestamp)); + } - @Test - public void testMessageHeaderIsSettable() { + @Test + public void testMessageHeaderIsSettable() { - Object payload = new Object(); - Map headerMap = new HashMap<>(); - Map additional = new HashMap<>(); + Object payload = new Object(); + Map headerMap = new HashMap<>(); + Map additional = new HashMap<>(); - MutableMessage mutableMessage = new MutableMessage<>(payload, headerMap); - MutableMessageHeaders headers = mutableMessage.getHeaders(); + MutableMessage mutableMessage = new MutableMessage<>(payload, headerMap); + MutableMessageHeaders headers = mutableMessage.getHeaders(); - // Should not throw an UnsupportedOperationException - headers.put("foo", "bar"); - headers.put("eep", "bar"); - headers.remove("eep"); - headers.putAll(additional); + // Should not throw an UnsupportedOperationException + headers.put("foo", "bar"); + headers.put("eep", "bar"); + headers.remove("eep"); + headers.putAll(additional); - assertThat(headers.getRawHeaders(), hasEntry("foo", (Object) "bar")); - } + assertThat(headers.getRawHeaders(), hasEntry("foo", (Object) "bar")); + } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MessageHistoryParameterTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MessageHistoryParameterTests.java index 4bf9479257..83ef1e37dc 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/MessageHistoryParameterTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/MessageHistoryParameterTests.java @@ -20,15 +20,16 @@ import static org.junit.Assert.assertNotNull; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.integration.annotation.Transformer; +import org.springframework.integration.history.MessageHistory; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHeaders; +import org.springframework.messaging.PollableChannel; import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.Headers; import org.springframework.messaging.handler.annotation.Payload; -import org.springframework.integration.annotation.Transformer; -import org.springframework.messaging.PollableChannel; -import org.springframework.integration.history.MessageHistory; import org.springframework.messaging.support.GenericMessage; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -58,10 +59,10 @@ public class MessageHistoryParameterTests { @Transformer public Object transform(@Headers MessageHeaders headers, - @Header("history") MessageHistory history, @Payload Object payload) { + @Header("history") MessageHistory history, @Payload Object payload) { - return payload; - } + return payload; + } } } diff --git a/spring-integration-core/src/test/java/org/springframework/integration/transformer/SysLogTransformerTests.java b/spring-integration-core/src/test/java/org/springframework/integration/transformer/SysLogTransformerTests.java index a4ea4340f7..c49362e89b 100644 --- a/spring-integration-core/src/test/java/org/springframework/integration/transformer/SysLogTransformerTests.java +++ b/spring-integration-core/src/test/java/org/springframework/integration/transformer/SysLogTransformerTests.java @@ -49,10 +49,10 @@ public class SysLogTransformerTests { assertEquals("TESTING", transformed.get(SyslogToMapTransformer.TAG)); assertEquals("[70729]: TEST SYSLOG MESSAGE", transformed.get(SyslogToMapTransformer.MESSAGE)); - String[] fields = {SyslogToMapTransformer.FACILITY, SyslogToMapTransformer.SEVERITY, + String[] fields = { SyslogToMapTransformer.FACILITY, SyslogToMapTransformer.SEVERITY, SyslogToMapTransformer.TIMESTAMP, SyslogToMapTransformer.HOST, - SyslogToMapTransformer.TAG, SyslogToMapTransformer.MESSAGE}; - Object[] values = {19, 6, date, "WEBERN", "TESTING", "[70729]: TEST SYSLOG MESSAGE"}; + SyslogToMapTransformer.TAG, SyslogToMapTransformer.MESSAGE }; + Object[] values = { 19, 6, date, "WEBERN", "TESTING", "[70729]: TEST SYSLOG MESSAGE" }; assertIterationOrder(fields, values, transformed); } @@ -85,10 +85,10 @@ public class SysLogTransformerTests { assertFalse(transformed.containsKey(SyslogToMapTransformer.TAG)); assertEquals("[70729]: TEST SYSLOG MESSAGE", transformed.get(SyslogToMapTransformer.MESSAGE)); - String[] fields = {SyslogToMapTransformer.FACILITY, SyslogToMapTransformer.SEVERITY, + String[] fields = { SyslogToMapTransformer.FACILITY, SyslogToMapTransformer.SEVERITY, SyslogToMapTransformer.TIMESTAMP, SyslogToMapTransformer.HOST, - SyslogToMapTransformer.MESSAGE}; - Object[] values = {19, 6, date, "WEBERN", "[70729]: TEST SYSLOG MESSAGE"}; + SyslogToMapTransformer.MESSAGE }; + Object[] values = { 19, 6, date, "WEBERN", "[70729]: TEST SYSLOG MESSAGE" }; assertIterationOrder(fields, values, transformed); } @@ -105,15 +105,15 @@ public class SysLogTransformerTests { assertEquals("ABCDE1234567890ABCDE1234567890UV", transformed.get(SyslogToMapTransformer.TAG)); assertEquals("XYZ TEST SYSLOG MESSAGE", transformed.get(SyslogToMapTransformer.MESSAGE)); - String[] fields = {SyslogToMapTransformer.FACILITY, SyslogToMapTransformer.SEVERITY, + String[] fields = { SyslogToMapTransformer.FACILITY, SyslogToMapTransformer.SEVERITY, SyslogToMapTransformer.TIMESTAMP, SyslogToMapTransformer.HOST, - SyslogToMapTransformer.TAG, SyslogToMapTransformer.MESSAGE}; - Object[] values = {19, 6, date, "WEBERN", "ABCDE1234567890ABCDE1234567890UV", "XYZ TEST SYSLOG MESSAGE"}; + SyslogToMapTransformer.TAG, SyslogToMapTransformer.MESSAGE }; + Object[] values = { 19, 6, date, "WEBERN", "ABCDE1234567890ABCDE1234567890UV", "XYZ TEST SYSLOG MESSAGE" }; assertIterationOrder(fields, values, transformed); } private static void assertIterationOrder(String[] expectedFields, Object[] expectedValues, - Map actualTransformed) { + Map actualTransformed) { int n = 0; for (Entry entry : actualTransformed.entrySet()) { assertEquals(expectedFields[n++], entry.getKey()); diff --git a/spring-integration-file/src/main/java/org/springframework/integration/file/DefaultDirectoryScanner.java b/spring-integration-file/src/main/java/org/springframework/integration/file/DefaultDirectoryScanner.java index ddb0a0e11c..f998c0e6e6 100644 --- a/spring-integration-file/src/main/java/org/springframework/integration/file/DefaultDirectoryScanner.java +++ b/spring-integration-file/src/main/java/org/springframework/integration/file/DefaultDirectoryScanner.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 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,11 +21,11 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import org.springframework.messaging.MessagingException; import org.springframework.integration.file.filters.AcceptOnceFileListFilter; import org.springframework.integration.file.filters.CompositeFileListFilter; import org.springframework.integration.file.filters.FileListFilter; import org.springframework.integration.file.filters.IgnoreHiddenFileListFilter; +import org.springframework.messaging.MessagingException; /** * Default directory scanner and base class for other directory scanners. @@ -33,6 +33,7 @@ import org.springframework.integration.file.filters.IgnoreHiddenFileListFilter; * * @author Iwein Fuld * @author Gunnar Hillert + * @author Artem Bilan * @since 2.0 */ public class DefaultDirectoryScanner implements DirectoryScanner { @@ -41,17 +42,6 @@ public class DefaultDirectoryScanner implements DirectoryScanner { private volatile FileLocker locker; - public void setFilter(FileListFilter filter) { - this.filter = filter; - } - - /** - * {@inheritDoc} - */ - public final void setLocker(FileLocker locker) { - this.locker = locker; - } - /** * Initializes {@link DefaultDirectoryScanner#filter} with a default list of * {@link FileListFilter}s using a {@link CompositeFileListFilter}: @@ -61,22 +51,32 @@ public class DefaultDirectoryScanner implements DirectoryScanner { * */ public DefaultDirectoryScanner() { - final List> defaultFilters = new ArrayList>(2); + final List> defaultFilters = new ArrayList<>(2); defaultFilters.add(new IgnoreHiddenFileListFilter()); - defaultFilters.add(new AcceptOnceFileListFilter()); - this.filter = new CompositeFileListFilter(defaultFilters); + defaultFilters.add(new AcceptOnceFileListFilter<>()); + this.filter = new CompositeFileListFilter<>(defaultFilters); + } + + @Override + public void setFilter(FileListFilter filter) { + this.filter = filter; + } + + @Override + public final void setLocker(FileLocker locker) { + this.locker = locker; } /** - * {@inheritDoc} - *

- * This class takes the minimal implementation and merely delegates to the - * locker if set. + * This class takes the minimal implementation and merely delegates to the locker if set. + * @param file the file to try to claim. */ + @Override public final boolean tryClaim(File file) { return (this.locker == null) || this.locker.lock(file); } + @Override public final List listFiles(File directory) throws IllegalArgumentException { File[] files = listEligibleFiles(directory); if (files == null) { @@ -89,7 +89,6 @@ public class DefaultDirectoryScanner implements DirectoryScanner { /** * Subclasses may refine the listing strategy by overriding this method. The * files returned here are passed onto the filter. - * * @param directory root directory to use for listing * @return the files this scanner should consider */ diff --git a/spring-integration-file/src/main/java/org/springframework/integration/file/FileLocker.java b/spring-integration-file/src/main/java/org/springframework/integration/file/FileLocker.java index c2fc25ea5f..6a27406984 100644 --- a/spring-integration-file/src/main/java/org/springframework/integration/file/FileLocker.java +++ b/spring-integration-file/src/main/java/org/springframework/integration/file/FileLocker.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -35,25 +35,24 @@ public interface FileLocker { /** * Tries to lock the given file and returns true if it was * successful, false otherwise. - * - * @param fileToLock the file that should be locked according to this locker - * @return true if successful. - */ + * @param fileToLock the file that should be locked according to this locker + * @return true if successful. + */ boolean lock(File fileToLock); - /** - * Checks whether the file passed in can be locked by this locker. This method never changes the locked state. - * - * @param file The file. - * @return true if the file was locked by another locker than this locker - */ - boolean isLockable(File file); + /** + * Checks whether the file passed in can be locked by this locker. This method never changes the locked state. + * + * @param file The file. + * @return true if the file was locked by another locker than this locker + */ + boolean isLockable(File file); /** * Unlocks the given file. - * - * @param fileToUnlock the file that should be unlocked according to this locker - */ + * + * @param fileToUnlock the file that should be unlocked according to this locker + */ void unlock(File fileToUnlock); } diff --git a/spring-integration-file/src/main/java/org/springframework/integration/file/FileWritingMessageHandler.java b/spring-integration-file/src/main/java/org/springframework/integration/file/FileWritingMessageHandler.java index 340b226f7d..25911600b6 100644 --- a/spring-integration-file/src/main/java/org/springframework/integration/file/FileWritingMessageHandler.java +++ b/spring-integration-file/src/main/java/org/springframework/integration/file/FileWritingMessageHandler.java @@ -352,7 +352,7 @@ public class FileWritingMessageHandler extends AbstractReplyProducingMessageHand } Assert.state(!(this.temporaryFileSuffixSet - && (FileExistsMode.APPEND.equals(this.fileExistsMode) + && (FileExistsMode.APPEND.equals(this.fileExistsMode) || FileExistsMode.APPEND_NO_FLUSH.equals(this.fileExistsMode))), "'temporaryFileSuffix' can not be set when appending to an existing file"); @@ -510,7 +510,7 @@ public class FileWritingMessageHandler extends AbstractReplyProducingMessageHand } private File handleInputStreamMessage(final InputStream sourceFileInputStream, File originalFile, File tempFile, - final File resultFile) throws IOException { + final File resultFile) throws IOException { final boolean append = FileExistsMode.APPEND.equals(this.fileExistsMode) || FileExistsMode.APPEND_NO_FLUSH.equals(this.fileExistsMode); @@ -879,7 +879,7 @@ public class FileWritingMessageHandler extends AbstractReplyProducingMessageHand private final BufferedWriter writer; - private final BufferedOutputStream stream; + private final BufferedOutputStream stream; private volatile long lastWrite; diff --git a/spring-integration-file/src/main/java/org/springframework/integration/file/config/FileOutboundGatewayParser.java b/spring-integration-file/src/main/java/org/springframework/integration/file/config/FileOutboundGatewayParser.java index 284b76a4f5..005cb63335 100644 --- a/spring-integration-file/src/main/java/org/springframework/integration/file/config/FileOutboundGatewayParser.java +++ b/spring-integration-file/src/main/java/org/springframework/integration/file/config/FileOutboundGatewayParser.java @@ -16,12 +16,12 @@ package org.springframework.integration.file.config; -import org.springframework.integration.config.xml.IntegrationNamespaceUtils; import org.w3c.dom.Element; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.integration.config.xml.AbstractConsumerEndpointParser; +import org.springframework.integration.config.xml.IntegrationNamespaceUtils; /** * Parser for the 'outbound-gateway' element of the file namespace. @@ -46,7 +46,7 @@ public class FileOutboundGatewayParser extends AbstractConsumerEndpointParser { IntegrationNamespaceUtils.setValueIfAttributeDefined(handlerBuilder, element, "reply-timeout", "sendTimeout"); IntegrationNamespaceUtils.setValueIfAttributeDefined(handlerBuilder, element, "requires-reply"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(handlerBuilder, element, "reply-channel", "outputChannel"); - return handlerBuilder; + return handlerBuilder; } } diff --git a/spring-integration-file/src/main/java/org/springframework/integration/file/config/FileTailInboundChannelAdapterFactoryBean.java b/spring-integration-file/src/main/java/org/springframework/integration/file/config/FileTailInboundChannelAdapterFactoryBean.java index 4128b99d4e..f8feb79891 100644 --- a/spring-integration-file/src/main/java/org/springframework/integration/file/config/FileTailInboundChannelAdapterFactoryBean.java +++ b/spring-integration-file/src/main/java/org/springframework/integration/file/config/FileTailInboundChannelAdapterFactoryBean.java @@ -186,7 +186,7 @@ public class FileTailInboundChannelAdapterFactoryBean extends AbstractFactoryBea } else { Assert.isTrue(this.nativeOptions == null, - "'native-options' is not allowed with 'delay', 'end', or 'reopen'"); + "'native-options' is not allowed with 'delay', 'end', or 'reopen'"); adapter = new ApacheCommonsFileTailingMessageProducer(); if (this.delay != null) { ((ApacheCommonsFileTailingMessageProducer) adapter).setPollingDelay(this.delay); diff --git a/spring-integration-file/src/main/java/org/springframework/integration/file/filters/AbstractFileListFilter.java b/spring-integration-file/src/main/java/org/springframework/integration/file/filters/AbstractFileListFilter.java index 0e58abd00c..745d940c08 100644 --- a/spring-integration-file/src/main/java/org/springframework/integration/file/filters/AbstractFileListFilter.java +++ b/spring-integration-file/src/main/java/org/springframework/integration/file/filters/AbstractFileListFilter.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2014 the original author or authors. + * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,28 +29,24 @@ import java.util.List; */ public abstract class AbstractFileListFilter implements FileListFilter { - /** - * {@inheritDoc} - */ - @Override + @Override public final List filterFiles(F[] files) { - List accepted = new ArrayList(); - if (files != null) { - for (F file : files) { - if (this.accept(file)) { - accepted.add(file); - } - } - } - return accepted; - } + List accepted = new ArrayList(); + if (files != null) { + for (F file : files) { + if (this.accept(file)) { + accepted.add(file); + } + } + } + return accepted; + } - /** - * Subclasses must implement this method. - * - * @param file The file. - * @return true if the file passes the filter. - */ - protected abstract boolean accept(F file); + /** + * Subclasses must implement this method. + * @param file The file. + * @return true if the file passes the filter. + */ + protected abstract boolean accept(F file); } diff --git a/spring-integration-file/src/main/java/org/springframework/integration/file/filters/FileListFilter.java b/spring-integration-file/src/main/java/org/springframework/integration/file/filters/FileListFilter.java index 875d496c52..00518c8bd5 100644 --- a/spring-integration-file/src/main/java/org/springframework/integration/file/filters/FileListFilter.java +++ b/spring-integration-file/src/main/java/org/springframework/integration/file/filters/FileListFilter.java @@ -30,13 +30,12 @@ import java.util.List; @FunctionalInterface public interface FileListFilter { - /** - * Filters out files and returns the files that are left in a list, or an - * empty list when a null is passed in. - * - * @param files The files. - * @return The filtered files. - */ - List filterFiles(F[] files); + /** + * Filters out files and returns the files that are left in a list, or an + * empty list when a null is passed in. + * @param files The files. + * @return The filtered files. + */ + List filterFiles(F[] files); } diff --git a/spring-integration-file/src/main/java/org/springframework/integration/file/locking/AbstractFileLockerFilter.java b/spring-integration-file/src/main/java/org/springframework/integration/file/locking/AbstractFileLockerFilter.java index d7d865426a..03d6a9923b 100644 --- a/spring-integration-file/src/main/java/org/springframework/integration/file/locking/AbstractFileLockerFilter.java +++ b/spring-integration-file/src/main/java/org/springframework/integration/file/locking/AbstractFileLockerFilter.java @@ -31,9 +31,9 @@ import org.springframework.integration.file.filters.AbstractFileListFilter; */ public abstract class AbstractFileLockerFilter extends AbstractFileListFilter implements FileLocker { - @Override - public boolean accept(File file) { - return this.isLockable(file); - } + @Override + public boolean accept(File file) { + return this.isLockable(file); + } } diff --git a/spring-integration-file/src/main/java/org/springframework/integration/file/locking/NioFileLocker.java b/spring-integration-file/src/main/java/org/springframework/integration/file/locking/NioFileLocker.java index d8ae1150d5..1039ef8081 100644 --- a/spring-integration-file/src/main/java/org/springframework/integration/file/locking/NioFileLocker.java +++ b/spring-integration-file/src/main/java/org/springframework/integration/file/locking/NioFileLocker.java @@ -16,15 +16,15 @@ package org.springframework.integration.file.locking; -import org.springframework.messaging.MessagingException; -import org.springframework.integration.file.FileReadingMessageSource; - import java.io.File; import java.io.IOException; import java.nio.channels.FileLock; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import org.springframework.integration.file.FileReadingMessageSource; +import org.springframework.messaging.MessagingException; + /** * File locking strategy that uses java.nio. The locks taken by FileChannel are shared with all the threads in a single * JVM, so this locking strategy does not prevent files being picked up multiple times within the same JVM. @@ -39,45 +39,44 @@ import java.util.concurrent.ConcurrentMap; */ public class NioFileLocker extends AbstractFileLockerFilter { - private final ConcurrentMap lockCache = new ConcurrentHashMap(); + private final ConcurrentMap lockCache = new ConcurrentHashMap(); - /** - * {@inheritDoc} - */ - public boolean lock(File fileToLock) { - FileLock lock = this.lockCache.get(fileToLock); - if (lock == null) { - FileLock newLock = null; - try { - newLock = FileChannelCache.tryLockFor(fileToLock); - } -catch (IOException e) { - throw new MessagingException("Failed to lock file: " - + fileToLock, e); - } - if (newLock != null) { - FileLock original = this.lockCache.putIfAbsent(fileToLock, newLock); - lock = original != null ? original : newLock; - } - } - return lock != null; - } - - public boolean isLockable(File file) { - return this.lockCache.containsKey(file) || !FileChannelCache.isLocked(file); - } - - public void unlock(File fileToUnlock) { - FileLock fileLock = this.lockCache.get(fileToUnlock); - try { - if (fileLock != null) { - fileLock.release(); - } - FileChannelCache.closeChannelFor(fileToUnlock); - } -catch (IOException e) { - throw new MessagingException("Failed to unlock file: " - + fileToUnlock, e); - } + @Override + public boolean lock(File fileToLock) { + FileLock lock = this.lockCache.get(fileToLock); + if (lock == null) { + FileLock newLock = null; + try { + newLock = FileChannelCache.tryLockFor(fileToLock); + } + catch (IOException e) { + throw new MessagingException("Failed to lock file: " + fileToLock, e); + } + if (newLock != null) { + FileLock original = this.lockCache.putIfAbsent(fileToLock, newLock); + lock = original != null ? original : newLock; + } + } + return lock != null; } + + @Override + public boolean isLockable(File file) { + return this.lockCache.containsKey(file) || !FileChannelCache.isLocked(file); + } + + @Override + public void unlock(File fileToUnlock) { + FileLock fileLock = this.lockCache.get(fileToUnlock); + try { + if (fileLock != null) { + fileLock.release(); + } + FileChannelCache.closeChannelFor(fileToUnlock); + } + catch (IOException e) { + throw new MessagingException("Failed to unlock file: " + fileToUnlock, e); + } + } + } diff --git a/spring-integration-file/src/main/java/org/springframework/integration/file/remote/RemoteFileTemplate.java b/spring-integration-file/src/main/java/org/springframework/integration/file/remote/RemoteFileTemplate.java index 6963fa6c09..b95f071851 100644 --- a/spring-integration-file/src/main/java/org/springframework/integration/file/remote/RemoteFileTemplate.java +++ b/spring-integration-file/src/main/java/org/springframework/integration/file/remote/RemoteFileTemplate.java @@ -357,13 +357,13 @@ public class RemoteFileTemplate implements RemoteFileOperations, Initializ Assert.hasText(toPath, "New filename cannot be null or empty"); this.execute((SessionCallbackWithoutResult) session -> { - int lastSeparator = toPath.lastIndexOf(RemoteFileTemplate.this.remoteFileSeparator); - if (lastSeparator > 0) { - String remoteFileDirectory = toPath.substring(0, lastSeparator + 1); - RemoteFileUtils.makeDirectories(remoteFileDirectory, session, - RemoteFileTemplate.this.remoteFileSeparator, RemoteFileTemplate.this.logger); - } - session.rename(fromPath, toPath); + int lastSeparator = toPath.lastIndexOf(RemoteFileTemplate.this.remoteFileSeparator); + if (lastSeparator > 0) { + String remoteFileDirectory = toPath.substring(0, lastSeparator + 1); + RemoteFileUtils.makeDirectories(remoteFileDirectory, session, + RemoteFileTemplate.this.remoteFileSeparator, RemoteFileTemplate.this.logger); + } + session.rename(fromPath, toPath); }); } @@ -461,7 +461,7 @@ public class RemoteFileTemplate implements RemoteFileOperations, Initializ } else { throw new IllegalArgumentException("Unsupported payload type. The only supported payloads are " + - "java.io.File, java.lang.String, and byte[]"); + "java.io.File, java.lang.String, and byte[]"); } if (dataInputStream == null) { return null; @@ -524,7 +524,7 @@ public class RemoteFileTemplate implements RemoteFileOperations, Initializ } // then rename it to its final name if necessary if (rename) { - session.rename(tempFilePath, remoteFilePath); + session.rename(tempFilePath, remoteFilePath); } } catch (Exception e) { diff --git a/spring-integration-file/src/main/java/org/springframework/integration/file/remote/gateway/AbstractRemoteFileOutboundGateway.java b/spring-integration-file/src/main/java/org/springframework/integration/file/remote/gateway/AbstractRemoteFileOutboundGateway.java index 2aeeb64513..b552d8d0b2 100644 --- a/spring-integration-file/src/main/java/org/springframework/integration/file/remote/gateway/AbstractRemoteFileOutboundGateway.java +++ b/spring-integration-file/src/main/java/org/springframework/integration/file/remote/gateway/AbstractRemoteFileOutboundGateway.java @@ -308,8 +308,7 @@ public abstract class AbstractRemoteFileOutboundGateway extends AbstractReply this.remoteFileTemplate = remoteFileTemplate; this.command = command; Expression parsedExpression = new SpelExpressionParser().parseExpression(expression); - this.fileNameProcessor = new ExpressionEvaluatingMessageProcessor( - parsedExpression); + this.fileNameProcessor = new ExpressionEvaluatingMessageProcessor<>(parsedExpression); this.messageSessionCallback = null; setPrimaryExpression(parsedExpression); } @@ -491,8 +490,8 @@ public abstract class AbstractRemoteFileOutboundGateway extends AbstractReply } if (Command.MGET.equals(this.command)) { Assert.isTrue(!(this.options.contains(Option.SUBDIRS)), - "Cannot use " + Option.SUBDIRS.toString() + " when using 'mget' use " - + Option.RECURSIVE.toString() + " to obtain files in subdirectories"); + "Cannot use " + Option.SUBDIRS.toString() + " when using 'mget' use " + + Option.RECURSIVE.toString() + " to obtain files in subdirectories"); } if (this.fileNameProcessor != null && getBeanFactory() != null) { this.fileNameProcessor.setBeanFactory(this.getBeanFactory()); @@ -505,20 +504,20 @@ public abstract class AbstractRemoteFileOutboundGateway extends AbstractReply protected Object handleRequestMessage(final Message requestMessage) { if (this.command != null) { switch (this.command) { - case LS: - return doLs(requestMessage); - case GET: - return doGet(requestMessage); - case MGET: - return doMget(requestMessage); - case RM: - return doRm(requestMessage); - case MV: - return doMv(requestMessage); - case PUT: - return doPut(requestMessage); - case MPUT: - return doMput(requestMessage); + case LS: + return doLs(requestMessage); + case GET: + return doGet(requestMessage); + case MGET: + return doMget(requestMessage); + case RM: + return doRm(requestMessage); + case MV: + return doMv(requestMessage); + case PUT: + return doPut(requestMessage); + case MPUT: + return doMput(requestMessage); } } return this.remoteFileTemplate.execute(new SessionCallback() { @@ -546,8 +545,8 @@ public abstract class AbstractRemoteFileOutboundGateway extends AbstractReply } }); return this.getMessageBuilderFactory().withPayload(payload) - .setHeader(FileHeaders.REMOTE_DIRECTORY, dir) - .build(); + .setHeader(FileHeaders.REMOTE_DIRECTORY, dir) + .build(); } private Object doGet(final Message requestMessage) { @@ -597,9 +596,9 @@ public abstract class AbstractRemoteFileOutboundGateway extends AbstractReply } }); return this.getMessageBuilderFactory().withPayload(payload) - .setHeader(FileHeaders.REMOTE_DIRECTORY, remoteDir) - .setHeader(FileHeaders.REMOTE_FILE, remoteFilename) - .build(); + .setHeader(FileHeaders.REMOTE_DIRECTORY, remoteDir) + .setHeader(FileHeaders.REMOTE_FILE, remoteFilename) + .build(); } private Object doRm(Message requestMessage) { @@ -610,13 +609,13 @@ public abstract class AbstractRemoteFileOutboundGateway extends AbstractReply boolean payload = this.remoteFileTemplate.remove(remoteFilePath); return this.getMessageBuilderFactory().withPayload(payload) - .setHeader(FileHeaders.REMOTE_DIRECTORY, remoteDir) - .setHeader(FileHeaders.REMOTE_FILE, remoteFilename) - .build(); + .setHeader(FileHeaders.REMOTE_DIRECTORY, remoteDir) + .setHeader(FileHeaders.REMOTE_FILE, remoteFilename) + .build(); } private Object doMv(Message requestMessage) { - String remoteFilePath = this.fileNameProcessor.processMessage(requestMessage); + String remoteFilePath = this.fileNameProcessor.processMessage(requestMessage); String remoteFilename = getRemoteFilename(remoteFilePath); String remoteDir = getRemoteDirectory(remoteFilePath, remoteFilename); String remoteFileNewPath = this.renameProcessor.processMessage(requestMessage); @@ -624,10 +623,10 @@ public abstract class AbstractRemoteFileOutboundGateway extends AbstractReply this.remoteFileTemplate.rename(remoteFilePath, remoteFileNewPath); return this.getMessageBuilderFactory().withPayload(Boolean.TRUE) - .setHeader(FileHeaders.REMOTE_DIRECTORY, remoteDir) - .setHeader(FileHeaders.REMOTE_FILE, remoteFilename) - .setHeader(FileHeaders.RENAME_TO, remoteFileNewPath) - .build(); + .setHeader(FileHeaders.REMOTE_DIRECTORY, remoteDir) + .setHeader(FileHeaders.REMOTE_FILE, remoteFilename) + .setHeader(FileHeaders.RENAME_TO, remoteFileNewPath) + .build(); } private String doPut(Message requestMessage) { @@ -698,7 +697,7 @@ public abstract class AbstractRemoteFileOutboundGateway extends AbstractReply else if (this.options.contains(Option.RECURSIVE)) { String newSubDirectory = (StringUtils.hasText(subDirectory) ? subDirectory + this.remoteFileTemplate.getRemoteFileSeparator() : "") - + filteredFile.getName(); + + filteredFile.getName(); replies.addAll(this.putLocalDirectory(requestMessage, filteredFile, newSubDirectory)); } } @@ -771,7 +770,7 @@ public abstract class AbstractRemoteFileOutboundGateway extends AbstractReply } } if (recursion && this.isDirectory(file) && !(".".equals(fileName)) && !("..".equals(fileName))) { - lsFiles.addAll(listFilesInRemoteDir(session, directory, subDirectory + fileName + lsFiles.addAll(listFilesInRemoteDir(session, directory, subDirectory + fileName + this.remoteFileTemplate.getRemoteFileSeparator())); } } @@ -834,7 +833,7 @@ public abstract class AbstractRemoteFileOutboundGateway extends AbstractReply * @throws IOException Any IOException. */ protected File get(Message message, Session session, String remoteDir, String remoteFilePath, - String remoteFilename, boolean lsFirst) throws IOException { + String remoteFilename, boolean lsFirst) throws IOException { F[] files = null; if (lsFirst) { files = session.list(remoteFilePath); @@ -907,7 +906,7 @@ public abstract class AbstractRemoteFileOutboundGateway extends AbstractReply } protected List mGet(Message message, Session session, String remoteDirectory, - String remoteFilename) throws IOException { + String remoteFilename) throws IOException { if (this.options.contains(Option.RECURSIVE)) { if (logger.isWarnEnabled() && !("*".equals(remoteFilename))) { logger.warn("File name pattern must be '*' when using recursion"); @@ -991,7 +990,7 @@ public abstract class AbstractRemoteFileOutboundGateway extends AbstractReply String fileName = this.getRemoteFilename(fullFileName); String actualRemoteDirectory = this.getRemoteDirectory(fullFileName, fileName); File file = this.get(message, session, actualRemoteDirectory, - fullFileName, fileName, false); + fullFileName, fileName, false); files.add(file); } } diff --git a/spring-integration-file/src/main/java/org/springframework/integration/file/transformer/AbstractFilePayloadTransformer.java b/spring-integration-file/src/main/java/org/springframework/integration/file/transformer/AbstractFilePayloadTransformer.java index a817af5174..65289ab6f8 100644 --- a/spring-integration-file/src/main/java/org/springframework/integration/file/transformer/AbstractFilePayloadTransformer.java +++ b/spring-integration-file/src/main/java/org/springframework/integration/file/transformer/AbstractFilePayloadTransformer.java @@ -84,22 +84,22 @@ public abstract class AbstractFilePayloadTransformer implements Transformer, Assert.notNull(payload, "Message payload must not be null"); Assert.isInstanceOf(File.class, payload, "Message payload must be of type [java.io.File]"); File file = (File) payload; - T result = this.transformFile(file); - Message transformedMessage = getMessageBuilderFactory().withPayload(result) - .copyHeaders(message.getHeaders()) - .setHeaderIfAbsent(FileHeaders.ORIGINAL_FILE, file) - .setHeaderIfAbsent(FileHeaders.FILENAME, file.getName()) - .build(); + T result = this.transformFile(file); + Message transformedMessage = getMessageBuilderFactory().withPayload(result) + .copyHeaders(message.getHeaders()) + .setHeaderIfAbsent(FileHeaders.ORIGINAL_FILE, file) + .setHeaderIfAbsent(FileHeaders.FILENAME, file.getName()) + .build(); if (this.deleteFiles) { if (!file.delete() && this.logger.isWarnEnabled()) { this.logger.warn("failed to delete File '" + file + "'"); } } return transformedMessage; - } -catch (Exception e) { - throw new MessagingException(message, "failed to transform File Message", e); - } + } + catch (Exception e) { + throw new MessagingException(message, "failed to transform File Message", e); + } } /** diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceIntegrationTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceIntegrationTests.java index 7e02d3db12..b0bdf28bf0 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceIntegrationTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourceIntegrationTests.java @@ -54,9 +54,9 @@ public class FileReadingMessageSourceIntegrationTests { @AfterClass public static void cleanUp() throws Throwable { - if (inputDir.exists()) { - inputDir.delete(); - } + if (inputDir.exists()) { + inputDir.delete(); + } } @BeforeClass @@ -184,8 +184,8 @@ public class FileReadingMessageSourceIntegrationTests { * Convenience method to run part of a test concurrently in multiple threads * * @param numberOfThreads how many threads to spawn - * @param runnable the runnable that should be run by all the threads - * @param start the {@link java.util.concurrent.CountDownLatch} instance + * @param runnable the runnable that should be run by all the threads + * @param start the {@link java.util.concurrent.CountDownLatch} instance * telling it when to assume everything works * @return a latch that will be counted down once all threads have run their * runnable. diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourcePersistentFilterIntegrationTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourcePersistentFilterIntegrationTests.java index 16526160f0..a06330af98 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourcePersistentFilterIntegrationTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/FileReadingMessageSourcePersistentFilterIntegrationTests.java @@ -48,9 +48,9 @@ public class FileReadingMessageSourcePersistentFilterIntegrationTests { @AfterClass public static void cleanUp() throws Throwable { - if (inputDir.exists()) { - inputDir.delete(); - } + if (inputDir.exists()) { + inputDir.delete(); + } } @BeforeClass diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/AutoCreateDirectoryIntegrationTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/AutoCreateDirectoryIntegrationTests.java index 2918672304..a7d9ac64d2 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/AutoCreateDirectoryIntegrationTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/AutoCreateDirectoryIntegrationTests.java @@ -16,10 +16,16 @@ package org.springframework.integration.file.config; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.File; + import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; + import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; @@ -28,11 +34,6 @@ import org.springframework.integration.file.FileWritingMessageHandler; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import java.io.File; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - /** * @author Mark Fisher */ @@ -40,92 +41,92 @@ import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) public class AutoCreateDirectoryIntegrationTests { - private static final String BASE_PATH = - System.getProperty("java.io.tmpdir") + File.separator + AutoCreateDirectoryIntegrationTests.class.getSimpleName(); + private static final String BASE_PATH = + System.getProperty("java.io.tmpdir") + File.separator + AutoCreateDirectoryIntegrationTests.class.getSimpleName(); - @Autowired - private ApplicationContext context; + @Autowired + private ApplicationContext context; - @BeforeClass - public static void setupNonAutoCreatedDirectories() { - new File(BASE_PATH).delete(); - new File(BASE_PATH + File.separator + "customInbound").mkdirs(); - new File(BASE_PATH + File.separator + "customOutbound").mkdirs(); - new File(BASE_PATH + File.separator + "customOutboundGateway").mkdirs(); - } + @BeforeClass + public static void setupNonAutoCreatedDirectories() { + new File(BASE_PATH).delete(); + new File(BASE_PATH + File.separator + "customInbound").mkdirs(); + new File(BASE_PATH + File.separator + "customOutbound").mkdirs(); + new File(BASE_PATH + File.separator + "customOutboundGateway").mkdirs(); + } - @AfterClass - public static void deleteBaseDirectory() { - new File(BASE_PATH).delete(); - } + @AfterClass + public static void deleteBaseDirectory() { + new File(BASE_PATH).delete(); + } - @Test - public void defaultInbound() throws Exception { - Object adapter = context.getBean("defaultInbound"); - DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); - FileReadingMessageSource source = (FileReadingMessageSource) - adapterAccessor.getPropertyValue("source"); - assertEquals(Boolean.TRUE, - new DirectFieldAccessor(source).getPropertyValue("autoCreateDirectory")); - assertTrue(new File(BASE_PATH + File.separator + "defaultInbound").exists()); - } + @Test + public void defaultInbound() throws Exception { + Object adapter = context.getBean("defaultInbound"); + DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); + FileReadingMessageSource source = (FileReadingMessageSource) + adapterAccessor.getPropertyValue("source"); + assertEquals(Boolean.TRUE, + new DirectFieldAccessor(source).getPropertyValue("autoCreateDirectory")); + assertTrue(new File(BASE_PATH + File.separator + "defaultInbound").exists()); + } - @Test - public void customInbound() throws Exception { - Object adapter = context.getBean("customInbound"); - DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); - FileReadingMessageSource source = (FileReadingMessageSource) - adapterAccessor.getPropertyValue("source"); - assertTrue(new File(BASE_PATH + File.separator + "customInbound").exists()); - assertEquals(Boolean.FALSE, - new DirectFieldAccessor(source).getPropertyValue("autoCreateDirectory")); - } + @Test + public void customInbound() throws Exception { + Object adapter = context.getBean("customInbound"); + DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); + FileReadingMessageSource source = (FileReadingMessageSource) + adapterAccessor.getPropertyValue("source"); + assertTrue(new File(BASE_PATH + File.separator + "customInbound").exists()); + assertEquals(Boolean.FALSE, + new DirectFieldAccessor(source).getPropertyValue("autoCreateDirectory")); + } - @Test - public void defaultOutbound() throws Exception { - Object adapter = context.getBean("defaultOutbound"); - DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); - FileWritingMessageHandler handler = (FileWritingMessageHandler) - adapterAccessor.getPropertyValue("handler"); - assertEquals(Boolean.TRUE, - new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")); - assertTrue(new File(BASE_PATH + File.separator + "defaultOutbound").exists()); - } + @Test + public void defaultOutbound() throws Exception { + Object adapter = context.getBean("defaultOutbound"); + DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); + FileWritingMessageHandler handler = (FileWritingMessageHandler) + adapterAccessor.getPropertyValue("handler"); + assertEquals(Boolean.TRUE, + new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")); + assertTrue(new File(BASE_PATH + File.separator + "defaultOutbound").exists()); + } - @Test - public void customOutbound() throws Exception { - Object adapter = context.getBean("customOutbound"); - DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); - FileWritingMessageHandler handler = (FileWritingMessageHandler) - adapterAccessor.getPropertyValue("handler"); - assertTrue(new File(BASE_PATH + File.separator + "customOutbound").exists()); - assertEquals(Boolean.FALSE, - new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")); - } + @Test + public void customOutbound() throws Exception { + Object adapter = context.getBean("customOutbound"); + DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter); + FileWritingMessageHandler handler = (FileWritingMessageHandler) + adapterAccessor.getPropertyValue("handler"); + assertTrue(new File(BASE_PATH + File.separator + "customOutbound").exists()); + assertEquals(Boolean.FALSE, + new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")); + } - @Test - public void defaultOutboundGateway() throws Exception { - Object gateway = context.getBean("defaultOutboundGateway"); - DirectFieldAccessor gatewayAccessor = new DirectFieldAccessor(gateway); - FileWritingMessageHandler handler = (FileWritingMessageHandler) - gatewayAccessor.getPropertyValue("handler"); - assertEquals(Boolean.TRUE, - new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")); - assertTrue(new File(BASE_PATH + File.separator + "defaultOutboundGateway").exists()); - } + @Test + public void defaultOutboundGateway() throws Exception { + Object gateway = context.getBean("defaultOutboundGateway"); + DirectFieldAccessor gatewayAccessor = new DirectFieldAccessor(gateway); + FileWritingMessageHandler handler = (FileWritingMessageHandler) + gatewayAccessor.getPropertyValue("handler"); + assertEquals(Boolean.TRUE, + new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")); + assertTrue(new File(BASE_PATH + File.separator + "defaultOutboundGateway").exists()); + } - @Test - public void customOutboundGateway() throws Exception { - Object gateway = context.getBean("customOutboundGateway"); - DirectFieldAccessor gatewayAccessor = new DirectFieldAccessor(gateway); - FileWritingMessageHandler handler = (FileWritingMessageHandler) - gatewayAccessor.getPropertyValue("handler"); - assertTrue(new File(BASE_PATH + File.separator + "customOutboundGateway").exists()); - assertEquals(Boolean.FALSE, - new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")); - } + @Test + public void customOutboundGateway() throws Exception { + Object gateway = context.getBean("customOutboundGateway"); + DirectFieldAccessor gatewayAccessor = new DirectFieldAccessor(gateway); + FileWritingMessageHandler handler = (FileWritingMessageHandler) + gatewayAccessor.getPropertyValue("handler"); + assertTrue(new File(BASE_PATH + File.separator + "customOutboundGateway").exists()); + assertEquals(Boolean.FALSE, + new DirectFieldAccessor(handler).getPropertyValue("autoCreateDirectory")); + } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/CustomFileNameGenerator.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/CustomFileNameGenerator.java index 0d7e93cd87..7f4ab632aa 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/CustomFileNameGenerator.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/CustomFileNameGenerator.java @@ -16,18 +16,18 @@ package org.springframework.integration.file.config; -import org.springframework.messaging.Message; -import org.springframework.integration.file.FileNameGenerator; - import java.util.Date; +import org.springframework.integration.file.FileNameGenerator; +import org.springframework.messaging.Message; + /** * @author Marius Bogoevici */ public class CustomFileNameGenerator implements FileNameGenerator { - public String generateFileName(Message message) { - return "file" + new Date().getTime(); - } + public String generateFileName(Message message) { + return "file" + new Date().getTime(); + } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithPatternParserTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithPatternParserTests.java index 5eab436483..9c14b9382d 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithPatternParserTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileInboundChannelAdapterWithPatternParserTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2010 the original author or authors. + * Copyright 2002-2016 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,85 +49,85 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) public class FileInboundChannelAdapterWithPatternParserTests { - @Autowired(required = true) - private ApplicationContext context; + @Autowired + private ApplicationContext context; - @Autowired(required = true) - @Qualifier("adapterWithPattern.adapter") - private AbstractEndpoint endpoint; + @Autowired + @Qualifier("adapterWithPattern.adapter") + private AbstractEndpoint endpoint; - private DirectFieldAccessor accessor; + private DirectFieldAccessor accessor; - @Autowired(required = true) - public void setSource(FileReadingMessageSource source) { - this.accessor = new DirectFieldAccessor(source); - } + @Autowired + public void setSource(FileReadingMessageSource source) { + this.accessor = new DirectFieldAccessor(source); + } - @Test - public void channelName() { - AbstractMessageChannel channel = context.getBean("adapterWithPattern", AbstractMessageChannel.class); - assertEquals("adapterWithPattern", channel.getComponentName()); - } + @Test + public void channelName() { + AbstractMessageChannel channel = context.getBean("adapterWithPattern", AbstractMessageChannel.class); + assertEquals("adapterWithPattern", channel.getComponentName()); + } - @Test - public void autoStartupDisabled() { - assertFalse(this.endpoint.isRunning()); - assertEquals(Boolean.FALSE, new DirectFieldAccessor(endpoint).getPropertyValue("autoStartup")); - } + @Test + public void autoStartupDisabled() { + assertFalse(this.endpoint.isRunning()); + assertEquals(Boolean.FALSE, new DirectFieldAccessor(endpoint).getPropertyValue("autoStartup")); + } - @Test - public void inputDirectory() { - File expected = new File(System.getProperty("java.io.tmpdir")); - File actual = (File) accessor.getPropertyValue("directory"); - assertEquals(expected, actual); - } + @Test + public void inputDirectory() { + File expected = new File(System.getProperty("java.io.tmpdir")); + File actual = (File) accessor.getPropertyValue("directory"); + assertEquals(expected, actual); + } - @Test - public void compositeFilterType() { - DirectFieldAccessor scannerAccessor = new DirectFieldAccessor(accessor.getPropertyValue("scanner")); - assertTrue(scannerAccessor.getPropertyValue("filter") instanceof CompositeFileListFilter); - } + @Test + public void compositeFilterType() { + DirectFieldAccessor scannerAccessor = new DirectFieldAccessor(accessor.getPropertyValue("scanner")); + assertTrue(scannerAccessor.getPropertyValue("filter") instanceof CompositeFileListFilter); + } - @Test - @SuppressWarnings("unchecked") - public void compositeFilterSetSize() { - DirectFieldAccessor scannerAccessor = new DirectFieldAccessor(accessor.getPropertyValue("scanner")); - Set> filters = (Set>) new DirectFieldAccessor( - scannerAccessor.getPropertyValue("filter")).getPropertyValue("fileFilters"); - assertEquals(2, filters.size()); - } + @Test + @SuppressWarnings("unchecked") + public void compositeFilterSetSize() { + DirectFieldAccessor scannerAccessor = new DirectFieldAccessor(accessor.getPropertyValue("scanner")); + Set> filters = (Set>) new DirectFieldAccessor( + scannerAccessor.getPropertyValue("filter")).getPropertyValue("fileFilters"); + assertEquals(2, filters.size()); + } - @Test - @SuppressWarnings("unchecked") - public void acceptOnceFilter() { - DirectFieldAccessor scannerAccessor = new DirectFieldAccessor(accessor.getPropertyValue("scanner")); - Set> filters = (Set>) new DirectFieldAccessor( - scannerAccessor.getPropertyValue("filter")).getPropertyValue("fileFilters"); - boolean hasAcceptOnceFilter = false; - for (FileListFilter filter : filters) { - if (filter instanceof AcceptOnceFileListFilter) { - hasAcceptOnceFilter = true; - } - } - assertTrue("expected AcceptOnceFileListFilter", hasAcceptOnceFilter); - } + @Test + @SuppressWarnings("unchecked") + public void acceptOnceFilter() { + DirectFieldAccessor scannerAccessor = new DirectFieldAccessor(accessor.getPropertyValue("scanner")); + Set> filters = (Set>) new DirectFieldAccessor( + scannerAccessor.getPropertyValue("filter")).getPropertyValue("fileFilters"); + boolean hasAcceptOnceFilter = false; + for (FileListFilter filter : filters) { + if (filter instanceof AcceptOnceFileListFilter) { + hasAcceptOnceFilter = true; + } + } + assertTrue("expected AcceptOnceFileListFilter", hasAcceptOnceFilter); + } - @Test - @SuppressWarnings("unchecked") - public void patternFilter() { - DirectFieldAccessor scannerAccessor = new DirectFieldAccessor(accessor.getPropertyValue("scanner")); - Set> filters = (Set>) new DirectFieldAccessor( - scannerAccessor.getPropertyValue("filter")).getPropertyValue("fileFilters"); - String pattern = null; - for (FileListFilter filter : filters) { - if (filter instanceof SimplePatternFileListFilter) { - pattern = (String) new DirectFieldAccessor(filter).getPropertyValue("path"); - } - } - assertNotNull("expected SimplePatternFileListFilterTest", pattern); - assertEquals("*.txt", pattern.toString()); - } + @Test + @SuppressWarnings("unchecked") + public void patternFilter() { + DirectFieldAccessor scannerAccessor = new DirectFieldAccessor(accessor.getPropertyValue("scanner")); + Set> filters = (Set>) new DirectFieldAccessor( + scannerAccessor.getPropertyValue("filter")).getPropertyValue("fileFilters"); + String pattern = null; + for (FileListFilter filter : filters) { + if (filter instanceof SimplePatternFileListFilter) { + pattern = (String) new DirectFieldAccessor(filter).getPropertyValue("path"); + } + } + assertNotNull("expected SimplePatternFileListFilterTest", pattern); + assertEquals("*.txt", pattern.toString()); + } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileMessageHistoryTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileMessageHistoryTests.java index eaf1919b00..8068a1f23c 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileMessageHistoryTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileMessageHistoryTests.java @@ -53,17 +53,17 @@ public class FileMessageHistoryTests { TemporaryFolder input = context.getBean(TemporaryFolder.class); File file = input.newFile("FileMessageHistoryTest.txt"); BufferedWriter out = new BufferedWriter(new FileWriter(file)); - out.write("hello"); - out.close(); + out.write("hello"); + out.close(); - PollableChannel outChannel = context.getBean("outChannel", PollableChannel.class); - Message message = outChannel.receive(10000); + PollableChannel outChannel = context.getBean("outChannel", PollableChannel.class); + Message message = outChannel.receive(10000); assertThat(message, is(notNullValue())); - MessageHistory history = MessageHistory.read(message); - assertThat(history, is(notNullValue())); - Properties componentHistoryRecord = TestUtils.locateComponentInHistory(history, "fileAdapter", 0); - assertNotNull(componentHistoryRecord); - assertEquals("file:inbound-channel-adapter", componentHistoryRecord.get("type")); + MessageHistory history = MessageHistory.read(message); + assertThat(history, is(notNullValue())); + Properties componentHistoryRecord = TestUtils.locateComponentInHistory(history, "fileAdapter", 0); + assertNotNull(componentHistoryRecord); + assertEquals("file:inbound-channel-adapter", componentHistoryRecord.get("type")); context.close(); } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileToStringTransformerParserTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileToStringTransformerParserTests.java index 109f14a425..d45a2a124d 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileToStringTransformerParserTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/config/FileToStringTransformerParserTests.java @@ -38,20 +38,20 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) public class FileToStringTransformerParserTests { - @Autowired - @Qualifier("transformer") - EventDrivenConsumer endpoint; + @Autowired + @Qualifier("transformer") + EventDrivenConsumer endpoint; - @Test - public void checkDeleteFilesValue() { - DirectFieldAccessor endpointAccessor = new DirectFieldAccessor(endpoint); - MessageTransformingHandler handler = (MessageTransformingHandler) - endpointAccessor.getPropertyValue("handler"); - DirectFieldAccessor handlerAccessor = new DirectFieldAccessor(handler); - FileToStringTransformer transformer = (FileToStringTransformer) - handlerAccessor.getPropertyValue("transformer"); - DirectFieldAccessor transformerAccessor = new DirectFieldAccessor(transformer); - assertEquals(Boolean.TRUE, transformerAccessor.getPropertyValue("deleteFiles")); - } + @Test + public void checkDeleteFilesValue() { + DirectFieldAccessor endpointAccessor = new DirectFieldAccessor(endpoint); + MessageTransformingHandler handler = (MessageTransformingHandler) + endpointAccessor.getPropertyValue("handler"); + DirectFieldAccessor handlerAccessor = new DirectFieldAccessor(handler); + FileToStringTransformer transformer = (FileToStringTransformer) + handlerAccessor.getPropertyValue("transformer"); + DirectFieldAccessor transformerAccessor = new DirectFieldAccessor(transformer); + assertEquals(Boolean.TRUE, transformerAccessor.getPropertyValue("deleteFiles")); + } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/locking/NioFileLockerTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/locking/NioFileLockerTests.java index 7a87f179c9..3aa230cd64 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/locking/NioFileLockerTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/locking/NioFileLockerTests.java @@ -35,10 +35,11 @@ import org.springframework.integration.file.filters.FileListFilter; */ public class NioFileLockerTests { - private File workdir; + private File workdir; @Rule public TemporaryFolder temp = new TemporaryFolder() { + @Override public void create() throws IOException { super.create(); @@ -46,25 +47,25 @@ public class NioFileLockerTests { } }; - @Test - public void fileListedByFirstFilter() throws IOException { - NioFileLocker filter = new NioFileLocker(); - File testFile = new File(workdir, "test0"); - testFile.createNewFile(); - assertThat(filter.filterFiles(workdir.listFiles()).get(0), is(testFile)); - filter.lock(testFile); - assertThat(filter.filterFiles(workdir.listFiles()).get(0), is(testFile)); - } + @Test + public void fileListedByFirstFilter() throws IOException { + NioFileLocker filter = new NioFileLocker(); + File testFile = new File(workdir, "test0"); + testFile.createNewFile(); + assertThat(filter.filterFiles(workdir.listFiles()).get(0), is(testFile)); + filter.lock(testFile); + assertThat(filter.filterFiles(workdir.listFiles()).get(0), is(testFile)); + } - @Test - public void fileNotListedWhenLockedByOtherFilter() throws IOException { - NioFileLocker filter1 = new NioFileLocker(); - FileListFilter filter2 = new NioFileLocker(); - File testFile = new File(workdir, "test1"); - testFile.createNewFile(); - assertThat(filter1.filterFiles(workdir.listFiles()).get(0), is(testFile)); - filter1.lock(testFile); - assertThat(filter2.filterFiles(workdir.listFiles()), is((List) new ArrayList())); - } + @Test + public void fileNotListedWhenLockedByOtherFilter() throws IOException { + NioFileLocker filter1 = new NioFileLocker(); + FileListFilter filter2 = new NioFileLocker(); + File testFile = new File(workdir, "test1"); + testFile.createNewFile(); + assertThat(filter1.filterFiles(workdir.listFiles()).get(0), is(testFile)); + filter1.lock(testFile); + assertThat(filter2.filterFiles(workdir.listFiles()), is((List) new ArrayList())); + } } diff --git a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/gateway/RemoteFileOutboundGatewayTests.java b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/gateway/RemoteFileOutboundGatewayTests.java index 44273e1c84..199cd6665e 100644 --- a/spring-integration-file/src/test/java/org/springframework/integration/file/remote/gateway/RemoteFileOutboundGatewayTests.java +++ b/spring-integration-file/src/test/java/org/springframework/integration/file/remote/gateway/RemoteFileOutboundGatewayTests.java @@ -169,6 +169,7 @@ public class RemoteFileOutboundGatewayTests { new File(this.tmpDir + "/f1").delete(); new File(this.tmpDir + "/f2").delete(); when(sessionFactory.getSession()).thenReturn(new TestSession() { + int n; @Override @@ -187,7 +188,7 @@ public class RemoteFileOutboundGatewayTests { public TestLsEntry[] list(String path) throws IOException { return new TestLsEntry[] { new TestLsEntry(path1.replaceFirst("testremote/", ""), 123, false, false, 1234, "-r--r--r--"), - new TestLsEntry(path2.replaceFirst("testremote/", ""), 123, false, false, 1234, "-r--r--r--")}; + new TestLsEntry(path2.replaceFirst("testremote/", ""), 123, false, false, 1234, "-r--r--r--") }; } }); @@ -218,7 +219,7 @@ public class RemoteFileOutboundGatewayTests { @Override public TestLsEntry[] list(String path) throws IOException { - return new TestLsEntry[]{new TestLsEntry("f1", 123, false, false, 1234, "-r--r--r--")}; + return new TestLsEntry[] { new TestLsEntry("f1", 123, false, false, 1234, "-r--r--r--") }; } }); @@ -260,6 +261,7 @@ public class RemoteFileOutboundGatewayTests { Session session = mock(Session.class); final AtomicReference args = new AtomicReference(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { Object[] arguments = invocation.getArguments(); @@ -286,6 +288,7 @@ public class RemoteFileOutboundGatewayTests { Session session = mock(Session.class); final AtomicReference args = new AtomicReference(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { Object[] arguments = invocation.getArguments(); @@ -310,6 +313,7 @@ public class RemoteFileOutboundGatewayTests { Session session = mock(Session.class); final AtomicReference args = new AtomicReference(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { Object[] arguments = invocation.getArguments(); @@ -319,6 +323,7 @@ public class RemoteFileOutboundGatewayTests { }).when(session).rename(anyString(), anyString()); final List madeDirs = new ArrayList(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { madeDirs.add((String) invocation.getArguments()[0]); @@ -370,7 +375,7 @@ public class RemoteFileOutboundGatewayTests { } public TestLsEntry[] level1List() { - return new TestLsEntry[]{ + return new TestLsEntry[] { new TestLsEntry("f1", 123, false, false, 1234, "-r--r--r--"), new TestLsEntry("d1", 0, true, false, 12345, "drw-r--r--"), new TestLsEntry("f2", 12345, false, false, 123456, "-rw-r--r--") @@ -378,14 +383,14 @@ public class RemoteFileOutboundGatewayTests { } public TestLsEntry[] level2List() { - return new TestLsEntry[]{ + return new TestLsEntry[] { new TestLsEntry("d2", 0, true, false, 12345, "drw-r--r--"), new TestLsEntry("f3", 12345, false, false, 123456, "-rw-r--r--") }; } public TestLsEntry[] level3List() { - return new TestLsEntry[]{ + return new TestLsEntry[] { new TestLsEntry("f4", 12345, false, false, 123456, "-rw-r--r--") }; } @@ -585,7 +590,7 @@ public class RemoteFileOutboundGatewayTests { @Override public TestLsEntry[] list(String path) throws IOException { - return new TestLsEntry[]{ + return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, 12345, "-rw-r--r--") }; } @@ -622,7 +627,7 @@ public class RemoteFileOutboundGatewayTests { @Override public TestLsEntry[] list(String path) throws IOException { - return new TestLsEntry[]{ + return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, 12345, "-rw-r--r--") }; } @@ -689,7 +694,7 @@ public class RemoteFileOutboundGatewayTests { @Override public TestLsEntry[] list(String path) throws IOException { - return new TestLsEntry[]{ + return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, 12345, "-rw-r--r--") }; } @@ -730,7 +735,7 @@ public class RemoteFileOutboundGatewayTests { @Override public TestLsEntry[] list(String path) throws IOException { - return new TestLsEntry[]{ + return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, modified.getTime(), "-rw-r--r--") }; } @@ -767,7 +772,7 @@ public class RemoteFileOutboundGatewayTests { @Override public TestLsEntry[] list(String path) throws IOException { - return new TestLsEntry[]{ + return new TestLsEntry[] { new TestLsEntry("f1", 1234, false, false, 12345, "-rw-r--r--") }; } @@ -1070,18 +1075,17 @@ public class RemoteFileOutboundGatewayTests { } - static class TestRemoteFileOutboundGateway extends AbstractRemoteFileOutboundGateway { - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) TestRemoteFileOutboundGateway(SessionFactory sessionFactory, - String command, String expression) { + String command, String expression) { super(sessionFactory, Command.toCommand(command), expression); this.setBeanFactory(mock(BeanFactory.class)); } TestRemoteFileOutboundGateway(RemoteFileTemplate remoteFileTemplate, String command, - String expression) { + String expression) { super(remoteFileTemplate, command, expression); this.setBeanFactory(mock(BeanFactory.class)); } @@ -1129,14 +1133,19 @@ public class RemoteFileOutboundGatewayTests { static class TestLsEntry extends AbstractFileInfo { private volatile String filename; + private final long size; + private final boolean dir; + private final boolean link; + private final long modified; + private final String permissions; TestLsEntry(String filename, long size, boolean dir, boolean link, - long modified, String permissions) { + long modified, String permissions) { this.filename = filename; this.size = size; this.dir = dir; diff --git a/spring-integration-ftp/src/main/java/org/springframework/integration/ftp/session/AbstractFtpSessionFactory.java b/spring-integration-ftp/src/main/java/org/springframework/integration/ftp/session/AbstractFtpSessionFactory.java index 01561009af..2cddbc48c8 100644 --- a/spring-integration-ftp/src/main/java/org/springframework/integration/ftp/session/AbstractFtpSessionFactory.java +++ b/spring-integration-ftp/src/main/java/org/springframework/integration/ftp/session/AbstractFtpSessionFactory.java @@ -114,6 +114,7 @@ public abstract class AbstractFtpSessionFactory implements Assert.notNull(pass, "password should not be null"); this.password = pass; } + /** * ACTIVE_LOCAL_DATA_CONNECTION_MODE = 0
* A constant indicating the FTP session is expecting all transfers @@ -131,7 +132,7 @@ public abstract class AbstractFtpSessionFactory implements */ public void setClientMode(int clientMode) { Assert.isTrue(clientMode == FTPClient.ACTIVE_LOCAL_DATA_CONNECTION_MODE || - clientMode == FTPClient.PASSIVE_LOCAL_DATA_CONNECTION_MODE, + clientMode == FTPClient.PASSIVE_LOCAL_DATA_CONNECTION_MODE, "Only local modes are supported. Was: " + clientMode); this.clientMode = clientMode; } @@ -141,7 +142,7 @@ public abstract class AbstractFtpSessionFactory implements * @param connectTimeout the timeout */ public void setConnectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; + this.connectTimeout = connectTimeout; } /** @@ -239,6 +240,7 @@ public abstract class AbstractFtpSessionFactory implements protected void postProcessClientAfterConnect(T t) throws IOException { // NOOP } + /** * Will handle additional initialization before client.connect() method was invoked. * diff --git a/spring-integration-ftp/src/main/java/org/springframework/integration/ftp/session/DefaultFtpsSessionFactory.java b/spring-integration-ftp/src/main/java/org/springframework/integration/ftp/session/DefaultFtpsSessionFactory.java index ec479f18d9..ca4df88020 100644 --- a/spring-integration-ftp/src/main/java/org/springframework/integration/ftp/session/DefaultFtpsSessionFactory.java +++ b/spring-integration-ftp/src/main/java/org/springframework/integration/ftp/session/DefaultFtpsSessionFactory.java @@ -127,8 +127,8 @@ public class DefaultFtpsSessionFactory extends AbstractFtpSessionFactory { @Override public boolean remove(String path) throws IOException { Assert.hasText(path, "path must not be null"); - if (!this.client.deleteFile(path)) { + if (!this.client.deleteFile(path)) { throw new IOException("Failed to delete '" + path + "'. Server replied with: " + this.client.getReplyString()); } else { - return true; - } + return true; + } } @Override 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 60a5e73a51..9109c5cadb 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 @@ -100,7 +100,7 @@ public class GroovyScriptExecutingMessageProcessor extends AbstractScriptExecuti * @param scriptVariableGenerator The variable generator. */ public GroovyScriptExecutingMessageProcessor(ScriptSource scriptSource, - ScriptVariableGenerator scriptVariableGenerator) { + ScriptVariableGenerator scriptVariableGenerator) { super(scriptVariableGenerator); this.scriptSource = scriptSource; } diff --git a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingMessagingGatewayWithPathMappingTests.java b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingMessagingGatewayWithPathMappingTests.java index 323ecd5ddc..e4b4fe8b6e 100644 --- a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingMessagingGatewayWithPathMappingTests.java +++ b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/HttpRequestHandlingMessagingGatewayWithPathMappingTests.java @@ -16,8 +16,9 @@ package org.springframework.integration.http.inbound; +import static org.hamcrest.Matchers.instanceOf; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import java.util.Map; @@ -31,8 +32,6 @@ import org.springframework.integration.channel.DirectChannel; import org.springframework.integration.http.AbstractHttpInboundTests; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; -import org.springframework.messaging.MessageHandler; -import org.springframework.messaging.MessagingException; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.util.AntPathMatcher; @@ -54,18 +53,13 @@ public class HttpRequestHandlingMessagingGatewayWithPathMappingTests extends Abs @Test public void withoutExpression() throws Exception { DirectChannel echoChannel = new DirectChannel(); - echoChannel.subscribe(new MessageHandler() { - - public void handleMessage(Message message) throws MessagingException { - MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); - replyChannel.send(message); - } + echoChannel.subscribe(message -> { + MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); + replyChannel.send(message); }); MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("POST"); - //request.setContentType("text/plain"); //Works in Spring 3.1.2.RELEASE but NOT in 3.0.7.RELEASE - //Instead do: - request.addHeader("Content-Type", "text/plain"); + request.setContentType("text/plain"); request.setParameter("foo", "bar"); request.setContent("hello".getBytes()); @@ -74,18 +68,18 @@ public class HttpRequestHandlingMessagingGatewayWithPathMappingTests extends Abs HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); gateway.setBeanFactory(mock(BeanFactory.class)); - RequestMapping requestMapping = new RequestMapping(); + RequestMapping requestMapping = new RequestMapping(); requestMapping.setPathPatterns("/fname/{f}/lname/{l}"); gateway.setRequestMapping(requestMapping); gateway.afterPropertiesSet(); gateway.start(); - gateway.setRequestChannel(echoChannel); + gateway.setRequestChannel(echoChannel); MockHttpServletResponse response = new MockHttpServletResponse(); - Object result = gateway.doHandleRequest(request, response); - assertTrue(result instanceof Message); + Object result = gateway.doHandleRequest(request, response); + assertThat(result, instanceOf(Message.class)); assertEquals("hello", ((Message) result).getPayload()); } @@ -93,11 +87,9 @@ public class HttpRequestHandlingMessagingGatewayWithPathMappingTests extends Abs @Test public void withPayloadExpressionPointingToPathVariable() throws Exception { DirectChannel echoChannel = new DirectChannel(); - echoChannel.subscribe(new MessageHandler() { - public void handleMessage(Message message) throws MessagingException { - MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); - replyChannel.send(message); - } + echoChannel.subscribe(message -> { + MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); + replyChannel.send(message); }); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -119,17 +111,17 @@ public class HttpRequestHandlingMessagingGatewayWithPathMappingTests extends Abs HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); gateway.setBeanFactory(mock(BeanFactory.class)); - RequestMapping requestMapping = new RequestMapping(); + RequestMapping requestMapping = new RequestMapping(); requestMapping.setPathPatterns("/fname/{f}/lname/{l}"); gateway.setRequestMapping(requestMapping); - gateway.setRequestChannel(echoChannel); + gateway.setRequestChannel(echoChannel); gateway.setPayloadExpression(PARSER.parseExpression("#pathVariables.f")); gateway.afterPropertiesSet(); gateway.start(); - Object result = gateway.doHandleRequest(request, response); - assertTrue(result instanceof Message); + Object result = gateway.doHandleRequest(request, response); + assertThat(result, instanceOf(Message.class)); assertEquals("bill", ((Message) result).getPayload()); } @@ -138,12 +130,9 @@ public class HttpRequestHandlingMessagingGatewayWithPathMappingTests extends Abs public void withoutPayloadExpressionPointingToUriVariables() throws Exception { DirectChannel echoChannel = new DirectChannel(); - echoChannel.subscribe(new MessageHandler() { - - public void handleMessage(Message message) throws MessagingException { - MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); - replyChannel.send(message); - } + echoChannel.subscribe(message -> { + MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel(); + replyChannel.send(message); }); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); @@ -165,17 +154,17 @@ public class HttpRequestHandlingMessagingGatewayWithPathMappingTests extends Abs HttpRequestHandlingMessagingGateway gateway = new HttpRequestHandlingMessagingGateway(true); gateway.setBeanFactory(mock(BeanFactory.class)); - RequestMapping requestMapping = new RequestMapping(); + RequestMapping requestMapping = new RequestMapping(); requestMapping.setPathPatterns("/fname/{f}/lname/{l}"); gateway.setRequestMapping(requestMapping); - gateway.setRequestChannel(echoChannel); + gateway.setRequestChannel(echoChannel); gateway.setPayloadExpression(PARSER.parseExpression("#pathVariables")); gateway.afterPropertiesSet(); gateway.start(); - Object result = gateway.doHandleRequest(request, response); - assertTrue(result instanceof Message); + Object result = gateway.doHandleRequest(request, response); + assertThat(result, instanceOf(Message.class)); assertEquals("bill", ((Map) ((Message) result).getPayload()).get("f")); } diff --git a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/Int2312RequestMappingIntegrationTests.java b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/Int2312RequestMappingIntegrationTests.java index d38ecc76b8..34c01acb0c 100644 --- a/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/Int2312RequestMappingIntegrationTests.java +++ b/spring-integration-http/src/test/java/org/springframework/integration/http/inbound/Int2312RequestMappingIntegrationTests.java @@ -96,7 +96,6 @@ public class Int2312RequestMappingIntegrationTests extends AbstractHttpInboundTe } - @Test @SuppressWarnings("unchecked") //INT-1362 @@ -120,6 +119,7 @@ public class Int2312RequestMappingIntegrationTests extends AbstractHttpInboundTe RequestContextHolder.setRequestAttributes(attributes); this.toLowerCaseChannel.subscribe(new MessageHandler() { + @Override public void handleMessage(Message message) throws MessagingException { MessageHeaders headers = message.getHeaders(); @@ -162,15 +162,15 @@ public class Int2312RequestMappingIntegrationTests extends AbstractHttpInboundTe @Test public void testParams() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", "/params"); - Object handler = null; - try { - handler = this.handlerMapping.getHandler(request); - } - catch (Exception e) { - // There is no matching handlers and some default handler - //See org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping#handleNoMatch - assertTrue(e instanceof UnsatisfiedServletRequestParameterException); - } + Object handler = null; + try { + handler = this.handlerMapping.getHandler(request); + } + catch (Exception e) { + // There is no matching handlers and some default handler + //See org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping#handleNoMatch + assertTrue(e instanceof UnsatisfiedServletRequestParameterException); + } request = new MockHttpServletRequest("GET", "/params"); request.addParameter("param1", "1"); diff --git a/spring-integration-http/src/test/java/org/springframework/integration/http/support/DefaultHttpHeaderMapperFromMessageInboundTests.java b/spring-integration-http/src/test/java/org/springframework/integration/http/support/DefaultHttpHeaderMapperFromMessageInboundTests.java index ca162933f2..5c519a0f5c 100644 --- a/spring-integration-http/src/test/java/org/springframework/integration/http/support/DefaultHttpHeaderMapperFromMessageInboundTests.java +++ b/spring-integration-http/src/test/java/org/springframework/integration/http/support/DefaultHttpHeaderMapperFromMessageInboundTests.java @@ -57,7 +57,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { // Allow tests @Test(expected = IllegalArgumentException.class) public void validateAllowWithWrongMethodName() { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("Allow", "bar"); HttpHeaders headers = new HttpHeaders(); @@ -67,7 +67,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateAllowAsString() { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("Allow", "GET"); HttpHeaders headers = new HttpHeaders(); @@ -79,7 +79,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateAllowAsStringCaseInsensitive() { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("allow", "GET"); HttpHeaders headers = new HttpHeaders(); @@ -91,7 +91,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateAllowAsHttpMethod() { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("Allow", HttpMethod.GET); HttpHeaders headers = new HttpHeaders(); @@ -103,7 +103,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateAllowAsDelimitedString() { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("Allow", "GET, POST"); HttpHeaders headers = new HttpHeaders(); @@ -116,9 +116,9 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateAllowAsStringArray() { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); - messageHeaders.put("Allow", new String[]{"GET", "POST"}); + messageHeaders.put("Allow", new String[] { "GET", "POST" }); HttpHeaders headers = new HttpHeaders(); mapper.fromHeaders(new MessageHeaders(messageHeaders), headers); @@ -129,9 +129,9 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateAllowAsHttpMethodArray() { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); - messageHeaders.put("Allow", new HttpMethod[]{HttpMethod.GET, HttpMethod.POST}); + messageHeaders.put("Allow", new HttpMethod[] { HttpMethod.GET, HttpMethod.POST }); HttpHeaders headers = new HttpHeaders(); mapper.fromHeaders(new MessageHeaders(messageHeaders), headers); @@ -142,9 +142,9 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateAllowAsCollectionOfString() { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); - messageHeaders.put("Allow", CollectionUtils.arrayToList(new String[]{"GET", "POST"})); + messageHeaders.put("Allow", CollectionUtils.arrayToList(new String[] { "GET", "POST" })); HttpHeaders headers = new HttpHeaders(); mapper.fromHeaders(new MessageHeaders(messageHeaders), headers); @@ -155,9 +155,9 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateAllowAsCollectionOfHttpMethods() { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); - messageHeaders.put("Allow", CollectionUtils.arrayToList(new HttpMethod[]{HttpMethod.GET, HttpMethod.POST})); + messageHeaders.put("Allow", CollectionUtils.arrayToList(new HttpMethod[] { HttpMethod.GET, HttpMethod.POST })); HttpHeaders headers = new HttpHeaders(); mapper.fromHeaders(new MessageHeaders(messageHeaders), headers); @@ -175,7 +175,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateETag() { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("ETag", "\"1234\""); HttpHeaders headers = new HttpHeaders(); @@ -188,7 +188,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateExpiresAsNumber() throws ParseException { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("Expires", 12345678); HttpHeaders headers = new HttpHeaders(); @@ -201,7 +201,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateExpiresAsString() throws ParseException { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("Expires", "12345678"); HttpHeaders headers = new HttpHeaders(); @@ -211,9 +211,10 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { assertEquals(simpleDateFormat.parse("Thu, 01 Jan 1970 03:25:45 GMT").getTime(), headers.getExpires()); } + @Test public void validateExpiresAsDate() throws ParseException { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("Expires", new Date(12345678)); HttpHeaders headers = new HttpHeaders(); @@ -228,7 +229,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateLastModifiedAsNumber() throws ParseException { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("Last-Modified", 12345678); HttpHeaders headers = new HttpHeaders(); @@ -241,7 +242,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateLastModifiedAsString() throws ParseException { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("Last-Modified", "12345678"); HttpHeaders headers = new HttpHeaders(); @@ -251,9 +252,10 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { assertEquals(simpleDateFormat.parse("Thu, 01 Jan 1970 03:25:45 GMT").getTime(), headers.getLastModified()); } + @Test public void validateLastModifiedAsDate() throws ParseException { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("Last-Modified", new Date(12345678)); HttpHeaders headers = new HttpHeaders(); @@ -268,7 +270,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateLocation() throws Exception { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("Location", "http://foo.com"); HttpHeaders headers = new HttpHeaders(); @@ -281,7 +283,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateTransferEncodingNotMappedFromMessageHeaders() throws Exception { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map messageHeaders = new HashMap(); messageHeaders.put("Transfer-Encoding", "chunked"); HttpHeaders headers = new HttpHeaders(); @@ -294,7 +296,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateTransferEncodingMappedFromHttpHeaders() throws Exception { DefaultHttpHeaderMapper mapper = new DefaultHttpHeaderMapper(); - mapper.setInboundHeaderNames(new String[] {"Transfer-Encoding"}); + mapper.setInboundHeaderNames(new String[] { "Transfer-Encoding" }); HttpHeaders headers = new HttpHeaders(); headers.set("Transfer-Encoding", "chunked"); @@ -322,7 +324,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateCustomHeaderNamesMappedToHttpHeaders() throws Exception { DefaultHttpHeaderMapper mapper = new DefaultHttpHeaderMapper(); - mapper.setOutboundHeaderNames(new String[] {"foo", "bar"}); + mapper.setOutboundHeaderNames(new String[] { "foo", "bar" }); Map messageHeaders = new HashMap(); messageHeaders.put("foo", "abc"); messageHeaders.put("bar", "123"); @@ -338,7 +340,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateCustomHeaderNamePatternsMappedToHttpHeaders() throws Exception { DefaultHttpHeaderMapper mapper = new DefaultHttpHeaderMapper(); - mapper.setOutboundHeaderNames(new String[] {"x*", "*z", "a*f"}); + mapper.setOutboundHeaderNames(new String[] { "x*", "*z", "a*f" }); Map messageHeaders = new HashMap(); messageHeaders.put("x1", "x1-value"); messageHeaders.put("1x", "1x-value"); @@ -365,7 +367,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateCustomHeaderNamePatternsAndStandardResponseHeadersMappedToHttpHeaders() throws Exception { DefaultHttpHeaderMapper mapper = new DefaultHttpHeaderMapper(); - mapper.setOutboundHeaderNames(new String[] {"foo*", "HTTP_RESPONSE_HEADERS"}); + mapper.setOutboundHeaderNames(new String[] { "foo*", "HTTP_RESPONSE_HEADERS" }); Map messageHeaders = new HashMap(); messageHeaders.put("foobar", "abc"); messageHeaders.put("Accept", "text/html"); @@ -383,7 +385,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { public void validateCustomHeaderNamePatternsAndStandardResponseHeadersMappedToHttpHeadersWithCustomPrefix() throws Exception { DefaultHttpHeaderMapper mapper = new DefaultHttpHeaderMapper(); mapper.setUserDefinedHeaderPrefix("Z-"); - mapper.setOutboundHeaderNames(new String[] {"foo*", "HTTP_RESPONSE_HEADERS"}); + mapper.setOutboundHeaderNames(new String[] { "foo*", "HTTP_RESPONSE_HEADERS" }); Map messageHeaders = new HashMap(); messageHeaders.put("foobar", "abc"); messageHeaders.put("Accept", "text/html"); @@ -401,7 +403,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { public void validateCustomHeaderNamePatternsAndStandardResponseHeadersMappedToHttpHeadersWithCustomPrefixEmptyString() throws Exception { DefaultHttpHeaderMapper mapper = new DefaultHttpHeaderMapper(); mapper.setUserDefinedHeaderPrefix(""); - mapper.setOutboundHeaderNames(new String[] {"foo*", "HTTP_RESPONSE_HEADERS"}); + mapper.setOutboundHeaderNames(new String[] { "foo*", "HTTP_RESPONSE_HEADERS" }); Map messageHeaders = new HashMap(); messageHeaders.put("foobar", "abc"); messageHeaders.put("Accept", "text/html"); @@ -419,7 +421,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { public void validateCustomHeaderNamePatternsAndStandardResponseHeadersMappedToHttpHeadersWithCustomPrefixNull() throws Exception { DefaultHttpHeaderMapper mapper = new DefaultHttpHeaderMapper(); mapper.setUserDefinedHeaderPrefix(null); - mapper.setOutboundHeaderNames(new String[] {"foo*", "HTTP_RESPONSE_HEADERS"}); + mapper.setOutboundHeaderNames(new String[] { "foo*", "HTTP_RESPONSE_HEADERS" }); Map messageHeaders = new HashMap(); messageHeaders.put("foobar", "abc"); messageHeaders.put("Accept", "text/html"); @@ -436,7 +438,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateCustomHeaderNamesMappedFromHttpHeaders() throws Exception { DefaultHttpHeaderMapper mapper = new DefaultHttpHeaderMapper(); - mapper.setInboundHeaderNames(new String[] {"foo", "bar"}); + mapper.setInboundHeaderNames(new String[] { "foo", "bar" }); HttpHeaders headers = new HttpHeaders(); headers.set("foo", "abc"); headers.set("bar", "123"); @@ -449,7 +451,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateCustomHeaderNamePatternsMappedFromHttpHeaders() throws Exception { DefaultHttpHeaderMapper mapper = new DefaultHttpHeaderMapper(); - mapper.setInboundHeaderNames(new String[] {"x*", "*z", "a*f"}); + mapper.setInboundHeaderNames(new String[] { "x*", "*z", "a*f" }); HttpHeaders headers = new HttpHeaders(); headers.set("x1", "x1-value"); headers.set("1x", "1x-value"); @@ -472,7 +474,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateCustomHeaderNamePatternsAndStandardRequestHeadersMappedFromHttpHeaders() throws Exception { DefaultHttpHeaderMapper mapper = new DefaultHttpHeaderMapper(); - mapper.setInboundHeaderNames(new String[] {"foo*", "HTTP_REQUEST_HEADERS"}); + mapper.setInboundHeaderNames(new String[] { "foo*", "HTTP_REQUEST_HEADERS" }); HttpHeaders headers = new HttpHeaders(); headers.set("foobar", "abc"); headers.setAccept(Collections.singletonList(MediaType.TEXT_XML)); @@ -487,7 +489,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateCustomHeadersWithNonStringValuesAndNoConverter() throws Exception { DefaultHttpHeaderMapper mapper = new DefaultHttpHeaderMapper(); - mapper.setOutboundHeaderNames(new String[] {"customHeader*"}); + mapper.setOutboundHeaderNames(new String[] { "customHeader*" }); HttpHeaders headers = new HttpHeaders(); Map messageHeaders = new HashMap(); @@ -503,7 +505,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateCustomHeadersWithNonStringValuesAndDefaultConverterOnly() throws Exception { DefaultHttpHeaderMapper mapper = new DefaultHttpHeaderMapper(); - mapper.setOutboundHeaderNames(new String[] {"customHeader*"}); + mapper.setOutboundHeaderNames(new String[] { "customHeader*" }); ConversionService cs = new DefaultConversionService(); DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.registerSingleton("integrationConversionService", cs); @@ -524,7 +526,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void validateCustomHeadersWithNonStringValuesAndDefaultConverterWithCustomConverter() throws Exception { DefaultHttpHeaderMapper mapper = new DefaultHttpHeaderMapper(); - mapper.setOutboundHeaderNames(new String[] {"customHeader*"}); + mapper.setOutboundHeaderNames(new String[] { "customHeader*" }); GenericConversionService cs = new DefaultConversionService(); cs.addConverter(new TestClassConverter()); DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); @@ -544,21 +546,21 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { assertEquals("TestClass.class", headers.get("X-customHeaderB").get(0)); } - @Test - public void dontPropagateContentLength() { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); - HttpHeaders headers = new HttpHeaders(); - // suppressed in response on inbound, by default - headers.put("Content-Length", Collections.singletonList("3")); - Map messageHeaders = mapper.toHeaders(headers); - headers = new HttpHeaders(); - mapper.fromHeaders(new MessageHeaders(messageHeaders), headers); - assertNull(headers.get("Content-Length")); - } + @Test + public void dontPropagateContentLength() { + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HttpHeaders headers = new HttpHeaders(); + // suppressed in response on inbound, by default + headers.put("Content-Length", Collections.singletonList("3")); + Map messageHeaders = mapper.toHeaders(headers); + headers = new HttpHeaders(); + mapper.fromHeaders(new MessageHeaders(messageHeaders), headers); + assertNull(headers.get("Content-Length")); + } @Test public void testInt2995IfModifiedSince() throws Exception { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Date ifModifiedSince = new Date(); long ifModifiedSinceTime = ifModifiedSince.getTime(); HttpHeaders headers = new HttpHeaders(); @@ -572,7 +574,7 @@ public class DefaultHttpHeaderMapperFromMessageInboundTests { @Test public void testContentTypeHeader() throws Exception { - HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); + HeaderMapper mapper = DefaultHttpHeaderMapper.inboundMapper(); Map map = new HashMap(); map.put(MessageHeaders.CONTENT_TYPE, "text/plain"); MessageHeaders messageHeaders = new MessageHeaders(map); diff --git a/spring-integration-ip/src/main/java/org/springframework/integration/ip/config/IpAdapterParserUtils.java b/spring-integration-ip/src/main/java/org/springframework/integration/ip/config/IpAdapterParserUtils.java index ad68af0111..fe912c1dce 100644 --- a/spring-integration-ip/src/main/java/org/springframework/integration/ip/config/IpAdapterParserUtils.java +++ b/spring-integration-ip/src/main/java/org/springframework/integration/ip/config/IpAdapterParserUtils.java @@ -124,7 +124,8 @@ public abstract class IpAdapterParserUtils { public static final String MAPPER = "mapper"; - private IpAdapterParserUtils() { } + private IpAdapterParserUtils() { + } /** * Adds a constructor-arg to the provided bean definition builder @@ -151,7 +152,7 @@ public abstract class IpAdapterParserUtils { * @param parserContext The parser context. */ public static void addDestinationConfigToConstructor(Element element, - BeanDefinitionBuilder builder, ParserContext parserContext) { + BeanDefinitionBuilder builder, ParserContext parserContext) { String destinationExpression = element.getAttribute("destination-expression"); if (StringUtils.hasText(destinationExpression)) { addDestinationExpressionToConstructor(destinationExpression, element, builder, parserContext); @@ -162,7 +163,7 @@ public abstract class IpAdapterParserUtils { } private static void addDestinationExpressionToConstructor(String destinationExpression, - Element element, BeanDefinitionBuilder builder, ParserContext parserContext) { + Element element, BeanDefinitionBuilder builder, ParserContext parserContext) { String host = element.getAttribute(IpAdapterParserUtils.HOST); String port = element.getAttribute(IpAdapterParserUtils.PORT); if (StringUtils.hasText(host) || StringUtils.hasText(port)) { diff --git a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/AbstractConnectionFactory.java b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/AbstractConnectionFactory.java index 49c3d4939d..3d5c4d4a0e 100644 --- a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/AbstractConnectionFactory.java +++ b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/AbstractConnectionFactory.java @@ -84,7 +84,7 @@ public abstract class AbstractConnectionFactory extends IntegrationObjectSupport private volatile boolean soTcpNoDelay; - private volatile int soLinger = -1; // don't set by default + private volatile int soLinger = -1; // don't set by default private volatile boolean soKeepAlive; @@ -526,7 +526,7 @@ public abstract class AbstractConnectionFactory extends IntegrationObjectSupport return connection; } TcpConnectionInterceptorFactory[] interceptorFactories = - this.interceptorFactoryChain.getInterceptorFactories(); + this.interceptorFactoryChain.getInterceptorFactories(); if (interceptorFactories == null) { return connection; } @@ -584,17 +584,16 @@ public abstract class AbstractConnectionFactory extends IntegrationObjectSupport * send was within the current timeout. */ if (!connection.isServer() && - now - connection.getLastSend() < this.soTimeout && - now - connection.getLastRead() < this.soTimeout * 2) { + now - connection.getLastSend() < this.soTimeout && + now - connection.getLastRead() < this.soTimeout * 2) { if (logger.isDebugEnabled()) { - logger.debug("Skipping a connection timeout because we have a recent send " - + connection.getConnectionId()); + logger.debug("Skipping a connection timeout because we have a recent send " + + connection.getConnectionId()); } } else { if (logger.isWarnEnabled()) { - logger.warn("Timing out TcpNioConnection " + - connection.getConnectionId()); + logger.warn("Timing out TcpNioConnection " + connection.getConnectionId()); } SocketTimeoutException exception = new SocketTimeoutException("Timing out connection"); connection.publishConnectionExceptionEvent(exception); @@ -781,7 +780,7 @@ public abstract class AbstractConnectionFactory extends IntegrationObjectSupport } this.connections.put(connection.getConnectionId(), connection); if (logger.isDebugEnabled()) { - logger.debug(getComponentName() + ": Added new connection: " + connection.getConnectionId()); + logger.debug(getComponentName() + ": Added new connection: " + connection.getConnectionId()); } } } @@ -800,13 +799,13 @@ public abstract class AbstractConnectionFactory extends IntegrationObjectSupport if (!connection.isOpen()) { iterator.remove(); if (logger.isDebugEnabled()) { - logger.debug(getComponentName() + ": Removed closed connection: " + connection.getConnectionId()); + logger.debug(getComponentName() + ": Removed closed connection: " + connection.getConnectionId()); } } else { openConnectionIds.add(entry.getKey()); if (logger.isTraceEnabled()) { - logger.trace(getComponentName() + ": Connection is open: " + connection.getConnectionId()); + logger.trace(getComponentName() + ": Connection is open: " + connection.getConnectionId()); } } } diff --git a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpConnectionSupport.java b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpConnectionSupport.java index cb9935e1d6..9cad55113f 100644 --- a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpConnectionSupport.java +++ b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpConnectionSupport.java @@ -190,7 +190,7 @@ public abstract class TcpConnectionSupport implements TcpConnection { Assert.notNull(mapper, this.getClass().getName() + " Mapper may not be null"); this.mapper = mapper; if (this.serializer != null && - !(this.serializer instanceof AbstractByteArraySerializer)) { + !(this.serializer instanceof AbstractByteArraySerializer)) { mapper.setStringToBytes(false); } } diff --git a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNetConnection.java b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNetConnection.java index f61b4cec5a..722912c1a9 100644 --- a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNetConnection.java +++ b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNetConnection.java @@ -82,7 +82,8 @@ public class TcpNetConnection extends TcpConnectionSupport implements Scheduling try { this.socket.close(); } - catch (Exception e) { } + catch (Exception e) { + } super.close(); } @@ -184,9 +185,9 @@ public class TcpNetConnection extends TcpConnectionSupport implements Scheduling catch (NoListenerException nle) { // could also be thrown by an interceptor if (logger.isWarnEnabled()) { logger.warn("Unexpected message - no endpoint registered with connection interceptor: " - + getConnectionId() - + " - " - + message); + + getConnectionId() + + " - " + + message); } } catch (Exception e2) { @@ -230,24 +231,24 @@ public class TcpNetConnection extends TcpConnectionSupport implements Scheduling if (noReadErrorOnClose) { if (logger.isTraceEnabled()) { logger.trace("Read exception " + - this.getConnectionId(), e); + this.getConnectionId(), e); } else if (logger.isDebugEnabled()) { logger.debug("Read exception " + - this.getConnectionId() + " " + - e.getClass().getSimpleName() + - ":" + (e.getCause() != null ? e.getCause() + ":" : "") + e.getMessage()); + this.getConnectionId() + " " + + e.getClass().getSimpleName() + + ":" + (e.getCause() != null ? e.getCause() + ":" : "") + e.getMessage()); } } else if (logger.isTraceEnabled()) { logger.error("Read exception " + - this.getConnectionId(), e); + this.getConnectionId(), e); } else { logger.error("Read exception " + - this.getConnectionId() + " " + - e.getClass().getSimpleName() + - ":" + (e.getCause() != null ? e.getCause() + ":" : "") + e.getMessage()); + this.getConnectionId() + " " + + e.getClass().getSimpleName() + + ":" + (e.getCause() != null ? e.getCause() + ":" : "") + e.getMessage()); } } this.sendExceptionToListener(e); diff --git a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNioConnection.java b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNioConnection.java index bb82895546..e92a7f9ebc 100644 --- a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNioConnection.java +++ b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/connection/TcpNioConnection.java @@ -101,7 +101,7 @@ public class TcpNioConnection extends TcpConnectionSupport { public TcpNioConnection(SocketChannel socketChannel, boolean server, boolean lookupHost, ApplicationEventPublisher applicationEventPublisher, String connectionFactoryName) throws Exception { - super(socketChannel.socket(), server, lookupHost, applicationEventPublisher, connectionFactoryName); + super(socketChannel.socket(), server, lookupHost, applicationEventPublisher, connectionFactoryName); this.socketChannel = socketChannel; int receiveBufferSize = socketChannel.socket().getReceiveBufferSize(); if (receiveBufferSize <= 0) { @@ -124,11 +124,13 @@ public class TcpNioConnection extends TcpConnectionSupport { try { this.channelInputStream.close(); } - catch (IOException e) { } + catch (IOException e) { + } try { this.socketChannel.close(); } - catch (Exception e) { } + catch (Exception e) { + } super.close(); } @@ -247,20 +249,20 @@ public class TcpNioConnection extends TcpConnectionSupport { catch (Exception e) { if (logger.isTraceEnabled()) { logger.error("Read exception " + - this.getConnectionId(), e); + this.getConnectionId(), e); } else if (!this.isNoReadErrorOnClose()) { logger.error("Read exception " + - this.getConnectionId() + " " + - e.getClass().getSimpleName() + - ":" + e.getCause() + ":" + e.getMessage()); + this.getConnectionId() + " " + + e.getClass().getSimpleName() + + ":" + e.getCause() + ":" + e.getMessage()); } else { if (logger.isDebugEnabled()) { logger.debug("Read exception " + - this.getConnectionId() + " " + - e.getClass().getSimpleName() + - ":" + e.getCause() + ":" + e.getMessage()); + this.getConnectionId() + " " + + e.getClass().getSimpleName() + + ":" + e.getCause() + ":" + e.getMessage()); } } this.closeConnection(true); @@ -375,9 +377,9 @@ public class TcpNioConnection extends TcpConnectionSupport { if (e instanceof NoListenerException) { // could also be thrown by an interceptor if (logger.isWarnEnabled()) { logger.warn("Unexpected message - no endpoint registered with connection: " - + getConnectionId() - + " - " - + message); + + getConnectionId() + + " - " + + message); } } else { @@ -490,8 +492,8 @@ public class TcpNioConnection extends TcpConnectionSupport { } catch (Exception e) { logger.error("Exception on Read " + - this.getConnectionId() + " " + - e.getMessage(), e); + this.getConnectionId() + " " + + e.getMessage(), e); this.closeConnection(true); } } @@ -656,7 +658,7 @@ public class TcpNioConnection extends TcpConnectionSupport { int n = 0; while ((this.available.get() > 0 || n == 0) && - n < len) { + n < len) { int bite = read(); if (bite < 0) { if (n == 0) { diff --git a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/serializer/ByteArrayLengthHeaderSerializer.java b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/serializer/ByteArrayLengthHeaderSerializer.java index 8bbabead71..6f0e082921 100644 --- a/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/serializer/ByteArrayLengthHeaderSerializer.java +++ b/spring-integration-ip/src/main/java/org/springframework/integration/ip/tcp/serializer/ByteArrayLengthHeaderSerializer.java @@ -15,6 +15,7 @@ */ package org.springframework.integration.ip.tcp.serializer; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -79,8 +80,8 @@ public class ByteArrayLengthHeaderSerializer extends AbstractByteArraySerializer */ public ByteArrayLengthHeaderSerializer(int headerSize) { if (headerSize != HEADER_SIZE_INT && - headerSize != HEADER_SIZE_UNSIGNED_BYTE && - headerSize != HEADER_SIZE_UNSIGNED_SHORT) { + headerSize != HEADER_SIZE_UNSIGNED_BYTE && + headerSize != HEADER_SIZE_UNSIGNED_SHORT) { throw new IllegalArgumentException("Illegal header size:" + headerSize); } this.headerSize = headerSize; @@ -162,8 +163,8 @@ public class ByteArrayLengthHeaderSerializer extends AbstractByteArraySerializer lengthRead += len; if (this.logger.isDebugEnabled()) { this.logger.debug("Read " + len + " bytes, buffer is now at " + - lengthRead + " of " + - needed); + lengthRead + " of " + + needed); } } return 0; @@ -178,27 +179,27 @@ public class ByteArrayLengthHeaderSerializer extends AbstractByteArraySerializer protected void writeHeader(OutputStream outputStream, int length) throws IOException { ByteBuffer lengthPart = ByteBuffer.allocate(this.headerSize); switch (this.headerSize) { - case HEADER_SIZE_INT: - lengthPart.putInt(length); - break; - case HEADER_SIZE_UNSIGNED_BYTE: - if (length > 0xff) { - throw new IllegalArgumentException("Length header:" - + this.headerSize - + " too short to accommodate message length:" + length); - } - lengthPart.put((byte) length); - break; - case HEADER_SIZE_UNSIGNED_SHORT: - if (length > 0xffff) { - throw new IllegalArgumentException("Length header:" - + this.headerSize - + " too short to accommodate message length:" + length); - } - lengthPart.putShort((short) length); - break; - default: - throw new IllegalArgumentException("Bad header size:" + this.headerSize); + case HEADER_SIZE_INT: + lengthPart.putInt(length); + break; + case HEADER_SIZE_UNSIGNED_BYTE: + if (length > 0xff) { + throw new IllegalArgumentException("Length header:" + + this.headerSize + + " too short to accommodate message length:" + length); + } + lengthPart.put((byte) length); + break; + case HEADER_SIZE_UNSIGNED_SHORT: + if (length > 0xffff) { + throw new IllegalArgumentException("Length header:" + + this.headerSize + + " too short to accommodate message length:" + length); + } + lengthPart.putShort((short) length); + break; + default: + throw new IllegalArgumentException("Bad header size:" + this.headerSize); } outputStream.write(lengthPart.array()); } @@ -221,22 +222,22 @@ public class ByteArrayLengthHeaderSerializer extends AbstractByteArraySerializer } int messageLength; switch (this.headerSize) { - case HEADER_SIZE_INT: - messageLength = ByteBuffer.wrap(lengthPart).getInt(); - if (messageLength < 0) { - throw new IllegalArgumentException("Length header:" - + messageLength - + " is negative"); - } - break; - case HEADER_SIZE_UNSIGNED_BYTE: - messageLength = ByteBuffer.wrap(lengthPart).get() & 0xff; - break; - case HEADER_SIZE_UNSIGNED_SHORT: - messageLength = ByteBuffer.wrap(lengthPart).getShort() & 0xffff; - break; - default: - throw new IllegalArgumentException("Bad header size:" + this.headerSize); + case HEADER_SIZE_INT: + messageLength = ByteBuffer.wrap(lengthPart).getInt(); + if (messageLength < 0) { + throw new IllegalArgumentException("Length header:" + + messageLength + + " is negative"); + } + break; + case HEADER_SIZE_UNSIGNED_BYTE: + messageLength = ByteBuffer.wrap(lengthPart).get() & 0xff; + break; + case HEADER_SIZE_UNSIGNED_SHORT: + messageLength = ByteBuffer.wrap(lengthPart).getShort() & 0xffff; + break; + default: + throw new IllegalArgumentException("Bad header size:" + this.headerSize); } return messageLength; } diff --git a/spring-integration-ip/src/main/java/org/springframework/integration/ip/udp/UnicastSendingMessageHandler.java b/spring-integration-ip/src/main/java/org/springframework/integration/ip/udp/UnicastSendingMessageHandler.java index 26baf5b526..9d62a3df3a 100644 --- a/spring-integration-ip/src/main/java/org/springframework/integration/ip/udp/UnicastSendingMessageHandler.java +++ b/spring-integration-ip/src/main/java/org/springframework/integration/ip/udp/UnicastSendingMessageHandler.java @@ -166,11 +166,11 @@ public class UnicastSendingMessageHandler extends * @param ackTimeout How long we will wait (milliseconds) for the ack. */ public UnicastSendingMessageHandler(String host, - int port, - boolean acknowledge, - String ackHost, - int ackPort, - int ackTimeout) { + int port, + boolean acknowledge, + String ackHost, + int ackPort, + int ackTimeout) { super(host, port); this.destinationExpression = null; setReliabilityAttributes(false, acknowledge, ackHost, ackPort, @@ -188,12 +188,12 @@ public class UnicastSendingMessageHandler extends * @param ackTimeout How long we will wait (milliseconds) for the ack. */ public UnicastSendingMessageHandler(String host, - int port, - boolean lengthCheck, - boolean acknowledge, - String ackHost, - int ackPort, - int ackTimeout) { + int port, + boolean lengthCheck, + boolean acknowledge, + String ackHost, + int ackPort, + int ackTimeout) { super(host, port); this.destinationExpression = null; setReliabilityAttributes(lengthCheck, acknowledge, ackHost, ackPort, @@ -223,6 +223,7 @@ public class UnicastSendingMessageHandler extends if (this.taskExecutor == null) { Executor executor = Executors .newSingleThreadExecutor(new ThreadFactory() { + private final AtomicInteger n = new AtomicInteger(); @Override @@ -284,7 +285,8 @@ public class UnicastSendingMessageHandler extends try { this.socket.close(); } - catch (Exception e1) { } + catch (Exception e1) { + } this.socket = null; throw new MessageHandlingException(message, "failed to send UDP packet", e); } @@ -456,7 +458,7 @@ public class UnicastSendingMessageHandler extends if (this.ackPort == 0 && socket != null) { return socket.getLocalPort(); } - else { + else { return this.ackPort; } } diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/config/ParserUnitTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/config/ParserUnitTests.java index 657c5bb1c6..24fa91092a 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/config/ParserUnitTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/config/ParserUnitTests.java @@ -93,62 +93,62 @@ public class ParserUnitTests { ApplicationContext ctx; @Autowired - @Qualifier(value = "testInUdp") + @Qualifier("testInUdp") UnicastReceivingChannelAdapter udpIn; @Autowired - @Qualifier(value = "testInUdpMulticast") + @Qualifier("testInUdpMulticast") MulticastReceivingChannelAdapter udpInMulticast; @Autowired - @Qualifier(value = "testInTcp") + @Qualifier("testInTcp") TcpReceivingChannelAdapter tcpIn; @Autowired - @Qualifier(value = "testOutUdp.handler") + @Qualifier("testOutUdp.handler") UnicastSendingMessageHandler udpOut; @Autowired - @Qualifier(value = "testOutUdpiMulticast.handler") + @Qualifier("testOutUdpiMulticast.handler") MulticastSendingMessageHandler udpOutMulticast; @Autowired - @Qualifier(value = "testOutTcpNio") + @Qualifier("testOutTcpNio") AbstractEndpoint tcpOutEndpoint; @Autowired - @Qualifier(value = "testOutTcpNio.handler") + @Qualifier("testOutTcpNio.handler") TcpSendingMessageHandler tcpOut; @Autowired EventDrivenConsumer testOutTcpNio; @Autowired - @Qualifier(value = "inGateway1") + @Qualifier("inGateway1") TcpInboundGateway tcpInboundGateway1; @Autowired - @Qualifier(value = "inGateway2") + @Qualifier("inGateway2") TcpInboundGateway tcpInboundGateway2; @Autowired - @Qualifier(value = "outGateway.handler") + @Qualifier("outGateway.handler") TcpOutboundGateway tcpOutboundGateway; @Autowired - @Qualifier(value = "outAdviceGateway.handler") + @Qualifier("outAdviceGateway.handler") TcpOutboundGateway outAdviceGateway; // verify we can still inject by generated name @Autowired - @Qualifier(value = "org.springframework.integration.ip.tcp.TcpOutboundGateway#0") + @Qualifier("org.springframework.integration.ip.tcp.TcpOutboundGateway#0") TcpOutboundGateway tcpOutboundGatewayByGeneratedName; @Autowired EventDrivenConsumer outGateway; @Autowired - @Qualifier(value = "externalTE") + @Qualifier("externalTE") TaskExecutor taskExecutor; @Autowired @@ -197,11 +197,11 @@ public class ParserUnitTests { AbstractConnectionFactory cfS3; @Autowired - @Qualifier(value = "tcpNewOut1.handler") + @Qualifier("tcpNewOut1.handler") TcpSendingMessageHandler tcpNewOut1; @Autowired - @Qualifier(value = "tcpNewOut2.handler") + @Qualifier("tcpNewOut2.handler") TcpSendingMessageHandler tcpNewOut2; @Autowired @@ -238,7 +238,7 @@ public class ParserUnitTests { TaskScheduler sched; @Autowired - @Qualifier(value = "tcpOutClientMode.handler") + @Qualifier("tcpOutClientMode.handler") TcpSendingMessageHandler tcpOutClientMode; @Autowired diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/InterceptedSharedConnectionTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/InterceptedSharedConnectionTests.java index afd2317267..7348a7c9e6 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/InterceptedSharedConnectionTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/InterceptedSharedConnectionTests.java @@ -49,7 +49,7 @@ public class InterceptedSharedConnectionTests { AbstractApplicationContext ctx; @Autowired - @Qualifier(value = "inboundServer") + @Qualifier("inboundServer") TcpReceivingChannelAdapter listener; private static Level existingLogLevel; diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/SharedConnectionTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/SharedConnectionTests.java index ea9e3751bd..6b01c92e1b 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/SharedConnectionTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/SharedConnectionTests.java @@ -49,7 +49,7 @@ public class SharedConnectionTests { AbstractApplicationContext ctx; @Autowired - @Qualifier(value = "inboundServer") + @Qualifier("inboundServer") TcpReceivingChannelAdapter listener; /** diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpConfigInboundGatewayTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpConfigInboundGatewayTests.java index a82cf25bb8..894e4fac0c 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpConfigInboundGatewayTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpConfigInboundGatewayTests.java @@ -53,99 +53,99 @@ public class TcpConfigInboundGatewayTests { AbstractApplicationContext ctx; @Autowired - @Qualifier(value = "crLfServer") + @Qualifier("crLfServer") AbstractServerConnectionFactory crLfServer; @Autowired - @Qualifier(value = "stxEtxServer") + @Qualifier("stxEtxServer") AbstractServerConnectionFactory stxEtxServer; @Autowired - @Qualifier(value = "lengthHeaderServer") + @Qualifier("lengthHeaderServer") AbstractServerConnectionFactory lengthHeaderServer; @Autowired - @Qualifier(value = "javaSerialServer") + @Qualifier("javaSerialServer") AbstractServerConnectionFactory javaSerialServer; @Autowired - @Qualifier(value = "crLfClient") + @Qualifier("crLfClient") AbstractClientConnectionFactory crLfClient; @Autowired - @Qualifier(value = "stxEtxClient") + @Qualifier("stxEtxClient") AbstractClientConnectionFactory stxEtxClient; @Autowired - @Qualifier(value = "lengthHeaderClient") + @Qualifier("lengthHeaderClient") AbstractClientConnectionFactory lengthHeaderClient; @Autowired - @Qualifier(value = "javaSerialClient") + @Qualifier("javaSerialClient") AbstractClientConnectionFactory javaSerialClient; @Autowired - @Qualifier(value = "crLfServerNio") + @Qualifier("crLfServerNio") AbstractServerConnectionFactory crLfServerNio; @Autowired - @Qualifier(value = "stxEtxServerNio") + @Qualifier("stxEtxServerNio") AbstractServerConnectionFactory stxEtxServerNio; @Autowired - @Qualifier(value = "lengthHeaderServerNio") + @Qualifier("lengthHeaderServerNio") AbstractServerConnectionFactory lengthHeaderServerNio; @Autowired - @Qualifier(value = "javaSerialServerNio") + @Qualifier("javaSerialServerNio") AbstractServerConnectionFactory javaSerialServerNio; @Autowired - @Qualifier(value = "crLfClientNio") + @Qualifier("crLfClientNio") AbstractClientConnectionFactory crLfClientNio; @Autowired - @Qualifier(value = "stxEtxClientNio") + @Qualifier("stxEtxClientNio") AbstractClientConnectionFactory stxEtxClientNio; @Autowired - @Qualifier(value = "lengthHeaderClientNio") + @Qualifier("lengthHeaderClientNio") AbstractClientConnectionFactory lengthHeaderClientNio; @Autowired - @Qualifier(value = "javaSerialClientNio") + @Qualifier("javaSerialClientNio") AbstractClientConnectionFactory javaSerialClientNio; @Autowired - @Qualifier(value = "gatewayCrLf") + @Qualifier("gatewayCrLf") TcpInboundGateway gatewayCrLf; @Autowired - @Qualifier(value = "gatewayStxEtx") + @Qualifier("gatewayStxEtx") TcpInboundGateway gatewayStxEtx; @Autowired - @Qualifier(value = "gatewayLength") + @Qualifier("gatewayLength") TcpInboundGateway gatewayLength; @Autowired - @Qualifier(value = "gatewaySerialized") + @Qualifier("gatewaySerialized") TcpInboundGateway gatewaySerialized; @Autowired - @Qualifier(value = "gatewayCrLfNio") + @Qualifier("gatewayCrLfNio") TcpInboundGateway gatewayCrLfNio; @Autowired - @Qualifier(value = "gatewayStxEtxNio") + @Qualifier("gatewayStxEtxNio") TcpInboundGateway gatewayStxEtxNio; @Autowired - @Qualifier(value = "gatewayLengthNio") + @Qualifier("gatewayLengthNio") TcpInboundGateway gatewayLengthNio; @Autowired - @Qualifier(value = "gatewaySerializedNio") + @Qualifier("gatewaySerializedNio") TcpInboundGateway gatewaySerializedNio; @Test diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpConfigOutboundGatewayTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpConfigOutboundGatewayTests.java index ec82bfc450..11e20a92a4 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpConfigOutboundGatewayTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpConfigOutboundGatewayTests.java @@ -51,39 +51,39 @@ public class TcpConfigOutboundGatewayTests { AbstractApplicationContext ctx; @Autowired - @Qualifier(value = "crLfServer") + @Qualifier("crLfServer") AbstractServerConnectionFactory crLfServer; @Autowired - @Qualifier(value = "stxEtxServer") + @Qualifier("stxEtxServer") AbstractServerConnectionFactory stxEtxServer; @Autowired - @Qualifier(value = "lengthHeaderServer") + @Qualifier("lengthHeaderServer") AbstractServerConnectionFactory lengthHeaderServer; @Autowired - @Qualifier(value = "javaSerialServer") + @Qualifier("javaSerialServer") AbstractServerConnectionFactory javaSerialServer; @Autowired - @Qualifier(value = "crLfClient") + @Qualifier("crLfClient") AbstractClientConnectionFactory crLfClient; @Autowired - @Qualifier(value = "stxEtxClient") + @Qualifier("stxEtxClient") AbstractClientConnectionFactory stxEtxClient; @Autowired - @Qualifier(value = "lengthHeaderClient") + @Qualifier("lengthHeaderClient") AbstractClientConnectionFactory lengthHeaderClient; @Autowired - @Qualifier(value = "javaSerialClient") + @Qualifier("javaSerialClient") AbstractClientConnectionFactory javaSerialClient; @Autowired - @Qualifier(value = "gatewayCrLf") + @Qualifier("gatewayCrLf") TcpInboundGateway gatewayCrLf; // @Autowired diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpOutboundGatewayTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpOutboundGatewayTests.java index e1c7c051ca..accbe3892d 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpOutboundGatewayTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/TcpOutboundGatewayTests.java @@ -324,7 +324,7 @@ public class TcpOutboundGatewayTests extends LogAdjustingTestSupport { * @throws Exception */ private void testGoodNetGWTimeoutGuts(final int port, AbstractClientConnectionFactory ccf, - final ServerSocket server) throws InterruptedException { + final ServerSocket server) throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); /* @@ -654,7 +654,7 @@ public class TcpOutboundGatewayTests extends LogAdjustingTestSupport { } private void testGWPropagatesSocketCloseGuts(final int port, AbstractClientConnectionFactory ccf, - final ServerSocket server) throws Exception { + final ServerSocket server) throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); final AtomicReference lastReceived = new AtomicReference(); @@ -779,7 +779,7 @@ public class TcpOutboundGatewayTests extends LogAdjustingTestSupport { } private void testGWPropagatesSocketTimeoutGuts(final int port, AbstractClientConnectionFactory ccf, - final ServerSocket server) throws Exception { + final ServerSocket server) throws Exception { final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean done = new AtomicBoolean(); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/HelloWorldInterceptor.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/HelloWorldInterceptor.java index 2f8fdf97cf..38d45d7382 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/HelloWorldInterceptor.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/HelloWorldInterceptor.java @@ -80,7 +80,7 @@ public class HelloWorldInterceptor extends TcpConnectionInterceptorSupport { } else { throw new MessagingException("Negotiation error, expected '" + hello + - "' received '" + payload + "'"); + "' received '" + payload + "'"); } } else { @@ -90,7 +90,7 @@ public class HelloWorldInterceptor extends TcpConnectionInterceptorSupport { } else { throw new MessagingException("Negotiation error - expected '" + world + - "' received " + payload); + "' received " + payload); } return true; } diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionReadTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionReadTests.java index debdb500db..ceaa70e251 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionReadTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/connection/TcpNioConnectionReadTests.java @@ -87,13 +87,12 @@ public class TcpNioConnectionReadTests { assertEquals("Data", SocketTestUtils.TEST_STRING + SocketTestUtils.TEST_STRING, new String((byte[]) responses.get(0).getPayload())); assertEquals("Data", SocketTestUtils.TEST_STRING + SocketTestUtils.TEST_STRING, - new String((byte[]) responses.get(1).getPayload())); + new String((byte[]) responses.get(1).getPayload())); scf.stop(); done.countDown(); } - @SuppressWarnings("unchecked") @Test public void testFragmented() throws Exception { @@ -120,7 +119,7 @@ public class TcpNioConnectionReadTests { assertEquals("Expected", howMany, responses.size()); for (int i = 0; i < howMany; i++) { assertEquals("Data", "xx", - new String(((Message) responses.get(0)).getPayload())); + new String(((Message) responses.get(0)).getPayload())); } scf.stop(); done.countDown(); @@ -146,9 +145,9 @@ public class TcpNioConnectionReadTests { assertTrue(semaphore.tryAcquire(1, 10000, TimeUnit.MILLISECONDS)); assertEquals("Did not receive data", 2, responses.size()); assertEquals("Data", SocketTestUtils.TEST_STRING + SocketTestUtils.TEST_STRING, - new String(((Message) responses.get(0)).getPayload())); + new String(((Message) responses.get(0)).getPayload())); assertEquals("Data", SocketTestUtils.TEST_STRING + SocketTestUtils.TEST_STRING, - new String(((Message) responses.get(1)).getPayload())); + new String(((Message) responses.get(1)).getPayload())); scf.stop(); done.countDown(); } @@ -173,9 +172,9 @@ public class TcpNioConnectionReadTests { assertTrue(semaphore.tryAcquire(1, 10000, TimeUnit.MILLISECONDS)); assertEquals("Did not receive data", 2, responses.size()); assertEquals("Data", SocketTestUtils.TEST_STRING + SocketTestUtils.TEST_STRING, - new String(((Message) responses.get(0)).getPayload())); + new String(((Message) responses.get(0)).getPayload())); assertEquals("Data", SocketTestUtils.TEST_STRING + SocketTestUtils.TEST_STRING, - new String(((Message) responses.get(1)).getPayload())); + new String(((Message) responses.get(1)).getPayload())); scf.stop(); done.countDown(); } @@ -414,11 +413,13 @@ public class TcpNioConnectionReadTests { responses.add(message); return false; }, new TcpSender() { + @Override public void addNewConnection(TcpConnection connection) { added.add(connection); semaphore.release(); } + @Override public void removeDeadConnection(TcpConnection connection) { removed.add(connection); 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 dc5b11eba6..eb1ed934c2 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 @@ -140,7 +140,7 @@ public class TcpNioConnectionTests { } catch (Exception e) { assertTrue("Expected SocketTimeoutException, got " + e.getClass().getSimpleName() + - ":" + e.getMessage(), e instanceof SocketTimeoutException); + ":" + e.getMessage(), e instanceof SocketTimeoutException); } done.countDown(); serverSocket.get().close(); @@ -352,6 +352,7 @@ public class TcpNioConnectionTests { final TcpNioConnection connection = new TcpNioConnection(channel, false, false, null, null); connection.setTaskExecutor(exec); connection.registerListener(new TcpListener() { + @Override public boolean onMessage(Message message) { messageLatch.countDown(); @@ -441,12 +442,14 @@ public class TcpNioConnectionTests { stream.read(out, 1, 5); fail("Expected IndexOutOfBoundsException"); } - catch (IndexOutOfBoundsException e) { } + catch (IndexOutOfBoundsException e) { + } try { stream.read(null, 1, 5); fail("Expected IllegalArgumentException"); } - catch (IllegalArgumentException e) { } + catch (IllegalArgumentException e) { + } assertEquals(0, stream.read(out, 0, 0)); assertEquals(3, stream.read(out)); } @@ -463,6 +466,7 @@ public class TcpNioConnectionTests { final byte[] out = new byte[4]; ExecutorService exec = Executors.newSingleThreadExecutor(); exec.execute(new Runnable() { + @Override public void run() { try { @@ -494,6 +498,7 @@ public class TcpNioConnectionTests { inboundConnection.setMapper(inMapper); final ByteArrayOutputStream written = new ByteArrayOutputStream(); doAnswer(new Answer() { + @Override public Integer answer(InvocationOnMock invocation) throws Throwable { ByteBuffer buff = (ByteBuffer) invocation.getArguments()[0]; @@ -508,6 +513,7 @@ public class TcpNioConnectionTests { when(outChannel.socket()).thenReturn(outSocket); TcpNioConnection outboundConnection = new TcpNioConnection(outChannel, true, false, nullPublisher, null); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { ByteBuffer buff = (ByteBuffer) invocation.getArguments()[0]; @@ -582,7 +588,8 @@ public class TcpNioConnectionTests { socket = SocketFactory.getDefault().createSocket("localhost", port); break; } - catch (ConnectException e) { } + catch (ConnectException e) { + } Thread.sleep(100); } assertTrue("Could not open socket to localhost:" + port, n < 100); @@ -629,7 +636,8 @@ public class TcpNioConnectionTests { socket = SocketFactory.getDefault().createSocket("localhost", port); break; } - catch (ConnectException e) { } + catch (ConnectException e) { + } Thread.sleep(100); } assertTrue("Could not open socket to localhost:" + port, n < 100); @@ -728,7 +736,7 @@ public class TcpNioConnectionTests { TestingUtilities.waitListening(factory, 10000L); int port = factory.getPort(); Socket socket = SocketFactory.getDefault().createSocket("localhost", port); - assertTrue(connectionLatch.await(10, TimeUnit.SECONDS)); + assertTrue(connectionLatch.await(10, TimeUnit.SECONDS)); TcpNioConnection connection = (TcpNioConnection) TestUtils.getPropertyValue(factory, "connections", Map.class) .values().iterator().next(); diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/serializer/DeserializationTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/serializer/DeserializationTests.java index 180097fd97..10c7c22fbb 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/serializer/DeserializationTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/tcp/serializer/DeserializationTests.java @@ -80,10 +80,10 @@ public class DeserializationTests { ByteArrayLengthHeaderSerializer serializer = new ByteArrayLengthHeaderSerializer(); byte[] out = serializer.deserialize(socket.getInputStream()); assertEquals("Data", SocketTestUtils.TEST_STRING + SocketTestUtils.TEST_STRING, - new String(out)); + new String(out)); out = serializer.deserialize(socket.getInputStream()); assertEquals("Data", SocketTestUtils.TEST_STRING + SocketTestUtils.TEST_STRING, - new String(out)); + new String(out)); server.close(); done.countDown(); } @@ -99,10 +99,10 @@ public class DeserializationTests { ByteArrayStxEtxSerializer serializer = new ByteArrayStxEtxSerializer(); byte[] out = serializer.deserialize(socket.getInputStream()); assertEquals("Data", SocketTestUtils.TEST_STRING + SocketTestUtils.TEST_STRING, - new String(out)); + new String(out)); out = serializer.deserialize(socket.getInputStream()); assertEquals("Data", SocketTestUtils.TEST_STRING + SocketTestUtils.TEST_STRING, - new String(out)); + new String(out)); server.close(); done.countDown(); } @@ -118,10 +118,10 @@ public class DeserializationTests { ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); byte[] out = serializer.deserialize(socket.getInputStream()); assertEquals("Data", SocketTestUtils.TEST_STRING + SocketTestUtils.TEST_STRING, - new String(out)); + new String(out)); out = serializer.deserialize(socket.getInputStream()); assertEquals("Data", SocketTestUtils.TEST_STRING + SocketTestUtils.TEST_STRING, - new String(out)); + new String(out)); server.close(); done.countDown(); } @@ -137,7 +137,7 @@ public class DeserializationTests { ByteArrayRawSerializer serializer = new ByteArrayRawSerializer(); byte[] out = serializer.deserialize(socket.getInputStream()); assertEquals("Data", SocketTestUtils.TEST_STRING + SocketTestUtils.TEST_STRING, - new String(out)); + new String(out)); server.close(); } @@ -169,7 +169,7 @@ public class DeserializationTests { ByteArrayLengthHeaderSerializer serializer = new ByteArrayLengthHeaderSerializer(); try { serializer.deserialize(socket.getInputStream()); - fail("Expected message length exceeded exception"); + fail("Expected message length exceeded exception"); } catch (IOException e) { if (!e.getMessage().startsWith("Message length")) { @@ -192,7 +192,7 @@ public class DeserializationTests { ByteArrayStxEtxSerializer serializer = new ByteArrayStxEtxSerializer(); try { serializer.deserialize(socket.getInputStream()); - fail("Expected timeout exception"); + fail("Expected timeout exception"); } catch (IOException e) { if (!e.getMessage().startsWith("Read timed out")) { @@ -216,7 +216,7 @@ public class DeserializationTests { serializer.setMaxMessageSize(1024); try { serializer.deserialize(socket.getInputStream()); - fail("Expected message length exceeded exception"); + fail("Expected message length exceeded exception"); } catch (IOException e) { if (!e.getMessage().startsWith("ETX not found")) { @@ -239,7 +239,7 @@ public class DeserializationTests { ByteArrayCrLfSerializer serializer = new ByteArrayCrLfSerializer(); try { serializer.deserialize(socket.getInputStream()); - fail("Expected timout exception"); + fail("Expected timout exception"); } catch (IOException e) { if (!e.getMessage().startsWith("Read timed out")) { @@ -263,7 +263,7 @@ public class DeserializationTests { serializer.setMaxMessageSize(1024); try { serializer.deserialize(socket.getInputStream()); - fail("Expected message length exceeded exception"); + fail("Expected message length exceeded exception"); } catch (IOException e) { if (!e.getMessage().startsWith("CRLF not found")) { diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketMessageMapperTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketMessageMapperTests.java index eed024afa7..d01f65e52c 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketMessageMapperTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketMessageMapperTests.java @@ -71,7 +71,7 @@ public class DatagramPacketMessageMapperTests { assertEquals(new String(message.getPayload()), new String(messageOut.getPayload())); if (ack) { assertEquals(messageOut.getHeaders().get(IpHeaders.ACK_ID).toString(), - message.getHeaders().getId().toString()); + message.getHeaders().getId().toString()); } assertTrue(((String) messageOut.getHeaders().get(IpHeaders.HOSTNAME)).contains("localhost")); mapper.setLookupHost(false); @@ -79,7 +79,7 @@ public class DatagramPacketMessageMapperTests { assertEquals(new String(message.getPayload()), new String(messageOut.getPayload())); if (ack) { assertEquals(messageOut.getHeaders().get(IpHeaders.ACK_ID).toString(), - message.getHeaders().getId().toString()); + message.getHeaders().getId().toString()); } assertFalse(((String) messageOut.getHeaders().get(IpHeaders.HOSTNAME)).contains("localhost")); } diff --git a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketSendingHandlerTests.java b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketSendingHandlerTests.java index 1179e4a452..01fca4e365 100644 --- a/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketSendingHandlerTests.java +++ b/spring-integration-ip/src/test/java/org/springframework/integration/ip/udp/DatagramPacketSendingHandlerTests.java @@ -104,7 +104,7 @@ public class DatagramPacketSendingHandlerTests { Object id = message.getHeaders().get(IpHeaders.ACK_ID); byte[] ack = id.toString().getBytes(); DatagramPacket ackPack = new DatagramPacket(ack, ack.length, - new InetSocketAddress("localHost", ackPort.get())); + new InetSocketAddress("localHost", ackPort.get())); DatagramSocket out = new DatagramSocket(); out.send(ackPack); out.close(); diff --git a/spring-integration-jdbc/src/main/java/org/springframework/integration/jdbc/StoredProcExecutor.java b/spring-integration-jdbc/src/main/java/org/springframework/integration/jdbc/StoredProcExecutor.java index 25e23f10f5..0723c3743c 100644 --- a/spring-integration-jdbc/src/main/java/org/springframework/integration/jdbc/StoredProcExecutor.java +++ b/spring-integration-jdbc/src/main/java/org/springframework/integration/jdbc/StoredProcExecutor.java @@ -59,7 +59,6 @@ import com.google.common.cache.CacheStats; import com.google.common.cache.LoadingCache; - /** * This class is used by all Stored Procedure (Stored Function) components and * provides the core functionality to execute those. @@ -100,7 +99,7 @@ public class StoredProcExecutor implements BeanFactoryAware, InitializingBean { * not support meta data lookups or if you like to provide customized * parameter definitions, this flag can be set to 'true'. It defaults to 'false'. */ - private volatile boolean ignoreColumnMetaData = false; + private volatile boolean ignoreColumnMetaData = false; /** * If this variable is set to true then all results from a stored procedure call @@ -110,7 +109,7 @@ public class StoredProcExecutor implements BeanFactoryAware, InitializingBean { * * Value defaults to true. */ - private volatile boolean skipUndeclaredResults = true; + private volatile boolean skipUndeclaredResults = true; /** * If your database system is not fully supported by Spring and thus obtaining @@ -171,21 +170,20 @@ public class StoredProcExecutor implements BeanFactoryAware, InitializingBean { * Verifies parameters, sets the parameters on {@link SimpleJdbcCallOperations} * and ensures the appropriate {@link SqlParameterSourceFactory} is defined * when {@link ProcedureParameter} are passed in. - * {@inheritDoc} */ @Override public void afterPropertiesSet() { if (this.storedProcedureNameExpression == null) { throw new IllegalArgumentException("You must either provide a " - + "Stored Procedure Name or a Stored Procedure Name Expression."); + + "Stored Procedure Name or a Stored Procedure Name Expression."); } if (this.procedureParameters != null) { if (this.sqlParameterSourceFactory == null) { ExpressionEvaluatingSqlParameterSourceFactory expressionSourceFactory = - new ExpressionEvaluatingSqlParameterSourceFactory(); + new ExpressionEvaluatingSqlParameterSourceFactory(); expressionSourceFactory.setBeanFactory(this.beanFactory); expressionSourceFactory.setStaticParameters(ProcedureParameter.convertStaticParameters(this.procedureParameters)); @@ -198,9 +196,9 @@ public class StoredProcExecutor implements BeanFactoryAware, InitializingBean { if (!(this.sqlParameterSourceFactory instanceof ExpressionEvaluatingSqlParameterSourceFactory)) { throw new IllegalStateException("You are providing 'ProcedureParameters'. " - + "Was expecting the the provided sqlParameterSourceFactory " - + "to be an instance of 'ExpressionEvaluatingSqlParameterSourceFactory', " - + "however the provided one is of type '" + this.sqlParameterSourceFactory.getClass().getName() + "'"); + + "Was expecting the the provided sqlParameterSourceFactory " + + "to be an instance of 'ExpressionEvaluatingSqlParameterSourceFactory', " + + "however the provided one is of type '" + this.sqlParameterSourceFactory.getClass().getName() + "'"); } } @@ -298,7 +296,7 @@ public class StoredProcExecutor implements BeanFactoryAware, InitializingBean { Assert.notNull(message, "The message parameter must not be null."); Assert.notNull(this.usePayloadAsParameterSource, "Property usePayloadAsParameterSource " - + "was Null. Did you call afterPropertiesSet()?"); + + "was Null. Did you call afterPropertiesSet()?"); final Object input; @@ -333,7 +331,7 @@ public class StoredProcExecutor implements BeanFactoryAware, InitializingBean { private Map executeStoredProcedureInternal(Object input, String storedProcedureName) { Assert.notNull(this.sqlParameterSourceFactory, "Property sqlParameterSourceFactory " - + "was Null. Did you call afterPropertiesSet()?"); + + "was Null. Did you call afterPropertiesSet()?"); SimpleJdbcCallOperations localSimpleJdbcCall = obtainSimpleJdbcCall(storedProcedureName); @@ -615,7 +613,7 @@ public class StoredProcExecutor implements BeanFactoryAware, InitializingBean { throw new UnsupportedOperationException("The Google Guava library isn't present in the classpath."); } final CacheStats cacheStats = (CacheStats) getJdbcCallOperationsCacheStatistics(); - final Map cacheStatistics = new HashMap(11); + final Map cacheStatistics = new HashMap(11); cacheStatistics.put("averageLoadPenalty", cacheStats.averageLoadPenalty()); cacheStatistics.put("evictionCount", cacheStats.evictionCount()); cacheStatistics.put("hitCount", cacheStats.hitCount()); diff --git a/spring-integration-jdbc/src/main/java/org/springframework/integration/jdbc/StoredProcOutboundGateway.java b/spring-integration-jdbc/src/main/java/org/springframework/integration/jdbc/StoredProcOutboundGateway.java index 5e3fa6ef5f..2d3c065498 100644 --- a/spring-integration-jdbc/src/main/java/org/springframework/integration/jdbc/StoredProcOutboundGateway.java +++ b/spring-integration-jdbc/src/main/java/org/springframework/integration/jdbc/StoredProcOutboundGateway.java @@ -73,7 +73,7 @@ public class StoredProcOutboundGateway extends AbstractReplyProducingMessageHand throw new MessageHandlingException(requestMessage, "Stored Procedure/Function call returned more than " - + "1 result object and expectSingleResult was 'true'. "); + + "1 result object and expectSingleResult was 'true'. "); } else { diff --git a/spring-integration-jdbc/src/main/java/org/springframework/integration/jdbc/StoredProcPollingChannelAdapter.java b/spring-integration-jdbc/src/main/java/org/springframework/integration/jdbc/StoredProcPollingChannelAdapter.java index 21e9301ebe..3a5eae1304 100644 --- a/spring-integration-jdbc/src/main/java/org/springframework/integration/jdbc/StoredProcPollingChannelAdapter.java +++ b/spring-integration-jdbc/src/main/java/org/springframework/integration/jdbc/StoredProcPollingChannelAdapter.java @@ -91,7 +91,7 @@ public class StoredProcPollingChannelAdapter extends IntegrationObjectSupport im throw new MessagingException( "Stored Procedure/Function call returned more than " - + "1 result object and expectSingleResult was 'true'. "); + + "1 result object and expectSingleResult was 'true'. "); } else { diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcExecutorTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcExecutorTests.java index 36844d2da3..86d4b4cfb3 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcExecutorTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcExecutorTests.java @@ -58,7 +58,7 @@ public class StoredProcExecutorTests { public void testStoredProcExecutorWithNullDataSource() { try { - new StoredProcExecutor(null); + new StoredProcExecutor(null); } catch (IllegalArgumentException e) { assertEquals("dataSource must not be null.", e.getMessage()); @@ -80,7 +80,7 @@ public class StoredProcExecutorTests { } catch (IllegalArgumentException e) { assertEquals("You must either provide a " - + "Stored Procedure Name or a Stored Procedure Name Expression.", e.getMessage()); + + "Stored Procedure Name or a Stored Procedure Name Expression.", e.getMessage()); return; } @@ -182,7 +182,7 @@ public class StoredProcExecutorTests { Map> rowmappers = new HashMap>(); - storedProcExecutor.setReturningResultSetRowMappers(rowmappers); + storedProcExecutor.setReturningResultSetRowMappers(rowmappers); //Should Successfully finish @@ -344,17 +344,17 @@ public class StoredProcExecutorTests { //This should work storedProcExecutor.executeStoredProcedure( - MessageBuilder.withPayload("test") - .setHeader("stored_procedure_name", "123") - .build()); + MessageBuilder.withPayload("test") + .setHeader("stored_procedure_name", "123") + .build()); //This should cause an exception try { storedProcExecutor.executeStoredProcedure( MessageBuilder.withPayload("test") - .setHeader("some_other_header", "123") - .build()); + .setHeader("some_other_header", "123") + .build()); } catch (IllegalArgumentException e) { assertEquals("Unable to resolve Stored Procedure/Function name for the provided Expression 'headers['stored_procedure_name']'.", e.getMessage()); @@ -386,8 +386,8 @@ public class StoredProcExecutorTests { for (int i = 1; i <= 3; i++) { storedProcExecutor.executeStoredProcedure( MessageBuilder.withPayload("test") - .setHeader("stored_procedure_name", "123") - .build()); + .setHeader("stored_procedure_name", "123") + .build()); } final CacheStats stats = (CacheStats) storedProcExecutor.getJdbcCallOperationsCacheStatistics(); @@ -423,8 +423,8 @@ public class StoredProcExecutorTests { for (int i = 1; i <= 10; i++) { storedProcExecutor.executeStoredProcedure( MessageBuilder.withPayload("test") - .setHeader("stored_procedure_name", "123") - .build()); + .setHeader("stored_procedure_name", "123") + .build()); } final CacheStats stats = (CacheStats) storedProcExecutor.getJdbcCallOperationsCacheStatistics(); @@ -438,6 +438,7 @@ public class StoredProcExecutorTests { "guavaCacheWrapper.jdbcCallOperationsCache.localCache"); new DirectFieldAccessor(cache) .setPropertyValue("defaultLoader", new CacheLoader() { + @Override public SimpleJdbcCall load(String storedProcedureName) { return mock(SimpleJdbcCall.class); diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcOutboundGatewayWithSpringContextIntegrationTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcOutboundGatewayWithSpringContextIntegrationTests.java index 5b1a04685e..d9c6712598 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcOutboundGatewayWithSpringContextIntegrationTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/StoredProcOutboundGatewayWithSpringContextIntegrationTests.java @@ -48,61 +48,61 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @DirtiesContext // close at the end after class public class StoredProcOutboundGatewayWithSpringContextIntegrationTests { - @Autowired - private AbstractApplicationContext context; + @Autowired + private AbstractApplicationContext context; - @Autowired - private Consumer consumer; + @Autowired + private Consumer consumer; - @Autowired - CreateUser createUser; + @Autowired + CreateUser createUser; @Test - public void test() throws Exception { + public void test() throws Exception { - createUser.createUser(new User("myUsername", "myPassword", "myEmail")); + createUser.createUser(new User("myUsername", "myPassword", "myEmail")); - List>> received = new ArrayList>>(); + List>> received = new ArrayList>>(); - received.add(consumer.poll(2000)); + received.add(consumer.poll(2000)); - Message> message = received.get(0); - context.stop(); - assertNotNull(message); - assertNotNull(message.getPayload()); - assertNotNull(message.getPayload() instanceof Collection); + Message> message = received.get(0); + context.stop(); + assertNotNull(message); + assertNotNull(message.getPayload()); + assertNotNull(message.getPayload() instanceof Collection); - Collection allUsers = message.getPayload(); + Collection allUsers = message.getPayload(); - assertTrue(allUsers.size() == 1); + assertTrue(allUsers.size() == 1); - } + } - static class Counter { + static class Counter { - private final AtomicInteger count = new AtomicInteger(); + private final AtomicInteger count = new AtomicInteger(); - public Integer next() throws InterruptedException { - if (count.get() > 2) { - //prevent message overload - return null; - } - return Integer.valueOf(count.incrementAndGet()); - } - } + public Integer next() throws InterruptedException { + if (count.get() > 2) { + //prevent message overload + return null; + } + return Integer.valueOf(count.incrementAndGet()); + } + } - static class Consumer { + static class Consumer { - private final BlockingQueue>> messages = new LinkedBlockingQueue>>(); + private final BlockingQueue>> messages = new LinkedBlockingQueue>>(); - @ServiceActivator - public void receive(Message> message) { - messages.add(message); - } + @ServiceActivator + public void receive(Message> message) { + messages.add(message); + } - Message> poll(long timeoutInMillis) throws InterruptedException { - return messages.poll(timeoutInMillis, TimeUnit.MILLISECONDS); - } - } + Message> poll(long timeoutInMillis) throws InterruptedException { + return messages.poll(timeoutInMillis, TimeUnit.MILLISECONDS); + } + } } diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/config/JdbcTypesEnumTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/config/JdbcTypesEnumTests.java index 364a5b6a0c..e5a28aac85 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/config/JdbcTypesEnumTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/config/JdbcTypesEnumTests.java @@ -22,6 +22,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.sql.Types; + import org.junit.Test; public class JdbcTypesEnumTests { @@ -47,7 +48,7 @@ public class JdbcTypesEnumTests { public void testConvertToJdbcTypesEnumWithNullParameter() { try { - JdbcTypesEnum.convertToJdbcTypesEnum(null); + JdbcTypesEnum.convertToJdbcTypesEnum(null); } catch (IllegalArgumentException e) { assertEquals("Parameter sqlTypeAsString, must not be null nor empty", e.getMessage()); @@ -62,7 +63,7 @@ public class JdbcTypesEnumTests { public void testConvertToJdbcTypesEnumWithEmptyParameter() { try { - JdbcTypesEnum.convertToJdbcTypesEnum(" "); + JdbcTypesEnum.convertToJdbcTypesEnum(" "); } catch (IllegalArgumentException e) { assertEquals("Parameter sqlTypeAsString, must not be null nor empty", e.getMessage()); diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/config/StoredProcOutboundGatewayParserTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/config/StoredProcOutboundGatewayParserTests.java index efa4c52022..6adeacb363 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/config/StoredProcOutboundGatewayParserTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/config/StoredProcOutboundGatewayParserTests.java @@ -73,8 +73,8 @@ public class StoredProcOutboundGatewayParserTests { assertEquals(Boolean.TRUE, accessor.getPropertyValue("requiresReply")); source = accessor.getPropertyValue("executor"); accessor = new DirectFieldAccessor(source); - Expression storedProcedureName = (Expression) accessor.getPropertyValue("storedProcedureNameExpression"); - assertEquals("Wrong stored procedure name", "GET_PRIME_NUMBERS", storedProcedureName.getValue()); + Expression storedProcedureName = (Expression) accessor.getPropertyValue("storedProcedureNameExpression"); + assertEquals("Wrong stored procedure name", "GET_PRIME_NUMBERS", storedProcedureName.getValue()); } @Test @@ -90,8 +90,8 @@ public class StoredProcOutboundGatewayParserTests { accessor = new DirectFieldAccessor(messagingTemplate); - Long sendTimeout = (Long) accessor.getPropertyValue("sendTimeout"); - assertEquals("Wrong sendTimeout", Long.valueOf(555L), sendTimeout); + Long sendTimeout = (Long) accessor.getPropertyValue("sendTimeout"); + assertEquals("Wrong sendTimeout", Long.valueOf(555L), sendTimeout); } @@ -104,7 +104,7 @@ public class StoredProcOutboundGatewayParserTests { accessor = new DirectFieldAccessor(source); source = accessor.getPropertyValue("executor"); accessor = new DirectFieldAccessor(source); - boolean skipUndeclaredResults = (Boolean) accessor.getPropertyValue("skipUndeclaredResults"); + boolean skipUndeclaredResults = (Boolean) accessor.getPropertyValue("skipUndeclaredResults"); assertFalse(skipUndeclaredResults); } @@ -179,7 +179,7 @@ public class StoredProcOutboundGatewayParserTests { accessor = new DirectFieldAccessor(source); source = accessor.getPropertyValue("executor"); accessor = new DirectFieldAccessor(source); - Object procedureParameters = accessor.getPropertyValue("procedureParameters"); + Object procedureParameters = accessor.getPropertyValue("procedureParameters"); assertNotNull(procedureParameters); assertTrue(procedureParameters instanceof List); @@ -192,15 +192,15 @@ public class StoredProcOutboundGatewayParserTests { ProcedureParameter parameter3 = procedureParametersAsList.get(2); ProcedureParameter parameter4 = procedureParametersAsList.get(3); - assertEquals("username", parameter1.getName()); + assertEquals("username", parameter1.getName()); assertEquals("description", parameter2.getName()); - assertEquals("password", parameter3.getName()); - assertEquals("age", parameter4.getName()); + assertEquals("password", parameter3.getName()); + assertEquals("age", parameter4.getName()); - assertEquals("kenny", parameter1.getValue()); - assertEquals("Who killed Kenny?", parameter2.getValue()); + assertEquals("kenny", parameter1.getValue()); + assertEquals("Who killed Kenny?", parameter2.getValue()); assertNull(parameter3.getValue()); - assertEquals(Integer.valueOf(30), parameter4.getValue()); + assertEquals(Integer.valueOf(30), parameter4.getValue()); assertNull(parameter1.getExpression()); assertNull(parameter2.getExpression()); @@ -219,7 +219,7 @@ public class StoredProcOutboundGatewayParserTests { accessor = new DirectFieldAccessor(source); source = accessor.getPropertyValue("executor"); accessor = new DirectFieldAccessor(source); - Object returningResultSetRowMappers = accessor.getPropertyValue("returningResultSetRowMappers"); + Object returningResultSetRowMappers = accessor.getPropertyValue("returningResultSetRowMappers"); assertNotNull(returningResultSetRowMappers); assertTrue(returningResultSetRowMappers instanceof Map); @@ -229,7 +229,7 @@ public class StoredProcOutboundGatewayParserTests { Entry mapEntry1 = returningResultSetRowMappersAsMap.entrySet().iterator().next(); - assertEquals("out", mapEntry1.getKey()); + assertEquals("out", mapEntry1.getKey()); assertTrue(mapEntry1.getValue() instanceof PrimeMapper); } @@ -245,7 +245,7 @@ public class StoredProcOutboundGatewayParserTests { accessor = new DirectFieldAccessor(source); source = accessor.getPropertyValue("executor"); accessor = new DirectFieldAccessor(source); - Object sqlParameters = accessor.getPropertyValue("sqlParameters"); + Object sqlParameters = accessor.getPropertyValue("sqlParameters"); assertNotNull(sqlParameters); assertTrue(sqlParameters instanceof List); @@ -258,14 +258,14 @@ public class StoredProcOutboundGatewayParserTests { SqlParameter parameter3 = sqlParametersAsList.get(2); SqlParameter parameter4 = sqlParametersAsList.get(3); - assertEquals("username", parameter1.getName()); - assertEquals("password", parameter2.getName()); - assertEquals("age", parameter3.getName()); + assertEquals("username", parameter1.getName()); + assertEquals("password", parameter2.getName()); + assertEquals("age", parameter3.getName()); assertEquals("description", parameter4.getName()); assertNull("Expect that the scale is null.", parameter1.getScale()); assertNull("Expect that the scale is null.", parameter2.getScale()); - assertEquals("Expect that the scale is 5.", Integer.valueOf(5), parameter3.getScale()); + assertEquals("Expect that the scale is 5.", Integer.valueOf(5), parameter3.getScale()); assertNull("Expect that the scale is null.", parameter4.getScale()); assertEquals("SqlType is ", Types.VARCHAR, parameter1.getSqlType()); @@ -297,8 +297,8 @@ public class StoredProcOutboundGatewayParserTests { } public void setUp(String name, Class cls) { - this.context = new ClassPathXmlApplicationContext(name, cls); - this.outboundGateway = this.context.getBean("storedProcedureOutboundGateway", EventDrivenConsumer.class); + this.context = new ClassPathXmlApplicationContext(name, cls); + this.outboundGateway = this.context.getBean("storedProcedureOutboundGateway", EventDrivenConsumer.class); } public static class FooAdvice extends AbstractRequestHandlerAdvice { diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/storedproc/ProcedureParameterTests.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/storedproc/ProcedureParameterTests.java index 0436120f68..7ce7f6ab65 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/storedproc/ProcedureParameterTests.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/storedproc/ProcedureParameterTests.java @@ -48,7 +48,7 @@ public class ProcedureParameterTests { Map expressionParameters = ProcedureParameter.convertExpressions(procedureParameters); - assertTrue("Expected 2 expression parameters.", expressionParameters.size() == 2); + assertTrue("Expected 2 expression parameters.", expressionParameters.size() == 2); } @Test @@ -58,7 +58,7 @@ public class ProcedureParameterTests { Map staticParameters = ProcedureParameter.convertStaticParameters(procedureParameters); - assertTrue("Expected 3 static parameters.", staticParameters.size() == 3); + assertTrue("Expected 3 static parameters.", staticParameters.size() == 3); } @Test diff --git a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/storedproc/derby/DerbyFunctions.java b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/storedproc/derby/DerbyFunctions.java index 5eb4703f65..c0410bef97 100644 --- a/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/storedproc/derby/DerbyFunctions.java +++ b/spring-integration-jdbc/src/test/java/org/springframework/integration/jdbc/storedproc/derby/DerbyFunctions.java @@ -31,7 +31,7 @@ public final class DerbyFunctions { } public static String convertStringToUpperCase(String invalue) { - return invalue.toUpperCase(Locale.ENGLISH); - } + return invalue.toUpperCase(Locale.ENGLISH); + } } diff --git a/spring-integration-jms/src/main/java/org/springframework/integration/jms/JmsMessageDrivenEndpoint.java b/spring-integration-jms/src/main/java/org/springframework/integration/jms/JmsMessageDrivenEndpoint.java index c0658c1355..06e8bf5bf5 100644 --- a/spring-integration-jms/src/main/java/org/springframework/integration/jms/JmsMessageDrivenEndpoint.java +++ b/spring-integration-jms/src/main/java/org/springframework/integration/jms/JmsMessageDrivenEndpoint.java @@ -63,7 +63,7 @@ public class JmsMessageDrivenEndpoint extends AbstractEndpoint implements Dispos * coerced when no sessionAcknowledgeMode was supplied. */ private JmsMessageDrivenEndpoint(AbstractMessageListenerContainer listenerContainer, - ChannelPublishingJmsMessageListener listener, boolean externalContainer) { + ChannelPublishingJmsMessageListener listener, boolean externalContainer) { Assert.notNull(listenerContainer, "listener container must not be null"); Assert.notNull(listener, "listener must not be null"); if (logger.isWarnEnabled() && listenerContainer.getMessageListener() != null) { diff --git a/spring-integration-jms/src/main/java/org/springframework/integration/jms/JmsOutboundGateway.java b/spring-integration-jms/src/main/java/org/springframework/integration/jms/JmsOutboundGateway.java index 35d10c52d9..7c4e3157fe 100644 --- a/spring-integration-jms/src/main/java/org/springframework/integration/jms/JmsOutboundGateway.java +++ b/spring-integration-jms/src/main/java/org/springframework/integration/jms/JmsOutboundGateway.java @@ -531,8 +531,8 @@ public class JmsOutboundGateway extends AbstractReplyProducingMessageHandler imp } Assert.notNull(this.connectionFactory, "connectionFactory must not be null"); Assert.isTrue(this.requestDestination != null - ^ this.requestDestinationName != null - ^ this.requestDestinationExpressionProcessor != null, + ^ this.requestDestinationName != null + ^ this.requestDestinationExpressionProcessor != null, "Exactly one of 'requestDestination', 'requestDestinationName', " + "or 'requestDestinationExpression' is required."); if (this.requestDestinationExpressionProcessor != null) { @@ -549,7 +549,7 @@ public class JmsOutboundGateway extends AbstractReplyProducingMessageHandler imp */ if (this.useReplyContainer && (this.correlationKey == null && (this.replyDestination != null || this.replyDestinationName != null) || - this.replyDestinationExpressionProcessor != null)) { + this.replyDestinationExpressionProcessor != null)) { if (logger.isWarnEnabled()) { logger.warn("The gateway cannot use a reply listener container with a specified " + "destination(Name/Expression) " + @@ -643,7 +643,7 @@ public class JmsOutboundGateway extends AbstractReplyProducingMessageHandler imp } } } - else if (this.replyContainerProperties.getSessionAcknowledgeMode() != null) { + else if (this.replyContainerProperties.getSessionAcknowledgeMode() != null) { Integer sessionAcknowledgeMode = this.replyContainerProperties.getSessionAcknowledgeMode(); if (Session.SESSION_TRANSACTED == sessionAcknowledgeMode) { container.setSessionTransacted(true); @@ -986,8 +986,8 @@ public class JmsOutboundGateway extends AbstractReplyProducingMessageHandler imp long replyTimeout = isTemporaryReplyTo ? Long.MIN_VALUE : this.receiveTimeout < 0 - ? Long.MAX_VALUE - : System.currentTimeMillis() + this.receiveTimeout; + ? Long.MAX_VALUE + : System.currentTimeMillis() + this.receiveTimeout; try { do { try { 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 2c8ce8cf0a..f58d8773e8 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 @@ -54,7 +54,9 @@ public class DefaultJmsHeaderMapperTests { @Test public void testJmsReplyToMappedFromHeader() throws JMSException { - Destination replyTo = new Destination() { }; + Destination replyTo = new Destination() { + + }; Message message = MessageBuilder.withPayload("test") .setHeader(JmsHeaders.REPLY_TO, replyTo).build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); @@ -172,7 +174,9 @@ public class DefaultJmsHeaderMapperTests { @Test public void testUserDefinedPropertyWithUnsupportedType() throws JMSException { - Destination destination = new Destination() { }; + Destination destination = new Destination() { + + }; Message message = MessageBuilder.withPayload("test") .setHeader("destination", destination) .build(); @@ -185,7 +189,9 @@ public class DefaultJmsHeaderMapperTests { @Test public void testJmsReplyToMappedToHeader() throws JMSException { - Destination replyTo = new Destination() { }; + Destination replyTo = new Destination() { + + }; javax.jms.Message jmsMessage = new StubTextMessage(); jmsMessage.setJMSReplyTo(replyTo); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); @@ -310,13 +316,14 @@ public class DefaultJmsHeaderMapperTests { .build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage() { - @Override - public void setObjectProperty(String name, Object value) throws JMSException { - if (name.equals("bad")) { - throw new JMSException("illegal property"); - } - super.setObjectProperty(name, value); - } + + @Override + public void setObjectProperty(String name, Object value) throws JMSException { + if (name.equals("bad")) { + throw new JMSException("illegal property"); + } + super.setObjectProperty(name, value); + } }; mapper.fromHeaders(message.getHeaders(), jmsMessage); Object foo = jmsMessage.getObjectProperty("foo"); @@ -336,13 +343,14 @@ public class DefaultJmsHeaderMapperTests { .build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage() { - @Override - public void setObjectProperty(String name, Object value) throws JMSException { - if (name.equals("bad")) { - throw new IllegalArgumentException("illegal property"); - } - super.setObjectProperty(name, value); - } + + @Override + public void setObjectProperty(String name, Object value) throws JMSException { + if (name.equals("bad")) { + throw new IllegalArgumentException("illegal property"); + } + super.setObjectProperty(name, value); + } }; mapper.fromHeaders(message.getHeaders(), jmsMessage); Object foo = jmsMessage.getObjectProperty("foo"); @@ -361,10 +369,11 @@ public class DefaultJmsHeaderMapperTests { .build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage() { - @Override - public void setJMSReplyTo(Destination replyTo) throws JMSException { - throw new JMSException("illegal property"); - } + + @Override + public void setJMSReplyTo(Destination replyTo) throws JMSException { + throw new JMSException("illegal property"); + } }; mapper.fromHeaders(message.getHeaders(), jmsMessage); assertNull(jmsMessage.getJMSReplyTo()); @@ -380,10 +389,11 @@ public class DefaultJmsHeaderMapperTests { .build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage() { - @Override - public void setJMSType(String type) throws JMSException { - throw new JMSException("illegal property"); - } + + @Override + public void setJMSType(String type) throws JMSException { + throw new JMSException("illegal property"); + } }; mapper.fromHeaders(message.getHeaders(), jmsMessage); assertNull(jmsMessage.getJMSType()); @@ -399,10 +409,11 @@ public class DefaultJmsHeaderMapperTests { .build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage() { - @Override - public void setJMSCorrelationID(String correlationId) throws JMSException { - throw new JMSException("illegal property"); - } + + @Override + public void setJMSCorrelationID(String correlationId) throws JMSException { + throw new JMSException("illegal property"); + } }; mapper.fromHeaders(message.getHeaders(), jmsMessage); assertNull(jmsMessage.getJMSCorrelationID()); @@ -418,10 +429,11 @@ public class DefaultJmsHeaderMapperTests { .build(); DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage() { - @Override - public void setJMSCorrelationID(String correlationId) throws JMSException { - throw new JMSException("illegal property"); - } + + @Override + public void setJMSCorrelationID(String correlationId) throws JMSException { + throw new JMSException("illegal property"); + } }; mapper.fromHeaders(message.getHeaders(), jmsMessage); assertNull(jmsMessage.getJMSCorrelationID()); @@ -433,10 +445,11 @@ public class DefaultJmsHeaderMapperTests { public void attemptToReadDisallowedMessageIdPropertyIsNotFatal() throws JMSException { DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage() { - @Override - public String getJMSMessageID() throws JMSException { - throw new JMSException("illegal property"); - } + + @Override + public String getJMSMessageID() throws JMSException { + throw new JMSException("illegal property"); + } }; jmsMessage.setStringProperty("foo", "bar"); Map headers = mapper.toHeaders(jmsMessage); @@ -449,10 +462,11 @@ public class DefaultJmsHeaderMapperTests { public void attemptToReadDisallowedCorrelationIdPropertyIsNotFatal() throws JMSException { DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage() { - @Override - public String getJMSCorrelationID() throws JMSException { - throw new JMSException("illegal property"); - } + + @Override + public String getJMSCorrelationID() throws JMSException { + throw new JMSException("illegal property"); + } }; jmsMessage.setStringProperty("foo", "bar"); Map headers = mapper.toHeaders(jmsMessage); @@ -465,10 +479,11 @@ public class DefaultJmsHeaderMapperTests { public void attemptToReadDisallowedTypePropertyIsNotFatal() throws JMSException { DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage() { - @Override - public String getJMSType() throws JMSException { - throw new JMSException("illegal property"); - } + + @Override + public String getJMSType() throws JMSException { + throw new JMSException("illegal property"); + } }; jmsMessage.setStringProperty("foo", "bar"); Map headers = mapper.toHeaders(jmsMessage); @@ -481,10 +496,11 @@ public class DefaultJmsHeaderMapperTests { public void attemptToReadDisallowedReplyToPropertyIsNotFatal() throws JMSException { DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage() { - @Override - public Destination getJMSReplyTo() throws JMSException { - throw new JMSException("illegal property"); - } + + @Override + public Destination getJMSReplyTo() throws JMSException { + throw new JMSException("illegal property"); + } }; jmsMessage.setStringProperty("foo", "bar"); Map headers = mapper.toHeaders(jmsMessage); @@ -497,10 +513,11 @@ public class DefaultJmsHeaderMapperTests { public void attemptToReadDisallowedRedeliveredPropertyIsNotFatal() throws JMSException { DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); javax.jms.Message jmsMessage = new StubTextMessage() { - @Override - public boolean getJMSRedelivered() throws JMSException { - throw new JMSException("illegal property"); - } + + @Override + public boolean getJMSRedelivered() throws JMSException { + throw new JMSException("illegal property"); + } }; jmsMessage.setStringProperty("foo", "bar"); Map headers = mapper.toHeaders(jmsMessage); diff --git a/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/ActiveMqTestUtils.java b/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/ActiveMqTestUtils.java index 8403b85232..b573a08f31 100644 --- a/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/ActiveMqTestUtils.java +++ b/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/ActiveMqTestUtils.java @@ -47,9 +47,9 @@ public class ActiveMqTestUtils { if (directory.exists()) { String[] children = directory.list(); if (children != null) { - for (int i = 0; i < children.length; i++) { - deleteDir(new File(directory, children[i])); - } + for (int i = 0; i < children.length; i++) { + deleteDir(new File(directory, children[i])); + } } } directory.delete(); diff --git a/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/JmsChannelHistoryTests.java b/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/JmsChannelHistoryTests.java index 9b7e96d1c4..2ed3d0241e 100644 --- a/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/JmsChannelHistoryTests.java +++ b/spring-integration-jms/src/test/java/org/springframework/integration/jms/config/JmsChannelHistoryTests.java @@ -56,6 +56,7 @@ public class JmsChannelHistoryTests { Message message = new GenericMessage("hello"); doAnswer(new Answer() { + @Override @SuppressWarnings("unchecked") public Object answer(InvocationOnMock invocation) { @@ -80,7 +81,7 @@ public class JmsChannelHistoryTests { channel.send(new GenericMessage("hello")); Message resultMessage = resultChannel.receive(10000); MessageHistory history = MessageHistory.read(resultMessage); - assertTrue(history.get(0).contains("jmsChannel")); + assertTrue(history.get(0).contains("jmsChannel")); ac.close(); } diff --git a/spring-integration-jmx/src/main/java/org/springframework/integration/jmx/NotificationListeningMessageProducer.java b/spring-integration-jmx/src/main/java/org/springframework/integration/jmx/NotificationListeningMessageProducer.java index 2b4f8e7863..53c5a7aed9 100644 --- a/spring-integration-jmx/src/main/java/org/springframework/integration/jmx/NotificationListeningMessageProducer.java +++ b/spring-integration-jmx/src/main/java/org/springframework/integration/jmx/NotificationListeningMessageProducer.java @@ -143,7 +143,7 @@ public class NotificationListeningMessageProducer extends MessageProducerSupport @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (!this.listenerRegisteredOnStartup.getAndSet(true) && isAutoStartup()) { - doStart(); + doStart(); } } @@ -162,7 +162,7 @@ public class NotificationListeningMessageProducer extends MessageProducerSupport Collection objectNames = this.retrieveMBeanNames(); if (objectNames.size() < 1) { this.logger.error("No MBeans found matching ObjectName pattern(s): " + - Arrays.asList(this.objectNames)); + Arrays.asList(this.objectNames)); } for (ObjectName objectName : objectNames) { this.server.addNotificationListener(objectName, this, this.filter, this.handback); diff --git a/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/config/xml/JpaParserUtils.java b/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/config/xml/JpaParserUtils.java index 59538e940d..3141649b53 100644 --- a/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/config/xml/JpaParserUtils.java +++ b/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/config/xml/JpaParserUtils.java @@ -20,6 +20,8 @@ import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Element; + import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.TypedStringValue; import org.springframework.beans.factory.support.BeanDefinitionBuilder; @@ -31,7 +33,6 @@ import org.springframework.integration.jpa.support.JpaParameter; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import org.springframework.util.xml.DomUtils; -import org.w3c.dom.Element; /** * Contains various utility methods for parsing JPA Adapter specific namesspace @@ -61,9 +62,9 @@ public final class JpaParserUtils { * @return The BeanDefinitionBuilder for the JpaExecutor */ public static BeanDefinitionBuilder getJpaExecutorBuilder(final Element element, - final ParserContext parserContext) { + final ParserContext parserContext) { - Assert.notNull(element, "The provided element must not be null."); + Assert.notNull(element, "The provided element must not be null."); Assert.notNull(parserContext, "The provided parserContext must not be null."); final Object source = parserContext.extractSource(element); @@ -72,9 +73,9 @@ public final class JpaParserUtils { int attributeCount = 0; - final String entityManagerRef = element.getAttribute("entity-manager"); + final String entityManagerRef = element.getAttribute("entity-manager"); final String entityManagerFactoryRef = element.getAttribute("entity-manager-factory"); - final String jpaOperationsRef = element.getAttribute("jpa-operations"); + final String jpaOperationsRef = element.getAttribute("jpa-operations"); if (StringUtils.hasText(jpaOperationsRef)) { attributeCount++; @@ -159,7 +160,7 @@ public final class JpaParserUtils { public static ManagedList getJpaParameterBeanDefinitions( Element jpaComponent, ParserContext parserContext) { - Assert.notNull(jpaComponent, "The provided element must not be null."); + Assert.notNull(jpaComponent, "The provided element must not be null."); Assert.notNull(parserContext, "The provided parserContext must not be null."); final ManagedList parameterList = new ManagedList(); @@ -171,10 +172,10 @@ public final class JpaParserUtils { final BeanDefinitionBuilder parameterBuilder = BeanDefinitionBuilder.genericBeanDefinition(JpaParameter.class); - String name = childElement.getAttribute("name"); + String name = childElement.getAttribute("name"); String expression = childElement.getAttribute("expression"); - String value = childElement.getAttribute("value"); - String type = childElement.getAttribute("type"); + String value = childElement.getAttribute("value"); + String type = childElement.getAttribute("type"); if (StringUtils.hasText(name)) { parameterBuilder.addPropertyValue("name", name); @@ -191,7 +192,7 @@ public final class JpaParserUtils { if (logger.isInfoEnabled()) { logger.info(String .format("Type attribute not set for parameter '%s'. Defaulting to " - + "'java.lang.String'.", value)); + + "'java.lang.String'.", value)); } parameterBuilder.addPropertyValue("value", diff --git a/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/core/AbstractJpaOperations.java b/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/core/AbstractJpaOperations.java index 72e4baa1bf..3ca95d914b 100644 --- a/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/core/AbstractJpaOperations.java +++ b/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/core/AbstractJpaOperations.java @@ -38,13 +38,13 @@ abstract class AbstractJpaOperations implements JpaOperations, InitializingBean public void setEntityManager(EntityManager entityManager) { - Assert.notNull(entityManager, "The provided entitymanager must not be null."); + Assert.notNull(entityManager, "The provided entityManager must not be null."); this.entityManager = entityManager; } public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) { - Assert.notNull(entityManagerFactory, "The provided entitymanagerFactory must not be null."); + Assert.notNull(entityManagerFactory, "The provided entityManagerFactory must not be null."); this.entityManagerFactory = entityManagerFactory; } @@ -62,8 +62,8 @@ abstract class AbstractJpaOperations implements JpaOperations, InitializingBean this.entityManager = SharedEntityManagerCreator.createSharedEntityManager(this.entityManagerFactory); } - Assert.notNull(this.entityManager, "The entitymanager is null. Please set " + - "either the entityManager or the entityManagerFactory."); + Assert.notNull(this.entityManager, "The entityManager is null. Please set " + + "either the entityManager or the entityManagerFactory."); } diff --git a/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/core/JpaExecutor.java b/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/core/JpaExecutor.java index 8c08dad83d..e51e7e36b8 100644 --- a/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/core/JpaExecutor.java +++ b/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/core/JpaExecutor.java @@ -73,9 +73,12 @@ public class JpaExecutor implements InitializingBean, BeanFactoryAware { private volatile List jpaParameters; private volatile Class entityClass; - private volatile String jpaQuery; - private volatile String nativeQuery; - private volatile String namedQuery; + + private volatile String jpaQuery; + + private volatile String nativeQuery; + + private volatile String namedQuery; private volatile Expression maxResultsExpression; @@ -86,19 +89,20 @@ public class JpaExecutor implements InitializingBean, BeanFactoryAware { private volatile PersistMode persistMode = PersistMode.MERGE; private volatile ParameterSourceFactory parameterSourceFactory = null; + private volatile ParameterSource parameterSource; - private volatile boolean flush = false; + private volatile boolean flush = false; private volatile int flushSize = 0; - private volatile boolean clearOnFlush = false; + private volatile boolean clearOnFlush = false; - private volatile boolean deleteAfterPoll = false; + private volatile boolean deleteAfterPoll = false; - private volatile boolean deleteInBatch = false; + private volatile boolean deleteInBatch = false; - private volatile boolean expectSingleResult = false; + private volatile boolean expectSingleResult = false; /** * Indicates that whether only the payload of the passed in {@link Message} @@ -172,7 +176,7 @@ public class JpaExecutor implements InitializingBean, BeanFactoryAware { if (this.parameterSourceFactory == null) { ExpressionEvaluatingParameterSourceFactory expressionSourceFactory = - new ExpressionEvaluatingParameterSourceFactory(this.beanFactory); + new ExpressionEvaluatingParameterSourceFactory(this.beanFactory); expressionSourceFactory.setParameters(this.jpaParameters); this.parameterSourceFactory = expressionSourceFactory; @@ -181,9 +185,9 @@ public class JpaExecutor implements InitializingBean, BeanFactoryAware { if (!(this.parameterSourceFactory instanceof ExpressionEvaluatingParameterSourceFactory)) { throw new IllegalStateException("You are providing 'JpaParameters'. " - + "Was expecting the the provided jpaParameterSourceFactory " - + "to be an instance of 'ExpressionEvaluatingJpaParameterSourceFactory', " - + "however the provided one is of type '" + this.parameterSourceFactory.getClass().getName() + "'"); + + "Was expecting the the provided jpaParameterSourceFactory " + + "to be an instance of 'ExpressionEvaluatingJpaParameterSourceFactory', " + + "however the provided one is of type '" + this.parameterSourceFactory.getClass().getName() + "'"); } } @@ -373,7 +377,7 @@ public class JpaExecutor implements InitializingBean, BeanFactoryAware { } else { throw new IllegalArgumentException("Expected the value to be a Number" + - " got " + evaluationResult.getClass().getName()); + " got " + evaluationResult.getClass().getName()); } } } @@ -403,23 +407,23 @@ public class JpaExecutor implements InitializingBean, BeanFactoryAware { List payload = null; if (this.jpaQuery != null) { payload = this.jpaOperations.getResultListForQuery(this.jpaQuery, jpaQLParameterSource, - firstResult, maxNumberOfResults); + firstResult, maxNumberOfResults); } else if (this.nativeQuery != null) { payload = this.jpaOperations.getResultListForNativeQuery(this.nativeQuery, this.entityClass, jpaQLParameterSource, - firstResult, maxNumberOfResults); + firstResult, maxNumberOfResults); } else if (this.namedQuery != null) { payload = this.jpaOperations.getResultListForNamedQuery(this.namedQuery, jpaQLParameterSource, - firstResult, maxNumberOfResults); + firstResult, maxNumberOfResults); } else if (this.entityClass != null) { payload = this.jpaOperations.getResultListForClass(this.entityClass, firstResult, maxNumberOfResults); } else { throw new IllegalStateException("For the polling operation, one of " - + "the following properties must be specified: " - + "query, namedQuery or entityClass."); + + "the following properties must be specified: " + + "query, namedQuery or entityClass."); } return payload; } @@ -439,7 +443,7 @@ public class JpaExecutor implements InitializingBean, BeanFactoryAware { */ public void setJpaQuery(String jpaQuery) { Assert.isTrue(this.nativeQuery == null && this.namedQuery == null, "You can define only one of the " - + "properties 'jpaQuery', 'nativeQuery', 'namedQuery'"); + + "properties 'jpaQuery', 'nativeQuery', 'namedQuery'"); Assert.hasText(jpaQuery, "jpaQuery must neither be null nor empty."); this.jpaQuery = jpaQuery; } @@ -605,7 +609,6 @@ public class JpaExecutor implements InitializingBean, BeanFactoryAware { } - /** * Set the expression for maximum number of results expression. It has be a non null value * Not setting one will default to the behavior of fetching all the records @@ -623,7 +626,7 @@ public class JpaExecutor implements InitializingBean, BeanFactoryAware { * @see Query#setMaxResults(int) */ public void setMaxNumberOfResults(int maxNumberOfResults) { - this.setMaxResultsExpression(new LiteralExpression("" + maxNumberOfResults)); + this.setMaxResultsExpression(new LiteralExpression("" + maxNumberOfResults)); } } diff --git a/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/inbound/JpaPollingChannelAdapter.java b/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/inbound/JpaPollingChannelAdapter.java index 2a030a549c..6e9de2699a 100644 --- a/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/inbound/JpaPollingChannelAdapter.java +++ b/spring-integration-jpa/src/main/java/org/springframework/integration/jpa/inbound/JpaPollingChannelAdapter.java @@ -69,8 +69,8 @@ public class JpaPollingChannelAdapter extends IntegrationObjectSupport implement */ @Override protected void onInit() throws Exception { - super.onInit(); - this.jpaExecutor.setBeanFactory(this.getBeanFactory()); + super.onInit(); + this.jpaExecutor.setBeanFactory(this.getBeanFactory()); } /** diff --git a/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/core/AbstractJpaOperationsTests.java b/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/core/AbstractJpaOperationsTests.java index ba055e3518..352034637d 100644 --- a/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/core/AbstractJpaOperationsTests.java +++ b/spring-integration-jpa/src/test/java/org/springframework/integration/jpa/core/AbstractJpaOperationsTests.java @@ -60,9 +60,6 @@ public class AbstractJpaOperationsTests { @Autowired protected EntityManager entityManager; - /** - * Test method for {@link org.springframework.integration.jpa.core.DefaultJpaOperations#executeUpdate(java.lang.String, org.springframework.integration.jpa.core.JpaQLParameterSource)}. - */ public void testGetAllStudents() { final JpaOperations jpaOperations = getJpaOperations(entityManager); @@ -72,22 +69,16 @@ public class AbstractJpaOperationsTests { } - /** - * Test method for {@link org.springframework.integration.jpa.core.DefaultJpaOperations#executeUpdate(java.lang.String, org.springframework.integration.jpa.core.JpaQLParameterSource)}. - */ public void testGetAllStudentsWithMaxResults() { final JpaOperations jpaOperations = getJpaOperations(entityManager); final List students = jpaOperations.getResultListForClass(StudentDomain.class, 0, 2); Assert.assertTrue(String.format("Was expecting 2 Students to be returned but got '%s'.", students.size()), - students.size() == 2); + students.size() == 2); } - /** - * Test method for {@link org.springframework.integration.jpa.core.DefaultJpaOperations#executeUpdate(java.lang.String, org.springframework.integration.jpa.core.JpaQLParameterSource)}. - */ public void testExecuteUpdate() { final JpaOperations jpaOperations = getJpaOperations(entityManager); @@ -101,8 +92,9 @@ public class AbstractJpaOperationsTests { new ExpressionEvaluatingParameterSourceFactory(mock(BeanFactory.class)); ParameterSource source = requestParameterSourceFactory.createParameterSource(student); - int updatedRecords = jpaOperations.executeUpdate("update Student s set s.lastName = :lastName, s.lastUpdated = :lastUpdated " - + "where s.rollNumber in (select max(a.rollNumber) from Student a)", source); + int updatedRecords = jpaOperations.executeUpdate("update Student s " + + "set s.lastName = :lastName, s.lastUpdated = :lastUpdated " + + "where s.rollNumber in (select max(a.rollNumber) from Student a)", source); entityManager.flush(); @@ -111,9 +103,6 @@ public class AbstractJpaOperationsTests { } - /** - * Test method for {@link org.springframework.integration.jpa.core.DefaultJpaOperations#executeUpdateWithNamedQuery(java.lang.String, org.springframework.integration.jpa.core.JpaQLParameterSource)}. - */ public void testExecuteUpdateWithNamedQuery() { final JpaOperations jpaOperations = getJpaOperations(entityManager); @@ -131,9 +120,6 @@ public class AbstractJpaOperationsTests { Assert.assertNull(student.getRollNumber()); } - /** - * Test method for {@link org.springframework.integration.jpa.core.DefaultJpaOperations#executeUpdateWithNativeQuery(java.lang.String, org.springframework.integration.jpa.core.JpaQLParameterSource)}. - */ public void testExecuteUpdateWithNativeQuery() { final JpaOperations jpaOperations = getJpaOperations(entityManager); @@ -143,8 +129,9 @@ public class AbstractJpaOperationsTests { new ExpressionEvaluatingParameterSourceFactory(mock(BeanFactory.class)); ParameterSource source = requestParameterSourceFactory.createParameterSource(student); - int updatedRecords = jpaOperations.executeUpdateWithNativeQuery("update Student set lastName = :lastName, lastUpdated = :lastUpdated " - + "where rollNumber in (select max(a.rollNumber) from Student a)", source); + int updatedRecords = jpaOperations.executeUpdateWithNativeQuery("update Student " + + "set lastName = :lastName, lastUpdated = :lastUpdated " + + "where rollNumber in (select max(a.rollNumber) from Student a)", source); entityManager.flush(); @@ -152,10 +139,6 @@ public class AbstractJpaOperationsTests { Assert.assertNull(student.getRollNumber()); } - /** - * Test method for {@link DefaultJpaOperations#getResultListForNativeQuery(String, Class, JpaQLParameterSource, int, int)}. - * @throws ParseException - */ public void testExecuteSelectWithNativeQueryReturningEntityClass() throws ParseException { final JpaOperations jpaOperations = getJpaOperations(entityManager); @@ -179,14 +162,11 @@ public class AbstractJpaOperationsTests { } - /** - * Test method for {@link DefaultJpaOperations#getResultListForNativeQuery(String, Class, JpaQLParameterSource, int, int)}. - * @throws ParseException - */ public void testExecuteSelectWithNativeQuery() throws ParseException { final JpaOperations jpaOperations = getJpaOperations(entityManager); - String selectSqlQuery = "select rollNumber, firstName, lastName, gender, dateOfBirth, lastUpdated from Student where lastName = 'Last One'"; + String selectSqlQuery = "select rollNumber, firstName, lastName, gender, dateOfBirth, lastUpdated " + + "from Student where lastName = 'Last One'"; List students = jpaOperations.getResultListForNativeQuery(selectSqlQuery, null, null, 0, 0); diff --git a/spring-integration-mail/src/main/java/org/springframework/integration/mail/MailTransportUtils.java b/spring-integration-mail/src/main/java/org/springframework/integration/mail/MailTransportUtils.java index 47a08477ab..e134265f8f 100644 --- a/spring-integration-mail/src/main/java/org/springframework/integration/mail/MailTransportUtils.java +++ b/spring-integration-mail/src/main/java/org/springframework/integration/mail/MailTransportUtils.java @@ -36,27 +36,27 @@ import org.springframework.util.StringUtils; */ public abstract class MailTransportUtils { - private static final Log logger = LogFactory.getLog(MailTransportUtils.class); + private static final Log logger = LogFactory.getLog(MailTransportUtils.class); - /** - * Close the given JavaMail Service and ignore any thrown exception. This is useful for typical finally - * blocks in manual JavaMail code. - * - * @param service the JavaMail Service to close (may be null) - * @see Transport - * @see Store - */ - public static void closeService(Service service) { - if (service != null) { - try { - service.close(); - } - catch (MessagingException ex) { - logger.debug("Could not close JavaMail Service", ex); - } - } - } + /** + * Close the given JavaMail Service and ignore any thrown exception. This is useful for typical finally + * blocks in manual JavaMail code. + * + * @param service the JavaMail Service to close (may be null) + * @see Transport + * @see Store + */ + public static void closeService(Service service) { + if (service != null) { + try { + service.close(); + } + catch (MessagingException ex) { + logger.debug("Could not close JavaMail Service", ex); + } + } + } // /** // * Close the given JavaMail Folder and ignore any thrown exception. This is @@ -69,73 +69,73 @@ public abstract class MailTransportUtils { // closeFolder(folder, false); // } - /** - * Close the given JavaMail Folder and ignore any thrown exception. This is - * useful for typical finally blocks in manual JavaMail code. - * - * @param folder the JavaMail Folder to close (may be null) - * @param expunge whether all deleted messages should be expunged from the folder - */ - public static void closeFolder(Folder folder, boolean expunge) { - if (folder != null && folder.isOpen()) { - try { - folder.close(expunge); - } - catch (MessagingException ex) { - logger.debug("Could not close JavaMail Folder", ex); - } - catch (NullPointerException ex) { - // JavaMail prior to 1.4.1 may throw this - logger.debug("Could not close JavaMail Folder", ex); - } - } - } + /** + * Close the given JavaMail Folder and ignore any thrown exception. This is + * useful for typical finally blocks in manual JavaMail code. + * + * @param folder the JavaMail Folder to close (may be null) + * @param expunge whether all deleted messages should be expunged from the folder + */ + public static void closeFolder(Folder folder, boolean expunge) { + if (folder != null && folder.isOpen()) { + try { + folder.close(expunge); + } + catch (MessagingException ex) { + logger.debug("Could not close JavaMail Folder", ex); + } + catch (NullPointerException ex) { + // JavaMail prior to 1.4.1 may throw this + logger.debug("Could not close JavaMail Folder", ex); + } + } + } - /** - * Returns a string representation of the given {@link URLName}, where the - * password has been protected. - * - * @param name The URL name. - * @return The result with password protection. - */ - public static String toPasswordProtectedString(URLName name) { - String protocol = name.getProtocol(); - String username = name.getUsername(); - String password = name.getPassword(); - String host = name.getHost(); - int port = name.getPort(); - String file = name.getFile(); - String ref = name.getRef(); - StringBuffer tempURL = new StringBuffer(); - if (protocol != null) { - tempURL.append(protocol).append(':'); - } - if (StringUtils.hasLength(username) || StringUtils.hasLength(host)) { - tempURL.append("//"); - if (StringUtils.hasLength(username)) { - tempURL.append(username); - if (StringUtils.hasLength(password)) { - tempURL.append(":*****"); - } - tempURL.append("@"); - } - if (StringUtils.hasLength(host)) { - tempURL.append(host); - } - if (port != -1) { - tempURL.append(':').append(Integer.toString(port)); - } - if (StringUtils.hasLength(file)) { - tempURL.append('/'); - } - } - if (StringUtils.hasLength(file)) { - tempURL.append(file); - } - if (StringUtils.hasLength(ref)) { - tempURL.append('#').append(ref); - } - return tempURL.toString(); - } + /** + * Returns a string representation of the given {@link URLName}, where the + * password has been protected. + * + * @param name The URL name. + * @return The result with password protection. + */ + public static String toPasswordProtectedString(URLName name) { + String protocol = name.getProtocol(); + String username = name.getUsername(); + String password = name.getPassword(); + String host = name.getHost(); + int port = name.getPort(); + String file = name.getFile(); + String ref = name.getRef(); + StringBuffer tempURL = new StringBuffer(); + if (protocol != null) { + tempURL.append(protocol).append(':'); + } + if (StringUtils.hasLength(username) || StringUtils.hasLength(host)) { + tempURL.append("//"); + if (StringUtils.hasLength(username)) { + tempURL.append(username); + if (StringUtils.hasLength(password)) { + tempURL.append(":*****"); + } + tempURL.append("@"); + } + if (StringUtils.hasLength(host)) { + tempURL.append(host); + } + if (port != -1) { + tempURL.append(':').append(Integer.toString(port)); + } + if (StringUtils.hasLength(file)) { + tempURL.append('/'); + } + } + if (StringUtils.hasLength(file)) { + tempURL.append(file); + } + if (StringUtils.hasLength(ref)) { + tempURL.append('#').append(ref); + } + return tempURL.toString(); + } } diff --git a/spring-integration-mail/src/main/java/org/springframework/integration/mail/Pop3MailReceiver.java b/spring-integration-mail/src/main/java/org/springframework/integration/mail/Pop3MailReceiver.java index 9f34f12245..44c77b5eb9 100755 --- a/spring-integration-mail/src/main/java/org/springframework/integration/mail/Pop3MailReceiver.java +++ b/spring-integration-mail/src/main/java/org/springframework/integration/mail/Pop3MailReceiver.java @@ -73,7 +73,7 @@ public class Pop3MailReceiver extends AbstractMailReceiver { * @throws MessagingException in case of JavaMail errors */ @Override - protected void deleteMessages(Message[] messages) throws MessagingException { + protected void deleteMessages(Message[] messages) throws MessagingException { super.deleteMessages(messages); // expunge deleted mails, and make sure we've retrieved them before closing the folder for (int i = 0; i < messages.length; i++) { diff --git a/spring-integration-mail/src/test/java/org/springframework/integration/mail/ImapMailReceiverTests.java b/spring-integration-mail/src/test/java/org/springframework/integration/mail/ImapMailReceiverTests.java index e6c97875e9..4ea44b85ca 100644 --- a/spring-integration-mail/src/test/java/org/springframework/integration/mail/ImapMailReceiverTests.java +++ b/spring-integration-mail/src/test/java/org/springframework/integration/mail/ImapMailReceiverTests.java @@ -266,9 +266,10 @@ public class ImapMailReceiverTests { when(folder.getPermanentFlags()).thenReturn(new Flags(Flags.Flag.USER)); folderField.set(receiver, folder); - final Message[] messages = new Message[]{msg1, msg2}; + final Message[] messages = new Message[] { msg1, msg2 }; doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { DirectFieldAccessor accessor = new DirectFieldAccessor(invocation.getMock()); @@ -282,6 +283,7 @@ public class ImapMailReceiverTests { }).when(receiver).openFolder(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return messages; @@ -289,6 +291,7 @@ public class ImapMailReceiverTests { }).when(receiver).searchForNewMessages(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return null; @@ -344,8 +347,9 @@ public class ImapMailReceiverTests { Message msg1 = mock(MimeMessage.class); Message msg2 = mock(MimeMessage.class); - final Message[] messages = new Message[]{msg1, msg2}; + final Message[] messages = new Message[] { msg1, msg2 }; doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { DirectFieldAccessor accessor = new DirectFieldAccessor(invocation.getMock()); @@ -358,6 +362,7 @@ public class ImapMailReceiverTests { }).when(receiver).openFolder(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return messages; @@ -365,6 +370,7 @@ public class ImapMailReceiverTests { }).when(receiver).searchForNewMessages(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return null; @@ -393,8 +399,9 @@ public class ImapMailReceiverTests { Message msg1 = mock(MimeMessage.class); Message msg2 = mock(MimeMessage.class); - final Message[] messages = new Message[]{msg1, msg2}; + final Message[] messages = new Message[] { msg1, msg2 }; doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return null; @@ -402,6 +409,7 @@ public class ImapMailReceiverTests { }).when(receiver).openFolder(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return messages; @@ -409,6 +417,7 @@ public class ImapMailReceiverTests { }).when(receiver).searchForNewMessages(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return null; @@ -419,6 +428,7 @@ public class ImapMailReceiverTests { verify(msg1, times(0)).setFlag(Flag.SEEN, true); verify(msg2, times(0)).setFlag(Flag.SEEN, true); } + @Test public void receiveAndDontMarkAsReadButDelete() throws Exception { AbstractMailReceiver receiver = new ImapMailReceiver(); @@ -436,8 +446,9 @@ public class ImapMailReceiverTests { Message msg1 = mock(MimeMessage.class); Message msg2 = mock(MimeMessage.class); - final Message[] messages = new Message[]{msg1, msg2}; + final Message[] messages = new Message[] { msg1, msg2 }; doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { DirectFieldAccessor accessor = new DirectFieldAccessor(invocation.getMock()); @@ -450,6 +461,7 @@ public class ImapMailReceiverTests { }).when(receiver).openFolder(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return messages; @@ -457,6 +469,7 @@ public class ImapMailReceiverTests { }).when(receiver).searchForNewMessages(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return null; @@ -469,6 +482,7 @@ public class ImapMailReceiverTests { verify(msg1, times(1)).setFlag(Flag.DELETED, true); verify(msg2, times(1)).setFlag(Flag.DELETED, true); } + @Test public void receiveAndIgnoreMarkAsReadDontDelete() throws Exception { AbstractMailReceiver receiver = new ImapMailReceiver(); @@ -484,8 +498,9 @@ public class ImapMailReceiverTests { Message msg1 = mock(MimeMessage.class); Message msg2 = mock(MimeMessage.class); - final Message[] messages = new Message[]{msg1, msg2}; + final Message[] messages = new Message[] { msg1, msg2 }; doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { DirectFieldAccessor accessor = new DirectFieldAccessor(invocation.getMock()); @@ -498,6 +513,7 @@ public class ImapMailReceiverTests { }).when(receiver).openFolder(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return messages; @@ -505,6 +521,7 @@ public class ImapMailReceiverTests { }).when(receiver).searchForNewMessages(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return null; @@ -515,11 +532,12 @@ public class ImapMailReceiverTests { verify(msg2, times(1)).setFlag(Flag.SEEN, true); verify(receiver, times(0)).deleteMessages((Message[]) Mockito.any()); } + @Test @Ignore public void testMessageHistory() throws Exception { ConfigurableApplicationContext context = - new ClassPathXmlApplicationContext("ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); + new ClassPathXmlApplicationContext("ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class); AbstractMailReceiver receiver = new ImapMailReceiver(); @@ -533,13 +551,14 @@ public class ImapMailReceiverTests { MimeMessage mailMessage = mock(MimeMessage.class); Flags flags = mock(Flags.class); when(mailMessage.getFlags()).thenReturn(flags); - final Message[] messages = new Message[]{mailMessage}; + final Message[] messages = new Message[] { mailMessage }; doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { DirectFieldAccessor accessor = new DirectFieldAccessor((invocation.getMock())); - IMAPFolder folder = mock(IMAPFolder.class); + IMAPFolder folder = mock(IMAPFolder.class); accessor.setPropertyValue("folder", folder); when(folder.hasNewMessages()).thenReturn(true); return null; @@ -547,6 +566,7 @@ public class ImapMailReceiverTests { }).when(receiver).openFolder(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return messages; @@ -554,6 +574,7 @@ public class ImapMailReceiverTests { }).when(receiver).searchForNewMessages(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return null; @@ -576,15 +597,15 @@ public class ImapMailReceiverTests { @Test public void testIdleChannelAdapterException() throws Exception { ConfigurableApplicationContext context = - new ClassPathXmlApplicationContext("ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); + new ClassPathXmlApplicationContext("ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class); //ImapMailReceiver receiver = (ImapMailReceiver) TestUtils.getPropertyValue(adapter, "mailReceiver"); - DirectChannel channel = new DirectChannel(); channel.subscribe(new AbstractReplyProducingMessageHandler() { + @Override protected Object handleRequestMessage(org.springframework.messaging.Message requestMessage) { throw new RuntimeException("Failed"); @@ -606,6 +627,7 @@ public class ImapMailReceiverTests { folderField.set(receiver, folder); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return true; @@ -613,6 +635,7 @@ public class ImapMailReceiverTests { }).when(folder).isOpen(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return null; @@ -625,9 +648,10 @@ public class ImapMailReceiverTests { MimeMessage mailMessage = mock(MimeMessage.class); Flags flags = mock(Flags.class); when(mailMessage.getFlags()).thenReturn(flags); - final Message[] messages = new Message[]{mailMessage}; + final Message[] messages = new Message[] { mailMessage }; doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return messages; @@ -635,6 +659,7 @@ public class ImapMailReceiverTests { }).when(receiver).searchForNewMessages(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return null; @@ -652,7 +677,7 @@ public class ImapMailReceiverTests { @Test public void testNoInitialIdleDelayWhenRecentNotSupported() throws Exception { ConfigurableApplicationContext context = - new ClassPathXmlApplicationContext("ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); + new ClassPathXmlApplicationContext("ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class); QueueChannel channel = new QueueChannel(); @@ -679,6 +704,7 @@ public class ImapMailReceiverTests { storeField.set(receiver, store); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return folder; @@ -688,10 +714,11 @@ public class ImapMailReceiverTests { MimeMessage mailMessage = mock(MimeMessage.class); Flags flags = mock(Flags.class); when(mailMessage.getFlags()).thenReturn(flags); - final Message[] messages = new Message[]{mailMessage}; + final Message[] messages = new Message[] { mailMessage }; final AtomicInteger shouldFindMessagesCounter = new AtomicInteger(2); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { /* @@ -710,6 +737,7 @@ public class ImapMailReceiverTests { }).when(receiver).searchForNewMessages(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return null; @@ -717,6 +745,7 @@ public class ImapMailReceiverTests { }).when(receiver).fetchMessages(messages); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { Thread.sleep(5000); @@ -742,7 +771,7 @@ public class ImapMailReceiverTests { @Test public void testInitialIdleDelayWhenRecentIsSupported() throws Exception { ConfigurableApplicationContext context = - new ClassPathXmlApplicationContext("ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); + new ClassPathXmlApplicationContext("ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class); ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class); QueueChannel channel = new QueueChannel(); @@ -769,6 +798,7 @@ public class ImapMailReceiverTests { storeField.set(receiver, store); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return folder; @@ -778,9 +808,10 @@ public class ImapMailReceiverTests { MimeMessage mailMessage = mock(MimeMessage.class); Flags flags = mock(Flags.class); when(mailMessage.getFlags()).thenReturn(flags); - final Message[] messages = new Message[]{mailMessage}; + final Message[] messages = new Message[] { mailMessage }; doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return messages; @@ -788,6 +819,7 @@ public class ImapMailReceiverTests { }).when(receiver).searchForNewMessages(); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { return null; @@ -796,6 +828,7 @@ public class ImapMailReceiverTests { final CountDownLatch idles = new CountDownLatch(2); doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Throwable { idles.countDown(); @@ -855,7 +888,7 @@ public class ImapMailReceiverTests { Folder folder = mock(Folder.class); when(folder.exists()).thenReturn(true); when(folder.isOpen()).thenReturn(true); - when(folder.search((SearchTerm) Mockito.any())).thenReturn(new Message[]{}); + when(folder.search((SearchTerm) Mockito.any())).thenReturn(new Message[] { }); when(store.getFolder(Mockito.any(URLName.class))).thenReturn(folder); when(folder.getPermanentFlags()).thenReturn(new Flags(Flags.Flag.USER)); @@ -866,6 +899,7 @@ public class ImapMailReceiverTests { receiver.afterPropertiesSet(); new Thread(new Runnable() { + @Override public void run() { try { @@ -882,6 +916,7 @@ public class ImapMailReceiverTests { }).start(); new Thread(new Runnable() { + @Override public void run() { try { @@ -946,7 +981,7 @@ public class ImapMailReceiverTests { when(folder.isOpen()).thenReturn(true); Message message = new MimeMessage(null, new ClassPathResource("test.mail").getInputStream()); - when(folder.search((SearchTerm) Mockito.any())).thenReturn(new Message[]{message}); + when(folder.search((SearchTerm) Mockito.any())).thenReturn(new Message[] { message }); when(store.getFolder(Mockito.any(URLName.class))).thenReturn(folder); when(folder.getPermanentFlags()).thenReturn(new Flags(Flags.Flag.USER)); DirectFieldAccessor df = new DirectFieldAccessor(receiver); diff --git a/spring-integration-mail/src/test/java/org/springframework/integration/mail/MailSendingMessageHandlerContextTests.java b/spring-integration-mail/src/test/java/org/springframework/integration/mail/MailSendingMessageHandlerContextTests.java index 8178c9462a..5bb12866da 100644 --- a/spring-integration-mail/src/test/java/org/springframework/integration/mail/MailSendingMessageHandlerContextTests.java +++ b/spring-integration-mail/src/test/java/org/springframework/integration/mail/MailSendingMessageHandlerContextTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * Copyright 2002-2016 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. @@ -51,7 +51,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; * @author Marius Bogoevici * @author Artem Bilan */ -@RunWith(value = SpringJUnit4ClassRunner.class) +@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class MailSendingMessageHandlerContextTests { diff --git a/spring-integration-mail/src/test/java/org/springframework/integration/mail/Pop3MailReceiverTests.java b/spring-integration-mail/src/test/java/org/springframework/integration/mail/Pop3MailReceiverTests.java index 3dba513a79..bb2016e3bb 100644 --- a/spring-integration-mail/src/test/java/org/springframework/integration/mail/Pop3MailReceiverTests.java +++ b/spring-integration-mail/src/test/java/org/springframework/integration/mail/Pop3MailReceiverTests.java @@ -32,8 +32,6 @@ import javax.mail.Message; import javax.mail.internet.MimeMessage; import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.springframework.beans.DirectFieldAccessor; import org.springframework.beans.factory.BeanFactory; @@ -44,10 +42,11 @@ import org.springframework.beans.factory.BeanFactory; * */ public class Pop3MailReceiverTests { + @Test public void receiveAndDelete() throws Exception { AbstractMailReceiver receiver = new Pop3MailReceiver(); - ((Pop3MailReceiver) receiver).setShouldDeleteMessages(true); + receiver.setShouldDeleteMessages(true); receiver = spy(receiver); receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet(); @@ -60,38 +59,29 @@ public class Pop3MailReceiverTests { Message msg1 = mock(MimeMessage.class); Message msg2 = mock(MimeMessage.class); - final Message[] messages = new Message[]{msg1, msg2}; - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - DirectFieldAccessor accessor = new DirectFieldAccessor(invocation.getMock()); - int folderOpenMode = (Integer) accessor.getPropertyValue("folderOpenMode"); - if (folderOpenMode != Folder.READ_WRITE) { - throw new IllegalArgumentException("Folder had to be open in READ_WRITE mode"); - } - return null; + final Message[] messages = new Message[] { msg1, msg2 }; + doAnswer(invocation -> { + DirectFieldAccessor accessor = new DirectFieldAccessor(invocation.getMock()); + int folderOpenMode = (Integer) accessor.getPropertyValue("folderOpenMode"); + if (folderOpenMode != Folder.READ_WRITE) { + throw new IllegalArgumentException("Folder had to be open in READ_WRITE mode"); } + return null; }).when(receiver).openFolder(); - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return messages; - } - }).when(receiver).searchForNewMessages(); + doAnswer(invocation -> messages).when(receiver).searchForNewMessages(); - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return null; - } - }).when(receiver).fetchMessages(messages); + doAnswer(invocation -> null).when(receiver).fetchMessages(messages); receiver.afterPropertiesSet(); receiver.receive(); verify(msg1, times(1)).setFlag(Flag.DELETED, true); verify(msg2, times(1)).setFlag(Flag.DELETED, true); } + @Test public void receiveAndDontDelete() throws Exception { AbstractMailReceiver receiver = new Pop3MailReceiver(); - ((Pop3MailReceiver) receiver).setShouldDeleteMessages(false); + receiver.setShouldDeleteMessages(false); receiver = spy(receiver); receiver.setBeanFactory(mock(BeanFactory.class)); receiver.afterPropertiesSet(); @@ -104,29 +94,18 @@ public class Pop3MailReceiverTests { Message msg1 = mock(MimeMessage.class); Message msg2 = mock(MimeMessage.class); - final Message[] messages = new Message[]{msg1, msg2}; - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return null; - } - }).when(receiver).openFolder(); + final Message[] messages = new Message[] { msg1, msg2 }; + doAnswer(invocation -> null).when(receiver).openFolder(); - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return messages; - } - }).when(receiver).searchForNewMessages(); + doAnswer(invocation -> messages).when(receiver).searchForNewMessages(); - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return null; - } - }).when(receiver).fetchMessages(messages); + doAnswer(invocation -> null).when(receiver).fetchMessages(messages); receiver.afterPropertiesSet(); receiver.receive(); verify(msg1, times(0)).setFlag(Flag.DELETED, true); verify(msg2, times(0)).setFlag(Flag.DELETED, true); } + @Test public void receiveAndDontSetDeleteWithUrl() throws Exception { AbstractMailReceiver receiver = new Pop3MailReceiver("pop3://some.host"); @@ -142,29 +121,18 @@ public class Pop3MailReceiverTests { Message msg1 = mock(MimeMessage.class); Message msg2 = mock(MimeMessage.class); - final Message[] messages = new Message[]{msg1, msg2}; - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return null; - } - }).when(receiver).openFolder(); + final Message[] messages = new Message[] { msg1, msg2 }; + doAnswer(invocation -> null).when(receiver).openFolder(); - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return messages; - } - }).when(receiver).searchForNewMessages(); + doAnswer(invocation -> messages).when(receiver).searchForNewMessages(); - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return null; - } - }).when(receiver).fetchMessages(messages); + doAnswer(invocation -> null).when(receiver).fetchMessages(messages); receiver.afterPropertiesSet(); receiver.receive(); verify(msg1, times(0)).setFlag(Flag.DELETED, true); verify(msg2, times(0)).setFlag(Flag.DELETED, true); } + @Test public void receiveAndDontSetDeleteWithoutUrl() throws Exception { AbstractMailReceiver receiver = new Pop3MailReceiver(); @@ -180,27 +148,16 @@ public class Pop3MailReceiverTests { Message msg1 = mock(MimeMessage.class); Message msg2 = mock(MimeMessage.class); - final Message[] messages = new Message[]{msg1, msg2}; - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return null; - } - }).when(receiver).openFolder(); + final Message[] messages = new Message[] { msg1, msg2 }; + doAnswer(invocation -> null).when(receiver).openFolder(); - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return messages; - } - }).when(receiver).searchForNewMessages(); + doAnswer(invocation -> messages).when(receiver).searchForNewMessages(); - doAnswer(new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return null; - } - }).when(receiver).fetchMessages(messages); + doAnswer(invocation -> null).when(receiver).fetchMessages(messages); receiver.afterPropertiesSet(); receiver.receive(); verify(msg1, times(0)).setFlag(Flag.DELETED, true); verify(msg2, times(0)).setFlag(Flag.DELETED, true); } + } diff --git a/spring-integration-mail/src/test/java/org/springframework/integration/mail/StubJavaMailSender.java b/spring-integration-mail/src/test/java/org/springframework/integration/mail/StubJavaMailSender.java index 5e10768f9a..83041ee71b 100644 --- a/spring-integration-mail/src/test/java/org/springframework/integration/mail/StubJavaMailSender.java +++ b/spring-integration-mail/src/test/java/org/springframework/integration/mail/StubJavaMailSender.java @@ -81,7 +81,7 @@ public class StubJavaMailSender implements JavaMailSender { @Override public void send(MimeMessagePreparator... mimeMessagePreparators) throws MailException { - throw new UnsupportedOperationException("MimeMessagePreparator not supported"); + throw new UnsupportedOperationException("MimeMessagePreparator not supported"); } @Override diff --git a/spring-integration-mongodb/src/main/java/org/springframework/integration/mongodb/store/MongoDbMessageStore.java b/spring-integration-mongodb/src/main/java/org/springframework/integration/mongodb/store/MongoDbMessageStore.java index 85b3d695bc..528833d4bc 100644 --- a/spring-integration-mongodb/src/main/java/org/springframework/integration/mongodb/store/MongoDbMessageStore.java +++ b/spring-integration-mongodb/src/main/java/org/springframework/integration/mongodb/store/MongoDbMessageStore.java @@ -316,7 +316,7 @@ public class MongoDbMessageStore extends AbstractMessageGroupStore .initializeOrderedBulkOperation(); for (UUID id : ids) { bulkOp.find(whereMessageIdIsAndGroupIdIs(id, groupId).getQueryObject()) - .remove(); + .remove(); } bulkOp.execute(); } @@ -502,7 +502,7 @@ public class MongoDbMessageStore extends AbstractMessageGroupStore } @Override - @SuppressWarnings({"unchecked"}) + @SuppressWarnings({ "unchecked" }) public S read(Class clazz, DBObject source) { if (!MessageWrapper.class.equals(clazz)) { return super.read(clazz, source); @@ -600,6 +600,7 @@ public class MongoDbMessageStore extends AbstractMessageGroupStore } private static class UuidToDBObjectConverter implements Converter { + @Override public DBObject convert(UUID source) { BasicDBObject dbObject = new BasicDBObject(); @@ -610,6 +611,7 @@ public class MongoDbMessageStore extends AbstractMessageGroupStore } private static class DBObjectToUUIDConverter implements Converter { + @Override public UUID convert(DBObject source) { return UUID.fromString((String) source.get("_value")); diff --git a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/AbstractMongoDbMessageGroupStoreTests.java b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/AbstractMongoDbMessageGroupStoreTests.java index c51fc82cb1..b1412f3522 100644 --- a/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/AbstractMongoDbMessageGroupStoreTests.java +++ b/spring-integration-mongodb/src/test/java/org/springframework/integration/mongodb/store/AbstractMongoDbMessageGroupStoreTests.java @@ -97,7 +97,7 @@ public abstract class AbstractMongoDbMessageGroupStoreTests extends MongoDbAvail this.cleanupCollections(new SimpleMongoDbFactory(new MongoClient(), "test")); MessageGroupStore store = this.getMessageGroupStore(); MessageStore messageStore = this.getMessageStore(); - Object id = UUID.randomUUID(); + Object id = UUID.randomUUID(); MessageGroup messageGroup = store.getMessageGroup(id); UUID uuidA = UUID.randomUUID(); Message messageA = MessageBuilder.withPayload("A").setHeader("foo", uuidA).build(); diff --git a/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/config/xml/MqttOutboundChannelAdapterParser.java b/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/config/xml/MqttOutboundChannelAdapterParser.java index 729d28cc85..de510dad76 100644 --- a/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/config/xml/MqttOutboundChannelAdapterParser.java +++ b/spring-integration-mqtt/src/main/java/org/springframework/integration/mqtt/config/xml/MqttOutboundChannelAdapterParser.java @@ -54,7 +54,7 @@ public class MqttOutboundChannelAdapterParser extends AbstractOutboundChannelAda IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "default-topic"); if (StringUtils.hasText(element.getAttribute("converter")) && (StringUtils.hasText(element.getAttribute("default-qos")) || - StringUtils.hasText(element.getAttribute("default-retained")))) { + StringUtils.hasText(element.getAttribute("default-retained")))) { parserContext.getReaderContext().error("If a 'converter' is provided, you cannot provide " + "'default-qos' or 'default-retained'", element); } diff --git a/spring-integration-redis/src/main/java/org/springframework/integration/redis/inbound/RedisStoreMessageSource.java b/spring-integration-redis/src/main/java/org/springframework/integration/redis/inbound/RedisStoreMessageSource.java index e6539322a3..d0698d6201 100644 --- a/spring-integration-redis/src/main/java/org/springframework/integration/redis/inbound/RedisStoreMessageSource.java +++ b/spring-integration-redis/src/main/java/org/springframework/integration/redis/inbound/RedisStoreMessageSource.java @@ -34,6 +34,7 @@ import org.springframework.integration.transaction.IntegrationResourceHolder; import org.springframework.messaging.Message; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.util.Assert; + /** * Inbound channel adapter which returns a Message representing a view into * a Redis store. The type of store depends on the {@link #collectionType} attribute. @@ -67,7 +68,7 @@ public class RedisStoreMessageSource extends IntegrationObjectSupport * @param keyExpression The key expression. */ public RedisStoreMessageSource(RedisTemplate redisTemplate, - Expression keyExpression) { + Expression keyExpression) { Assert.notNull(keyExpression, "'keyExpression' must not be null"); Assert.notNull(redisTemplate, "'redisTemplate' must not be null"); @@ -88,7 +89,7 @@ public class RedisStoreMessageSource extends IntegrationObjectSupport * @param keyExpression The key expression. */ public RedisStoreMessageSource(RedisConnectionFactory connectionFactory, - Expression keyExpression) { + Expression keyExpression) { Assert.notNull(keyExpression, "'keyExpression' must not be null"); Assert.notNull(connectionFactory, "'connectionFactory' must not be null"); @@ -148,7 +149,7 @@ public class RedisStoreMessageSource extends IntegrationObjectSupport @Override protected void onInit() throws Exception { this.evaluationContext = - ExpressionUtils.createStandardEvaluationContext(this.getBeanFactory()); + ExpressionUtils.createStandardEvaluationContext(this.getBeanFactory()); } public RedisStore getResource() { diff --git a/spring-integration-redis/src/main/java/org/springframework/integration/redis/util/RedisLockRegistry.java b/spring-integration-redis/src/main/java/org/springframework/integration/redis/util/RedisLockRegistry.java index fc19ece988..ea5078b2eb 100644 --- a/spring-integration-redis/src/main/java/org/springframework/integration/redis/util/RedisLockRegistry.java +++ b/spring-integration-redis/src/main/java/org/springframework/integration/redis/util/RedisLockRegistry.java @@ -150,7 +150,7 @@ public final class RedisLockRegistry implements LockRegistry { * {@link DefaultLockRegistry} is used by default. */ public RedisLockRegistry(RedisConnectionFactory connectionFactory, String registryKey, - long expireAfter, LockRegistry localRegistry) { + long expireAfter, LockRegistry localRegistry) { Assert.notNull(connectionFactory, "'connectionFactory' cannot be null"); Assert.notNull(registryKey, "'registryKey' cannot be null"); Assert.notNull(localRegistry, "'localRegistry' cannot be null"); @@ -422,7 +422,7 @@ public final class RedisLockRegistry implements LockRegistry { try { success = RedisLockRegistry.this.redisTemplate.execute(new SessionCallback() { - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Boolean execute(RedisOperations ops) throws DataAccessException { String key = constructLockKey(); @@ -610,16 +610,16 @@ public final class RedisLockRegistry implements LockRegistry { int keyLength = t.lockKey.length(); int threadNameLength = t.threadName.length(); byte[] value = new byte[1 + hostLength + - 1 + keyLength + - 1 + threadNameLength + 8]; + 1 + keyLength + + 1 + threadNameLength + 8]; ByteBuffer buff = ByteBuffer.wrap(value); buff.put((byte) hostLength) - .put(t.lockHost) - .put((byte) keyLength) - .put(t.lockKey.getBytes()) - .put((byte) threadNameLength) - .put(t.threadName.getBytes()) - .putLong(t.lockedAt); + .put(t.lockHost) + .put((byte) keyLength) + .put(t.lockKey.getBytes()) + .put((byte) threadNameLength) + .put(t.threadName.getBytes()) + .putLong(t.lockedAt); return value; } diff --git a/spring-integration-redis/src/test/java/org/springframework/integration/redis/inbound/RedisQueueMessageDrivenEndpointTests.java b/spring-integration-redis/src/test/java/org/springframework/integration/redis/inbound/RedisQueueMessageDrivenEndpointTests.java index a9aaffb30f..25f2ef1f43 100644 --- a/spring-integration-redis/src/test/java/org/springframework/integration/redis/inbound/RedisQueueMessageDrivenEndpointTests.java +++ b/spring-integration-redis/src/test/java/org/springframework/integration/redis/inbound/RedisQueueMessageDrivenEndpointTests.java @@ -125,11 +125,11 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests { endpoint.afterPropertiesSet(); endpoint.start(); - Message receive = (Message) channel.receive(2000); + Message receive = (Message) channel.receive(10000); assertNotNull(receive); assertEquals(payload, receive.getPayload()); - receive = (Message) channel.receive(2000); + receive = (Message) channel.receive(10000); assertNotNull(receive); assertEquals(payload2, receive.getPayload()); @@ -170,12 +170,12 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests { endpoint.afterPropertiesSet(); endpoint.start(); - Message receive = (Message) channel.receive(2000); + Message receive = (Message) channel.receive(10000); assertNotNull(receive); assertEquals(message, receive); - receive = (Message) errorChannel.receive(2000); + receive = (Message) errorChannel.receive(10000); assertNotNull(receive); assertThat(receive, Matchers.instanceOf(ErrorMessage.class)); assertThat(receive.getPayload(), Matchers.instanceOf(MessagingException.class)); @@ -201,7 +201,7 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests { redisTemplate.boundListOps("si.test.Int3017IntegrationInbound") .leftPush("{\"payload\":\"" + payload + "\",\"headers\":{}}"); - Message receive = this.fromChannel.receive(2000); + Message receive = this.fromChannel.receive(10000); assertNotNull(receive); assertEquals(payload, receive.getPayload()); } @@ -216,7 +216,7 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests { this.symmetricalInputChannel.send(message); - Message receive = this.symmetricalOutputChannel.receive(2000); + Message receive = this.symmetricalOutputChannel.receive(10000); assertNotNull(receive); assertEquals(payload, receive.getPayload()); } @@ -340,7 +340,7 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests { redisTemplate.boundListOps(queueName).leftPush(payload); - Message receive = channel.receive(1000); + Message receive = channel.receive(10000); assertNotNull(receive); assertEquals(payload, receive.getPayload()); @@ -380,11 +380,11 @@ public class RedisQueueMessageDrivenEndpointTests extends RedisAvailableTests { endpoint.afterPropertiesSet(); endpoint.start(); - Message receive = (Message) channel.receive(2000); + Message receive = (Message) channel.receive(10000); assertNotNull(receive); assertEquals(payload, receive.getPayload()); - receive = (Message) channel.receive(2000); + receive = (Message) channel.receive(10000); assertNotNull(receive); assertEquals(payload2, receive.getPayload()); diff --git a/spring-integration-scripting/src/main/java/org/springframework/integration/scripting/config/AbstractScriptParser.java b/spring-integration-scripting/src/main/java/org/springframework/integration/scripting/config/AbstractScriptParser.java index dd8555e033..2df5387c14 100644 --- a/spring-integration-scripting/src/main/java/org/springframework/integration/scripting/config/AbstractScriptParser.java +++ b/spring-integration-scripting/src/main/java/org/springframework/integration/scripting/config/AbstractScriptParser.java @@ -41,6 +41,7 @@ import org.springframework.util.xml.DomUtils; * */ public abstract class AbstractScriptParser extends AbstractSingleBeanDefinitionParser { + protected static final String LOCATION_ATTRIBUTE = "location"; protected static final String REFRESH_CHECK_DELAY_ATTRIBUTE = "refresh-check-delay"; @@ -122,7 +123,7 @@ public abstract class AbstractScriptParser extends AbstractSingleBeanDefinitionP } private ManagedMap buildVariablesMap(final Element element, final ParserContext parserContext, - List variableElements) { + List variableElements) { @SuppressWarnings("serial") ManagedMap variableMap = new ManagedMap() { diff --git a/spring-integration-scripting/src/test/java/org/springframework/integration/scripting/jsr223/PythonScriptExecutorTests.java b/spring-integration-scripting/src/test/java/org/springframework/integration/scripting/jsr223/PythonScriptExecutorTests.java index 44e78bf917..a0fcd5b200 100644 --- a/spring-integration-scripting/src/test/java/org/springframework/integration/scripting/jsr223/PythonScriptExecutorTests.java +++ b/spring-integration-scripting/src/test/java/org/springframework/integration/scripting/jsr223/PythonScriptExecutorTests.java @@ -38,10 +38,12 @@ import org.springframework.scripting.support.StaticScriptSource; * */ public class PythonScriptExecutorTests { + ScriptExecutor executor; + @Before public void init() { - executor = new PythonScriptExecutor(); + executor = new PythonScriptExecutor(); } @Test @@ -49,8 +51,8 @@ public class PythonScriptExecutorTests { Object obj = executor.executeScript(new StaticScriptSource("3+4")); assertEquals(7, obj); - obj = executor.executeScript(new StaticScriptSource("'hello,world'")); - assertEquals("hello,world", obj); + obj = executor.executeScript(new StaticScriptSource("'hello,world'")); + assertEquals("hello,world", obj); } @Test @@ -62,16 +64,16 @@ public class PythonScriptExecutorTests { @Test public void test2() { - Object obj = executor.executeScript(new StaticScriptSource("def foo(y):\n\tx=y\n\treturn y\nz=foo(2)")); + Object obj = executor.executeScript(new StaticScriptSource("def foo(y):\n\tx=y\n\treturn y\nz=foo(2)")); assertEquals(2, obj); } @Test public void test3() { ScriptSource source = - new ResourceScriptSource( - new ClassPathResource("/org/springframework/integration/scripting/jsr223/test3.py")); - Object obj = executor.executeScript(source); + new ResourceScriptSource( + new ClassPathResource("/org/springframework/integration/scripting/jsr223/test3.py")); + Object obj = executor.executeScript(source); PyTuple tuple = (PyTuple) obj; assertEquals(1, tuple.get(0)); } @@ -79,11 +81,11 @@ public class PythonScriptExecutorTests { @Test public void test3WithVariables() { ScriptSource source = - new ResourceScriptSource( - new ClassPathResource("/org/springframework/integration/scripting/jsr223/test3.py")); + new ResourceScriptSource( + new ClassPathResource("/org/springframework/integration/scripting/jsr223/test3.py")); HashMap variables = new HashMap(); variables.put("foo", "bar"); - Object obj = executor.executeScript(source, variables); + Object obj = executor.executeScript(source, variables); PyTuple tuple = (PyTuple) obj; assertNotNull(tuple); assertEquals(1, tuple.get(0)); diff --git a/spring-integration-security/src/main/java/org/springframework/integration/security/channel/ChannelSecurityMetadataSource.java b/spring-integration-security/src/main/java/org/springframework/integration/security/channel/ChannelSecurityMetadataSource.java index a09e17367f..805ad70841 100644 --- a/spring-integration-security/src/main/java/org/springframework/integration/security/channel/ChannelSecurityMetadataSource.java +++ b/spring-integration-security/src/main/java/org/springframework/integration/security/channel/ChannelSecurityMetadataSource.java @@ -90,13 +90,13 @@ public class ChannelSecurityMetadataSource implements SecurityMetadataSource { public Collection getAllConfigAttributes() { Set allAttributes = new HashSet(); - for (ChannelAccessPolicy policy : this.patternMappings.values()) { - Collection receiveAttributes = policy.getConfigAttributesForReceive(); - allAttributes.addAll(receiveAttributes); - Collection sendAttributes = policy.getConfigAttributesForSend(); - allAttributes.addAll(sendAttributes); - } - return allAttributes; + for (ChannelAccessPolicy policy : this.patternMappings.values()) { + Collection receiveAttributes = policy.getConfigAttributesForReceive(); + allAttributes.addAll(receiveAttributes); + Collection sendAttributes = policy.getConfigAttributesForSend(); + allAttributes.addAll(sendAttributes); + } + return allAttributes; } public boolean supports(Class clazz) { diff --git a/spring-integration-security/src/main/java/org/springframework/integration/security/channel/SecurityContextPropagationChannelInterceptor.java b/spring-integration-security/src/main/java/org/springframework/integration/security/channel/SecurityContextPropagationChannelInterceptor.java index 3dbfe97b7f..a541e6b90a 100644 --- a/spring-integration-security/src/main/java/org/springframework/integration/security/channel/SecurityContextPropagationChannelInterceptor.java +++ b/spring-integration-security/src/main/java/org/springframework/integration/security/channel/SecurityContextPropagationChannelInterceptor.java @@ -62,7 +62,7 @@ public class SecurityContextPropagationChannelInterceptor @Override protected void populatePropagatedContext(Authentication authentication, Message message, - MessageChannel channel) { + MessageChannel channel) { if (authentication != null) { SecurityContext currentContext = SecurityContextHolder.getContext(); diff --git a/spring-integration-sftp/src/main/java/org/springframework/integration/sftp/session/DefaultSftpSessionFactory.java b/spring-integration-sftp/src/main/java/org/springframework/integration/sftp/session/DefaultSftpSessionFactory.java index fc545f2c18..800c86220c 100644 --- a/spring-integration-sftp/src/main/java/org/springframework/integration/sftp/session/DefaultSftpSessionFactory.java +++ b/spring-integration-sftp/src/main/java/org/springframework/integration/sftp/session/DefaultSftpSessionFactory.java @@ -562,7 +562,7 @@ public class DefaultSftpSessionFactory implements SessionFactory, Share @Override public String[] promptKeyboardInteractive(String destination, String name, String instruction, String[] prompt, - boolean[] echo) { + boolean[] echo) { if (hasDelegate() && getDelegate() instanceof UIKeyboardInteractive) { return ((UIKeyboardInteractive) getDelegate()).promptKeyboardInteractive(destination, name, instruction, prompt, echo); diff --git a/spring-integration-stomp/src/main/java/org/springframework/integration/stomp/AbstractStompSessionManager.java b/spring-integration-stomp/src/main/java/org/springframework/integration/stomp/AbstractStompSessionManager.java index 465a3a3b90..f699a07d2b 100644 --- a/spring-integration-stomp/src/main/java/org/springframework/integration/stomp/AbstractStompSessionManager.java +++ b/spring-integration-stomp/src/main/java/org/springframework/integration/stomp/AbstractStompSessionManager.java @@ -399,7 +399,7 @@ public abstract class AbstractStompSessionManager implements StompSessionManager @Override public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, - Throwable exception) { + Throwable exception) { synchronized (this.delegates) { for (StompSessionHandler delegate : this.delegates) { delegate.handleException(session, command, headers, payload, exception); diff --git a/spring-integration-stomp/src/main/java/org/springframework/integration/stomp/outbound/StompMessageHandler.java b/spring-integration-stomp/src/main/java/org/springframework/integration/stomp/outbound/StompMessageHandler.java index ee0459be64..5f40a0f0b3 100644 --- a/spring-integration-stomp/src/main/java/org/springframework/integration/stomp/outbound/StompMessageHandler.java +++ b/spring-integration-stomp/src/main/java/org/springframework/integration/stomp/outbound/StompMessageHandler.java @@ -253,7 +253,7 @@ public class StompMessageHandler extends AbstractMessageHandler implements Appli @Override public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, - Throwable exception) { + Throwable exception) { Message message = MessageBuilder.createMessage(payload, StompHeaderAccessor.create(command, headers).getMessageHeaders()); logger.error("The exception for session [" + session + "] on message [" + message + "]", exception); diff --git a/spring-integration-stomp/src/test/java/org/springframework/integration/stomp/outbound/StompMessageHandlerWebSocketIntegrationTests.java b/spring-integration-stomp/src/test/java/org/springframework/integration/stomp/outbound/StompMessageHandlerWebSocketIntegrationTests.java index 69b8543c8e..7b4c1b71c3 100644 --- a/spring-integration-stomp/src/test/java/org/springframework/integration/stomp/outbound/StompMessageHandlerWebSocketIntegrationTests.java +++ b/spring-integration-stomp/src/test/java/org/springframework/integration/stomp/outbound/StompMessageHandlerWebSocketIntegrationTests.java @@ -235,7 +235,7 @@ public class StompMessageHandlerWebSocketIntegrationTests extends LogAdjustingTe private final CountDownLatch latch = new CountDownLatch(1); - @MessageMapping(value = "/simple") + @MessageMapping("/simple") public void handle() { this.latch.countDown(); } diff --git a/spring-integration-stream/src/test/java/org/springframework/integration/stream/config/ConsoleOutboundChannelAdapterParserTests.java b/spring-integration-stream/src/test/java/org/springframework/integration/stream/config/ConsoleOutboundChannelAdapterParserTests.java index 682c38e8b7..d13d2d470c 100644 --- a/spring-integration-stream/src/test/java/org/springframework/integration/stream/config/ConsoleOutboundChannelAdapterParserTests.java +++ b/spring-integration-stream/src/test/java/org/springframework/integration/stream/config/ConsoleOutboundChannelAdapterParserTests.java @@ -162,7 +162,7 @@ public class ConsoleOutboundChannelAdapterParserTests { assertEquals(34, TestUtils.getPropertyValue(this.stderrAdapterHandler, "order")); } - @Test + @Test public void stdoutAdatperWithAppendNewLine() throws IOException { BufferedWriter bufferedWriter = TestUtils.getPropertyValue(this.newlineAdapterHandler, "writer", BufferedWriter.class); Writer writer = TestUtils.getPropertyValue(bufferedWriter, "out", Writer.class); diff --git a/spring-integration-syslog/src/main/java/org/springframework/integration/syslog/config/SyslogReceivingChannelAdapterFactoryBean.java b/spring-integration-syslog/src/main/java/org/springframework/integration/syslog/config/SyslogReceivingChannelAdapterFactoryBean.java index 6da977e9a1..b011b1b5cd 100644 --- a/spring-integration-syslog/src/main/java/org/springframework/integration/syslog/config/SyslogReceivingChannelAdapterFactoryBean.java +++ b/spring-integration-syslog/src/main/java/org/springframework/integration/syslog/config/SyslogReceivingChannelAdapterFactoryBean.java @@ -37,9 +37,11 @@ import org.springframework.util.Assert; * */ public class SyslogReceivingChannelAdapterFactoryBean extends AbstractFactoryBean - implements SmartLifecycle, BeanNameAware, ApplicationEventPublisherAware { + implements SmartLifecycle, BeanNameAware, ApplicationEventPublisherAware { - public enum Protocol { udp, tcp }; + public enum Protocol { + udp, tcp + } private volatile SyslogReceivingChannelAdapterSupport adapter; @@ -166,7 +168,7 @@ public class SyslogReceivingChannelAdapterFactoryBean extends AbstractFactoryBea @Override public Class getObjectType() { return this.adapter == null ? SyslogReceivingChannelAdapterSupport.class : - this.adapter.getClass(); + this.adapter.getClass(); } @Override diff --git a/spring-integration-test/src/main/java/org/springframework/integration/test/matcher/TypeSafeMatcher.java b/spring-integration-test/src/main/java/org/springframework/integration/test/matcher/TypeSafeMatcher.java index 7a6f1f0e0d..03e58048ae 100644 --- a/spring-integration-test/src/main/java/org/springframework/integration/test/matcher/TypeSafeMatcher.java +++ b/spring-integration-test/src/main/java/org/springframework/integration/test/matcher/TypeSafeMatcher.java @@ -32,53 +32,53 @@ import org.hamcrest.BaseMatcher; */ abstract class TypeSafeMatcher extends BaseMatcher { - private final Class expectedType; + private final Class expectedType; - /** - * Subclasses should implement this. The item will already have been checked for - * the specific type and will never be null. - * - * @param item The item. - * @return true if matches. - */ - public abstract boolean matchesSafely(T item); + /** + * Subclasses should implement this. The item will already have been checked for + * the specific type and will never be null. + * + * @param item The item. + * @return true if matches. + */ + public abstract boolean matchesSafely(T item); - protected TypeSafeMatcher() { - expectedType = findExpectedType(getClass()); - } + protected TypeSafeMatcher() { + expectedType = findExpectedType(getClass()); + } - private static Class findExpectedType(Class fromClass) { - for (Class c = fromClass; c != Object.class; c = c.getSuperclass()) { - for (Method method : c.getDeclaredMethods()) { - if (isMatchesSafelyMethod(method)) { - return method.getParameterTypes()[0]; - } - } - } + private static Class findExpectedType(Class fromClass) { + for (Class c = fromClass; c != Object.class; c = c.getSuperclass()) { + for (Method method : c.getDeclaredMethods()) { + if (isMatchesSafelyMethod(method)) { + return method.getParameterTypes()[0]; + } + } + } - throw new Error("Cannot determine correct type for matchesSafely() method."); - } + throw new Error("Cannot determine correct type for matchesSafely() method."); + } - private static boolean isMatchesSafelyMethod(Method method) { - return method.getName().equals("matchesSafely") - && method.getParameterTypes().length == 1 - && !method.isSynthetic(); - } + private static boolean isMatchesSafelyMethod(Method method) { + return method.getName().equals("matchesSafely") + && method.getParameterTypes().length == 1 + && !method.isSynthetic(); + } - protected TypeSafeMatcher(Class expectedType) { - this.expectedType = expectedType; - } + protected TypeSafeMatcher(Class expectedType) { + this.expectedType = expectedType; + } - /** - * Method made final to prevent accidental override. - * If you need to override this, there's no point on extending TypeSafeMatcher. - * Instead, extend the {@link BaseMatcher}. - */ - @Override - @SuppressWarnings({"unchecked"}) - public final boolean matches(Object item) { - return item != null - && expectedType.isInstance(item) - && matchesSafely((T) item); - } + /** + * Method made final to prevent accidental override. + * If you need to override this, there's no point on extending TypeSafeMatcher. + * Instead, extend the {@link BaseMatcher}. + */ + @Override + @SuppressWarnings({ "unchecked" }) + public final boolean matches(Object item) { + return item != null + && expectedType.isInstance(item) + && matchesSafely((T) item); + } } diff --git a/spring-integration-test/src/main/java/org/springframework/integration/test/support/AbstractResponseValidator.java b/spring-integration-test/src/main/java/org/springframework/integration/test/support/AbstractResponseValidator.java index 6acde53096..202b119ef9 100644 --- a/spring-integration-test/src/main/java/org/springframework/integration/test/support/AbstractResponseValidator.java +++ b/spring-integration-test/src/main/java/org/springframework/integration/test/support/AbstractResponseValidator.java @@ -19,6 +19,7 @@ package org.springframework.integration.test.support; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessagingException; + /** * The base class for response validators used for {@link RequestResponseScenario}s * @author David Turanski @@ -28,27 +29,27 @@ public abstract class AbstractResponseValidator implements MessageHandler { private Message lastMessage; - /** - * handle the message - */ - @Override + /** + * handle the message + */ + @Override @SuppressWarnings("unchecked") - public void handleMessage(Message message) throws MessagingException { - this.lastMessage = message; - validateResponse((T) (extractPayload() ? message.getPayload() : message)); - } + public void handleMessage(Message message) throws MessagingException { + this.lastMessage = message; + validateResponse((T) (extractPayload() ? message.getPayload() : message)); + } - /** - * Implement this method to validate the response (Message or Payload) - * @param response The response. - */ - protected abstract void validateResponse(T response); + /** + * Implement this method to validate the response (Message or Payload) + * @param response The response. + */ + protected abstract void validateResponse(T response); - /** - * If true will extract the payload as the parameter for validateResponse() - * @return true to extract the payload; false to process the message. - */ - protected abstract boolean extractPayload(); + /** + * If true will extract the payload as the parameter for validateResponse() + * @return true to extract the payload; false to process the message. + */ + protected abstract boolean extractPayload(); /** * @return the lastMessage diff --git a/spring-integration-test/src/main/java/org/springframework/integration/test/support/MessageValidator.java b/spring-integration-test/src/main/java/org/springframework/integration/test/support/MessageValidator.java index 2223c54865..0c4e41806f 100644 --- a/spring-integration-test/src/main/java/org/springframework/integration/test/support/MessageValidator.java +++ b/spring-integration-test/src/main/java/org/springframework/integration/test/support/MessageValidator.java @@ -21,25 +21,26 @@ import org.springframework.messaging.Message; /** * Validate a message. Create an anonymous instance or subclass to * implement the validateMessage() method + * * @author David Turanski * */ public abstract class MessageValidator extends AbstractResponseValidator> { - @Override + @Override protected final boolean extractPayload() { - return false; - } + return false; + } - @Override + @Override protected final void validateResponse(Message response) { - validateMessage(response); - } + validateMessage(response); + } - /** - * Implement this method to validate the message - * @param message The message. - */ - protected abstract void validateMessage(Message message); + /** + * Implement this method to validate the message + * @param message The message. + */ + protected abstract void validateMessage(Message message); } diff --git a/spring-integration-test/src/main/java/org/springframework/integration/test/support/PayloadValidator.java b/spring-integration-test/src/main/java/org/springframework/integration/test/support/PayloadValidator.java index b11a1204c1..a97046158c 100644 --- a/spring-integration-test/src/main/java/org/springframework/integration/test/support/PayloadValidator.java +++ b/spring-integration-test/src/main/java/org/springframework/integration/test/support/PayloadValidator.java @@ -15,14 +15,18 @@ */ package org.springframework.integration.test.support; + /** * Validate a message payload. Create an anonymous instance or subclass this * to validate a response payload. + * * @author David Turanski * */ public abstract class PayloadValidator extends AbstractResponseValidator { - protected final boolean extractPayload() { - return true; - } + + protected final boolean extractPayload() { + return true; + } + } diff --git a/spring-integration-test/src/main/java/org/springframework/integration/test/support/RequestResponseScenario.java b/spring-integration-test/src/main/java/org/springframework/integration/test/support/RequestResponseScenario.java index b0cec5e8fb..c7ac60cc1b 100644 --- a/spring-integration-test/src/main/java/org/springframework/integration/test/support/RequestResponseScenario.java +++ b/spring-integration-test/src/main/java/org/springframework/integration/test/support/RequestResponseScenario.java @@ -27,117 +27,123 @@ import org.springframework.util.Assert; * */ public class RequestResponseScenario { - private final String inputChannelName; - private final String outputChannelName; - private Object payload; - private Message message; - private AbstractResponseValidator responseValidator; - private String name; - protected Message getMessage() { - if (message == null) { - return new GenericMessage(this.payload); - } -else { - return message; - } - } + private final String inputChannelName; - /** - * Create an instance - * @param inputChannelName the input channel name - * @param outputChannelName the output channel name - */ - public RequestResponseScenario(String inputChannelName, String outputChannelName) { - this.inputChannelName = inputChannelName; - this.outputChannelName = outputChannelName; - } + private final String outputChannelName; - /** - * - * @return the input channel name - */ - public String getInputChannelName() { - return inputChannelName; - } + private Object payload; - /** - * - * @return the output channel name - */ - public String getOutputChannelName() { - return outputChannelName; - } + private Message message; - /** - * - * @return the request message payload - */ - public Object getPayload() { - return payload; - } + private AbstractResponseValidator responseValidator; - /** - * set the payload of the request message - * @param payload The payload. - * @return this - */ - public RequestResponseScenario setPayload(Object payload) { - this.payload = payload; - return this; - } + private String name; - /** - * - * @return the scenario name - */ - public String getName() { - return name; - } + protected Message getMessage() { + if (message == null) { + return new GenericMessage(this.payload); + } + else { + return message; + } + } - /** - * Set the scenario name (optional) - * @param name the name - * @return this - */ - public RequestResponseScenario setName(String name) { - this.name = name; - return this; - } + /** + * Create an instance + * @param inputChannelName the input channel name + * @param outputChannelName the output channel name + */ + public RequestResponseScenario(String inputChannelName, String outputChannelName) { + this.inputChannelName = inputChannelName; + this.outputChannelName = outputChannelName; + } - /** - * - * @return the response validator - * @see AbstractResponseValidator - */ - public AbstractResponseValidator getResponseValidator() { - return responseValidator; - } + /** + * + * @return the input channel name + */ + public String getInputChannelName() { + return inputChannelName; + } - /** - * Set the response validator - * @see AbstractResponseValidator - * @param responseValidator The response validator. - * @return this - */ - public RequestResponseScenario setResponseValidator(AbstractResponseValidator responseValidator) { - this.responseValidator = responseValidator; - return this; - } + /** + * + * @return the output channel name + */ + public String getOutputChannelName() { + return outputChannelName; + } + + /** + * + * @return the request message payload + */ + public Object getPayload() { + return payload; + } + + /** + * set the payload of the request message + * @param payload The payload. + * @return this + */ + public RequestResponseScenario setPayload(Object payload) { + this.payload = payload; + return this; + } + + /** + * + * @return the scenario name + */ + public String getName() { + return name; + } + + /** + * Set the scenario name (optional) + * @param name the name + * @return this + */ + public RequestResponseScenario setName(String name) { + this.name = name; + return this; + } + + /** + * + * @return the response validator + * @see AbstractResponseValidator + */ + public AbstractResponseValidator getResponseValidator() { + return responseValidator; + } + + /** + * Set the response validator + * @see AbstractResponseValidator + * @param responseValidator The response validator. + * @return this + */ + public RequestResponseScenario setResponseValidator(AbstractResponseValidator responseValidator) { + this.responseValidator = responseValidator; + return this; + } - /** - * Set the request message (as an alternative to setPayload()) - * @param message The message. - * @return this - */ - public RequestResponseScenario setMessage(Message message) { - this.message = message; - return this; - } + /** + * Set the request message (as an alternative to setPayload()) + * @param message The message. + * @return this + */ + public RequestResponseScenario setMessage(Message message) { + this.message = message; + return this; + } - protected void init() { - Assert.state(message == null || payload == null, "cannot set both message and payload"); - } + protected void init() { + Assert.state(message == null || payload == null, "cannot set both message and payload"); + } } diff --git a/spring-integration-twitter/src/main/java/org/springframework/integration/twitter/inbound/AbstractTwitterMessageSource.java b/spring-integration-twitter/src/main/java/org/springframework/integration/twitter/inbound/AbstractTwitterMessageSource.java index df1e766dc8..a2adf95b68 100644 --- a/spring-integration-twitter/src/main/java/org/springframework/integration/twitter/inbound/AbstractTwitterMessageSource.java +++ b/spring-integration-twitter/src/main/java/org/springframework/integration/twitter/inbound/AbstractTwitterMessageSource.java @@ -139,7 +139,7 @@ abstract class AbstractTwitterMessageSource extends IntegrationObjectSupport // initialize the last status ID from the metadataStore if (StringUtils.hasText(lastId)) { this.lastProcessedId = Long.parseLong(lastId); - this.lastEnqueuedId = this.lastProcessedId; + this.lastEnqueuedId = this.lastProcessedId; } } diff --git a/spring-integration-twitter/src/main/java/org/springframework/integration/twitter/inbound/TimelineReceivingMessageSource.java b/spring-integration-twitter/src/main/java/org/springframework/integration/twitter/inbound/TimelineReceivingMessageSource.java index 42e68e070d..9d6c3b6c22 100644 --- a/spring-integration-twitter/src/main/java/org/springframework/integration/twitter/inbound/TimelineReceivingMessageSource.java +++ b/spring-integration-twitter/src/main/java/org/springframework/integration/twitter/inbound/TimelineReceivingMessageSource.java @@ -37,7 +37,7 @@ public class TimelineReceivingMessageSource extends AbstractTwitterMessageSource } @Override - public String getComponentType() { + public String getComponentType() { return "twitter:inbound-channel-adapter"; } diff --git a/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/ignored/TestSendingDMsUsingNamespace.java b/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/ignored/TestSendingDMsUsingNamespace.java index 225d2f5403..148e44148e 100644 --- a/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/ignored/TestSendingDMsUsingNamespace.java +++ b/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/ignored/TestSendingDMsUsingNamespace.java @@ -21,9 +21,9 @@ import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.messaging.MessageChannel; import org.springframework.integration.support.MessageBuilder; import org.springframework.integration.twitter.core.TwitterHeaders; +import org.springframework.messaging.MessageChannel; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.springframework.util.StringUtils; @@ -40,12 +40,13 @@ public class TestSendingDMsUsingNamespace extends AbstractJUnit4SpringContextTes @Qualifier("inputChannel") private MessageChannel inputChannel; + @Autowired @Qualifier("dmOutboundWithinChain") private MessageChannel dmOutboundWithinChain; @Test - @Ignore + @Ignore public void testSendigRealDirectMessage() throws Throwable { String dmUsr = "z_oleg"; MessageBuilder mb = MessageBuilder.withPayload("'Hello world!', from the Spring Integration outbound Twitter adapter " diff --git a/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/inbound/DirectMessageReceivingMessageSourceTests.java b/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/inbound/DirectMessageReceivingMessageSourceTests.java index 59154c88c7..903dc28ed9 100644 --- a/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/inbound/DirectMessageReceivingMessageSourceTests.java +++ b/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/inbound/DirectMessageReceivingMessageSourceTests.java @@ -38,16 +38,17 @@ public class DirectMessageReceivingMessageSourceTests { private final Log logger = LogFactory.getLog(getClass()); @SuppressWarnings("unchecked") - @Test @Ignore + @Test + @Ignore public void demoReceiveDm() throws Exception { PropertiesFactoryBean pf = new PropertiesFactoryBean(); pf.setLocation(new ClassPathResource("sample.properties")); pf.afterPropertiesSet(); - Properties prop = pf.getObject(); + Properties prop = pf.getObject(); TwitterTemplate template = new TwitterTemplate(prop.getProperty("z_oleg.oauth.consumerKey"), - prop.getProperty("z_oleg.oauth.consumerSecret"), - prop.getProperty("z_oleg.oauth.accessToken"), - prop.getProperty("z_oleg.oauth.accessTokenSecret")); + prop.getProperty("z_oleg.oauth.consumerSecret"), + prop.getProperty("z_oleg.oauth.accessToken"), + prop.getProperty("z_oleg.oauth.accessTokenSecret")); DirectMessageReceivingMessageSource tSource = new DirectMessageReceivingMessageSource(template, "foo"); tSource.afterPropertiesSet(); for (int i = 0; i < 50; i++) { diff --git a/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/inbound/SearchReceivingMessageSourceTests.java b/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/inbound/SearchReceivingMessageSourceTests.java index 0d7afb142b..d16e2a8c80 100644 --- a/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/inbound/SearchReceivingMessageSourceTests.java +++ b/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/inbound/SearchReceivingMessageSourceTests.java @@ -60,16 +60,17 @@ public class SearchReceivingMessageSourceTests { private static final String SEARCH_QUERY = "#springsource"; @SuppressWarnings("unchecked") - @Test @Ignore + @Test + @Ignore public void demoReceiveSearchResults() throws Exception { PropertiesFactoryBean pf = new PropertiesFactoryBean(); pf.setLocation(new ClassPathResource("sample.properties")); pf.afterPropertiesSet(); - Properties prop = pf.getObject(); + Properties prop = pf.getObject(); TwitterTemplate template = new TwitterTemplate(prop.getProperty("z_oleg.oauth.consumerKey"), - prop.getProperty("z_oleg.oauth.consumerSecret"), - prop.getProperty("z_oleg.oauth.accessToken"), - prop.getProperty("z_oleg.oauth.accessTokenSecret")); + prop.getProperty("z_oleg.oauth.consumerSecret"), + prop.getProperty("z_oleg.oauth.accessToken"), + prop.getProperty("z_oleg.oauth.accessTokenSecret")); SearchReceivingMessageSource tSource = new SearchReceivingMessageSource(template, "foo"); tSource.setQuery(SEARCH_QUERY); tSource.afterPropertiesSet(); diff --git a/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/inbound/TimelineReceivingMessageSourceTests.java b/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/inbound/TimelineReceivingMessageSourceTests.java index b497a9ec6c..29eaaacaba 100644 --- a/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/inbound/TimelineReceivingMessageSourceTests.java +++ b/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/inbound/TimelineReceivingMessageSourceTests.java @@ -39,16 +39,17 @@ public class TimelineReceivingMessageSourceTests { private final Log logger = LogFactory.getLog(getClass()); @SuppressWarnings("unchecked") - @Test @Ignore + @Test + @Ignore public void demoReceiveTimeline() throws Exception { PropertiesFactoryBean pf = new PropertiesFactoryBean(); pf.setLocation(new ClassPathResource("sample.properties")); pf.afterPropertiesSet(); - Properties prop = pf.getObject(); + Properties prop = pf.getObject(); TwitterTemplate template = new TwitterTemplate(prop.getProperty("z_oleg.oauth.consumerKey"), - prop.getProperty("z_oleg.oauth.consumerSecret"), - prop.getProperty("z_oleg.oauth.accessToken"), - prop.getProperty("z_oleg.oauth.accessTokenSecret")); + prop.getProperty("z_oleg.oauth.consumerSecret"), + prop.getProperty("z_oleg.oauth.accessToken"), + prop.getProperty("z_oleg.oauth.accessTokenSecret")); TimelineReceivingMessageSource tSource = new TimelineReceivingMessageSource(template, "foo"); tSource.afterPropertiesSet(); for (int i = 0; i < 50; i++) { diff --git a/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/outbound/DirectMessageSendingMessageHandlerTests.java b/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/outbound/DirectMessageSendingMessageHandlerTests.java index 410c0c1bac..1ede6f0866 100644 --- a/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/outbound/DirectMessageSendingMessageHandlerTests.java +++ b/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/outbound/DirectMessageSendingMessageHandlerTests.java @@ -35,16 +35,17 @@ import org.springframework.social.twitter.api.impl.TwitterTemplate; */ public class DirectMessageSendingMessageHandlerTests { - @Test @Ignore + @Test + @Ignore public void validateSendDirectMessage() throws Exception { PropertiesFactoryBean pf = new PropertiesFactoryBean(); pf.setLocation(new ClassPathResource("sample.properties")); pf.afterPropertiesSet(); - Properties prop = pf.getObject(); + Properties prop = pf.getObject(); TwitterTemplate template = new TwitterTemplate(prop.getProperty("spring_eip.oauth.consumerKey"), - prop.getProperty("spring_eip.oauth.consumerSecret"), - prop.getProperty("spring_eip.oauth.accessToken"), - prop.getProperty("spring_eip.oauth.accessTokenSecret")); + prop.getProperty("spring_eip.oauth.consumerSecret"), + prop.getProperty("spring_eip.oauth.accessToken"), + prop.getProperty("spring_eip.oauth.accessTokenSecret")); Message message1 = MessageBuilder.withPayload("Polsihing SI Twitter migration") .setHeader(TwitterHeaders.DM_TARGET_USER_ID, "z_oleg").build(); DirectMessageSendingMessageHandler handler = new DirectMessageSendingMessageHandler(template); diff --git a/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/outbound/StatusUpdatingMessageHandlerTests.java b/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/outbound/StatusUpdatingMessageHandlerTests.java index 6b230c745a..91471b7e4d 100644 --- a/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/outbound/StatusUpdatingMessageHandlerTests.java +++ b/spring-integration-twitter/src/test/java/org/springframework/integration/twitter/outbound/StatusUpdatingMessageHandlerTests.java @@ -63,16 +63,17 @@ public class StatusUpdatingMessageHandlerTests { @Autowired Twitter twitter; - @Test @Ignore + @Test + @Ignore public void demoSendStatusMessage() throws Exception { PropertiesFactoryBean pf = new PropertiesFactoryBean(); pf.setLocation(new ClassPathResource("sample.properties")); pf.afterPropertiesSet(); - Properties prop = pf.getObject(); + Properties prop = pf.getObject(); TwitterTemplate template = new TwitterTemplate(prop.getProperty("z_oleg.oauth.consumerKey"), - prop.getProperty("z_oleg.oauth.consumerSecret"), - prop.getProperty("z_oleg.oauth.accessToken"), - prop.getProperty("z_oleg.oauth.accessTokenSecret")); + prop.getProperty("z_oleg.oauth.consumerSecret"), + prop.getProperty("z_oleg.oauth.accessToken"), + prop.getProperty("z_oleg.oauth.accessTokenSecret")); Message message1 = MessageBuilder.withPayload("Polishing #springintegration migration to Spring Social. test").build(); StatusUpdatingMessageHandler handler = new StatusUpdatingMessageHandler(template); handler.afterPropertiesSet(); diff --git a/spring-integration-websocket/src/test/java/org/springframework/integration/websocket/client/StompIntegrationTests.java b/spring-integration-websocket/src/test/java/org/springframework/integration/websocket/client/StompIntegrationTests.java index 9ab29d2dc1..7a91500044 100644 --- a/spring-integration-websocket/src/test/java/org/springframework/integration/websocket/client/StompIntegrationTests.java +++ b/spring-integration-websocket/src/test/java/org/springframework/integration/websocket/client/StompIntegrationTests.java @@ -405,12 +405,12 @@ public class StompIntegrationTests extends LogAdjustingTestSupport { private final CountDownLatch latch = new CountDownLatch(1); - @MessageMapping(value = "/simple") + @MessageMapping("/simple") public void handle() { this.latch.countDown(); } - @MessageMapping(value = "/exception") + @MessageMapping("/exception") public void handleWithError() { throw new IllegalArgumentException("Bad input"); } @@ -425,7 +425,7 @@ public class StompIntegrationTests extends LogAdjustingTestSupport { @IntegrationTestController static class IncrementController { - @MessageMapping(value = "/increment") + @MessageMapping("/increment") public int handle(int i) { return i + 1; } diff --git a/spring-integration-ws/src/main/java/org/springframework/integration/ws/DefaultSoapHeaderMapper.java b/spring-integration-ws/src/main/java/org/springframework/integration/ws/DefaultSoapHeaderMapper.java index 12e251e841..eaf35b6107 100644 --- a/spring-integration-ws/src/main/java/org/springframework/integration/ws/DefaultSoapHeaderMapper.java +++ b/spring-integration-ws/src/main/java/org/springframework/integration/ws/DefaultSoapHeaderMapper.java @@ -57,7 +57,7 @@ public class DefaultSoapHeaderMapper extends AbstractHeaderMapper i } public DefaultSoapHeaderMapper() { - super(WebServiceHeaders.PREFIX, STANDARD_HEADER_NAMES, Collections.emptyList()); + super(WebServiceHeaders.PREFIX, STANDARD_HEADER_NAMES, Collections.emptyList()); } @Override @@ -106,8 +106,8 @@ public class DefaultSoapHeaderMapper extends AbstractHeaderMapper i protected void populateStandardHeaders(Map headers, SoapMessage target) { String soapAction = getHeaderIfAvailable(headers, WebServiceHeaders.SOAP_ACTION, String.class); if (!StringUtils.hasText(soapAction)) { - soapAction = "\"\""; - } + soapAction = "\"\""; + } target.setSoapAction(soapAction); } diff --git a/spring-integration-ws/src/main/java/org/springframework/integration/ws/config/WebServiceInboundGatewayParser.java b/spring-integration-ws/src/main/java/org/springframework/integration/ws/config/WebServiceInboundGatewayParser.java index 89fb521c9a..f6617f4d05 100644 --- a/spring-integration-ws/src/main/java/org/springframework/integration/ws/config/WebServiceInboundGatewayParser.java +++ b/spring-integration-ws/src/main/java/org/springframework/integration/ws/config/WebServiceInboundGatewayParser.java @@ -18,13 +18,14 @@ package org.springframework.integration.ws.config; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Element; + import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.integration.config.xml.AbstractInboundGatewayParser; import org.springframework.integration.config.xml.IntegrationNamespaceUtils; import org.springframework.integration.ws.DefaultSoapHeaderMapper; import org.springframework.util.StringUtils; -import org.w3c.dom.Element; /** * @author Iwein Fuld @@ -32,7 +33,9 @@ import org.w3c.dom.Element; * @author Oleg Zhurakousky */ public class WebServiceInboundGatewayParser extends AbstractInboundGatewayParser { + protected final Log logger = LogFactory.getLog(getClass()); + @Override protected String getBeanClassName(Element element) { String simpleClassName = (StringUtils.hasText(element.getAttribute("marshaller"))) ? @@ -43,9 +46,9 @@ public class WebServiceInboundGatewayParser extends AbstractInboundGatewayParser @Override protected boolean isEligibleAttribute(String attributeName) { return !(attributeName.endsWith("marshaller")) && - !(attributeName.equals("mapped-reply-headers")) && - !(attributeName.equals("mapped-request-headers")) && - super.isEligibleAttribute(attributeName); + !(attributeName.equals("mapped-reply-headers")) && + !(attributeName.equals("mapped-request-headers")) && + super.isEligibleAttribute(attributeName); } @Override diff --git a/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/StubMessageFactory.java b/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/StubMessageFactory.java index c9b3e556a1..dae93ac28e 100644 --- a/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/StubMessageFactory.java +++ b/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/StubMessageFactory.java @@ -16,6 +16,9 @@ package org.springframework.integration.ws.config; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -33,9 +36,6 @@ import org.springframework.ws.WebServiceMessage; import org.springframework.ws.WebServiceMessageFactory; import org.springframework.ws.pox.dom.DomPoxMessage; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - /** * @author Mark Fisher */ @@ -52,10 +52,10 @@ public class StubMessageFactory implements WebServiceMessageFactory { try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); - DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - InputSource is = new InputSource(new InputStreamReader(inputStream)); - Document document = builder.parse(is); - return new DomPoxMessage(document, transformer, "text/xml"); + DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + InputSource is = new InputSource(new InputStreamReader(inputStream)); + Document document = builder.parse(is); + return new DomPoxMessage(document, transformer, "text/xml"); } catch (Exception e) { throw new IllegalArgumentException(e); diff --git a/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/StubWebServiceMessageCallback.java b/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/StubWebServiceMessageCallback.java index 9113412783..3cc7415e3b 100644 --- a/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/StubWebServiceMessageCallback.java +++ b/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/StubWebServiceMessageCallback.java @@ -28,7 +28,7 @@ import org.springframework.ws.client.core.WebServiceMessageCallback; */ public class StubWebServiceMessageCallback implements WebServiceMessageCallback { - public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { - } + public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException { + } } diff --git a/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/WebServiceInboundGatewayParserTests.java b/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/WebServiceInboundGatewayParserTests.java index b44a96a3ee..1a840bdbf8 100644 --- a/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/WebServiceInboundGatewayParserTests.java +++ b/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/WebServiceInboundGatewayParserTests.java @@ -211,7 +211,7 @@ public class WebServiceInboundGatewayParserTests { @Override public void fromHeadersToRequest(MessageHeaders headers, - SoapMessage target) { + SoapMessage target) { } @Override diff --git a/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/WebServiceOutboundGatewayWithHeaderMapperTests.java b/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/WebServiceOutboundGatewayWithHeaderMapperTests.java index 8814c687c8..97fcef87fc 100644 --- a/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/WebServiceOutboundGatewayWithHeaderMapperTests.java +++ b/spring-integration-ws/src/test/java/org/springframework/integration/ws/config/WebServiceOutboundGatewayWithHeaderMapperTests.java @@ -73,15 +73,15 @@ import org.springframework.xml.transform.StringResult; public class WebServiceOutboundGatewayWithHeaderMapperTests { String responseSoapMessage = " " + - " " + - "" + - " " + - "jane" + - " " + - ""; + " " + + "" + + " " + + "jane" + + " " + + ""; String responseNonSoapMessage = " " + - "oleg"; + "oleg"; @SuppressWarnings("unchecked") @Test @@ -202,6 +202,7 @@ public class WebServiceOutboundGatewayWithHeaderMapperTests { Mockito.when(messageSender.supports(Mockito.any(URI.class))).thenReturn(true); Mockito.doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); @@ -226,6 +227,7 @@ public class WebServiceOutboundGatewayWithHeaderMapperTests { }).when(wsConnection).send(Mockito.any(WebServiceMessage.class)); Mockito.doAnswer(new Answer() { + @Override public Object answer(InvocationOnMock invocation) throws Exception { Object[] args = invocation.getArguments(); @@ -257,8 +259,8 @@ public class WebServiceOutboundGatewayWithHeaderMapperTests { MessageChannel inputChannel = context.getBean(channelName, MessageChannel.class); Message message = MessageBuilder.withPayload(payload). - setHeader("foo", "foo").setHeader("foobar", "foobar").setHeader("abaz", "abaz").setHeader("bar", "bar"). - setHeader(WebServiceHeaders.SOAP_ACTION, "someAction").build(); + setHeader("foo", "foo").setHeader("foobar", "foobar").setHeader("abaz", "abaz").setHeader("bar", "bar"). + setHeader(WebServiceHeaders.SOAP_ACTION, "someAction").build(); inputChannel.send(message); QueueChannel outputChannel = context.getBean("outputChannel", QueueChannel.class); Message replyMessage = outputChannel.receive(0); @@ -267,6 +269,7 @@ public class WebServiceOutboundGatewayWithHeaderMapperTests { } public static class Person { + private String name; public String getName() { @@ -297,18 +300,18 @@ public class WebServiceOutboundGatewayWithHeaderMapperTests { } private String extractStringResult(Message replyMessage) throws Exception { - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - StringResult result = new StringResult(); - Object payload = replyMessage.getPayload(); - if (payload instanceof DOMSource) { - transformer.transform(((DOMSource) replyMessage.getPayload()), result); - } - else if (payload instanceof Document) { - transformer.transform(new DOMSource((Document) replyMessage.getPayload()), result); - } - else { - throw new IllegalArgumentException("Unsupported payload type: " + payload.getClass().getName()); - } - return result.toString(); + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + StringResult result = new StringResult(); + Object payload = replyMessage.getPayload(); + if (payload instanceof DOMSource) { + transformer.transform(((DOMSource) replyMessage.getPayload()), result); + } + else if (payload instanceof Document) { + transformer.transform(new DOMSource((Document) replyMessage.getPayload()), result); + } + else { + throw new IllegalArgumentException("Unsupported payload type: " + payload.getClass().getName()); + } + return result.toString(); } } diff --git a/spring-integration-xml/src/test/java/org/springframework/integration/xml/DefaultXmlPayloadConverterTests.java b/spring-integration-xml/src/test/java/org/springframework/integration/xml/DefaultXmlPayloadConverterTests.java index 3a4b389740..7d63dffd7d 100644 --- a/spring-integration-xml/src/test/java/org/springframework/integration/xml/DefaultXmlPayloadConverterTests.java +++ b/spring-integration-xml/src/test/java/org/springframework/integration/xml/DefaultXmlPayloadConverterTests.java @@ -120,12 +120,12 @@ public class DefaultXmlPayloadConverterTests { converter.convertToSource(12); } - @Test - public void testGetNodePassingDOMSource() { - Node element = testDocument.getElementsByTagName("test").item(0); + @Test + public void testGetNodePassingDOMSource() { + Node element = testDocument.getElementsByTagName("test").item(0); Node n = converter.convertToNode(new DOMSource(element)); assertTrue("Wrong node returned", element == n); - } + } @Test public void testConvertNodeToDocument() { diff --git a/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/TestXmlApplicationContextHelper.java b/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/TestXmlApplicationContextHelper.java index 660bacdd52..d3381d8364 100644 --- a/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/TestXmlApplicationContextHelper.java +++ b/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/TestXmlApplicationContextHelper.java @@ -43,8 +43,8 @@ public class TestXmlApplicationContextHelper { + "http://www.springframework.org/schema/integration/xml " + "http://www.springframework.org/schema/integration/xml/spring-integration-xml.xsd " + "http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd " + - "http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd' >" + - ""; + "http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd' >" + + ""; private final static String footer = ""; diff --git a/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/XPathExpressionParserTests.java b/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/XPathExpressionParserTests.java index e4e6d2d42d..bfcb48aad6 100644 --- a/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/XPathExpressionParserTests.java +++ b/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/XPathExpressionParserTests.java @@ -21,10 +21,11 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; +import org.xml.sax.SAXParseException; + import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.integration.xml.util.XmlTestUtil; import org.springframework.xml.xpath.XPathExpression; -import org.xml.sax.SAXParseException; public class XPathExpressionParserTests { @@ -56,8 +57,8 @@ public class XPathExpressionParserTests { public void testStringExpressionWithNamespaceInnerBean() throws Exception { StringBuilder xmlDoc = new StringBuilder("") - .append(" ") - .append(""); + .append(" ") + .append(""); XPathExpression xPathExpression = getXPathExpression(xmlDoc.toString()); assertEquals("outputOne", xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("outputOne"))); @@ -68,10 +69,10 @@ public class XPathExpressionParserTests { public void testStringExpressionWithMultipleNamespaceInnerBean() throws Exception { StringBuilder xmlDoc = new StringBuilder( - "") - .append(" ") - .append(" ") - .append(""); + "") + .append(" ") + .append(" ") + .append(""); try { getXPathExpression(xmlDoc.toString()); @@ -114,9 +115,9 @@ public class XPathExpressionParserTests { @Test public void testNamespacedStringExpressionWithNamespaceInnerBean() throws Exception { StringBuilder xmlDoc = new StringBuilder( - "") - .append(" ") - .append(""); + "") + .append(" ") + .append(""); try { getXPathExpression(xmlDoc.toString()); } @@ -132,10 +133,10 @@ public class XPathExpressionParserTests { @Test public void testStringExpressionWithNamespaceInnerBeanAndWithNamespaceMapReference() throws Exception { StringBuilder xmlDoc = new StringBuilder( - "") - .append(" ") - .append("") - .append(""); + "") + .append(" ") + .append("") + .append(""); try { getXPathExpression(xmlDoc.toString()); } @@ -154,6 +155,4 @@ public class XPathExpressionParserTests { } - - } diff --git a/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/XPathMessageSplitterParserTests.java b/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/XPathMessageSplitterParserTests.java index 7a2344ce94..6263164e40 100644 --- a/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/XPathMessageSplitterParserTests.java +++ b/spring-integration-xml/src/test/java/org/springframework/integration/xml/config/XPathMessageSplitterParserTests.java @@ -112,9 +112,9 @@ public class XPathMessageSplitterParserTests { public void testXPathExpressionRef() throws Exception { TestXmlApplicationContext ctx = TestXmlApplicationContextHelper .getTestAppContext( - channelDefinitions + - "" + - ""); + channelDefinitions + + "" + + ""); EventDrivenConsumer consumer = (EventDrivenConsumer) ctx.getBean("splitter"); DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(consumer); Object handler = fieldAccessor.getPropertyValue("handler"); diff --git a/spring-integration-xml/src/test/java/org/springframework/integration/xml/selector/XmlValidatingMessageSelectorTests.java b/spring-integration-xml/src/test/java/org/springframework/integration/xml/selector/XmlValidatingMessageSelectorTests.java index 9a69bc6ab8..474ab1c127 100644 --- a/spring-integration-xml/src/test/java/org/springframework/integration/xml/selector/XmlValidatingMessageSelectorTests.java +++ b/spring-integration-xml/src/test/java/org/springframework/integration/xml/selector/XmlValidatingMessageSelectorTests.java @@ -51,7 +51,7 @@ public class XmlValidatingMessageSelectorTests { context = new ClassPathXmlApplicationContext("XmlValidatingMessageSelectorTests-context.xml", this.getClass()); } catch (Exception e) { - assertTrue(e.getMessage().contains("java.lang.IllegalArgumentException: No enum constant")); + assertTrue(e.getMessage().contains("java.lang.IllegalArgumentException: No enum constant")); } finally { if (context != null) { diff --git a/spring-integration-xml/src/test/java/org/springframework/integration/xml/transformer/CustomTestResultFactory.java b/spring-integration-xml/src/test/java/org/springframework/integration/xml/transformer/CustomTestResultFactory.java index 5c60d4c033..53ecf898cc 100644 --- a/spring-integration-xml/src/test/java/org/springframework/integration/xml/transformer/CustomTestResultFactory.java +++ b/spring-integration-xml/src/test/java/org/springframework/integration/xml/transformer/CustomTestResultFactory.java @@ -17,43 +17,44 @@ package org.springframework.integration.xml.transformer; -import org.springframework.integration.xml.result.ResultFactory; +import java.io.StringWriter; import javax.xml.transform.Result; import javax.xml.transform.stream.StreamResult; -import java.io.StringWriter; + +import org.springframework.integration.xml.result.ResultFactory; public class CustomTestResultFactory implements ResultFactory { - private final String stringToReturn; + private final String stringToReturn; - public CustomTestResultFactory(String stringToReturn) { - this.stringToReturn = stringToReturn; - } + public CustomTestResultFactory(String stringToReturn) { + this.stringToReturn = stringToReturn; + } - public Result createResult(Object payload) { - return new FixedStringResult(this.stringToReturn); //To change body of implemented methods use File | Settings | File Templates. - } + public Result createResult(Object payload) { + return new FixedStringResult(this.stringToReturn); //To change body of implemented methods use File | Settings | File Templates. + } - public static class FixedStringResult extends StreamResult { + public static class FixedStringResult extends StreamResult { - private final String stringToReturn; + private final String stringToReturn; - public FixedStringResult(String stringToReturn) { - super(new StringWriter()); - this.stringToReturn = stringToReturn; - } + public FixedStringResult(String stringToReturn) { + super(new StringWriter()); + this.stringToReturn = stringToReturn; + } - /** - * Returns the written XML as a string. - */ - public String toString() { - return this.stringToReturn; - } + /** + * Returns the written XML as a string. + */ + public String toString() { + return this.stringToReturn; + } - } + } } diff --git a/src/checkstyle/checkstyle.xml b/src/checkstyle/checkstyle.xml index 838c963bda..33fec01af6 100644 --- a/src/checkstyle/checkstyle.xml +++ b/src/checkstyle/checkstyle.xml @@ -20,10 +20,10 @@ - - - - + + + + @@ -76,7 +76,18 @@ + value="org.assertj.core.api.Assertions.*, + org.junit.Assert.*, + org.junit.Assume.*, + org.hamcrest.CoreMatchers.*, + org.hamcrest.Matchers.*, + org.mockito.Mockito.*, + org.mockito.BDDMockito.*, + org.mockito.Matchers.*, + org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*, + org.springframework.test.web.servlet.result.MockMvcResultMatchers.*, + org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*, + org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*" /> @@ -130,12 +141,12 @@ - - - - - - + + + + +