Fix some Sonar smells

This commit is contained in:
Artem Bilan
2020-04-07 11:24:52 -04:00
parent cc0c2fd2fe
commit 3a846bad29
17 changed files with 145 additions and 122 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -68,12 +68,12 @@ import org.springframework.util.StringUtils;
*/
public class ReloadableResourceBundleExpressionSource implements ExpressionSource, ResourceLoaderAware {
private static final Log LOGGER = LogFactory.getLog(ReloadableResourceBundleExpressionSource.class);
private static final String PROPERTIES_SUFFIX = ".properties";
private static final String XML_SUFFIX = ".xml";
private static final Log LOGGER = LogFactory.getLog(ReloadableResourceBundleExpressionSource.class);
/**
* Cache to hold filename lists per Locale
@@ -211,7 +211,7 @@ public class ReloadableResourceBundleExpressionSource implements ExpressionSourc
* @param cacheSeconds The cache seconds.
*/
public void setCacheSeconds(int cacheSeconds) {
this.cacheMillis = (cacheSeconds * 1000);
this.cacheMillis = (cacheSeconds * 1000); // NOSONAR
}
/**
@@ -324,8 +324,7 @@ public class ReloadableResourceBundleExpressionSource implements ExpressionSourc
return filenames;
}
}
List<String> filenames = new ArrayList<>(7);
filenames.addAll(calculateFilenamesForLocale(basename, locale));
List<String> filenames = new ArrayList<>(calculateFilenamesForLocale(basename, locale));
if (this.fallbackToSystemLocale && !locale.equals(Locale.getDefault())) {
List<String> fallbackFilenames = calculateFilenamesForLocale(basename, Locale.getDefault());
for (String fallbackFilename : fallbackFilenames) {
@@ -359,7 +358,7 @@ public class ReloadableResourceBundleExpressionSource implements ExpressionSourc
* @return the List of filenames to check
*/
private List<String> calculateFilenamesForLocale(String basename, Locale locale) {
List<String> result = new ArrayList<>(3);
List<String> result = new ArrayList<>();
String language = locale.getLanguage();
String country = locale.getCountry();
String variant = locale.getVariant();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2019 the original author or authors.
* Copyright 2014-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -170,11 +170,8 @@ public class IdempotentReceiverInterceptor extends AbstractHandleMessageAdvice {
}
private MessageChannel obtainDiscardChannel() {
if (this.discardChannel == null) {
if (this.discardChannelName != null) {
this.discardChannel = getChannelResolver()
.resolveDestination(this.discardChannelName);
}
if (this.discardChannel == null && this.discardChannelName != null) {
this.discardChannel = getChannelResolver().resolveDestination(this.discardChannelName);
}
return this.discardChannel;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,9 +36,19 @@ import org.springframework.messaging.MessagingException;
*/
public class RequestHandlerCircuitBreakerAdvice extends AbstractRequestHandlerAdvice {
private volatile int threshold = 5;
/**
* A default failures threshold as {@value DEFAULT_THRESHOLD}.
*/
public static final int DEFAULT_THRESHOLD = 5;
private volatile long halfOpenAfter = 1000;
/**
* A half-open duration as {@value DEFAULT_HALF_OPEN_AFTER} .
*/
public static final int DEFAULT_HALF_OPEN_AFTER = 1000;
private int threshold = DEFAULT_THRESHOLD;
private long halfOpenAfter = DEFAULT_HALF_OPEN_AFTER;
private final ConcurrentMap<Object, AdvisedMetadata> metadataMap = new ConcurrentHashMap<>();
@@ -101,6 +111,7 @@ public class RequestHandlerCircuitBreakerAdvice extends AbstractRequestHandlerAd
private AtomicInteger getFailures() {
return this.failures;
}
}
/**

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,17 +37,18 @@ import org.springframework.util.Assert;
*
* @author Gary Russell
* @author Artem Bilan
*
* @since 2.2
*/
public class RequestHandlerRetryAdvice extends AbstractRequestHandlerAdvice
implements RetryListener {
private static final ThreadLocal<Message<?>> MESSAGE_HOLDER = new ThreadLocal<>();
private RetryTemplate retryTemplate = new RetryTemplate();
private RecoveryCallback<Object> recoveryCallback;
private static final ThreadLocal<Message<?>> messageHolder = new ThreadLocal<Message<?>>();
// Stateless unless a state generator is provided
private volatile RetryStateGenerator retryStateGenerator = message -> null;
@@ -78,9 +79,8 @@ public class RequestHandlerRetryAdvice extends AbstractRequestHandlerAdvice
@Override
protected Object doInvoke(final ExecutionCallback callback, Object target, final Message<?> message) {
RetryState retryState = null;
retryState = this.retryStateGenerator.determineRetryState(message);
messageHolder.set(message);
RetryState retryState = this.retryStateGenerator.determineRetryState(message);
MESSAGE_HOLDER.set(message);
try {
return this.retryTemplate.execute(context -> callback.cloneAndExecute(), this.recoveryCallback, retryState);
@@ -98,13 +98,13 @@ public class RequestHandlerRetryAdvice extends AbstractRequestHandlerAdvice
throw new ThrowableHolderException(e);
}
finally {
messageHolder.remove();
MESSAGE_HOLDER.remove();
}
}
@Override
public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
context.setAttribute(ErrorMessageUtils.FAILED_MESSAGE_CONTEXT_KEY, messageHolder.get());
context.setAttribute(ErrorMessageUtils.FAILED_MESSAGE_CONTEXT_KEY, MESSAGE_HOLDER.get());
return true;
}

View File

@@ -128,7 +128,6 @@ public abstract class AbstractHeaderMapper<T> implements RequestReplyHeaderMappe
* Provide the header names that should be mapped to a response
* from a {@link MessageHeaders}.
* <p>The values can also contain simple wildcard patterns (e.g. "foo*" or "*foo") to be matched.
*
* @param replyHeaderNames The reply header names.
*/
public void setReplyHeaderNames(String... replyHeaderNames) {
@@ -141,7 +140,7 @@ public abstract class AbstractHeaderMapper<T> implements RequestReplyHeaderMappe
* standard header prefix.
* @param standardHeaderPrefix the prefix for standard headers.
* @param headerNames the collection of header names to map.
* @return the deafault {@link HeaderMatcher} instance.
* @return the default {@link HeaderMatcher} instance.
*/
protected HeaderMatcher createDefaultHeaderMatcher(String standardHeaderPrefix, Collection<String> headerNames) {
return new ContentBasedHeaderMatcher(true, headerNames);
@@ -401,6 +400,7 @@ public abstract class AbstractHeaderMapper<T> implements RequestReplyHeaderMappe
/**
* Strategy interface to determine if a given header name matches.
*
* @since 4.1
*/
@FunctionalInterface
@@ -427,11 +427,12 @@ public abstract class AbstractHeaderMapper<T> implements RequestReplyHeaderMappe
* A content-based {@link HeaderMatcher} that matches if the specified
* header is contained within a list of candidates. The case of the
* header does not matter.
*
* @since 4.1
*/
protected static class ContentBasedHeaderMatcher implements HeaderMatcher {
private static final Log logger = LogFactory.getLog(HeaderMatcher.class);
private static final Log LOGGER = LogFactory.getLog(HeaderMatcher.class);
private final boolean match;
@@ -446,13 +447,13 @@ public abstract class AbstractHeaderMapper<T> implements RequestReplyHeaderMappe
@Override
public boolean matchHeader(String headerName) {
boolean result = (this.match == containsIgnoreCase(headerName));
if (result && logger.isDebugEnabled()) {
if (result && LOGGER.isDebugEnabled()) {
StringBuilder message = new StringBuilder("headerName=[{0}] WILL be mapped, ");
if (!this.match) {
message.append("not ");
}
message.append("found in {1}");
logger.debug(MessageFormat.format(message.toString(), headerName, this.content));
LOGGER.debug(MessageFormat.format(message.toString(), headerName, this.content));
}
return result;
}
@@ -471,12 +472,14 @@ public abstract class AbstractHeaderMapper<T> implements RequestReplyHeaderMappe
/**
* A pattern-based {@link HeaderMatcher} that matches if the specified
* header matches one of the specified simple patterns.
* @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
*
* @since 4.1
*
* @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
*/
protected static class PatternBasedHeaderMatcher implements HeaderMatcher {
private static final Log logger = LogFactory.getLog(HeaderMatcher.class);
private static final Log LOGGER = LogFactory.getLog(HeaderMatcher.class);
private final Collection<String> patterns = new ArrayList<>();
@@ -493,8 +496,8 @@ public abstract class AbstractHeaderMapper<T> implements RequestReplyHeaderMappe
String header = headerName.toLowerCase();
for (String pattern : this.patterns) {
if (PatternMatchUtils.simpleMatch(pattern, header)) {
if (logger.isDebugEnabled()) {
logger.debug(MessageFormat.format(
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(MessageFormat.format(
"headerName=[{0}] WILL be mapped, matched pattern={1}", headerName, pattern));
}
return true;
@@ -509,12 +512,14 @@ public abstract class AbstractHeaderMapper<T> implements RequestReplyHeaderMappe
* A pattern-based {@link HeaderMatcher} that matches if the specified
* header matches the specified simple pattern.
* <p> The {@code negate == true} state indicates if the matching should be treated as "not matched".
* @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
*
* @since 4.3
*
* @see org.springframework.util.PatternMatchUtils#simpleMatch(String, String)
*/
protected static class SinglePatternBasedHeaderMatcher implements HeaderMatcher {
private static final Log logger = LogFactory.getLog(HeaderMatcher.class);
private static final Log LOGGER = LogFactory.getLog(HeaderMatcher.class);
private final String pattern;
@@ -534,8 +539,8 @@ public abstract class AbstractHeaderMapper<T> implements RequestReplyHeaderMappe
public boolean matchHeader(String headerName) {
String header = headerName.toLowerCase();
if (PatternMatchUtils.simpleMatch(this.pattern, header)) {
if (logger.isDebugEnabled()) {
logger.debug(MessageFormat.format(
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(MessageFormat.format(
"headerName=[{0}] WILL be mapped, matched pattern={1}", headerName, this.pattern));
}
return true;
@@ -553,11 +558,12 @@ public abstract class AbstractHeaderMapper<T> implements RequestReplyHeaderMappe
/**
* A prefix-based {@link HeaderMatcher} that matches if the specified
* header starts with a configurable prefix.
*
* @since 4.1
*/
protected static class PrefixBasedMatcher implements HeaderMatcher {
private static final Log logger = LogFactory.getLog(HeaderMatcher.class);
private static final Log LOGGER = LogFactory.getLog(HeaderMatcher.class);
private final boolean match;
@@ -571,13 +577,13 @@ public abstract class AbstractHeaderMapper<T> implements RequestReplyHeaderMappe
@Override
public boolean matchHeader(String headerName) {
boolean result = (this.match == headerName.startsWith(this.prefix));
if (result && logger.isDebugEnabled()) {
if (result && LOGGER.isDebugEnabled()) {
StringBuilder message = new StringBuilder("headerName=[{0}] WILL be mapped, ");
if (!this.match) {
message.append("does not ");
}
message.append("start with [{1}]");
logger.debug(MessageFormat.format(message.toString(), headerName, this.prefix));
LOGGER.debug(MessageFormat.format(message.toString(), headerName, this.prefix));
}
return result;
}
@@ -587,11 +593,12 @@ public abstract class AbstractHeaderMapper<T> implements RequestReplyHeaderMappe
/**
* A composite {@link HeaderMatcher} that matches if one of provided
* {@link HeaderMatcher}s matches to the {@code headerName}.
*
* @since 4.1
*/
protected static class CompositeHeaderMatcher implements HeaderMatcher {
private static final Log logger = LogFactory.getLog(HeaderMatcher.class);
private static final Log LOGGER = LogFactory.getLog(HeaderMatcher.class);
private final Collection<HeaderMatcher> matchers;
@@ -613,8 +620,8 @@ public abstract class AbstractHeaderMapper<T> implements RequestReplyHeaderMappe
return true;
}
}
if (logger.isDebugEnabled()) {
logger.debug(MessageFormat.format("headerName=[{0}] WILL NOT be mapped", headerName));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(MessageFormat.format("headerName=[{0}] WILL NOT be mapped", headerName));
}
return false;
}

View File

@@ -114,7 +114,8 @@ public class MetadataStoreSelector implements MessageSelector {
? this.valueStrategy.processMessage(message)
: (timestamp == null ? "0" : Long.toString(timestamp));
if (this.compareValues == null) {
BiPredicate<String, String> predicate = this.compareValues;
if (predicate == null) {
return this.metadataStore.putIfAbsent(key, value) == null;
}
else {
@@ -123,7 +124,7 @@ public class MetadataStoreSelector implements MessageSelector {
if (oldValue == null) {
return this.metadataStore.putIfAbsent(key, value) == null;
}
if (this.compareValues.test(oldValue, value)) { // NOSONAR (null dereference)
if (predicate.test(oldValue, value)) {
return this.metadataStore.replace(key, oldValue, value);
}
return false;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2019 the original author or authors.
* Copyright 2014-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -46,7 +46,7 @@ public abstract class AbstractIntegrationMessageBuilder<T> {
return setHeader(IntegrationMessageHeaderAccessor.EXPIRATION_DATE, expirationDate);
}
public AbstractIntegrationMessageBuilder<T> setExpirationDate(Date expirationDate) {
public AbstractIntegrationMessageBuilder<T> setExpirationDate(@Nullable Date expirationDate) {
if (expirationDate != null) {
return setHeader(IntegrationMessageHeaderAccessor.EXPIRATION_DATE, expirationDate.getTime());
}
@@ -62,7 +62,7 @@ public abstract class AbstractIntegrationMessageBuilder<T> {
public AbstractIntegrationMessageBuilder<T> pushSequenceDetails(Object correlationId, int sequenceNumber,
int sequenceSize) {
Object incomingCorrelationId = this.getCorrelationId();
Object incomingCorrelationId = getCorrelationId();
List<List<Object>> incomingSequenceDetails = getSequenceDetails();
if (incomingCorrelationId != null) {
if (incomingSequenceDetails == null) {
@@ -92,8 +92,8 @@ public abstract class AbstractIntegrationMessageBuilder<T> {
incomingSequenceDetails = new ArrayList<>(incomingSequenceDetails);
}
List<Object> sequenceDetails = incomingSequenceDetails.remove(incomingSequenceDetails.size() - 1);
Assert.state(sequenceDetails.size() == 3, "Wrong sequence details (not created by MessageBuilder?): "
+ sequenceDetails);
Assert.state(sequenceDetails.size() == 3, // NOSONAR
() -> "Wrong sequence details (not created by MessageBuilder?): " + sequenceDetails);
setCorrelationId(sequenceDetails.get(0));
Integer sequenceNumber = (Integer) sequenceDetails.get(1);
Integer sequenceSize = (Integer) sequenceDetails.get(2);
@@ -166,10 +166,13 @@ public abstract class AbstractIntegrationMessageBuilder<T> {
@Nullable
protected abstract List<List<Object>> getSequenceDetails();
@Nullable
protected abstract Object getCorrelationId();
@Nullable
protected abstract Object getSequenceNumber();
@Nullable
protected abstract Object getSequenceSize();
public abstract T getPayload();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -48,7 +48,7 @@ import org.springframework.util.ObjectUtils;
*/
public final class MessageBuilder<T> extends AbstractIntegrationMessageBuilder<T> {
private static final Log logger = LogFactory.getLog(MessageBuilder.class);
private static final Log LOGGER = LogFactory.getLog(MessageBuilder.class);
private final T payload;
@@ -93,7 +93,6 @@ public final class MessageBuilder<T> extends AbstractIntegrationMessageBuilder<T
/**
* Create a builder for a new {@link Message} instance pre-populated with all of the headers copied from the
* provided message. The payload of the provided Message will also be used as the payload for the new message.
*
* @param message the Message from which the payload and all headers will be copied
* @param <T> The type of the payload.
* @return A MessageBuilder.
@@ -160,8 +159,8 @@ public final class MessageBuilder<T> extends AbstractIntegrationMessageBuilder<T
if (!this.headerAccessor.isReadOnly(headerName)) {
this.headerAccessor.removeHeader(headerName);
}
else if (logger.isInfoEnabled()) {
logger.info("The header [" + headerName + "] is ignored for removal because it is is readOnly.");
else if (LOGGER.isInfoEnabled()) {
LOGGER.info("The header [" + headerName + "] is ignored for removal because it is is readOnly.");
}
return this;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2019 the original author or authors.
* Copyright 2014-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -103,7 +103,7 @@ public class MutableMessage<T> implements Message<T>, Serializable {
@Override
public int hashCode() {
return this.headers.hashCode() * 23 + ObjectUtils.nullSafeHashCode(this.payload);
return this.headers.hashCode() * 23 + ObjectUtils.nullSafeHashCode(this.payload); // NOSONAR
}
@Override

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2019 the original author or authors.
* Copyright 2015-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -59,13 +59,13 @@ import org.springframework.util.MultiValueMap;
public class SmartLifecycleRoleController implements ApplicationListener<AbstractLeaderEvent>,
ApplicationContextAware {
private static final Log LOGGER = LogFactory.getLog(SmartLifecycleRoleController.class);
private static final String IN_ROLE = " in role ";
private static final Log logger = LogFactory.getLog(SmartLifecycleRoleController.class);
private final MultiValueMap<String, SmartLifecycle> lifecycles = new LinkedMultiValueMap<>();
private final MultiValueMap<String, SmartLifecycle> lifecycles = new LinkedMultiValueMap<String, SmartLifecycle>();
private final MultiValueMap<String, String> lazyLifecycles = new LinkedMultiValueMap<String, String>();
private final MultiValueMap<String, String> lazyLifecycles = new LinkedMultiValueMap<>();
private ApplicationContext applicationContext;
@@ -87,10 +87,10 @@ public class SmartLifecycleRoleController implements ApplicationListener<Abstrac
/**
* Construct an instance with the provided map of roles/instances.
* @param lifcycles the {@link MultiValueMap} of beans in roles.
* @param lifecycles the {@link MultiValueMap} of beans in roles.
*/
public SmartLifecycleRoleController(MultiValueMap<String, SmartLifecycle> lifcycles) {
lifcycles.forEach((role, values) -> values.forEach(lifecycle -> addLifecycleToRole(role, lifecycle)));
public SmartLifecycleRoleController(MultiValueMap<String, SmartLifecycle> lifecycles) {
lifecycles.forEach((role, values) -> values.forEach(lifecycle -> addLifecycleToRole(role, lifecycle)));
}
@Override
@@ -163,8 +163,8 @@ public class SmartLifecycleRoleController implements ApplicationListener<Abstrac
if (componentsInRole != null) {
componentsInRole = new ArrayList<>(componentsInRole);
componentsInRole.sort(Comparator.comparingInt(Phased::getPhase));
if (logger.isDebugEnabled()) {
logger.debug("Starting " + componentsInRole + IN_ROLE + role);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Starting " + componentsInRole + IN_ROLE + role);
}
componentsInRole.forEach(lifecycle -> {
@@ -172,13 +172,13 @@ public class SmartLifecycleRoleController implements ApplicationListener<Abstrac
lifecycle.start();
}
catch (Exception e) {
logger.error("Failed to start " + lifecycle + IN_ROLE + role, e);
LOGGER.error("Failed to start " + lifecycle + IN_ROLE + role, e);
}
});
}
else {
if (logger.isDebugEnabled()) {
logger.debug("No components in role " + role + ". Nothing to start");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No components in role " + role + ". Nothing to start");
}
}
}
@@ -195,8 +195,8 @@ public class SmartLifecycleRoleController implements ApplicationListener<Abstrac
if (componentsInRole != null) {
componentsInRole = new ArrayList<>(componentsInRole);
componentsInRole.sort((o1, o2) -> Integer.compare(o2.getPhase(), o1.getPhase()));
if (logger.isDebugEnabled()) {
logger.debug("Stopping " + componentsInRole + IN_ROLE + role);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Stopping " + componentsInRole + IN_ROLE + role);
}
componentsInRole.forEach(lifecycle -> {
@@ -204,13 +204,13 @@ public class SmartLifecycleRoleController implements ApplicationListener<Abstrac
lifecycle.stop();
}
catch (Exception e) {
logger.error("Failed to stop " + lifecycle + IN_ROLE + role, e);
LOGGER.error("Failed to stop " + lifecycle + IN_ROLE + role, e);
}
});
}
else {
if (logger.isDebugEnabled()) {
logger.debug("No components in role " + role + ". Nothing to stop");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("No components in role " + role + ". Nothing to stop");
}
}
}
@@ -287,7 +287,7 @@ public class SmartLifecycleRoleController implements ApplicationListener<Abstrac
addLifecycleToRole(role, lifecycle);
}
catch (NoSuchBeanDefinitionException e) {
logger.warn("Skipped; no such bean: " + lifecycleBeanName);
LOGGER.warn("Skipped; no such bean: " + lifecycleBeanName);
}
});
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2019 the original author or authors.
* Copyright 2017-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -205,7 +205,7 @@ public class EmbeddedJsonHeadersMessageMapper implements BytesMessageMapper {
private byte[] fromBytesPayload(byte[] payload, Map<String, Object> headersToEncode) {
try {
byte[] headers = this.objectMapper.writeValueAsBytes(headersToEncode);
ByteBuffer buffer = ByteBuffer.wrap(new byte[8 + headers.length + payload.length]);
ByteBuffer buffer = ByteBuffer.wrap(new byte[8 + headers.length + payload.length]); // NOSONAR
buffer.putInt(headers.length);
buffer.put(headers);
buffer.putInt(payload.length);
@@ -247,16 +247,16 @@ public class EmbeddedJsonHeadersMessageMapper implements BytesMessageMapper {
@Nullable
private Message<?> decodeNativeFormat(byte[] bytes, @Nullable Map<String, Object> headersToAdd) throws IOException {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
if (buffer.remaining() > 4) {
if (buffer.remaining() > 4) { // NOSONAR
int headersLen = buffer.getInt();
if (headersLen >= 0 && headersLen < buffer.remaining() - 4) {
buffer.position(headersLen + 4);
if (headersLen >= 0 && headersLen < buffer.remaining() - 4) { // NOSONAR
buffer.position(headersLen + 4); // NOSONAR
int payloadLen = buffer.getInt();
if (payloadLen != buffer.remaining()) {
return null;
}
else {
buffer.position(4);
buffer.position(4); // NOSONAR
@SuppressWarnings("unchecked")
Map<String, Object> headers = this.objectMapper.readValue(bytes, buffer.position(), headersLen,
Map.class);

View File

@@ -27,20 +27,24 @@ import org.springframework.util.ClassUtils;
*/
public final class JacksonPresent {
private static final ClassLoader classLoader = JacksonPresent.class.getClassLoader();
private static final ClassLoader CLASS_LOADER = ClassUtils.getDefaultClassLoader();
private static final boolean jackson2Present =
ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader);
ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", CLASS_LOADER) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", CLASS_LOADER);
private static final boolean jacksonPresent =
ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", classLoader) &&
ClassUtils.isPresent("org.codehaus.jackson.JsonGenerator", classLoader);
ClassUtils.isPresent("org.codehaus.jackson.map.ObjectMapper", CLASS_LOADER) &&
ClassUtils.isPresent("org.codehaus.jackson.JsonGenerator", CLASS_LOADER);
public static boolean isJackson2Present() {
return jackson2Present;
}
/**
* @deprecated Jackson 1.x is not supported any more. Use Jackson 2.x.
*/
@Deprecated
public static boolean isJacksonPresent() {
return jacksonPresent;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.integration.transformer;
import java.util.Collection;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.context.Lifecycle;
import org.springframework.integration.IntegrationPattern;
@@ -29,8 +30,7 @@ import org.springframework.util.Assert;
/**
* A reply-producing {@link org.springframework.messaging.MessageHandler}
* that delegates to a
* {@link Transformer} instance to modify the received {@link Message}
* that delegates to a {@link Transformer} instance to modify the received {@link Message}
* and sends the result to its output channel.
*
* @author Mark Fisher
@@ -42,11 +42,9 @@ public class MessageTransformingHandler extends AbstractReplyProducingMessageHan
private final Transformer transformer;
/**
* Create a {@link MessageTransformingHandler} instance that delegates to
* the provided {@link Transformer}.
*
* @param transformer The transformer.
*/
public MessageTransformingHandler(Transformer transformer) {
@@ -58,8 +56,9 @@ public class MessageTransformingHandler extends AbstractReplyProducingMessageHan
@Override
public String getComponentType() {
return (this.transformer instanceof NamedComponent) ?
((NamedComponent) this.transformer).getComponentType() : "transformer";
return (this.transformer instanceof NamedComponent)
? ((NamedComponent) this.transformer).getComponentType()
: "transformer";
}
@Override
@@ -77,8 +76,9 @@ public class MessageTransformingHandler extends AbstractReplyProducingMessageHan
@Override
protected void doInit() {
if (this.getBeanFactory() != null && this.transformer instanceof BeanFactoryAware) {
((BeanFactoryAware) this.transformer).setBeanFactory(this.getBeanFactory());
BeanFactory beanFactory = getBeanFactory();
if (beanFactory != null && this.transformer instanceof BeanFactoryAware) {
((BeanFactoryAware) this.transformer).setBeanFactory(beanFactory);
}
populateNotPropagatedHeadersIfAny();
@@ -118,11 +118,10 @@ public class MessageTransformingHandler extends AbstractReplyProducingMessageHan
return this.transformer.transform(message);
}
catch (Exception e) {
if (e instanceof MessageTransformationException) {
if (e instanceof MessageTransformationException) { // NOSONAR
throw (MessageTransformationException) e;
}
throw new MessageTransformationException(message,
"Failed to transform Message in " + this, e);
throw new MessageTransformationException(message, "Failed to transform Message in " + this, e);
}
}

View File

@@ -98,8 +98,8 @@ public class SyslogToMapTransformer extends AbstractPayloadTransformer<Object, M
try {
String facilityString = matcher.group(1); // NOSONAR
int facility = Integer.parseInt(facilityString);
int severity = facility & 0x7;
facility = facility >> 3;
int severity = facility & 0x7; // NOSONAR
facility = facility >> 3; // NOSONAR
map.put(FACILITY, facility);
map.put(SEVERITY, severity);
String timestamp = matcher.group(2); // NOSONAR

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2014-2019 the original author or authors.
* Copyright 2014-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -31,18 +31,20 @@ import org.apache.commons.logging.LogFactory;
* case a {@link RejectedExecutionException} is thrown.
*
* @author Gary Russell
* @author Artem Bilan
*
* @since 3.0.3
*
*/
public class CallerBlocksPolicy implements RejectedExecutionHandler {
private static final Log logger = LogFactory.getLog(CallerBlocksPolicy.class);
private static final Log LOGGER = LogFactory.getLog(CallerBlocksPolicy.class);
private final long maxWait;
/**
* @param maxWait The maximum time to wait for a queue slot to be
* available, in milliseconds.
* Construct instance based on the provided maximum wait time.
* @param maxWait The maximum time to wait for a queue slot to be available, in milliseconds.
*/
public CallerBlocksPolicy(long maxWait) {
this.maxWait = maxWait;
@@ -53,15 +55,13 @@ public class CallerBlocksPolicy implements RejectedExecutionHandler {
if (!executor.isShutdown()) {
try {
BlockingQueue<Runnable> queue = executor.getQueue();
if (logger.isDebugEnabled()) {
logger.debug("Attempting to queue task execution for " + this.maxWait + " milliseconds");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Attempting to queue task execution for " + this.maxWait + " milliseconds");
}
if (!queue.offer(r, this.maxWait, TimeUnit.MILLISECONDS)) {
throw new RejectedExecutionException("Max wait time expired to queue task");
}
if (logger.isDebugEnabled()) {
logger.debug("Task execution queued");
}
LOGGER.debug("Task execution queued");
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();

View File

@@ -145,7 +145,7 @@ public class DynamicPeriodicTrigger implements Trigger {
final int prime = 31;
int result = 1;
result = prime * result + ((this.duration == null) ? 0 : this.duration.hashCode());
result = prime * result + (this.fixedRate ? 1231 : 1237);
result = prime * result + (this.fixedRate ? 1231 : 1237); // NOSONAR
result = prime * result + ((this.initialDuration == null) ? 0 : this.initialDuration.hashCode());
return result;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,6 +28,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
@@ -37,6 +38,8 @@ import org.springframework.util.Assert;
*
* @author Gary Russell
* @author Sergey Bogatyrev
* @author Artem Bilan
*
* @since 2.2
*
*/
@@ -91,7 +94,8 @@ public class SimplePool<T> implements Pool<T> {
int delta = poolSize - this.poolSize.get();
this.targetPoolSize.addAndGet(delta);
if (this.logger.isDebugEnabled()) {
this.logger.debug(String.format("Target pool size changed by %d, now %d", delta, this.targetPoolSize.get()));
this.logger.debug(String.format("Target pool size changed by %d, now %d", delta,
this.targetPoolSize.get()));
}
if (delta > 0) {
this.poolSize.addAndGet(delta);
@@ -111,7 +115,8 @@ public class SimplePool<T> implements Pool<T> {
}
}
if (delta < 0 && this.logger.isDebugEnabled()) {
this.logger.debug(String.format("Pool is overcommitted by %d; items will be removed when returned", -delta));
this.logger.debug(String.format("Pool is overcommitted by %d; items will be removed when returned",
-delta));
}
}
@@ -175,7 +180,7 @@ public class SimplePool<T> implements Pool<T> {
if (permitted) {
this.permits.release();
}
if (e instanceof PoolItemNotAvailableException) {
if (e instanceof PoolItemNotAvailableException) { // NOSONAR
throw (PoolItemNotAvailableException) e;
}
throw new PoolItemNotAvailableException("Failed to obtain pooled item", e);
@@ -216,18 +221,14 @@ public class SimplePool<T> implements Pool<T> {
if (this.inUse.contains(item)) {
if (this.poolSize.get() > this.targetPoolSize.get()) {
this.poolSize.decrementAndGet();
if (item != null) {
doRemoveItem(item);
}
doRemoveItem(item);
}
else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Releasing " + item + " back to the pool");
}
if (item != null) {
this.available.add(item);
this.inUse.remove(item);
}
this.available.add(item);
this.inUse.remove(item);
this.permits.release();
}
}
@@ -286,5 +287,7 @@ public class SimplePool<T> implements Pool<T> {
* @param item The item.
*/
void removedFromPool(T item);
}
}