Enable ModifierOrderCheck Checkstyle rule (#2673)

* Enable ModifierOrderCheck Checkstyle rule

* Fix violations for `static` and `abstract` modifier
* Remove redundant code in the `TcpNioConnection`
* Mark `connectionFactoryName` as `@Nullable` in the `TcpConnectionSupport`
ctor and its inheritors
* Fix some smells according IDEA suggestions in the affected classes
* This should fix some Sonar smells as well

* * Fix `HeaderMapperTests`

* * Polishing `TcpConnection` code style and fix Javdocs
This commit is contained in:
Artem Bilan
2018-12-20 19:19:47 -05:00
committed by Gary Russell
parent a01d09f0f1
commit 93d7c58b64
56 changed files with 633 additions and 563 deletions

View File

@@ -310,7 +310,7 @@ public abstract class AbstractAmqpOutboundEndpoint extends AbstractReplyProducin
this.errorMessageStrategy = errorMessageStrategy;
}
protected synchronized final void setConnectionFactory(ConnectionFactory connectionFactory) {
protected final synchronized void setConnectionFactory(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,11 +28,13 @@ import com.esotericsoftware.kryo.Registration;
* Base class for {@link KryoRegistrar} implementations.
*
* @author David Turanski
* @author Artem Bilan
*
* @since 4.2
*/
public abstract class AbstractKryoRegistrar implements KryoRegistrar {
protected final static Kryo kryo = new Kryo();
protected static final Kryo kryo = new Kryo();
protected final Log log = LogFactory.getLog(this.getClass());
@@ -55,7 +57,7 @@ public abstract class AbstractKryoRegistrar implements KryoRegistrar {
Registration existing = kryo.getRegistration(id);
if (existing != null) {
throw new RuntimeException((String.format("registration already exists %s", existing)));
throw new RuntimeException("registration already exists " + existing);
}
if (this.log.isInfoEnabled()) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,12 +20,14 @@ package org.springframework.integration.codec.kryo;
* Default registration ids for serializers provided by the framework.
*
* @author Gary Russell
* @author Artem Bilan
*
* @since 4.2
*
*/
public final class RegistrationIds {
public final static int DEFAULT_FILE_REGISTRATION_ID = 40;
public static final int DEFAULT_FILE_REGISTRATION_ID = 40;
public static final int DEFAULT_MESSAGEHEADERS_ID = 41;

View File

@@ -89,7 +89,7 @@ class DefaultConfiguringBeanFactoryPostProcessor
private static final Log logger = LogFactory.getLog(DefaultConfiguringBeanFactoryPostProcessor.class);
private final static IntegrationConverterInitializer INTEGRATION_CONVERTER_INITIALIZER =
private static final IntegrationConverterInitializer INTEGRATION_CONVERTER_INITIALIZER =
new IntegrationConverterInitializer();
private static final Set<Integer> registriesProcessed = new HashSet<>();
@@ -152,17 +152,22 @@ class DefaultConfiguringBeanFactoryPostProcessor
*/
private void registerNullChannel() {
if (this.beanFactory.containsBean(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME)) {
BeanDefinition nullChannelDefinition;
BeanDefinition nullChannelDefinition = null;
if (this.beanFactory.containsBeanDefinition(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME)) {
nullChannelDefinition =
this.beanFactory.getBeanDefinition(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME);
}
else {
nullChannelDefinition =
((BeanDefinitionRegistry) this.beanFactory.getParentBeanFactory())
.getBeanDefinition(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME); // NOSONAR not null
BeanDefinitionRegistry parentBeanFactory =
(BeanDefinitionRegistry) this.beanFactory.getParentBeanFactory();
if (parentBeanFactory != null) {
nullChannelDefinition =
parentBeanFactory.getBeanDefinition(IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME);
}
}
if (!NullChannel.class.getName().equals(nullChannelDefinition.getBeanClassName())) {
if (nullChannelDefinition != null &&
!NullChannel.class.getName().equals(nullChannelDefinition.getBeanClassName())) {
throw new IllegalStateException("The bean name '" + IntegrationContextUtils.NULL_CHANNEL_BEAN_NAME
+ "' is reserved.");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2010 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,26 +27,27 @@ import org.springframework.util.Assert;
* FactoryBean for creating Expression instances.
*
* @author Mark Fisher
* @author Artem Bilan
*
* @since 2.0
*/
public class ExpressionFactoryBean extends AbstractFactoryBean<Expression> {
private final static ExpressionParser DEFAULT_PARSER = new SpelExpressionParser();
private static final ExpressionParser DEFAULT_PARSER = new SpelExpressionParser();
private final String expressionString;
private volatile ExpressionParser parser = DEFAULT_PARSER;
private ExpressionParser parser = DEFAULT_PARSER;
public ExpressionFactoryBean(String expressionString) {
Assert.hasText(expressionString, "expressionString must not be empty or null");
Assert.hasText(expressionString, "'expressionString' must not be empty or null");
this.expressionString = expressionString;
}
public void setParserConfiguration(SpelParserConfiguration parserConfiguration) {
Assert.notNull(parserConfiguration, "parserConfiguration must not be null");
Assert.notNull(parserConfiguration, "'parserConfiguration' must not be null");
this.parser = new SpelExpressionParser(parserConfiguration);
}
@@ -57,7 +58,7 @@ public class ExpressionFactoryBean extends AbstractFactoryBean<Expression> {
}
@Override
protected Expression createInstance() throws Exception {
protected Expression createInstance() {
return this.parser.parseExpression(this.expressionString);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2014 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,23 +32,27 @@ import org.springframework.util.StringUtils;
* @author Oleg Zhurakousky
* @author Mark Fisher
* @author Artem Bilan
*
* @since 2.0
*/
public class ConverterParser extends AbstractBeanDefinitionParser {
private final static IntegrationConverterInitializer INTEGRATION_CONVERTER_INITIALIZER = new IntegrationConverterInitializer();
private static final IntegrationConverterInitializer INTEGRATION_CONVERTER_INITIALIZER =
new IntegrationConverterInitializer();
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
BeanDefinitionRegistry registry = parserContext.getRegistry();
BeanComponentDefinition converterDefinition = IntegrationNamespaceUtils.parseInnerHandlerDefinition(element, parserContext);
BeanComponentDefinition converterDefinition =
IntegrationNamespaceUtils.parseInnerHandlerDefinition(element, parserContext);
if (converterDefinition != null) {
INTEGRATION_CONVERTER_INITIALIZER.registerConverter(registry, converterDefinition);
}
else {
String beanName = element.getAttribute("ref");
Assert.isTrue(StringUtils.hasText(beanName),
"Either a 'ref' attribute pointing to a Converter or a <bean> sub-element defining a Converter is required.");
"Either a 'ref' attribute pointing to a Converter " +
"or a <bean> sub-element defining a Converter is required.");
INTEGRATION_CONVERTER_INITIALIZER.registerConverter(registry, new RuntimeBeanReference(beanName));
}
return null;

View File

@@ -37,7 +37,7 @@ import org.springframework.expression.spel.standard.SpelExpressionParser;
public abstract class IntegrationComponentSpec<S extends IntegrationComponentSpec<S, T>, T>
implements FactoryBean<T>, InitializingBean, DisposableBean {
protected final static SpelExpressionParser PARSER = new SpelExpressionParser();
protected static final SpelExpressionParser PARSER = new SpelExpressionParser();
protected final Log logger = LogFactory.getLog(getClass()); // NOSONAR

View File

@@ -42,8 +42,8 @@ import org.springframework.integration.transformer.PayloadSerializingTransformer
import org.springframework.integration.transformer.PayloadTypeConvertingTransformer;
import org.springframework.integration.transformer.StreamTransformer;
import org.springframework.integration.transformer.SyslogToMapTransformer;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@@ -58,14 +58,16 @@ import reactor.core.publisher.Mono;
*/
public abstract class Transformers {
private final static SpelExpressionParser PARSER = new SpelExpressionParser();
private static final SpelExpressionParser PARSER = new SpelExpressionParser();
public static ObjectToStringTransformer objectToString() {
return objectToString(null);
}
public static ObjectToStringTransformer objectToString(String charset) {
return charset != null ? new ObjectToStringTransformer(charset) : new ObjectToStringTransformer();
public static ObjectToStringTransformer objectToString(@Nullable String charset) {
return charset != null
? new ObjectToStringTransformer(charset)
: new ObjectToStringTransformer();
}
public static ObjectToMapTransformer toMap() {
@@ -100,20 +102,21 @@ public abstract class Transformers {
return toJson(null, null, null);
}
public static ObjectToJsonTransformer toJson(JsonObjectMapper<?, ?> jsonObjectMapper) {
public static ObjectToJsonTransformer toJson(@Nullable JsonObjectMapper<?, ?> jsonObjectMapper) {
return toJson(jsonObjectMapper, null, null);
}
public static ObjectToJsonTransformer toJson(JsonObjectMapper<?, ?> jsonObjectMapper,
ObjectToJsonTransformer.ResultType resultType) {
public static ObjectToJsonTransformer toJson(@Nullable JsonObjectMapper<?, ?> jsonObjectMapper,
@Nullable ObjectToJsonTransformer.ResultType resultType) {
return toJson(jsonObjectMapper, resultType, null);
}
public static ObjectToJsonTransformer toJson(String contentType) {
public static ObjectToJsonTransformer toJson(@Nullable String contentType) {
return toJson(null, null, contentType);
}
public static ObjectToJsonTransformer toJson(JsonObjectMapper<?, ?> jsonObjectMapper, String contentType) {
public static ObjectToJsonTransformer toJson(@Nullable JsonObjectMapper<?, ?> jsonObjectMapper,
@Nullable String contentType) {
return toJson(jsonObjectMapper, null, contentType);
}
@@ -124,16 +127,18 @@ public abstract class Transformers {
* @return the ObjectToJsonTransformer
* @since 5.0.9
*/
public static ObjectToJsonTransformer toJson(ObjectToJsonTransformer.ResultType resultType) {
public static ObjectToJsonTransformer toJson(@Nullable ObjectToJsonTransformer.ResultType resultType) {
return toJson(null, resultType, null);
}
public static ObjectToJsonTransformer toJson(ObjectToJsonTransformer.ResultType resultType, String contentType) {
public static ObjectToJsonTransformer toJson(@Nullable ObjectToJsonTransformer.ResultType resultType,
@Nullable String contentType) {
return toJson(null, resultType, contentType);
}
public static ObjectToJsonTransformer toJson(JsonObjectMapper<?, ?> jsonObjectMapper,
ObjectToJsonTransformer.ResultType resultType, String contentType) {
public static ObjectToJsonTransformer toJson(@Nullable JsonObjectMapper<?, ?> jsonObjectMapper,
@Nullable ObjectToJsonTransformer.ResultType resultType, @Nullable String contentType) {
ObjectToJsonTransformer transformer;
if (jsonObjectMapper != null) {
if (resultType != null) {
@@ -159,15 +164,17 @@ public abstract class Transformers {
return fromJson(null, null);
}
public static JsonToObjectTransformer fromJson(Class<?> targetClass) {
public static JsonToObjectTransformer fromJson(@Nullable Class<?> targetClass) {
return fromJson(targetClass, null);
}
public static JsonToObjectTransformer fromJson(JsonObjectMapper<?, ?> jsonObjectMapper) {
public static JsonToObjectTransformer fromJson(@Nullable JsonObjectMapper<?, ?> jsonObjectMapper) {
return fromJson(null, jsonObjectMapper);
}
public static JsonToObjectTransformer fromJson(Class<?> targetClass, JsonObjectMapper<?, ?> jsonObjectMapper) {
public static JsonToObjectTransformer fromJson(@Nullable Class<?> targetClass,
@Nullable JsonObjectMapper<?, ?> jsonObjectMapper) {
return new JsonToObjectTransformer(targetClass, jsonObjectMapper);
}
@@ -175,7 +182,7 @@ public abstract class Transformers {
return serializer(null);
}
public static PayloadSerializingTransformer serializer(Serializer<Object> serializer) {
public static PayloadSerializingTransformer serializer(@Nullable Serializer<Object> serializer) {
PayloadSerializingTransformer transformer = new PayloadSerializingTransformer();
if (serializer != null) {
transformer.setSerializer(serializer);
@@ -187,7 +194,7 @@ public abstract class Transformers {
return deserializer(null, whiteListPatterns);
}
public static PayloadDeserializingTransformer deserializer(Deserializer<Object> deserializer,
public static PayloadDeserializingTransformer deserializer(@Nullable Deserializer<Object> deserializer,
String... whiteListPatterns) {
PayloadDeserializingTransformer transformer = new PayloadDeserializingTransformer();
transformer.setWhiteListPatterns(whiteListPatterns);
@@ -198,7 +205,6 @@ public abstract class Transformers {
}
public static <T, U> PayloadTypeConvertingTransformer<T, U> converter(Converter<T, U> converter) {
Assert.notNull(converter, "The Converter<?, ?> is required for the PayloadTypeConvertingTransformer");
PayloadTypeConvertingTransformer<T, U> transformer = new PayloadTypeConvertingTransformer<>();
transformer.setConverter(converter);
return transformer;
@@ -276,7 +282,7 @@ public abstract class Transformers {
* @param charset the charset.
* @return the {@link StreamTransformer} instance.
*/
public static StreamTransformer fromStream(String charset) {
public static StreamTransformer fromStream(@Nullable String charset) {
return new StreamTransformer(charset);
}

View File

@@ -84,10 +84,12 @@ import org.springframework.util.StringUtils;
*/
class GatewayMethodInboundMessageMapper implements InboundMessageMapper<Object[]>, BeanFactoryAware {
private final static Log logger = LogFactory.getLog(GatewayMethodInboundMessageMapper.class);
private static final Log logger = LogFactory.getLog(GatewayMethodInboundMessageMapper.class);
private static final SpelExpressionParser PARSER = new SpelExpressionParser();
private final Map<String, Expression> parameterPayloadExpressions = new HashMap<>();
private final Method method;
private final Map<String, Expression> headerExpressions;
@@ -102,13 +104,11 @@ class GatewayMethodInboundMessageMapper implements InboundMessageMapper<Object[]
private final MessageBuilderFactory messageBuilderFactory;
private volatile Expression payloadExpression;
private Expression payloadExpression;
private final Map<String, Expression> parameterPayloadExpressions = new HashMap<String, Expression>();
private EvaluationContext payloadExpressionEvaluationContext;
private volatile StandardEvaluationContext payloadExpressionEvaluationContext;
private volatile BeanFactory beanFactory;
private BeanFactory beanFactory;
private Expression sendTimeoutExpression;
@@ -127,6 +127,7 @@ class GatewayMethodInboundMessageMapper implements InboundMessageMapper<Object[]
@Nullable Map<String, Expression> globalHeaderExpressions,
@Nullable MethodArgsMessageMapper mapper,
@Nullable MessageBuilderFactory messageBuilderFactory) {
this(method, headerExpressions, globalHeaderExpressions, null, mapper, messageBuilderFactory);
}
@@ -189,7 +190,7 @@ class GatewayMethodInboundMessageMapper implements InboundMessageMapper<Object[]
}
@Nullable
private Message<?> mapArgumentsToMessage(Object[] arguments, Map<String, Object> headers) {
private Message<?> mapArgumentsToMessage(Object[] arguments, @Nullable Map<String, Object> headers) {
try {
return this.argsMapper.toMessage(new MethodArgsHolder(this.method, arguments), headers);
}
@@ -205,6 +206,7 @@ class GatewayMethodInboundMessageMapper implements InboundMessageMapper<Object[]
private Map<String, Object> evaluateHeaders(EvaluationContext methodInvocationEvaluationContext,
Map<String, Expression> headerExpressions) {
Map<String, Object> evaluatedHeaders = new HashMap<>();
for (Map.Entry<String, Expression> entry : headerExpressions.entrySet()) {
Object value = entry.getValue().getValue(methodInvocationEvaluationContext);
@@ -277,7 +279,7 @@ class GatewayMethodInboundMessageMapper implements InboundMessageMapper<Object[]
String expressionString = (String) AnnotationUtils.getValue(payload);
Assert.hasText(expressionString,
"@Payload at method-level on a Gateway must provide a non-empty Expression.");
expression = PARSER.parseExpression(expressionString);
expression = PARSER.parseExpression(expressionString); // NOSONAR protected with hasText()
}
return expression;
}
@@ -285,7 +287,7 @@ class GatewayMethodInboundMessageMapper implements InboundMessageMapper<Object[]
public class DefaultMethodArgsMessageMapper implements MethodArgsMessageMapper {
@Override
public Message<?> toMessage(MethodArgsHolder holder, @Nullable Map<String, Object> headers) throws Exception {
public Message<?> toMessage(MethodArgsHolder holder, @Nullable Map<String, Object> headers) {
Object messageOrPayload = null;
boolean foundPayloadAnnotation = false;
Object[] arguments = holder.getArgs();
@@ -296,13 +298,15 @@ class GatewayMethodInboundMessageMapper implements InboundMessageMapper<Object[]
: new HashMap<>();
if (GatewayMethodInboundMessageMapper.this.payloadExpression != null) {
messageOrPayload =
GatewayMethodInboundMessageMapper.this.payloadExpression.getValue(methodInvocationEvaluationContext);
GatewayMethodInboundMessageMapper.this.payloadExpression.getValue(
methodInvocationEvaluationContext);
}
for (int i = 0; i < GatewayMethodInboundMessageMapper.this.parameterList.size(); i++) {
Object argumentValue = arguments[i];
MethodParameter methodParameter = GatewayMethodInboundMessageMapper.this.parameterList.get(i);
Annotation annotation =
MessagingAnnotationUtils.findMessagePartAnnotation(methodParameter.getParameterAnnotations(), false);
MessagingAnnotationUtils.findMessagePartAnnotation(methodParameter.getParameterAnnotations(),
false);
if (annotation != null) {
if (annotation.annotationType().equals(Payload.class)) {
if (messageOrPayload != null) {
@@ -329,7 +333,8 @@ class GatewayMethodInboundMessageMapper implements InboundMessageMapper<Object[]
else if (annotation.annotationType().equals(Headers.class)) {
if (argumentValue != null) {
if (!(argumentValue instanceof Map)) {
throw new IllegalArgumentException("@Headers annotation is only valid for Map-typed parameters");
throw new IllegalArgumentException(
"@Headers annotation is only valid for Map-typed parameters");
}
for (Object key : ((Map<?, ?>) argumentValue).keySet()) {
Assert.isInstanceOf(String.class, key, "Invalid header name [" + key +
@@ -369,10 +374,11 @@ class GatewayMethodInboundMessageMapper implements InboundMessageMapper<Object[]
v -> GatewayMethodInboundMessageMapper.this.replyTimeoutExpression
.getValue(methodInvocationEvaluationContext, Long.class));
}
MessageBuilderFactory messageBuilderFactory = GatewayMethodInboundMessageMapper.this.messageBuilderFactory;
AbstractIntegrationMessageBuilder<?> builder =
(messageOrPayload instanceof Message)
? GatewayMethodInboundMessageMapper.this.messageBuilderFactory.fromMessage((Message<?>) messageOrPayload)
: GatewayMethodInboundMessageMapper.this.messageBuilderFactory.withPayload(messageOrPayload);
? messageBuilderFactory.fromMessage((Message<?>) messageOrPayload)
: messageBuilderFactory.withPayload(messageOrPayload);
builder.copyHeadersIfAbsent(headers);
// Explicit headers in XML override any @Header annotations...
if (!CollectionUtils.isEmpty(GatewayMethodInboundMessageMapper.this.headerExpressions)) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,10 +22,12 @@ import org.springframework.messaging.Message;
/**
* @author Mark Fisher
* @author Dave Syer
* @author Artem Bilan
*
* @since 2.0
*/
public abstract class AbstractMessageProcessor<T> extends AbstractExpressionEvaluator implements MessageProcessor<T> {
abstract public T processMessage(Message<?> message);
public abstract T processMessage(Message<?> message);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016 the original author or authors.
* Copyright 2016-2018 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,13 +29,14 @@ import org.springframework.expression.spel.standard.SpelExpressionParser;
* @param <V> The Map value type.
*
* @author Artem Bilan
*
* @since 5.0
*/
public class MapBuilder<B extends MapBuilder<B, K, V>, K, V> {
protected final static SpelExpressionParser PARSER = new SpelExpressionParser();
protected static final SpelExpressionParser PARSER = new SpelExpressionParser();
private final Map<K, V> map = new HashMap<K, V>();
private final Map<K, V> map = new HashMap<>();
public B put(K key, V value) {
this.map.put(key, value);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 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.
@@ -45,11 +45,11 @@ import org.springframework.util.Assert;
*/
public class BeanFactoryChannelResolver implements DestinationResolver<MessageChannel>, BeanFactoryAware {
private final static Log logger = LogFactory.getLog(BeanFactoryChannelResolver.class);
private static final Log logger = LogFactory.getLog(BeanFactoryChannelResolver.class);
private volatile BeanFactory beanFactory;
private BeanFactory beanFactory;
private volatile HeaderChannelRegistry replyChannelRegistry;
private HeaderChannelRegistry replyChannelRegistry;
private volatile boolean initialized;

View File

@@ -40,6 +40,7 @@ import io.micrometer.core.instrument.Timer;
* The Micrometer implementation of {@link MetricsCaptor}.
*
* @author Gary Russell
* @author Artem Bilan
*
* @since 5.0.4
*
@@ -148,7 +149,7 @@ public class MicrometerMetricsCaptor implements MetricsCaptor {
}
protected static abstract class AbstractMeter<M extends Meter> implements MeterFacade {
protected abstract static class AbstractMeter<M extends Meter> implements MeterFacade {
protected final MeterRegistry meterRegistry; // NOSONAR

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 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.
@@ -141,7 +141,7 @@ public class SubscriberOrderTests {
}
static abstract class AbstractTestBean {
abstract static class AbstractTestBean {
@Order(4)
abstract void fourth(Message<?> message);
@@ -157,7 +157,7 @@ public class SubscriberOrderTests {
private final int maxCallsPerMethod;
private volatile List<Integer> calls = new ArrayList<Integer>();
private final List<Integer> calls = new ArrayList<>();
TestBean(int maxCallsPerMethod) {
@@ -166,7 +166,7 @@ public class SubscriberOrderTests {
void reset() {
this.calls = new ArrayList<Integer>();
this.calls.clear();
}
@Order(3)
@@ -211,6 +211,7 @@ public class SubscriberOrderTests {
}
this.calls.add(methodNumber);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,18 +24,22 @@ import java.util.logging.Logger;
/**
* @author Oleg Zhurakousky
* @author Artem Bilan
*
*/
class TimeBasedUUIDGenerator {
static final Object lock = new Object();
private static final Logger logger = Logger.getLogger(TimeBasedUUIDGenerator.class.getName());
public static final Object lock = new Object();
private static final long macAddress = getMac();
private static boolean canNotDetermineMac = true;
private static long lastTime;
private static long clockSequence = 0;
private static final long macAddress = getMac();
private TimeBasedUUIDGenerator() {
super();
@@ -45,11 +49,11 @@ class TimeBasedUUIDGenerator {
* Will generate unique time based UUID where the next UUID is
* always greater then the previous.
*/
public final static UUID generateId() {
static UUID generateId() {
return generateIdFromTimestamp(System.currentTimeMillis());
}
public final static UUID generateIdFromTimestamp(long currentTimeMillis) {
static UUID generateIdFromTimestamp(long currentTimeMillis) {
long time;
synchronized (lock) {
@@ -78,11 +82,12 @@ class TimeBasedUUIDGenerator {
clock_seq_hi_and_reserved <<= 48;
long cls = 0 | clock_seq_hi_and_reserved;
long cls = clock_seq_hi_and_reserved;
long lsb = cls | macAddress;
if (canNotDetermineMac) {
logger.warning("UUID generation process was not able to determine your MAC address. Returning random UUID (non version 1 UUID)");
logger.warning("UUID generation process was not able to determine your MAC address. " +
"Returning random UUID (non version 1 UUID)");
return UUID.randomUUID();
}
else {
@@ -98,11 +103,9 @@ class TimeBasedUUIDGenerator {
//byte[] mac = ni.getHardwareAddress(); // availabe since Java 1.6
byte[] mac = "01:23:45:67:89:ab".getBytes();
//Converts array of unsigned bytes to an long
if (mac != null) {
for (int i = 0; i < mac.length; i++) {
macAddressAsLong <<= 8;
macAddressAsLong ^= (long) mac[i] & 0xFF;
}
for (byte aMac : mac) {
macAddressAsLong <<= 8;
macAddressAsLong ^= (long) aMac & 0xFF;
}
}
canNotDetermineMac = false;
@@ -112,4 +115,5 @@ class TimeBasedUUIDGenerator {
}
return macAddressAsLong;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 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.
@@ -34,11 +34,14 @@ import org.springframework.integration.mapping.AbstractHeaderMapper.HeaderMatche
import org.springframework.integration.mapping.AbstractHeaderMapper.PatternBasedHeaderMatcher;
import org.springframework.integration.mapping.AbstractHeaderMapper.PrefixBasedMatcher;
import org.springframework.integration.mapping.AbstractHeaderMapper.SinglePatternBasedHeaderMatcher;
import org.springframework.lang.Nullable;
import org.springframework.messaging.MessageHeaders;
import org.springframework.util.StringUtils;
/**
* @author Stephane Nicoll
* @author Artem Bilan
*
* @since 4.1
*/
public class HeaderMapperTests {
@@ -75,8 +78,8 @@ public class HeaderMapperTests {
GenericTestProperties properties = createSimpleGenericTestProperties();
Map<String, Object> attributes = this.mapper.toHeadersFromRequest(properties);
assertEquals(null, attributes.get(GenericTestHeaders.APP_ID));
assertEquals(null, attributes.get(GenericTestHeaders.REQUEST_ONLY));
assertNull(attributes.get(GenericTestHeaders.APP_ID));
assertNull(attributes.get(GenericTestHeaders.REQUEST_ONLY));
assertEquals("reply-123", attributes.get(GenericTestHeaders.REPLY_ONLY));
assertEquals("bar", attributes.get("foo"));
assertEquals("Wrong number of mapped header(s)", 2, attributes.size());
@@ -310,7 +313,7 @@ public class HeaderMapperTests {
}
public MessageHeaders createSimpleMessageHeaders() {
Map<String, Object> headers = new HashMap<String, Object>();
Map<String, Object> headers = new HashMap<>();
headers.put(GenericTestHeaders.APP_ID, "myAppId");
headers.put(GenericTestHeaders.REDELIVERED, true);
headers.put(GenericTestHeaders.REQUEST_ONLY, "request-456");
@@ -324,7 +327,6 @@ public class HeaderMapperTests {
@Test
public void prefixHeaderPatternMatching() {
@SuppressWarnings("deprecation")
PatternBasedHeaderMatcher strategy =
new PatternBasedHeaderMatcher(Collections.singleton("fOo*"));
@@ -338,7 +340,6 @@ public class HeaderMapperTests {
@Test
public void suffixHeaderPatternMatching() {
@SuppressWarnings("deprecation")
PatternBasedHeaderMatcher strategy =
new PatternBasedHeaderMatcher(Collections.singleton("*fOo"));
@@ -435,7 +436,7 @@ public class HeaderMapperTests {
}
private static abstract class GenericTestHeaders {
private abstract static class GenericTestHeaders {
public static final String PREFIX = "generic_";
@@ -464,7 +465,7 @@ public class HeaderMapperTests {
@Override
protected Map<String, Object> extractStandardHeaders(GenericTestProperties source) {
Map<String, Object> result = new HashMap<String, Object>();
Map<String, Object> result = new HashMap<>();
if (StringUtils.hasText(source.getAppId())) {
result.put(GenericTestHeaders.APP_ID, source.getAppId());
}
@@ -547,6 +548,7 @@ public class HeaderMapperTests {
this.appId = appId;
}
@Nullable
public Integer getTransactionSize() {
return transactionSize;
}
@@ -555,6 +557,7 @@ public class HeaderMapperTests {
this.transactionSize = transactionSize;
}
@Nullable
public Boolean getRedelivered() {
return redelivered;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,6 +25,7 @@ import org.springframework.messaging.Message;
* Factory for handler beans that are useful for testing.
*
* @author Mark Fisher
* @author Artem Bilan
*/
@SuppressWarnings("unused")
public abstract class TestHandlers {
@@ -32,8 +33,9 @@ public abstract class TestHandlers {
/**
* Create a handler that always returns null.
*/
public final static Object nullHandler() {
public static final Object nullHandler() {
return new Object() {
public Message<?> handle(Message<?> message) {
return null;
}
@@ -43,8 +45,9 @@ public abstract class TestHandlers {
/**
* Create a handler that simply returns the {@link Message} it receives.
*/
public final static Object echoHandler() {
public static final Object echoHandler() {
return new Object() {
public Message<?> handle(Message<?> message) {
return message;
}
@@ -54,8 +57,9 @@ public abstract class TestHandlers {
/**
* Create a handler that increments the provided counter.
*/
public final static Object countingHandler(final AtomicInteger counter) {
public static final Object countingHandler(final AtomicInteger counter) {
return new Object() {
public Message<?> handle(Message<?> message) {
counter.incrementAndGet();
return null;
@@ -66,8 +70,9 @@ public abstract class TestHandlers {
/**
* Create a handler that counts down on the provided latch.
*/
public final static Object countDownHandler(final CountDownLatch latch) {
public static final Object countDownHandler(final CountDownLatch latch) {
return new Object() {
public Message<?> handle(Message<?> message) {
latch.countDown();
return null;
@@ -79,8 +84,9 @@ public abstract class TestHandlers {
* Create a handler that counts down on the provided latch
* and also increments the provided counter.
*/
public final static Object countingCountDownHandler(final AtomicInteger counter, final CountDownLatch latch) {
public static final Object countingCountDownHandler(final AtomicInteger counter, final CountDownLatch latch) {
return new Object() {
public Message<?> handle(Message<?> message) {
counter.incrementAndGet();
latch.countDown();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,12 +25,13 @@ import org.springframework.messaging.Message;
/**
* @author Ivan Krizsan
* @author Artem Bilan
*/
public class DefaultMessageChannelMetricsTests {
protected final static int MESSAGE_COUNT = 10;
protected static final int MESSAGE_COUNT = 10;
protected final static long SEND_TIMEOUT = 1;
protected static final long SEND_TIMEOUT = 1;
@Test
public void errorCountWithCountsEnabledOnlySuccessTest() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,6 @@ package org.springframework.integration.support.management;
import static org.hamcrest.Matchers.lessThan;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@@ -37,11 +36,12 @@ import org.springframework.util.StopWatch;
* @author Dave Syer
* @author Gary Russell
* @author Steven Swor
* @author Artem Bilan
*/
@Ignore("Very sensitive to the time. Don't forget to test after some changes.")
public class ExponentialMovingAverageRateTests {
private final static Log logger = LogFactory.getLog(ExponentialMovingAverageRateTests.class);
private static final Log logger = LogFactory.getLog(ExponentialMovingAverageRateTests.class);
private final ExponentialMovingAverageRate history = new ExponentialMovingAverageRate(1., 10., 10, true);
@@ -54,7 +54,7 @@ public class ExponentialMovingAverageRateTests {
@Test
@SuppressWarnings("unchecked")
public void testGetTimeSinceLastMeasurement() throws Exception {
public void testGetTimeSinceLastMeasurement() {
long sleepTime = 20L;
// fill history with the same value.
@@ -67,7 +67,7 @@ public class ExponentialMovingAverageRateTests {
assertEquals(Long.valueOf(now), times.peekLast());
//increment just so we'll have a different value between first and last
history.increment(System.nanoTime() - sleepTime * 1000000);
history.increment(System.nanoTime() - sleepTime * 1000000);
assertNotEquals(times.peekFirst(), times.peekLast());
/*
@@ -76,7 +76,7 @@ public class ExponentialMovingAverageRateTests {
* the queue, then we should be closer to the sleep time than we are to
* 2 x sleepTime, but we should definitely be greater than the sleep
* time.
*/
*/
double timeSinceLastMeasurement = history.getTimeSinceLastMeasurement();
assertTrue(timeSinceLastMeasurement > sleepTime);
assertTrue(timeSinceLastMeasurement <= (1.5 * sleepTime));
@@ -126,7 +126,6 @@ public class ExponentialMovingAverageRateTests {
}
@Test
@Ignore
public void testGetStandardDeviation() throws Exception {
assertEquals(0, history.getStandardDeviation(), 0.01);
Thread.sleep(20L);
@@ -138,13 +137,12 @@ public class ExponentialMovingAverageRateTests {
}
@Test
@Ignore
public void testReset() throws Exception {
assertEquals(0, history.getStandardDeviation(), 0.01);
history.increment();
Thread.sleep(30L);
history.increment();
assertFalse(0 == history.getStandardDeviation());
assertNotEquals(0, history.getStandardDeviation(), 0.0);
history.reset();
assertEquals(0, history.getStandardDeviation(), 0.01);
assertEquals(0, history.getCount());
@@ -155,7 +153,6 @@ public class ExponentialMovingAverageRateTests {
}
@Test
@Ignore // tolerance needed is too dependent on hardware
public void testRate() {
ExponentialMovingAverageRate rate = new ExponentialMovingAverageRate(1, 60, 10);
int count = 1000000;
@@ -170,7 +167,6 @@ public class ExponentialMovingAverageRateTests {
}
@Test
@Ignore
public void testPerf() {
ExponentialMovingAverageRate rate = new ExponentialMovingAverageRate(1, 60, 10);
for (int i = 0; i < 1000000; i++) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -63,7 +63,7 @@ import com.rometools.rome.io.SyndFeedInput;
public class FeedInboundChannelAdapterParserTests {
@ClassRule
public final static TemporaryFolder tempFolder = new TemporaryFolder();
public static final TemporaryFolder tempFolder = new TemporaryFolder();
private static CountDownLatch latch;
@@ -144,7 +144,7 @@ public class FeedInboundChannelAdapterParserTests {
public void receiveFeedEntry(Message<?> message) {
MessageHistory history = MessageHistory.read(message);
assertTrue(history.size() == 3);
assertEquals(3, history.size());
Properties historyItem = history.get(0);
assertEquals("feedAdapterUsage", historyItem.get("name"));
assertEquals("feed:inbound-channel-adapter", historyItem.get("type"));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016 the original author or authors.
* Copyright 2016-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,7 @@
package org.springframework.integration.feed.dsl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
@@ -56,7 +57,7 @@ import com.rometools.rome.feed.synd.SyndEntry;
public class FeedDslTests {
@ClassRule
public final static TemporaryFolder tempFolder = new TemporaryFolder();
public static final TemporaryFolder tempFolder = new TemporaryFolder();
@Autowired
private PollableChannel entries;
@@ -70,6 +71,9 @@ public class FeedDslTests {
Message<SyndEntry> message1 = (Message<SyndEntry>) this.entries.receive(10000);
Message<SyndEntry> message2 = (Message<SyndEntry>) this.entries.receive(10000);
Message<SyndEntry> message3 = (Message<SyndEntry>) this.entries.receive(10000);
assertThat(message1).isNotNull();
assertThat(message2).isNotNull();
assertThat(message3).isNotNull();
long time1 = message1.getPayload().getPublishedDate().getTime();
long time2 = message2.getPayload().getPublishedDate().getTime();
long time3 = message3.getPayload().getPublishedDate().getTime();

View File

@@ -37,6 +37,7 @@ import org.springframework.integration.file.filters.FileListFilter;
import org.springframework.integration.file.filters.ReversibleFileListFilter;
import org.springframework.integration.file.remote.session.Session;
import org.springframework.integration.file.support.FileUtils;
import org.springframework.lang.Nullable;
import org.springframework.messaging.MessagingException;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
@@ -56,7 +57,7 @@ public abstract class AbstractRemoteFileStreamingMessageSource<F>
private final RemoteFileTemplate<F> remoteFileTemplate;
private final BlockingQueue<AbstractFileInfo<F>> toBeReceived = new LinkedBlockingQueue<AbstractFileInfo<F>>();
private final BlockingQueue<AbstractFileInfo<F>> toBeReceived = new LinkedBlockingQueue<>();
private final Comparator<F> comparator;
@@ -65,24 +66,25 @@ public abstract class AbstractRemoteFileStreamingMessageSource<F>
/**
* the path on the remote server.
*/
private volatile Expression remoteDirectoryExpression;
private Expression remoteDirectoryExpression;
private volatile String remoteFileSeparator = "/";
private String remoteFileSeparator = "/";
/**
* An {@link FileListFilter} that runs against the <em>remote</em> file system view.
*/
private volatile FileListFilter<F> filter;
private FileListFilter<F> filter;
protected AbstractRemoteFileStreamingMessageSource(RemoteFileTemplate<F> template,
Comparator<F> comparator) {
@Nullable Comparator<F> comparator) {
Assert.notNull(template, "'template' must not be null");
this.remoteFileTemplate = template;
this.comparator = comparator;
}
/**
* Specify the full path to the remote directory.
*
* @param remoteDirectory The remote directory.
*/
public void setRemoteDirectory(String remoteDirectory) {
@@ -91,7 +93,6 @@ public abstract class AbstractRemoteFileStreamingMessageSource<F>
/**
* Specify an expression that evaluates to the full path to the remote directory.
*
* @param remoteDirectoryExpression The remote directory expression.
*/
public void setRemoteDirectoryExpression(Expression remoteDirectoryExpression) {
@@ -183,10 +184,9 @@ public abstract class AbstractRemoteFileStreamingMessageSource<F>
}
protected String remotePath(AbstractFileInfo<F> file) {
String remotePath = file.getRemoteDirectory().endsWith(this.remoteFileSeparator)
return file.getRemoteDirectory().endsWith(this.remoteFileSeparator)
? file.getRemoteDirectory() + file.getFilename()
: file.getRemoteDirectory() + this.remoteFileSeparator + file.getFilename();
return remotePath;
}
private void listFiles() {
@@ -219,8 +219,8 @@ public abstract class AbstractRemoteFileStreamingMessageSource<F>
}
}
abstract protected List<AbstractFileInfo<F>> asFileInfoList(Collection<F> files);
protected abstract List<AbstractFileInfo<F>> asFileInfoList(Collection<F> files);
abstract protected boolean isDirectory(F file);
protected abstract boolean isDirectory(F file);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,7 +27,6 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@@ -53,6 +52,7 @@ import org.springframework.integration.handler.AbstractReplyProducingMessageHand
import org.springframework.integration.handler.ExpressionEvaluatingMessageProcessor;
import org.springframework.integration.support.MutableMessage;
import org.springframework.integration.support.PartialSuccessException;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandlingException;
import org.springframework.messaging.MessagingException;
@@ -70,185 +70,42 @@ import org.springframework.util.StringUtils;
*/
public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReplyProducingMessageHandler {
protected final RemoteFileTemplate<F> remoteFileTemplate;
protected final Command command;
protected final RemoteFileTemplate<F> remoteFileTemplate; // NOSONAR
/**
* Enumeration of commands supported by the gateways.
*/
public enum Command {
protected final Command command; // NOSONAR
/**
* (ls) List remote files.
*/
LS("ls"),
/**
* (nlst) List remote file names.
*/
NLST("nlst"),
/**
* (get) Retrieve a remote file.
*/
GET("get"),
/**
* (rm) Remove a remote file (path - including wildcards).
*/
RM("rm"),
/**
* (mget) Retrieve multiple files matching a wildcard path.
*/
MGET("mget"),
/**
* (mv) Move (rename) a remote file.
*/
MV("mv"),
/**
* (put) Put a local file to the remote system.
*/
PUT("put"),
/**
* (mput) Put multiple local files to the remote system.
*/
MPUT("mput");
private String command;
Command(String command) {
this.command = command;
}
public String getCommand() {
return this.command;
}
public static Command toCommand(String cmd) {
for (Command command : values()) {
if (command.getCommand().equals(cmd)) {
return command;
}
}
throw new IllegalArgumentException("No Command with value '" + cmd + "'");
}
}
/**
* Enumeration of options supported by various commands.
*
*/
public enum Option {
/**
* (-1) Don't return full file information; just the name (ls).
*/
NAME_ONLY("-1"),
/**
* (-a) Include files beginning with {@code .}, including directories {@code .}
* and {@code ..} in the results (ls).
*/
ALL("-a"),
/**
* (-f) Do not sort the results (ls with NAME_ONLY).
*/
NOSORT("-f"),
/**
* (-dirs) Include directories in the results (ls).
*/
SUBDIRS("-dirs"),
/**
* (-links) Include links in the results (ls).
*/
LINKS("-links"),
/**
* (-P) Preserve the server timestamp (get, mget).
*/
PRESERVE_TIMESTAMP("-P"),
/**
* (-x) Throw an exception if no files returned (mget).
*/
EXCEPTION_WHEN_EMPTY("-x"),
/**
* (-R) Recursive (ls, mget)
*/
RECURSIVE("-R"),
/**
* (-stream) Streaming 'get' (returns InputStream); user must call {@link Session#close()}.
*/
STREAM("-stream"),
/**
* (-D) Delete the remote file after successful transfer (get, mget).
*/
DELETE("-D");
private String option;
Option(String option) {
this.option = option;
}
public String getOption() {
return this.option;
}
public static Option toOption(String opt) {
for (Option option : values()) {
if (option.getOption().equals(opt)) {
return option;
}
}
throw new IllegalArgumentException("No option with value '" + opt + "'");
}
}
protected final Set<Option> options = new HashSet<>();
private final ExpressionEvaluatingMessageProcessor<String> fileNameProcessor;
private final MessageSessionCallback<F, ?> messageSessionCallback;
protected final Set<Option> options = new HashSet<>();
private volatile ExpressionEvaluatingMessageProcessor<String> renameProcessor =
private ExpressionEvaluatingMessageProcessor<String> renameProcessor =
new ExpressionEvaluatingMessageProcessor<>(
new FunctionExpression<Message<?>>(m ->
m.getHeaders().get(FileHeaders.RENAME_TO)));
private volatile Expression localDirectoryExpression;
private Expression localDirectoryExpression;
private volatile boolean autoCreateLocalDirectory = true;
private boolean autoCreateLocalDirectory = true;
/**
* A {@link FileListFilter} that runs against the <em>remote</em> file system view.
*/
private volatile FileListFilter<F> filter;
private FileListFilter<F> filter;
/**
* A {@link FileListFilter} that runs against the <em>local</em> file system view when
* using MPUT.
*/
private volatile FileListFilter<File> mputFilter;
private FileListFilter<File> mputFilter;
private volatile Expression localFilenameGeneratorExpression;
private Expression localFilenameGeneratorExpression;
private volatile FileExistsMode fileExistsMode;
private FileExistsMode fileExistsMode;
private volatile Integer chmod;
private Integer chmod;
/**
* Construct an instance using the provided session factory and callback for
@@ -258,6 +115,7 @@ public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReply
*/
public AbstractRemoteFileOutboundGateway(SessionFactory<F> sessionFactory,
MessageSessionCallback<F, ?> messageSessionCallback) {
this(new RemoteFileTemplate<F>(sessionFactory), messageSessionCallback);
}
@@ -269,6 +127,7 @@ public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReply
*/
public AbstractRemoteFileOutboundGateway(RemoteFileTemplate<F> remoteFileTemplate,
MessageSessionCallback<F, ?> messageSessionCallback) {
Assert.notNull(remoteFileTemplate, "'remoteFileTemplate' cannot be null");
Assert.notNull(messageSessionCallback, "'messageSessionCallback' cannot be null");
this.remoteFileTemplate = remoteFileTemplate;
@@ -285,7 +144,8 @@ public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReply
* @param expression the filename expression.
*/
public AbstractRemoteFileOutboundGateway(SessionFactory<F> sessionFactory, String command,
String expression) {
@Nullable String expression) {
this(sessionFactory, Command.toCommand(command), expression);
}
@@ -296,7 +156,9 @@ public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReply
* @param command the command.
* @param expression the filename expression.
*/
public AbstractRemoteFileOutboundGateway(SessionFactory<F> sessionFactory, Command command, String expression) {
public AbstractRemoteFileOutboundGateway(SessionFactory<F> sessionFactory, Command command,
@Nullable String expression) {
this(new RemoteFileTemplate<F>(sessionFactory), command, expression);
}
@@ -308,7 +170,8 @@ public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReply
* @param expression the filename expression.
*/
public AbstractRemoteFileOutboundGateway(RemoteFileTemplate<F> remoteFileTemplate, String command,
String expression) {
@Nullable String expression) {
this(remoteFileTemplate, Command.toCommand(command), expression);
}
@@ -320,7 +183,8 @@ public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReply
* @param expression the filename expression.
*/
public AbstractRemoteFileOutboundGateway(RemoteFileTemplate<F> remoteFileTemplate, Command command,
String expression) {
@Nullable String expression) {
Assert.notNull(remoteFileTemplate, "'remoteFileTemplate' cannot be null");
this.remoteFileTemplate = remoteFileTemplate;
this.command = command;
@@ -913,7 +777,7 @@ public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReply
purgeDots(lsFiles);
}
if (this.options.contains(Option.NAME_ONLY)) {
List<String> results = new ArrayList<String>();
List<String> results = new ArrayList<>();
for (F file : lsFiles) {
results.add(getFilename(file));
}
@@ -934,7 +798,9 @@ public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReply
}
}
private List<F> listFilesInRemoteDir(Session<F> session, String directory, String subDirectory) throws IOException {
private List<F> listFilesInRemoteDir(Session<F> session, String directory, String subDirectory)
throws IOException {
List<F> lsFiles = new ArrayList<F>();
String remoteDirectory = buildRemotePath(directory, subDirectory);
@@ -986,21 +852,11 @@ public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReply
}
protected void purgeLinks(List<F> lsFiles) {
Iterator<F> iterator = lsFiles.iterator();
while (iterator.hasNext()) {
if (this.isLink(iterator.next())) {
iterator.remove();
}
}
lsFiles.removeIf(this::isLink);
}
protected void purgeDots(List<F> lsFiles) {
Iterator<F> iterator = lsFiles.iterator();
while (iterator.hasNext()) {
if (getFilename(iterator.next()).startsWith(".")) {
iterator.remove();
}
}
lsFiles.removeIf(f -> getFilename(f).startsWith("."));
}
/**
@@ -1119,9 +975,7 @@ public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReply
if (logger.isWarnEnabled() && !("*".equals(remoteFilename))) {
logger.warn("File name pattern must be '*' when using recursion");
}
if (this.options.contains(Option.NAME_ONLY)) {
this.options.remove(Option.NAME_ONLY);
}
this.options.remove(Option.NAME_ONLY);
return mGetWithRecursion(message, session, remoteDirectory, remoteFilename);
}
else {
@@ -1131,7 +985,8 @@ public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReply
private List<File> mGetWithoutRecursion(Message<?> message, Session<F> session, String remoteDirectory,
String remoteFilename) throws IOException {
List<File> files = new ArrayList<File>();
List<File> files = new ArrayList<>();
String remotePath = buildRemotePath(remoteDirectory, remoteFilename);
@SuppressWarnings("unchecked")
List<AbstractFileInfo<F>> remoteFiles = (List<AbstractFileInfo<F>>) ls(message, session, remotePath);
@@ -1179,7 +1034,7 @@ public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReply
private List<File> mGetWithRecursion(Message<?> message, Session<F> session, String remoteDirectory,
String remoteFilename) throws IOException {
List<File> files = new ArrayList<File>();
List<File> files = new ArrayList<>();
@SuppressWarnings("unchecked")
List<AbstractFileInfo<F>> fileNames = (List<AbstractFileInfo<F>>) ls(message, session, remoteDirectory);
if (fileNames.size() == 0 && this.options.contains(Option.EXCEPTION_WHEN_EMPTY)) {
@@ -1268,18 +1123,162 @@ public abstract class AbstractRemoteFileOutboundGateway<F> extends AbstractReply
return remoteFileName;
}
abstract protected boolean isDirectory(F file);
protected abstract boolean isDirectory(F file);
abstract protected boolean isLink(F file);
protected abstract boolean isLink(F file);
abstract protected String getFilename(F file);
protected abstract String getFilename(F file);
abstract protected String getFilename(AbstractFileInfo<F> file);
protected abstract String getFilename(AbstractFileInfo<F> file);
abstract protected long getModified(F file);
protected abstract long getModified(F file);
abstract protected List<AbstractFileInfo<F>> asFileInfoList(Collection<F> files);
protected abstract List<AbstractFileInfo<F>> asFileInfoList(Collection<F> files);
abstract protected F enhanceNameWithSubDirectory(F file, String directory);
protected abstract F enhanceNameWithSubDirectory(F file, String directory);
/**
* Enumeration of commands supported by the gateways.
*/
public enum Command {
/**
* (ls) List remote files.
*/
LS("ls"),
/**
* (nlst) List remote file names.
*/
NLST("nlst"),
/**
* (get) Retrieve a remote file.
*/
GET("get"),
/**
* (rm) Remove a remote file (path - including wildcards).
*/
RM("rm"),
/**
* (mget) Retrieve multiple files matching a wildcard path.
*/
MGET("mget"),
/**
* (mv) Move (rename) a remote file.
*/
MV("mv"),
/**
* (put) Put a local file to the remote system.
*/
PUT("put"),
/**
* (mput) Put multiple local files to the remote system.
*/
MPUT("mput");
private final String command;
Command(String command) {
this.command = command;
}
public String getCommand() {
return this.command;
}
public static Command toCommand(String cmd) {
for (Command command : values()) {
if (command.getCommand().equals(cmd)) {
return command;
}
}
throw new IllegalArgumentException("No Command with value '" + cmd + "'");
}
}
/**
* Enumeration of options supported by various commands.
*
*/
public enum Option {
/**
* (-1) Don't return full file information; just the name (ls).
*/
NAME_ONLY("-1"),
/**
* (-a) Include files beginning with {@code .}, including directories {@code .}
* and {@code ..} in the results (ls).
*/
ALL("-a"),
/**
* (-f) Do not sort the results (ls with NAME_ONLY).
*/
NOSORT("-f"),
/**
* (-dirs) Include directories in the results (ls).
*/
SUBDIRS("-dirs"),
/**
* (-links) Include links in the results (ls).
*/
LINKS("-links"),
/**
* (-P) Preserve the server timestamp (get, mget).
*/
PRESERVE_TIMESTAMP("-P"),
/**
* (-x) Throw an exception if no files returned (mget).
*/
EXCEPTION_WHEN_EMPTY("-x"),
/**
* (-R) Recursive (ls, mget)
*/
RECURSIVE("-R"),
/**
* (-stream) Streaming 'get' (returns InputStream); user must call {@link Session#close()}.
*/
STREAM("-stream"),
/**
* (-D) Delete the remote file after successful transfer (get, mget).
*/
DELETE("-D");
private final String option;
Option(String option) {
this.option = option;
}
public String getOption() {
return this.option;
}
public static Option toOption(String opt) {
for (Option option : values()) {
if (option.getOption().equals(opt)) {
return option;
}
}
throw new IllegalArgumentException("No option with value '" + opt + "'");
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,7 @@
package org.springframework.integration.file.config;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertEquals;
@@ -120,7 +121,7 @@ public class FileOutboundChannelAdapterParserTests {
@Autowired
MessageFlushPredicate predicate;
private volatile static int adviceCalled;
private static volatile int adviceCalled;
@Test
public void simpleAdapter() {
@@ -237,10 +238,10 @@ public class FileOutboundChannelAdapterParserTests {
if (testFile.exists()) {
testFile.delete();
}
usageChannel.send(new GenericMessage<String>("Initial File Content:"));
usageChannel.send(new GenericMessage<String>("String content:"));
usageChannel.send(new GenericMessage<byte[]>("byte[] content:".getBytes()));
usageChannel.send(new GenericMessage<File>(new File("test/input.txt")));
usageChannel.send(new GenericMessage<>("Initial File Content:"));
usageChannel.send(new GenericMessage<>("String content:"));
usageChannel.send(new GenericMessage<>("byte[] content:".getBytes()));
usageChannel.send(new GenericMessage<>(new File("test/input.txt")));
String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile));
assertEquals(expectedFileContent, actualFileContent);
@@ -259,10 +260,10 @@ public class FileOutboundChannelAdapterParserTests {
if (testFile.exists()) {
testFile.delete();
}
adapterUsageWithAppendAndAppendNewLineTrue.send(new GenericMessage<String>("Initial File Content:"));
adapterUsageWithAppendAndAppendNewLineTrue.send(new GenericMessage<String>("String content:"));
adapterUsageWithAppendAndAppendNewLineTrue.send(new GenericMessage<byte[]>("byte[] content:".getBytes()));
adapterUsageWithAppendAndAppendNewLineTrue.send(new GenericMessage<File>(new File("test/input.txt")));
adapterUsageWithAppendAndAppendNewLineTrue.send(new GenericMessage<>("Initial File Content:"));
adapterUsageWithAppendAndAppendNewLineTrue.send(new GenericMessage<>("String content:"));
adapterUsageWithAppendAndAppendNewLineTrue.send(new GenericMessage<>("byte[] content:".getBytes()));
adapterUsageWithAppendAndAppendNewLineTrue.send(new GenericMessage<>(new File("test/input.txt")));
String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile));
assertEquals(expectedFileContent, actualFileContent);
@@ -277,10 +278,10 @@ public class FileOutboundChannelAdapterParserTests {
if (testFile.exists()) {
testFile.delete();
}
adapterUsageWithAppendAndAppendNewLineFalse.send(new GenericMessage<String>("Initial File Content:"));
adapterUsageWithAppendAndAppendNewLineFalse.send(new GenericMessage<String>("String content:"));
adapterUsageWithAppendAndAppendNewLineFalse.send(new GenericMessage<byte[]>("byte[] content:".getBytes()));
adapterUsageWithAppendAndAppendNewLineFalse.send(new GenericMessage<File>(new File("test/input.txt")));
adapterUsageWithAppendAndAppendNewLineFalse.send(new GenericMessage<>("Initial File Content:"));
adapterUsageWithAppendAndAppendNewLineFalse.send(new GenericMessage<>("String content:"));
adapterUsageWithAppendAndAppendNewLineFalse.send(new GenericMessage<>("byte[] content:".getBytes()));
adapterUsageWithAppendAndAppendNewLineFalse.send(new GenericMessage<>(new File("test/input.txt")));
String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile));
assertEquals(expectedFileContent, actualFileContent);
@@ -288,20 +289,20 @@ public class FileOutboundChannelAdapterParserTests {
}
@Test
public void adapterUsageWithFailMode() throws Exception {
public void adapterUsageWithFailMode() {
File testFile = new File("test/fileToFail.txt");
if (testFile.exists()) {
testFile.delete();
}
usageChannelWithFailMode.send(new GenericMessage<String>("Initial File Content:"));
usageChannelWithFailMode.send(new GenericMessage<>("Initial File Content:"));
try {
usageChannelWithFailMode.send(new GenericMessage<String>("String content:"));
usageChannelWithFailMode.send(new GenericMessage<>("String content:"));
}
catch (MessagingException e) {
assertTrue(e.getMessage().contains("The destination file already exists at"));
assertThat(e.getMessage(), containsString("The destination file already exists at"));
testFile.delete();
return;
}
@@ -320,8 +321,8 @@ public class FileOutboundChannelAdapterParserTests {
testFile.delete();
}
usageChannelWithIgnoreMode.send(new GenericMessage<String>("Initial File Content:"));
usageChannelWithIgnoreMode.send(new GenericMessage<String>("String content:"));
usageChannelWithIgnoreMode.send(new GenericMessage<>("Initial File Content:"));
usageChannelWithIgnoreMode.send(new GenericMessage<>("String content:"));
String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile));
assertEquals(expectedFileContent, actualFileContent);
@@ -347,8 +348,8 @@ public class FileOutboundChannelAdapterParserTests {
String bString = bBuffer.toString();
for (int i = 0; i < 1; i++) {
usageChannelConcurrent.send(new GenericMessage<String>(aString));
usageChannelConcurrent.send(new GenericMessage<String>(bString));
usageChannelConcurrent.send(new GenericMessage<>(aString));
usageChannelConcurrent.send(new GenericMessage<>(bString));
}
assertTrue(this.fileWriteLatch.await(10, TimeUnit.SECONDS));

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,9 +16,11 @@
package org.springframework.integration.file.config;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -84,11 +86,10 @@ public class FileOutboundGatewayParserTests {
@Autowired
EventDrivenConsumer gatewayWithAppendNewLine;
private volatile static int adviceCalled;
private static volatile int adviceCalled;
@Test
public void checkOrderedGateway() throws Exception {
public void checkOrderedGateway() {
DirectFieldAccessor gatewayAccessor = new DirectFieldAccessor(ordered);
FileWritingMessageHandler handler = (FileWritingMessageHandler)
gatewayAccessor.getPropertyValue("handler");
@@ -109,13 +110,13 @@ public class FileOutboundGatewayParserTests {
}
@Test
public void testOutboundGatewayWithDirectoryExpression() throws Exception {
public void testOutboundGatewayWithDirectoryExpression() {
FileWritingMessageHandler handler =
TestUtils.getPropertyValue(gatewayWithDirectoryExpression, "handler", FileWritingMessageHandler.class);
assertEquals("'build/foo'",
TestUtils.getPropertyValue(handler, "destinationDirectoryExpression", Expression.class)
.getExpressionString());
handler.handleMessage(new GenericMessage<String>("foo"));
handler.handleMessage(new GenericMessage<>("foo"));
assertEquals(1, adviceCalled);
}
@@ -130,7 +131,6 @@ public class FileOutboundGatewayParserTests {
*/
@Test
public void gatewayWithIgnoreMode() throws Exception {
final MessagingTemplate messagingTemplate = new MessagingTemplate();
messagingTemplate.setDefaultDestination(this.gatewayWithIgnoreModeChannel);
@@ -141,9 +141,9 @@ public class FileOutboundGatewayParserTests {
testFile.delete();
}
messagingTemplate.sendAndReceive(new GenericMessage<String>("Initial File Content:"));
messagingTemplate.sendAndReceive(new GenericMessage<>("Initial File Content:"));
Message<?> replyMessage = messagingTemplate.sendAndReceive(new GenericMessage<String>("String content:"));
Message<?> replyMessage = messagingTemplate.sendAndReceive(new GenericMessage<>("String content:"));
String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile));
assertEquals(expectedFileContent, actualFileContent);
@@ -166,7 +166,6 @@ public class FileOutboundGatewayParserTests {
*/
@Test
public void gatewayWithFailMode() throws Exception {
final MessagingTemplate messagingTemplate = new MessagingTemplate();
messagingTemplate.setDefaultDestination(this.gatewayWithFailModeChannel);
@@ -178,18 +177,18 @@ public class FileOutboundGatewayParserTests {
testFile.delete();
}
messagingTemplate.sendAndReceive(new GenericMessage<String>("Initial File Content:"));
messagingTemplate.sendAndReceive(new GenericMessage<>("Initial File Content:"));
final String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile));
assertEquals(expectedFileContent, actualFileContent);
try {
messagingTemplate.sendAndReceive(new GenericMessage<String>("String content:"));
messagingTemplate.sendAndReceive(new GenericMessage<>("String content:"));
}
catch (MessageHandlingException e) {
assertTrue(e.getMessage().startsWith("The destination file already exists at '"));
assertThat(e.getMessage(), startsWith("The destination file already exists at '"));
return;
}
@@ -219,18 +218,18 @@ public class FileOutboundGatewayParserTests {
testFile.delete();
}
messagingTemplate.sendAndReceive(new GenericMessage<String>("Initial File Content:"));
messagingTemplate.sendAndReceive(new GenericMessage<>("Initial File Content:"));
final String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile));
assertEquals(expectedFileContent, actualFileContent);
try {
messagingTemplate.sendAndReceive(new GenericMessage<String>("String content:"));
messagingTemplate.sendAndReceive(new GenericMessage<>("String content:"));
}
catch (MessageHandlingException e) {
assertTrue(e.getMessage().startsWith("The destination file already exists at '"));
assertThat(e.getMessage(), startsWith("The destination file already exists at '"));
return;
}
@@ -262,8 +261,8 @@ public class FileOutboundGatewayParserTests {
testFile.delete();
}
messagingTemplate.sendAndReceive(new GenericMessage<String>("Initial File Content:"));
Message<?> m = messagingTemplate.sendAndReceive(new GenericMessage<String>("String content:"));
messagingTemplate.sendAndReceive(new GenericMessage<>("Initial File Content:"));
Message<?> m = messagingTemplate.sendAndReceive(new GenericMessage<>("String content:"));
String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile));
assertEquals(expectedFileContent, actualFileContent);
@@ -301,8 +300,8 @@ public class FileOutboundGatewayParserTests {
testFile.delete();
}
messagingTemplate.sendAndReceive(new GenericMessage<String>("Initial File Content:"));
Message<?> m = messagingTemplate.sendAndReceive(new GenericMessage<String>("String content:"));
messagingTemplate.sendAndReceive(new GenericMessage<>("Initial File Content:"));
Message<?> m = messagingTemplate.sendAndReceive(new GenericMessage<>("String content:"));
String actualFileContent = new String(FileCopyUtils.copyToByteArray(testFile));
assertEquals(expectedFileContent, actualFileContent);
@@ -327,7 +326,7 @@ public class FileOutboundGatewayParserTests {
public static class FooAdvice extends AbstractRequestHandlerAdvice {
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
adviceCalled++;
return null;
}

View File

@@ -34,7 +34,7 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping(IntegrationGraphController.REQUEST_MAPPING_PATH_VARIABLE)
public class IntegrationGraphController {
final static String REQUEST_MAPPING_PATH_VARIABLE =
static final String REQUEST_MAPPING_PATH_VARIABLE =
"${" + HttpContextUtils.GRAPH_CONTROLLER_PATH_PROPERTY + ":" +
HttpContextUtils.GRAPH_CONTROLLER_DEFAULT_PATH + "}";

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 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,12 +21,16 @@ import java.io.PushbackInputStream;
import java.nio.channels.SocketChannel;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.lang.Nullable;
/**
* Implementation of {@link TcpNioConnectionSupport} for non-SSL
* NIO connections.
*
* @author Gary Russell
* @author Artem Bilan
*
* @since 2.2
*
*/
@@ -56,8 +60,9 @@ public class DefaultTcpNioConnectionSupport extends AbstractTcpConnectionSupport
private volatile InputStream wrapped;
PushBackTcpNioConnection(SocketChannel socketChannel, boolean server, boolean lookupHost,
ApplicationEventPublisher applicationEventPublisher, String connectionFactoryName,
ApplicationEventPublisher applicationEventPublisher, @Nullable String connectionFactoryName,
int bufferSize) throws Exception {
super(socketChannel, server, lookupHost, applicationEventPublisher, connectionFactoryName);
this.pushbackBufferSize = bufferSize;
this.connectionId = "pushback:" + super.getConnectionId();

View File

@@ -45,6 +45,8 @@ import org.springframework.util.Assert;
* (incoming).
*
* @author Gary Russell
* @author Artem Bilan
*
* @since 2.0
*
*/
@@ -114,7 +116,8 @@ public abstract class TcpConnectionSupport implements TcpConnection {
*/
public TcpConnectionSupport(Socket socket, boolean server, boolean lookupHost,
ApplicationEventPublisher applicationEventPublisher,
String connectionFactoryName) {
@Nullable String connectionFactoryName) {
this.socketInfo = new SocketInfo(socket);
this.server = server;
InetAddress inetAddress = socket.getInetAddress();

View File

@@ -67,9 +67,13 @@ public class TcpNioConnection extends TcpConnectionSupport {
private final ChannelInputStream channelInputStream = new ChannelInputStream();
private volatile OutputStream bufferedOutputStream;
private final AtomicInteger executionControl = new AtomicInteger();
private volatile boolean usingDirectBuffers;
private boolean usingDirectBuffers;
private long pipeTimeout = DEFAULT_PIPE_TIMEOUT;
private volatile OutputStream bufferedOutputStream;
private volatile CompositeExecutor taskExecutor;
@@ -81,14 +85,10 @@ public class TcpNioConnection extends TcpConnectionSupport {
private volatile long lastSend;
private final AtomicInteger executionControl = new AtomicInteger();
private volatile boolean writingToPipe;
private volatile CountDownLatch writingLatch;
private volatile long pipeTimeout = DEFAULT_PIPE_TIMEOUT;
private volatile boolean timedOut;
/**
@@ -99,17 +99,13 @@ public class TcpNioConnection extends TcpConnectionSupport {
* @param lookupHost true to perform reverse lookups.
* @param applicationEventPublisher The event publisher.
* @param connectionFactoryName The name of the connection factory creating this connection.
* @throws Exception Any Exception.
*/
public TcpNioConnection(SocketChannel socketChannel, boolean server, boolean lookupHost,
ApplicationEventPublisher applicationEventPublisher,
String connectionFactoryName) throws Exception {
@Nullable String connectionFactoryName) {
super(socketChannel.socket(), server, lookupHost, applicationEventPublisher, connectionFactoryName);
this.socketChannel = socketChannel;
int receiveBufferSize = socketChannel.socket().getReceiveBufferSize();
if (receiveBufferSize <= 0) {
receiveBufferSize = this.maxMessageSize;
}
this.channelOutputStream = new ChannelOutputStream();
}
@@ -735,9 +731,8 @@ public class TcpNioConnection extends TcpConnectionSupport {
/**
* Blocks if the blocking queue already contains 5 buffers.
* @param array
* @param bytesToWrite
* @throws IOException
* @param byteBuffer to write
* @throws IOException writing to the buffer exception
*/
public void write(ByteBuffer byteBuffer) throws IOException {
int bytesToWrite = byteBuffer.limit() - byteBuffer.position();
@@ -774,7 +769,7 @@ public class TcpNioConnection extends TcpConnectionSupport {
}
@Override
public int available() throws IOException {
public int available() {
return this.available.get();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,6 +31,7 @@ import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.lang.Nullable;
import org.springframework.messaging.MessagingException;
import org.springframework.util.Assert;
@@ -48,7 +49,10 @@ import org.springframework.util.Assert;
* Also, it may be deemed necessary to re-perform handshaking.<p>
* This class supports the management of handshaking as necessary, both from the
* initiating and receiving peers.
*
* @author Gary Russell
* @author Artem Bilan
*
* @since 2.2
*
*/
@@ -77,8 +81,9 @@ public class TcpNioSSLConnection extends TcpNioConnection {
private SSLHandshakeException sslFatal;
public TcpNioSSLConnection(SocketChannel socketChannel, boolean server, boolean lookupHost,
ApplicationEventPublisher applicationEventPublisher, String connectionFactoryName,
ApplicationEventPublisher applicationEventPublisher, @Nullable String connectionFactoryName,
SSLEngine sslEngine) throws Exception {
super(socketChannel, server, lookupHost, applicationEventPublisher, connectionFactoryName);
this.sslEngine = sslEngine;
}

View File

@@ -105,7 +105,7 @@ import org.springframework.util.StopWatch;
*/
public class TcpNioConnectionTests {
private final static Log logger = LogFactory.getLog(TcpNioConnectionTests.class);
private static final Log logger = LogFactory.getLog(TcpNioConnectionTests.class);
@Rule
public Log4j2LevelAdjuster adjuster =
@@ -268,7 +268,7 @@ public class TcpNioConnectionTests {
connections.put(chan1, conn1);
connections.put(chan2, conn2);
connections.put(chan3, conn3);
final List<Field> fields = new ArrayList<Field>();
final List<Field> fields = new ArrayList<>();
ReflectionUtils.doWithFields(SocketChannel.class, field -> {
field.setAccessible(true);
fields.add(field);
@@ -279,7 +279,7 @@ public class TcpNioConnectionTests {
ReflectionUtils.setField(field, chan2, true);
ReflectionUtils.setField(field, chan3, true);
Selector selector = mock(Selector.class);
HashSet<SelectionKey> keys = new HashSet<SelectionKey>();
HashSet<SelectionKey> keys = new HashSet<>();
when(selector.selectedKeys()).thenReturn(keys);
factory.processNioSelections(1, selector, null, connections);
assertEquals(3, connections.size()); // all open

View File

@@ -17,13 +17,9 @@
package org.springframework.integration.jdbc;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionException;
import org.springframework.expression.ExpressionParser;
@@ -31,6 +27,7 @@ import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.integration.util.AbstractExpressionEvaluator;
import org.springframework.jdbc.core.namedparam.AbstractSqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.util.Assert;
/**
* An implementation of {@link SqlParameterSourceFactory} which creates
@@ -48,15 +45,13 @@ import org.springframework.jdbc.core.namedparam.SqlParameterSource;
public class ExpressionEvaluatingSqlParameterSourceFactory extends AbstractExpressionEvaluator
implements SqlParameterSourceFactory {
private final static Log logger = LogFactory.getLog(ExpressionEvaluatingSqlParameterSourceFactory.class);
private static final ExpressionParser PARSER = new SpelExpressionParser();
private static final Object ERROR = new Object();
private volatile Map<String, ?> staticParameters;
private final Map<String, Object> staticParameters = new HashMap<>();
private volatile Map<String, Integer> sqlParametersTypes;
private final Map<String, Integer> sqlParametersTypes = new HashMap<>();
/**
* The {@link Map} of parameters with expressions.
@@ -64,11 +59,9 @@ public class ExpressionEvaluatingSqlParameterSourceFactory extends AbstractExpre
* first element - direct {@link Expression}, second - collection projection {@link Expression}.
* Used in case of root object of evaluation is {@link Collection}.
*/
private volatile Map<String, Expression[]> parameterExpressions;
private final Map<String, Expression[]> parameterExpressions = new HashMap<>();
public ExpressionEvaluatingSqlParameterSourceFactory() {
this.staticParameters = Collections.unmodifiableMap(new HashMap<String, Object>());
this.parameterExpressions = new HashMap<>();
}
/**
@@ -77,16 +70,19 @@ public class ExpressionEvaluatingSqlParameterSourceFactory extends AbstractExpre
* first, and then from the expressions.
* @param staticParameters the static parameters to set
*/
public void setStaticParameters(Map<String, ?> staticParameters) {
this.staticParameters = staticParameters;
public void setStaticParameters(Map<String, Object> staticParameters) {
Assert.notNull(staticParameters, "'staticParameters' must not be null");
this.staticParameters.putAll(staticParameters);
}
/**
* Optionally maps parameter names to explicit expressions. The named parameter support in Spring is limited to
* simple parameter names with no special characters, so this feature allows you to specify a simple name in the SQL
* simple parameter names with no special characters, so this feature allows you to specify a simple name in the
* SQL
* query and then have it translated into an expression at runtime. The target of the expression depends on the
* context: generally in an outbound setting it is a Message, and in an inbound setting it is a result set row (a
* Map or a domain object if a RowMapper has been provided). The {@link #setStaticParameters(Map) static parameters}
* Map or a domain object if a RowMapper has been provided). The {@link #setStaticParameters(Map) static
* parameters}
* can be referred to in an expression using the variable <code>#staticParameters</code>, for example:
* <p>&nbsp;
* <table>
@@ -115,6 +111,7 @@ public class ExpressionEvaluatingSqlParameterSourceFactory extends AbstractExpre
* @param parameterExpressions the parameter expressions to set
*/
public void setParameterExpressions(Map<String, String> parameterExpressions) {
Assert.notNull(parameterExpressions, "'parameterExpressions' must not be null");
Map<String, Expression[]> paramExpressions = new HashMap<>(parameterExpressions.size());
for (Map.Entry<String, String> entry : parameterExpressions.entrySet()) {
String key = entry.getKey();
@@ -125,7 +122,7 @@ public class ExpressionEvaluatingSqlParameterSourceFactory extends AbstractExpre
};
paramExpressions.put(key, expressions);
}
this.parameterExpressions = paramExpressions;
this.parameterExpressions.putAll(paramExpressions);
}
/**
@@ -136,7 +133,8 @@ public class ExpressionEvaluatingSqlParameterSourceFactory extends AbstractExpre
* @see java.sql.Types
*/
public void setSqlParameterTypes(Map<String, Integer> sqlParametersTypes) {
this.sqlParametersTypes = sqlParametersTypes;
Assert.notNull(sqlParametersTypes, "'sqlParametersTypes' must not be null");
this.sqlParametersTypes.putAll(sqlParametersTypes);
}
@Override
@@ -166,7 +164,7 @@ public class ExpressionEvaluatingSqlParameterSourceFactory extends AbstractExpre
private final Object input;
private final Map<String, Object> values = new HashMap<String, Object>();
private final Map<String, Object> values = new HashMap<>();
private final Map<String, Expression[]> parameterExpressions;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,10 +28,11 @@ import org.springframework.integration.mapping.HeaderMapper;
* @author Mark Fisher
* @author Oleg Zhurakousky
* @author Gary Russell
* @author Artem Bilan
*/
public abstract class JmsHeaderMapper implements HeaderMapper<Message> {
protected final static String CONTENT_TYPE_PROPERTY = "content_type";
protected static final String CONTENT_TYPE_PROPERTY = "content_type";
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2015 the original author or authors.
* Copyright 2002-2018 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.
@@ -33,21 +33,23 @@ import org.springframework.util.StringUtils;
* @author Mark Fisher
* @author Oleg Zhurakusky
* @author Gary Russell
* @author Artem Bilan
*
* @since 2.0
*/
public class JmsChannelParser extends AbstractChannelParser {
private final static String CONTAINER_TYPE_ATTRIBUTE = "container-type";
private static final String CONTAINER_TYPE_ATTRIBUTE = "container-type";
private final static String CONTAINER_CLASS_ATTRIBUTE = "container-class";
private static final String CONTAINER_CLASS_ATTRIBUTE = "container-class";
private final static String ACKNOWLEDGE_ATTRIBUTE = "acknowledge";
private static final String ACKNOWLEDGE_ATTRIBUTE = "acknowledge";
@Override
protected BeanDefinitionBuilder buildBeanDefinition(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(
JmsChannelFactoryBean.class);
BeanDefinitionBuilder builder =
BeanDefinitionBuilder.genericBeanDefinition(JmsChannelFactoryBean.class);
String messageDriven = element.getAttribute("message-driven");
if (StringUtils.hasText(messageDriven)) {
builder.addConstructorArgValue(messageDriven);
@@ -129,13 +131,15 @@ public class JmsChannelParser extends AbstractChannelParser {
return builder;
}
private void parseDestination(Element element, ParserContext parserContext, BeanDefinitionBuilder builder, String type) {
private void parseDestination(Element element, ParserContext parserContext, BeanDefinitionBuilder builder,
String type) {
boolean isPubSub = "topic".equals(type);
String ref = element.getAttribute(type);
String name = element.getAttribute(type + "-name");
boolean isReference = StringUtils.hasText(ref);
boolean isName = StringUtils.hasText(name);
if (!(isReference ^ isName)) {
if (isReference == isName) {
parserContext.getReaderContext().error("Exactly one of the '" + type +
"' or '" + type + "-name' attributes is required.", element);
}
@@ -152,7 +156,8 @@ public class JmsChannelParser extends AbstractChannelParser {
}
if (isPubSub) {
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "durable", "subscriptionDurable");
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "subscription", "durableSubscriptionName");
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "subscription",
"durableSubscriptionName");
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "subscription-shared");
IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "client-id");
}
@@ -181,4 +186,5 @@ public class JmsChannelParser extends AbstractChannelParser {
return null;
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 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.
@@ -44,20 +44,19 @@ import org.springframework.util.Assert;
*/
public class ExpressionEvaluatingParameterSourceFactory implements ParameterSourceFactory {
private final static Log logger = LogFactory.getLog(ExpressionEvaluatingParameterSourceFactory.class);
private static final Log logger = LogFactory.getLog(ExpressionEvaluatingParameterSourceFactory.class);
private static final Object ERROR = new Object();
private volatile List<JpaParameter> parameters;
private final ParameterExpressionEvaluator expressionEvaluator = new ParameterExpressionEvaluator();
private final List<JpaParameter> parameters = new ArrayList<>();
public ExpressionEvaluatingParameterSourceFactory() {
this(null);
}
public ExpressionEvaluatingParameterSourceFactory(@Nullable BeanFactory beanFactory) {
this.parameters = new ArrayList<>();
this.expressionEvaluator.setBeanFactory(beanFactory);
}
@@ -66,14 +65,13 @@ public class ExpressionEvaluatingParameterSourceFactory implements ParameterSour
* @param parameters the parameters to be set
*/
public void setParameters(List<JpaParameter> parameters) {
Assert.notEmpty(parameters, "parameters must not be null or empty.");
for (JpaParameter parameter : parameters) {
Assert.notNull(parameter, "The provided list (parameters) cannot contain null values.");
}
this.parameters = parameters;
this.parameters.addAll(parameters);
this.expressionEvaluator.getEvaluationContext().setVariable("staticParameters",
ExpressionEvaluatingParameterSourceUtils.convertStaticParameters(parameters));
@@ -89,7 +87,7 @@ public class ExpressionEvaluatingParameterSourceFactory implements ParameterSour
private final Object input;
private volatile Map<String, Object> values = new HashMap<>();
private final Map<String, Object> values = new HashMap<>();
private final List<JpaParameter> parameters;

View File

@@ -38,9 +38,6 @@ import javax.mail.Store;
import javax.mail.URLName;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.support.StandardEvaluationContext;
@@ -68,9 +65,7 @@ public abstract class AbstractMailReceiver extends IntegrationObjectSupport impl
* Default user flag for marking messages as seen by this receiver:
* {@value #DEFAULT_SI_USER_FLAG}.
*/
public final static String DEFAULT_SI_USER_FLAG = "spring-integration-mail-adapter";
protected final Log logger = LogFactory.getLog(getClass()); // NOSONAR safe to use final
public static final String DEFAULT_SI_USER_FLAG = "spring-integration-mail-adapter";
private final URLName url;
@@ -500,8 +495,8 @@ public abstract class AbstractMailReceiver extends IntegrationObjectSupport impl
*/
private MimeMessage[] filterMessagesThruSelector(Message[] messages) throws MessagingException {
List<MimeMessage> filteredMessages = new LinkedList<>();
for (int i = 0; i < messages.length; i++) {
MimeMessage message = (MimeMessage) messages[i];
for (Message message1 : messages) {
MimeMessage message = (MimeMessage) message1;
if (this.selectorExpression != null) {
if (Boolean.TRUE.equals(
this.selectorExpression.getValue(this.evaluationContext, message, Boolean.class))) {
@@ -544,8 +539,8 @@ public abstract class AbstractMailReceiver extends IntegrationObjectSupport impl
* @throws MessagingException in case of JavaMail errors
*/
protected void deleteMessages(Message[] messages) throws MessagingException {
for (int i = 0; i < messages.length; i++) {
messages[i].setFlag(Flags.Flag.DELETED, true);
for (Message message : messages) {
message.setFlag(Flags.Flag.DELETED, true);
}
}

View File

@@ -112,13 +112,13 @@ import com.sun.mail.imap.IMAPFolder;
@DirtiesContext
public class ImapMailReceiverTests {
private static final ImapServer imapIdleServer = TestMailServer.imap(0);
@Rule
public final LongRunningIntegrationTest longRunningIntegrationTest = new LongRunningIntegrationTest();
private final AtomicInteger failed = new AtomicInteger(0);
private final static ImapServer imapIdleServer = TestMailServer.imap(0);
@Autowired
private ApplicationContext context;

View File

@@ -79,13 +79,13 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@DirtiesContext
public class MailTests {
private final static SmtpServer smtpServer = TestMailServer.smtp(0);
private static final SmtpServer smtpServer = TestMailServer.smtp(0);
private final static Pop3Server pop3Server = TestMailServer.pop3(0);
private static final Pop3Server pop3Server = TestMailServer.pop3(0);
private final static ImapServer imapServer = TestMailServer.imap(0);
private static final ImapServer imapServer = TestMailServer.imap(0);
private final static ImapServer imapIdleServer = TestMailServer.imap(0);
private static final ImapServer imapIdleServer = TestMailServer.imap(0);
@BeforeClass
@@ -173,7 +173,7 @@ public class MailTests {
}
@Test
public void testImapIdle() throws Exception {
public void testImapIdle() {
Message<?> message = this.imapIdleChannel.receive(10000);
assertNotNull(message);
MessageHeaders headers = message.getHeaders();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2018 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.
@@ -61,13 +61,14 @@ import org.springframework.util.Assert;
* for implementations of this class.
*
* @author Artem Bilan
*
* @since 4.0
*/
public abstract class AbstractConfigurableMongoDbMessageStore extends AbstractMessageGroupStore
implements BasicMessageGroupStore, InitializingBean, ApplicationContextAware {
public final static String SEQUENCE_NAME = "messagesSequence";
public static final String SEQUENCE_NAME = "messagesSequence";
/**
* The name of the message header that stores a flag to indicate that the message has been saved. This is an

View File

@@ -55,7 +55,7 @@ import org.springframework.util.Assert;
public class ConfigurableMongoDbMessageStore extends AbstractConfigurableMongoDbMessageStore
implements MessageStore {
public final static String DEFAULT_COLLECTION_NAME = "configurableStoreMessages";
public static final String DEFAULT_COLLECTION_NAME = "configurableStoreMessages";
public ConfigurableMongoDbMessageStore(MongoTemplate mongoTemplate) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2018 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.
@@ -43,14 +43,15 @@ import org.springframework.util.Assert;
* {@code priorityEnabled = true} option.
*
* @author Artem Bilan
*
* @since 4.0
*/
public class MongoDbChannelMessageStore extends AbstractConfigurableMongoDbMessageStore
implements PriorityCapableChannelMessageStore {
public final static String DEFAULT_COLLECTION_NAME = "channelMessages";
public static final String DEFAULT_COLLECTION_NAME = "channelMessages";
private volatile boolean priorityEnabled;
private boolean priorityEnabled;
public MongoDbChannelMessageStore(MongoTemplate mongoTemplate) {
this(mongoTemplate, DEFAULT_COLLECTION_NAME);

View File

@@ -100,9 +100,9 @@ import com.mongodb.DBObject;
public class MongoDbMessageStore extends AbstractMessageGroupStore
implements MessageStore, BeanClassLoaderAware, ApplicationContextAware, InitializingBean {
private final static String DEFAULT_COLLECTION_NAME = "messages";
public static final String SEQUENCE_NAME = "messagesSequence";
public final static String SEQUENCE_NAME = "messagesSequence";
private static final String DEFAULT_COLLECTION_NAME = "messages";
/**
* The name of the message header that stores a flag to indicate that the message has been saved. This is an
@@ -119,17 +119,17 @@ public class MongoDbMessageStore extends AbstractMessageGroupStore
@Deprecated
public static final String CREATED_DATE_KEY = ConfigurableMongoDbMessageStore.class.getSimpleName() + ".CREATED_DATE";
private final static String GROUP_ID_KEY = "_groupId";
private static final String GROUP_ID_KEY = "_groupId";
private final static String GROUP_COMPLETE_KEY = "_group_complete";
private static final String GROUP_COMPLETE_KEY = "_group_complete";
private final static String LAST_RELEASED_SEQUENCE_NUMBER = "_last_released_sequence";
private static final String LAST_RELEASED_SEQUENCE_NUMBER = "_last_released_sequence";
private final static String GROUP_TIMESTAMP_KEY = "_group_timestamp";
private static final String GROUP_TIMESTAMP_KEY = "_group_timestamp";
private final static String GROUP_UPDATE_TIMESTAMP_KEY = "_group_update_timestamp";
private static final String GROUP_UPDATE_TIMESTAMP_KEY = "_group_update_timestamp";
private final static String CREATED_DATE = "_createdDate";
private static final String CREATED_DATE = "_createdDate";
private static final String SEQUENCE = "sequence";
@@ -595,7 +595,7 @@ public class MongoDbMessageStore extends AbstractMessageGroupStore
}
private Map<String, Object> normalizeHeaders(Map<String, Object> headers) {
Map<String, Object> normalizedHeaders = new HashMap<String, Object>();
Map<String, Object> normalizedHeaders = new HashMap<>();
for (Entry<String, Object> entry : headers.entrySet()) {
String headerName = entry.getKey();
Object headerValue = entry.getValue();
@@ -634,7 +634,8 @@ public class MongoDbMessageStore extends AbstractMessageGroupStore
Bson payloadObject = (Bson) payload;
Object payloadType = asMap(payloadObject).get("_class");
try {
Class<?> payloadClass = ClassUtils.forName(payloadType.toString(), MongoDbMessageStore.this.classLoader);
Class<?> payloadClass =
ClassUtils.forName(payloadType.toString(), MongoDbMessageStore.this.classLoader);
payload = read(payloadClass, payloadObject);
}
catch (Exception e) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2018 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.
@@ -33,12 +33,13 @@ import org.springframework.integration.mongodb.rules.MongoDbAvailableTests;
/**
* @author Senthil Arumugam, Samiraj Panneer Selvam
* @author Artem Bilan
*
* @since 4.2
*
*/
public class MongoDbMetadataStoreTests extends MongoDbAvailableTests {
private final static String DEFAULT_COLLECTION_NAME = "metadataStore";
private static final String DEFAULT_COLLECTION_NAME = "metadataStore";
private final String file1 = "/remotepath/filesTodownload/file-1.txt";
@@ -47,14 +48,14 @@ public class MongoDbMetadataStoreTests extends MongoDbAvailableTests {
private MongoDbMetadataStore store = null;
@Before
public void configure() throws Exception {
public void configure() {
final MongoDbFactory mongoDbFactory = this.prepareMongoFactory(DEFAULT_COLLECTION_NAME);
this.store = new MongoDbMetadataStore(mongoDbFactory);
}
@MongoDbAvailable
@Test
public void testConfigureCustomCollection() throws Exception {
public void testConfigureCustomCollection() {
final String collectionName = "testMetadataStore";
final MongoDbFactory mongoDbFactory = this.prepareMongoFactory(collectionName);
final MongoTemplate template = new MongoTemplate(mongoDbFactory);
@@ -64,7 +65,7 @@ public class MongoDbMetadataStoreTests extends MongoDbAvailableTests {
@MongoDbAvailable
@Test
public void testConfigureFactory() throws Exception {
public void testConfigureFactory() {
final MongoDbFactory mongoDbFactory = this.prepareMongoFactory(DEFAULT_COLLECTION_NAME);
store = new MongoDbMetadataStore(mongoDbFactory);
testBasics();
@@ -72,7 +73,7 @@ public class MongoDbMetadataStoreTests extends MongoDbAvailableTests {
@MongoDbAvailable
@Test
public void testConfigureFactorCustomCollection() throws Exception {
public void testConfigureFactorCustomCollection() {
final String collectionName = "testMetadataStore";
final MongoDbFactory mongoDbFactory = this.prepareMongoFactory(collectionName);
store = new MongoDbMetadataStore(mongoDbFactory, collectionName);
@@ -98,7 +99,7 @@ public class MongoDbMetadataStoreTests extends MongoDbAvailableTests {
@Test
@MongoDbAvailable
public void testPutIfAbsent() throws Exception {
public void testPutIfAbsent() {
String fileID = store.get(file1);
assertNull("Get First time, Value must not exist", fileID);
@@ -115,7 +116,7 @@ public class MongoDbMetadataStoreTests extends MongoDbAvailableTests {
@Test
@MongoDbAvailable
public void testRemove() throws Exception {
public void testRemove() {
String fileID = store.remove(file1);
assertNull(fileID);
@@ -132,7 +133,7 @@ public class MongoDbMetadataStoreTests extends MongoDbAvailableTests {
@Test
@MongoDbAvailable
public void testReplace() throws Exception {
public void testReplace() {
boolean removedValue = store.replace(file1, file1Id, "4567");
assertFalse(removedValue);
String fileID = store.get(file1);
@@ -147,7 +148,6 @@ public class MongoDbMetadataStoreTests extends MongoDbAvailableTests {
fileID = store.get(file1);
assertNotNull(fileID);
assertEquals("4567", fileID);
}
}

View File

@@ -46,9 +46,9 @@ public class RedisQueueOutboundGateway extends AbstractReplyProducingMessageHand
private static final IdGenerator defaultIdGenerator = new AlternativeJdkIdGenerator();
private final static RedisSerializer<String> stringSerializer = new StringRedisSerializer();
private static final RedisSerializer<String> stringSerializer = new StringRedisSerializer();
private final RedisTemplate<String, Object> template;
private final RedisTemplate<String, Object> template = new RedisTemplate<>();
private final BoundListOperations<String, Object> boundListOps;
@@ -63,7 +63,6 @@ public class RedisQueueOutboundGateway extends AbstractReplyProducingMessageHand
public RedisQueueOutboundGateway(String queueName, RedisConnectionFactory connectionFactory) {
Assert.hasText(queueName, "'queueName' is required");
Assert.notNull(connectionFactory, "'connectionFactory' must not be null");
this.template = new RedisTemplate<String, Object>();
this.template.setConnectionFactory(connectionFactory);
this.template.setEnableDefaultSerializer(false);
this.template.setKeySerializer(new StringRedisSerializer());

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 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.
@@ -42,10 +42,11 @@ import org.springframework.util.SocketUtils;
/**
* @author Mark Fisher
* @author Gary Russell
* @author Artem Bilan
*/
public class RmiOutboundGatewayTests {
private final static int port = SocketUtils.findAvailableTcpPort();
private static final int port = SocketUtils.findAvailableTcpPort();
private final RmiOutboundGateway gateway =
new RmiOutboundGateway("rmi://localhost:" + port + "/testRemoteHandler");
@@ -69,16 +70,16 @@ public class RmiOutboundGatewayTests {
@Test
public void serializablePayload() throws RemoteException {
gateway.handleMessage(new GenericMessage<String>("test"));
public void serializablePayload() {
gateway.handleMessage(new GenericMessage<>("test"));
Message<?> replyMessage = output.receive(0);
assertNotNull(replyMessage);
assertEquals("TEST", replyMessage.getPayload());
}
@Test
public void failedMessage() throws RemoteException {
GenericMessage<String> message = new GenericMessage<String>("fail");
public void failedMessage() {
GenericMessage<String> message = new GenericMessage<>("fail");
try {
gateway.handleMessage(message);
fail("Exception expected");
@@ -90,7 +91,7 @@ public class RmiOutboundGatewayTests {
}
@Test
public void serializableAttribute() throws RemoteException {
public void serializableAttribute() {
Message<String> requestMessage = MessageBuilder.withPayload("test")
.setHeader("testAttribute", "foo").build();
gateway.handleMessage(requestMessage);
@@ -100,14 +101,14 @@ public class RmiOutboundGatewayTests {
}
@Test(expected = MessageHandlingException.class)
public void nonSerializablePayload() throws RemoteException {
public void nonSerializablePayload() {
NonSerializableTestObject payload = new NonSerializableTestObject();
Message<?> requestMessage = new GenericMessage<NonSerializableTestObject>(payload);
Message<?> requestMessage = new GenericMessage<>(payload);
gateway.handleMessage(requestMessage);
}
@Test
public void nonSerializableAttribute() throws RemoteException {
public void nonSerializableAttribute() {
Message<String> requestMessage = MessageBuilder.withPayload("test")
.setHeader("testAttribute", new NonSerializableTestObject()).build();
gateway.handleMessage(requestMessage);
@@ -117,11 +118,11 @@ public class RmiOutboundGatewayTests {
}
@Test
public void invalidServiceName() throws RemoteException {
public void invalidServiceName() {
RmiOutboundGateway gateway = new RmiOutboundGateway("rmi://localhost:1099/noSuchService");
boolean exceptionThrown = false;
try {
gateway.handleMessage(new GenericMessage<String>("test"));
gateway.handleMessage(new GenericMessage<>("test"));
}
catch (MessageHandlingException e) {
assertEquals(RemoteLookupFailureException.class, e.getCause().getClass());
@@ -135,7 +136,7 @@ public class RmiOutboundGatewayTests {
RmiOutboundGateway gateway = new RmiOutboundGateway("rmi://noSuchHost:1099/testRemoteHandler");
boolean exceptionThrown = false;
try {
gateway.handleMessage(new GenericMessage<String>("test"));
gateway.handleMessage(new GenericMessage<>("test"));
}
catch (MessageHandlingException e) {
assertEquals(RemoteLookupFailureException.class, e.getCause().getClass());
@@ -145,11 +146,11 @@ public class RmiOutboundGatewayTests {
}
@Test
public void invalidUrl() throws RemoteException {
public void invalidUrl() {
RmiOutboundGateway gateway = new RmiOutboundGateway("invalid");
boolean exceptionThrown = false;
try {
gateway.handleMessage(new GenericMessage<String>("test"));
gateway.handleMessage(new GenericMessage<>("test"));
}
catch (MessageHandlingException e) {
assertEquals(RemoteLookupFailureException.class, e.getCause().getClass());
@@ -174,9 +175,9 @@ public class RmiOutboundGatewayTests {
protected Object handleRequestMessage(Message<?> requestMessage) {
throw new RuntimeException("foo");
}
}.handleMessage(new GenericMessage<String>("bar"));
}.handleMessage(new GenericMessage<>("bar"));
}
return new GenericMessage<String>(message.getPayload().toString().toUpperCase(), message.getHeaders());
return new GenericMessage<>(message.getPayload().toString().toUpperCase(), message.getHeaders());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2018 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.
@@ -59,7 +59,7 @@ import org.springframework.util.SocketUtils;
@DirtiesContext
public class RmiOutboundGatewayParserTests {
public final static int port = SocketUtils.findAvailableTcpPort();
public static final int port = SocketUtils.findAvailableTcpPort();
private static final QueueChannel testChannel = new QueueChannel();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2016 the original author or authors.
* Copyright 2015-2018 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.
@@ -36,16 +36,19 @@ import org.springframework.security.core.context.SecurityContextHolder;
* in the containers Threads for channels like
* {@link org.springframework.integration.channel.ExecutorChannel}
* and {@link org.springframework.integration.channel.QueueChannel}.
*
* @author Artem Bilan
* @see ThreadStatePropagationChannelInterceptor
*
* @since 4.2
*
* @see ThreadStatePropagationChannelInterceptor
*/
public class SecurityContextPropagationChannelInterceptor
extends ThreadStatePropagationChannelInterceptor<Authentication> {
private final static SecurityContext EMPTY_CONTEXT = SecurityContextHolder.createEmptyContext();
private static final SecurityContext EMPTY_CONTEXT = SecurityContextHolder.createEmptyContext();
private final static ThreadLocal<SecurityContext> ORIGINAL_CONTEXT = new ThreadLocal<SecurityContext>();
private static final ThreadLocal<SecurityContext> ORIGINAL_CONTEXT = new ThreadLocal<>();
@Override
public void afterMessageHandled(Message<?> message, MessageChannel channel, MessageHandler handler, Exception ex) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,49 +23,51 @@ import com.jcraft.jsch.Logger;
/**
* @author Oleg Zhurakousky
* @author Artem Bilan
*
* @since 2.0.1
*/
class JschLogger implements Logger {
private final static Log logger = LogFactory.getLog("com.jcraft.jsch");
private static final Log logger = LogFactory.getLog("com.jcraft.jsch");
public boolean isEnabled(int level) {
switch (level) {
case Logger.INFO:
return logger.isInfoEnabled();
case Logger.WARN:
return logger.isWarnEnabled();
case Logger.DEBUG:
return logger.isDebugEnabled();
case Logger.ERROR:
return logger.isErrorEnabled();
case Logger.FATAL:
return logger.isFatalEnabled();
default:
return false;
case Logger.INFO:
return logger.isInfoEnabled();
case Logger.WARN:
return logger.isWarnEnabled();
case Logger.DEBUG:
return logger.isDebugEnabled();
case Logger.ERROR:
return logger.isErrorEnabled();
case Logger.FATAL:
return logger.isFatalEnabled();
default:
return false;
}
}
public void log(int level, String message) {
switch (level) {
case Logger.INFO:
logger.info(message);
break;
case Logger.WARN:
logger.warn(message);
break;
case Logger.DEBUG:
logger.debug(message);
break;
case Logger.ERROR:
logger.error(message);
break;
case Logger.FATAL:
logger.fatal(message);
break;
default:
break;
case Logger.INFO:
logger.info(message);
break;
case Logger.WARN:
logger.warn(message);
break;
case Logger.DEBUG:
logger.debug(message);
break;
case Logger.ERROR:
logger.error(message);
break;
case Logger.FATAL:
logger.fatal(message);
break;
default:
break;
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2018 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,12 +29,13 @@ import org.junit.runners.model.Statement;
*
* @author Gary Russell
* @author Artem Bilan
*
* @since 3.0
*
*/
public class LongRunningIntegrationTest extends TestWatcher {
private final static Log logger = LogFactory.getLog(LongRunningIntegrationTest.class);
private static final Log logger = LogFactory.getLog(LongRunningIntegrationTest.class);
private static final String RUN_LONG_PROP = "RUN_LONG_INTEGRATION_TESTS";
@@ -56,7 +57,7 @@ public class LongRunningIntegrationTest extends TestWatcher {
return new Statement() {
@Override
public void evaluate() throws Throwable {
public void evaluate() {
Assume.assumeTrue(false);
}
};

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014 the original author or authors.
* Copyright 2014-2018 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.
@@ -38,16 +38,17 @@ import org.springframework.web.socket.messaging.SubProtocolHandler;
*
* @author Andy Wilkinson
* @author Artem Bilan
*
* @since 4.1
*
* @see org.springframework.integration.websocket.inbound.WebSocketInboundChannelAdapter
* @see org.springframework.integration.websocket.outbound.WebSocketOutboundMessageHandler
*/
public final class SubProtocolHandlerRegistry {
private final static Log logger = LogFactory.getLog(SubProtocolHandlerRegistry.class);
private static final Log logger = LogFactory.getLog(SubProtocolHandlerRegistry.class);
private final Map<String, SubProtocolHandler> protocolHandlers =
new TreeMap<String, SubProtocolHandler>(String.CASE_INSENSITIVE_ORDER);
private final Map<String, SubProtocolHandler> protocolHandlers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
private final SubProtocolHandler defaultProtocolHandler;
@@ -68,7 +69,9 @@ public final class SubProtocolHandlerRegistry {
for (SubProtocolHandler handler : protocolHandlers) {
List<String> protocols = handler.getSupportedProtocols();
if (CollectionUtils.isEmpty(protocols)) {
logger.warn("No sub-protocols, ignoring handler " + handler);
if (logger.isWarnEnabled()) {
logger.warn("No sub-protocols, ignoring handler " + handler);
}
continue;
}
for (String protocol : protocols) {
@@ -112,7 +115,7 @@ public final class SubProtocolHandlerRegistry {
if (StringUtils.hasText(protocol)) {
handler = this.protocolHandlers.get(protocol);
Assert.state(handler != null,
"No handler for sub-protocol '" + protocol + "', handlers = " + this.protocolHandlers);
() -> "No handler for sub-protocol '" + protocol + "', handlers = " + this.protocolHandlers);
}
else {
handler = this.defaultProtocolHandler;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2017 the original author or authors.
* Copyright 2014-2018 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.
@@ -53,11 +53,12 @@ import org.springframework.web.socket.client.standard.StandardWebSocketClient;
/**
* @author Artem Bilan
*
* @since 4.1
*/
public class ClientWebSocketContainerTests {
private final static TomcatWebSocketTestServer server = new TomcatWebSocketTestServer(TestServerConfig.class);
private static final TomcatWebSocketTestServer server = new TomcatWebSocketTestServer(TestServerConfig.class);
@BeforeClass
public static void setup() throws Exception {
@@ -71,8 +72,7 @@ public class ClientWebSocketContainerTests {
@Test
public void testClientWebSocketContainer() throws Exception {
final AtomicBoolean failure = new AtomicBoolean();
AtomicBoolean failure = new AtomicBoolean();
StandardWebSocketClient webSocketClient = new StandardWebSocketClient() {
@@ -93,9 +93,8 @@ public class ClientWebSocketContainerTests {
};
Map<String, Object> userProperties = new HashMap<String, Object>();
userProperties.put(Constants.IO_TIMEOUT_MS_PROPERTY,
"" + (Constants.IO_TIMEOUT_MS_DEFAULT * 6));
Map<String, Object> userProperties = new HashMap<>();
userProperties.put(Constants.IO_TIMEOUT_MS_PROPERTY, "" + (Constants.IO_TIMEOUT_MS_DEFAULT * 6));
webSocketClient.setUserProperties(userProperties);
ClientWebSocketContainer container =
@@ -123,7 +122,8 @@ public class ClientWebSocketContainerTests {
}
catch (Exception e) {
assertThat(e, instanceOf(IllegalStateException.class));
assertEquals(e.getMessage(), "'clientSession' has not been established. Consider to 'start' this container.");
assertEquals(e.getMessage(),
"'clientSession' has not been established. Consider to 'start' this container.");
}
assertTrue(messageListener.sessionEndedLatch.await(10, TimeUnit.SECONDS));
@@ -164,18 +164,18 @@ public class ClientWebSocketContainerTests {
public final CountDownLatch sessionEndedLatch = new CountDownLatch(1);
@Override
public void onMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
public void onMessage(WebSocketSession session, WebSocketMessage<?> message) {
this.message = message;
this.messageLatch.countDown();
}
@Override
public void afterSessionStarted(WebSocketSession session) throws Exception {
public void afterSessionStarted(WebSocketSession session) {
this.started = true;
}
@Override
public void afterSessionEnded(WebSocketSession session, CloseStatus closeStatus) throws Exception {
public void afterSessionEnded(WebSocketSession session, CloseStatus closeStatus) {
sessionEndedLatch.countDown();
}

View File

@@ -93,7 +93,6 @@ import org.springframework.web.socket.server.RequestUpgradeStrategy;
import org.springframework.web.socket.server.standard.TomcatRequestUpgradeStrategy;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;
import org.springframework.web.socket.sockjs.client.SockJsClient;
import org.springframework.web.socket.sockjs.client.Transport;
import org.springframework.web.socket.sockjs.client.WebSocketTransport;
/**
@@ -106,7 +105,7 @@ import org.springframework.web.socket.sockjs.client.WebSocketTransport;
@DirtiesContext
public class WebSocketServerTests {
private final static SpelExpressionParser PARSER = new SpelExpressionParser();
private static final SpelExpressionParser PARSER = new SpelExpressionParser();
@Autowired
@Qualifier("webSocketOutputChannel")
@@ -126,7 +125,7 @@ public class WebSocketServerTests {
private Lifecycle requestUpgradeStrategy;
@Test
public void testWebSocketOutboundMessageHandler() throws Exception {
public void testWebSocketOutboundMessageHandler() {
StompHeaderAccessor headers = StompHeaderAccessor.create(StompCommand.SUBSCRIBE);
headers.setSubscriptionId("subs1");
headers.setDestination("/queue/foo");
@@ -166,7 +165,7 @@ public class WebSocketServerTests {
}
@Test
public void testBrokerIsNotPresented() throws Exception {
public void testBrokerIsNotPresented() {
WebSocketInboundChannelAdapter webSocketInboundChannelAdapter =
new WebSocketInboundChannelAdapter(Mockito.mock(ServerWebSocketContainer.class));
webSocketInboundChannelAdapter.setOutputChannel(new DirectChannel());
@@ -195,7 +194,7 @@ public class WebSocketServerTests {
@Bean
public WebSocketClient webSocketClient() {
return new SockJsClient(Collections.<Transport>singletonList(new WebSocketTransport(new StandardWebSocketClient())));
return new SockJsClient(Collections.singletonList(new WebSocketTransport(new StandardWebSocketClient())));
}
@Bean

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 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,6 +35,7 @@ import org.springframework.ws.soap.SoapMessage;
/**
* @author Oleg Zhurakousky
* @author Artem Bilan
*
* @since 2.1
*/
public abstract class AbstractWebServiceInboundGateway extends MessagingGatewaySupport
@@ -42,7 +43,7 @@ public abstract class AbstractWebServiceInboundGateway extends MessagingGatewayS
private final AtomicInteger activeCount = new AtomicInteger();
protected volatile SoapHeaderMapper headerMapper = new DefaultSoapHeaderMapper();
protected SoapHeaderMapper headerMapper = new DefaultSoapHeaderMapper();
@Override
public String getComponentType() {
@@ -111,6 +112,6 @@ public abstract class AbstractWebServiceInboundGateway extends MessagingGatewayS
return this.activeCount.get();
}
abstract protected void doInvoke(MessageContext messageContext) throws Exception;
protected abstract void doInvoke(MessageContext messageContext) throws Exception;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,19 +16,16 @@
package org.springframework.integration.xml.config;
/**
* @author Jonas Partner
* @author Mark Fisher
* @author Chris Beams
* @author Gary Russell
* @author Artem Bilan
*/
public class TestXmlApplicationContextHelper {
private TestXmlApplicationContextHelper() {
super();
}
public static TestXmlApplicationContext getTestAppContext(String xmlFragment) {
String xml = header + xmlFragment + footer;
TestXmlApplicationContext ctx = new TestXmlApplicationContext(xml);
return ctx;
}
private final static String header = "<?xml version='1.0' encoding='UTF-8'?>"
private static final String header = "<?xml version='1.0' encoding='UTF-8'?>"
+ "<beans xmlns='http://www.springframework.org/schema/beans' "
+ "xmlns:si-xml='http://www.springframework.org/schema/integration/xml' "
+ "xmlns:si='http://www.springframework.org/schema/integration' "
@@ -46,6 +43,14 @@ public class TestXmlApplicationContextHelper {
"http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd' >" +
"<context:annotation-config/>";
private final static String footer = "</beans>";
private static final String footer = "</beans>";
private TestXmlApplicationContextHelper() {
super();
}
public static TestXmlApplicationContext getTestAppContext(String xmlFragment) {
return new TestXmlApplicationContext(header + xmlFragment + footer);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2010 the original author or authors.
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,11 +24,13 @@ import org.springframework.beans.factory.xml.NamespaceHandlerSupport;
* @author Josh Long
* @author Mark Fisher
* @author Oleg Zhurakousky
* @author Artem Bilan
*
* @since 2.0
*/
public class XmppNamespaceHandler extends NamespaceHandlerSupport {
public final static String XMPP_CONNECTION_BEAN_NAME = "xmppConnection";
public static final String XMPP_CONNECTION_BEAN_NAME = "xmppConnection";
@Override
public void init() {

View File

@@ -158,6 +158,7 @@
<!-- Modifiers -->
<module name="RedundantModifier" />
<module name="ModifierOrderCheck"/>
<!-- Regexp -->
<module name="RegexpSinglelineJava">