Avoid throws Exception where possible - Phase I

* Polishing - PR Comments
This commit is contained in:
Gary Russell
2019-03-07 12:53:52 -05:00
committed by Artem Bilan
parent 005bc80680
commit b187bca36e
130 changed files with 992 additions and 784 deletions

View File

@@ -55,6 +55,7 @@ import org.springframework.integration.util.UUIDConverter;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageDeliveryException;
import org.springframework.messaging.MessageHandlingException;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
@@ -431,7 +432,7 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP
}
@Override
protected void handleMessageInternal(Message<?> message) throws InterruptedException {
protected void handleMessageInternal(Message<?> message) {
Object correlationKey = this.correlationStrategy.getCorrelationKey(message);
Assert.state(correlationKey != null,
"Null correlation not allowed. Maybe the CorrelationStrategy is failing?");
@@ -444,7 +445,13 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP
Lock lock = this.lockRegistry.obtain(groupIdUuid.toString());
boolean noOutput = true;
lock.lockInterruptibly();
try {
lock.lockInterruptibly();
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new MessageHandlingException(message, "Interrupted getting lock", e);
}
try {
noOutput = processMessageForGroup(message, correlationKey, groupIdUuid, lock);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -91,7 +91,7 @@ public class CorrelatingMessageBarrier extends AbstractMessageHandler implements
}
@Override
protected void handleMessageInternal(Message<?> message) throws Exception {
protected void handleMessageInternal(Message<?> message) {
Object correlationKey = this.correlationStrategy.getCorrelationKey(message);
Object lock = getLock(correlationKey);
synchronized (lock) {

View File

@@ -281,7 +281,7 @@ public class NullChannel implements PollableChannel, MessageChannelMetrics,
}
@Override
public void destroy() throws Exception {
public void destroy() {
if (this.successTimer != null) {
this.successTimer.remove();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -90,7 +90,7 @@ public abstract class AbstractEvaluationContextFactoryBean implements Applicatio
return this.functions;
}
protected void initialize(String beanName) throws Exception {
protected void initialize(String beanName) {
if (this.applicationContext != null) {
ConversionService conversionService = IntegrationUtils.getConversionService(getApplicationContext());
if (conversionService != null) {
@@ -115,7 +115,7 @@ public abstract class AbstractEvaluationContextFactoryBean implements Applicatio
}
}
}
catch (NoSuchBeanDefinitionException e) {
catch (@SuppressWarnings("unused") NoSuchBeanDefinitionException e) {
// There is no 'SpelPropertyAccessorRegistrar' bean in the application context.
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -61,7 +61,7 @@ final class ChannelInitializer implements BeanFactoryAware, InitializingBean {
}
@Override
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() {
Assert.notNull(this.beanFactory, "'beanFactory' must not be null");
if (!this.autoCreate) {
return;

View File

@@ -182,7 +182,7 @@ public class ConsumerEndpointFactoryBean
}
@Override
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() {
if (this.beanName == null) {
logger.error("The MessageHandler [" + this.handler + "] will be created without a 'componentName'. " +
"Consider specifying the 'beanName' property on this ConsumerEndpointFactoryBean.");
@@ -248,7 +248,7 @@ public class ConsumerEndpointFactoryBean
}
@Override
public AbstractEndpoint getObject() throws Exception {
public AbstractEndpoint getObject() {
if (!this.initialized) {
this.initializeEndpoint();
}
@@ -263,8 +263,7 @@ public class ConsumerEndpointFactoryBean
return this.endpoint.getClass();
}
@SuppressWarnings("unchecked")
private void initializeEndpoint() throws Exception {
private void initializeEndpoint() {
synchronized (this.initializationMonitor) {
if (this.initialized) {
return;
@@ -381,7 +380,7 @@ public class ConsumerEndpointFactoryBean
}
@Override
public void destroy() throws Exception {
public void destroy() {
if (this.endpoint != null) {
this.endpoint.destroy();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -56,7 +56,7 @@ public class CorrelationStrategyFactoryBean implements FactoryBean<CorrelationSt
}
@Override
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() {
if (this.target instanceof CorrelationStrategy && !StringUtils.hasText(this.methodName)) {
this.strategy = (CorrelationStrategy) this.target;
return;
@@ -75,14 +75,17 @@ public class CorrelationStrategyFactoryBean implements FactoryBean<CorrelationSt
}
}
public CorrelationStrategy getObject() throws Exception {
@Override
public CorrelationStrategy getObject() {
return this.strategy;
}
@Override
public Class<?> getObjectType() {
return CorrelationStrategy.class;
}
@Override
public boolean isSingleton() {
return true;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -79,7 +79,7 @@ public class IntegrationEvaluationContextFactoryBean extends AbstractEvaluationC
}
@Override
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() {
if (getApplicationContext() != null) {
this.beanResolver = new BeanFactoryResolver(getApplicationContext());
}
@@ -87,7 +87,7 @@ public class IntegrationEvaluationContextFactoryBean extends AbstractEvaluationC
}
@Override
public StandardEvaluationContext getObject() throws Exception {
public StandardEvaluationContext getObject() {
StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
if (this.typeLocator != null) {
evaluationContext.setTypeLocator(this.typeLocator);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2015-2018 the original author or authors.
* Copyright 2015-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -272,12 +272,12 @@ public class IntegrationManagementConfigurer
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
if (this.singletonsInstantiated) {
if (bean instanceof IntegrationManagement) {
((IntegrationManagement) bean).registerMetricsCaptor(this.metricsCaptor);
}
return doConfigureMetrics(bean, beanName);
return doConfigureMetrics(bean, name);
}
return bean;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -68,12 +68,12 @@ public class IntegrationSimpleEvaluationContextFactoryBean extends AbstractEvalu
}
@Override
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() {
initialize(IntegrationContextUtils.INTEGRATION_SIMPLE_EVALUATION_CONTEXT_BEAN_NAME);
}
@Override
public SimpleEvaluationContext getObject() throws Exception {
public SimpleEvaluationContext getObject() {
Collection<PropertyAccessor> accessors = getPropertyAccessors().values();
PropertyAccessor[] accessorArray = accessors.toArray(new PropertyAccessor[accessors.size() + 2]);
accessorArray[accessors.size()] = new MapAccessor();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -57,7 +57,7 @@ public class ReleaseStrategyFactoryBean implements FactoryBean<ReleaseStrategy>,
}
@Override
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() {
if (this.target instanceof ReleaseStrategy && !StringUtils.hasText(this.methodName)) {
this.strategy = (ReleaseStrategy) this.target;
return;
@@ -88,7 +88,7 @@ public class ReleaseStrategyFactoryBean implements FactoryBean<ReleaseStrategy>,
}
@Override
public ReleaseStrategy getObject() throws Exception {
public ReleaseStrategy getObject() {
return this.strategy;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -137,7 +137,7 @@ public class SourcePollingChannelAdapterFactoryBean implements FactoryBean<Sourc
}
@Override
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() {
if (this.channelResolver == null) {
this.channelResolver = new BeanFactoryMessageChannelDestinationResolver(this.beanFactory);
}
@@ -256,7 +256,7 @@ public class SourcePollingChannelAdapterFactoryBean implements FactoryBean<Sourc
}
@Override
public void destroy() throws Exception {
public void destroy() {
if (this.adapter != null) {
this.adapter.destroy();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -61,7 +61,7 @@ public class SpelFunctionFactoryBean implements FactoryBean<Method>, Initializin
}
@Override
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() {
this.method = BeanUtils.resolveSignature(this.functionMethodSignature, this.functionClass);
if (this.method == null) {
@@ -74,7 +74,7 @@ public class SpelFunctionFactoryBean implements FactoryBean<Method>, Initializin
}
@Override
public Method getObject() throws Exception {
public Method getObject() {
return this.method;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,17 +36,19 @@ class Disposables implements DisposableBean {
private final List<DisposableBean> disposables = new ArrayList<>();
public void add(DisposableBean... disposables) {
this.disposables.addAll(Arrays.asList(disposables));
@SafeVarargs
@SuppressWarnings("varargs")
public final void add(DisposableBean... disposablesToAdd) {
this.disposables.addAll(Arrays.asList(disposablesToAdd));
}
@Override
public void destroy() throws Exception {
public void destroy() {
this.disposables.forEach(d -> {
try {
d.destroy();
}
catch (Exception e) {
catch (@SuppressWarnings("unused") Exception e) {
// NOSONAR
}
});

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2016 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -54,7 +54,7 @@ class ConverterRegistrar implements InitializingBean, BeanFactoryAware {
}
@Override
public void afterPropertiesSet() throws Exception {
public void afterPropertiesSet() {
Assert.notNull(this.beanFactory, "BeanFactory is required");
ConversionService conversionService = IntegrationUtils.getConversionService(this.beanFactory);
if (conversionService instanceof GenericConversionService) {

View File

@@ -112,14 +112,14 @@ public abstract class AbstractEndpoint extends IntegrationObjectSupport
this.roleController.addLifecycleToRole(this.role, this);
}
catch (NoSuchBeanDefinitionException e) {
catch (@SuppressWarnings("unused") NoSuchBeanDefinitionException e) {
this.logger.trace("No LifecycleRoleController in the context");
}
}
}
@Override
public void destroy() throws Exception { // NOSONAR TODO: remove throws in 5.2
public void destroy() {
if (this.roleController != null) {
this.roleController.removeLifecycle(this);
}

View File

@@ -229,7 +229,7 @@ public abstract class AbstractMessageSource<T> extends AbstractExpressionEvaluat
protected abstract Object doReceive();
@Override
public void destroy() throws Exception {
public void destroy() {
if (this.receiveCounter != null) {
this.receiveCounter.remove();
}

View File

@@ -421,7 +421,7 @@ public class GatewayProxyFactoryBean extends AbstractEndpoint
}
@Override
public Object getObject() throws Exception {
public Object getObject() {
if (this.serviceProxy == null) {
this.onInit();
Assert.notNull(this.serviceProxy, "failed to initialize proxy");
@@ -436,7 +436,7 @@ public class GatewayProxyFactoryBean extends AbstractEndpoint
@Override
@Nullable
public Object invoke(final MethodInvocation invocation) throws Throwable {
public Object invoke(final MethodInvocation invocation) throws Throwable { // NOSONAR
final Class<?> returnType = invocation.getMethod().getReturnType();
if (this.asyncExecutor != null && !Object.class.equals(returnType)) {
Invoker invoker = new Invoker(invocation);
@@ -479,7 +479,7 @@ public class GatewayProxyFactoryBean extends AbstractEndpoint
}
@Nullable
private Object invokeGatewayMethod(MethodInvocation invocation, boolean runningOnCallerThread) throws Exception {
private Object invokeGatewayMethod(MethodInvocation invocation, boolean runningOnCallerThread) {
if (!this.initialized) {
this.afterPropertiesSet();
}

View File

@@ -96,8 +96,8 @@ public abstract class AbstractMessageHandler extends IntegrationObjectSupport
}
@Override
public void registerMetricsCaptor(MetricsCaptor metricsCaptor) {
this.metricsCaptor = metricsCaptor;
public void registerMetricsCaptor(MetricsCaptor metricsCaptorToRegister) {
this.metricsCaptor = metricsCaptorToRegister;
}
@Override
@@ -222,7 +222,7 @@ public abstract class AbstractMessageHandler extends IntegrationObjectSupport
}
protected abstract void handleMessageInternal(Message<?> message) throws Exception;
protected abstract void handleMessageInternal(Message<?> message);
@Override
public void reset() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ public class ExpressionEvaluatingMessageHandler extends AbstractMessageHandler {
}
@Override
protected void handleMessageInternal(Message<?> message) throws Exception {
protected void handleMessageInternal(Message<?> message) {
this.processor.processMessage(message);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -63,8 +63,8 @@ import org.springframework.util.Assert;
* @author Gary Russell
* @author Artem Bilan
*/
public class MessageHandlerChain extends AbstractMessageProducingHandler implements MessageProducer,
CompositeMessageHandler, Lifecycle {
public class MessageHandlerChain extends AbstractMessageProducingHandler
implements CompositeMessageHandler, Lifecycle {
private volatile List<MessageHandler> handlers;
@@ -103,7 +103,7 @@ public class MessageHandlerChain extends AbstractMessageProducingHandler impleme
}
@Override
protected void handleMessageInternal(Message<?> message) throws Exception {
protected void handleMessageInternal(Message<?> message) {
if (!this.initialized) {
this.onInit();
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,13 +20,12 @@ import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.ProxyMethodInvocation;
import org.springframework.integration.context.IntegrationObjectSupport;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
/**
* Base class for {@link MessageHandler} advice classes. Subclasses should provide an
@@ -42,8 +41,6 @@ import org.springframework.messaging.MessageHandler;
public abstract class AbstractRequestHandlerAdvice extends IntegrationObjectSupport
implements MethodInterceptor {
protected final Log logger = LogFactory.getLog(this.getClass());
@Override
public final Object invoke(final MethodInvocation invocation) throws Throwable {
@@ -70,20 +67,17 @@ public abstract class AbstractRequestHandlerAdvice extends IntegrationObjectSupp
return doInvoke(new ExecutionCallback() {
@Override
public Object execute() throws Exception {
public Object execute() {
try {
return invocation.proceed();
}
catch (Exception e) { //NOSONAR - catch necessary so we can wrap Errors
throw e;
}
catch (Throwable e) { //NOSONAR - ok to catch; unwrapped and rethrown below
throw new ThrowableHolderException(e);
}
}
@Override
public Object cloneAndExecute() throws Exception {
public Object cloneAndExecute() {
try {
/*
* If we don't copy the invocation carefully it won't keep a reference to the other
@@ -99,7 +93,7 @@ public abstract class AbstractRequestHandlerAdvice extends IntegrationObjectSupp
}
}
catch (Exception e) { //NOSONAR - catch necessary so we can wrap Errors
throw e;
throw new MessagingException(message, "Failed to handle", e);
}
catch (Throwable e) { //NOSONAR - ok to catch; unwrapped and rethrown below
throw new ThrowableHolderException(e);
@@ -122,9 +116,8 @@ public abstract class AbstractRequestHandlerAdvice extends IntegrationObjectSupp
* @param target The target handler.
* @param message The message that will be sent to the handler.
* @return the result after invoking the {@link MessageHandler}.
* @throws Exception Any Exception.
*/
protected abstract Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception;
protected abstract Object doInvoke(ExecutionCallback callback, Object target, Message<?> message);
/**
* Unwrap the cause of a {@link AbstractRequestHandlerAdvice.ThrowableHolderException}.
@@ -165,9 +158,8 @@ public abstract class AbstractRequestHandlerAdvice extends IntegrationObjectSupp
* Call this for a normal invocation.proceed().
*
* @return The result of the execution.
* @throws Exception Any Exception.
*/
Object execute() throws Exception;
Object execute();
/**
* Call this when it is necessary to clone the invocation before
@@ -175,14 +167,13 @@ public abstract class AbstractRequestHandlerAdvice extends IntegrationObjectSupp
* multiple times - for example in a retry advice.
*
* @return The result of the execution.
* @throws Exception Any Exception.
*/
Object cloneAndExecute() throws Exception;
Object cloneAndExecute();
}
@SuppressWarnings("serial")
private static final class ThrowableHolderException extends RuntimeException {
protected static final class ThrowableHolderException extends RuntimeException {
ThrowableHolderException(Throwable cause) {
super(cause);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -79,7 +79,7 @@ public class ErrorMessageSendingRecoverer extends ErrorMessagePublisher implemen
}
@Override
public Object recover(RetryContext context) throws Exception {
public Object recover(RetryContext context) {
publish(context.getLastThrowable(), context);
return null;
}

View File

@@ -232,9 +232,7 @@ public class ExpressionEvaluatingRequestHandlerAdvice extends AbstractRequestHan
}
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message)
throws Exception { // NOSONAR
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
try {
Object result = callback.execute();
if (this.onSuccessExpression != null) {
@@ -242,7 +240,7 @@ public class ExpressionEvaluatingRequestHandlerAdvice extends AbstractRequestHan
}
return result;
}
catch (Exception e) {
catch (RuntimeException e) {
Exception actualException = unwrapExceptionIfNecessary(e);
if (this.onFailureExpression != null) {
Object evalResult = evaluateFailureExpression(message, actualException);
@@ -251,13 +249,18 @@ public class ExpressionEvaluatingRequestHandlerAdvice extends AbstractRequestHan
}
}
if (!this.trapException) {
throw actualException;
if (e instanceof ThrowableHolderException) { // NOSONAR
throw (ThrowableHolderException) e;
}
else {
throw new ThrowableHolderException(actualException); // NOSONAR lost stack trace
}
}
return null;
}
}
private void evaluateSuccessExpression(Message<?> message) throws Exception { // NOSONAR
private void evaluateSuccessExpression(Message<?> message) {
Object evalResult;
try {
evalResult = this.onSuccessExpression.getValue(prepareEvaluationContextToUse(null), message);
@@ -274,7 +277,7 @@ public class ExpressionEvaluatingRequestHandlerAdvice extends AbstractRequestHan
this.messagingTemplate.send(this.successChannel, resultMessage);
}
if (evalResult instanceof Exception && this.propagateOnSuccessEvaluationFailures) {
throw (Exception) evalResult;
throw new ThrowableHolderException((Exception) evalResult);
}
}

View File

@@ -119,7 +119,7 @@ public class RateLimiterRequestHandlerAdvice extends AbstractRequestHandlerAdvic
}
/**
* Get a {@link RateLimiter} which is configured for this advice.
* Get the {@link RateLimiter} which is configured for this advice.
* @return the {@link RateLimiter} for this advice.
*/
public RateLimiter getRateLimiter() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2017 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -51,7 +51,7 @@ public class RequestHandlerCircuitBreakerAdvice extends AbstractRequestHandlerAd
}
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
AdvisedMetadata metadata = this.metadataMap.get(target);
if (metadata == null) {
this.metadataMap.putIfAbsent(target, new AdvisedMetadata());
@@ -72,7 +72,12 @@ public class RequestHandlerCircuitBreakerAdvice extends AbstractRequestHandlerAd
catch (Exception e) {
metadata.getFailures().incrementAndGet();
metadata.setLastFailure(System.currentTimeMillis());
throw this.unwrapExceptionIfNecessary(e);
if (e instanceof ThrowableHolderException) { // NOSONAR
throw (ThrowableHolderException) e;
}
else {
throw new ThrowableHolderException(e);
}
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -42,15 +42,20 @@ import org.springframework.util.Assert;
public class RequestHandlerRetryAdvice extends AbstractRequestHandlerAdvice
implements RetryListener {
private volatile RetryTemplate retryTemplate = new RetryTemplate();
private RetryTemplate retryTemplate = new RetryTemplate();
private volatile RecoveryCallback<Object> recoveryCallback;
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;
/**
* Set the retry template. Cause traversal should be enabled in the retry policy
* because user exceptions may be wrapped in a {@link MessagingException}.
* @param retryTemplate the retry template.
*/
public void setRetryTemplate(RetryTemplate retryTemplate) {
Assert.notNull(retryTemplate, "'retryTemplate' cannot be null");
this.retryTemplate = retryTemplate;
@@ -72,8 +77,7 @@ public class RequestHandlerRetryAdvice extends AbstractRequestHandlerAdvice
}
@Override
protected Object doInvoke(final ExecutionCallback callback, Object target, final Message<?> message)
throws Exception {
protected Object doInvoke(final ExecutionCallback callback, Object target, final Message<?> message) {
RetryState retryState = null;
retryState = this.retryStateGenerator.determineRetryState(message);
messageHolder.set(message);
@@ -87,8 +91,11 @@ public class RequestHandlerRetryAdvice extends AbstractRequestHandlerAdvice
}
throw e;
}
catch (ThrowableHolderException e) { // NOSONAR catch and rethrow
throw e;
}
catch (Exception e) {
throw new MessagingException(message, "Failed to invoke handler", unwrapExceptionIfNecessary(e));
throw new ThrowableHolderException(e);
}
finally {
messageHolder.remove();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2018 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -58,7 +58,7 @@ public class MapArgumentResolver extends AbstractExpressionEvaluator
@Override
@SuppressWarnings("unchecked")
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
public Object resolveArgument(MethodParameter parameter, Message<?> message) {
Object payload = message.getPayload();
if (Properties.class.isAssignableFrom(parameter.getParameterType())) {
Map<String, Object> map = message.getHeaders();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2018 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -50,7 +50,7 @@ public class PayloadExpressionArgumentResolver extends AbstractExpressionEvaluat
}
@Override
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
public Object resolveArgument(MethodParameter parameter, Message<?> message) {
Expression expression = this.expressionCache.get(parameter);
if (expression == null) {
Payload ann = parameter.getParameterAnnotation(Payload.class);

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2017-2018 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -55,7 +55,7 @@ public class PayloadsArgumentResolver extends AbstractExpressionEvaluator
@Override
@SuppressWarnings("unchecked")
public Object resolveArgument(MethodParameter parameter, Message<?> message) throws Exception {
public Object resolveArgument(MethodParameter parameter, Message<?> message) {
Object payload = message.getPayload();
Assert.state(payload instanceof Collection,
"This Argument Resolver support only messages with payload as Collection<Message<?>>");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2018 the original author or authors.
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -29,6 +29,6 @@ import org.springframework.messaging.Message;
public interface OutboundMessageMapper<T> {
@Nullable
T fromMessage(Message<?> message) throws Exception;
T fromMessage(Message<?> message) throws Exception; // NOSONAR
}

View File

@@ -16,8 +16,14 @@
package org.springframework.integration.util;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* Chained utility methods to simplify some Java repetitive code. Obtain a reference to
* the singleton {@link #INSTANCE} and then chain calls to the utility methods.
@@ -67,4 +73,103 @@ public final class JavaUtils {
return this;
}
/**
* Invoke {@link Consumer#accept(Object)} with the value if it is not null or empty.
* @param value the value.
* @param consumer the consumer.
* @return this.
* @since 5.2
*/
public JavaUtils acceptIfHasText(String value, Consumer<String> consumer) {
if (StringUtils.hasText(value)) {
consumer.accept(value);
}
return this;
}
/**
* Invoke {@link Consumer#accept(Object)} with the value if it is not null or empty.
* @param value the value.
* @param consumer the consumer.
* @param <T> the value type.
* @return this.
* @since 5.2
*/
public <T> JavaUtils acceptIfNotEmpty(List<T> value, Consumer<List<T>> consumer) {
if (!CollectionUtils.isEmpty(value)) {
consumer.accept(value);
}
return this;
}
/**
* Invoke {@link Consumer#accept(Object)} with the value if it is not null or empty.
* @param value the value.
* @param consumer the consumer.
* @param <T> the value type.
* @return this.
* @since 5.2
*/
public <T> JavaUtils acceptIfNotEmpty(T[] value, Consumer<T[]> consumer) {
if (!ObjectUtils.isEmpty(value)) {
consumer.accept(value);
}
return this;
}
/**
* Invoke {@link BiConsumer#accept(Object, Object)} with the arguments if the
* condition is true.
* @param condition the condition.
* @param t1 the first consumer argument
* @param t2 the second consumer argument
* @param consumer the consumer.
* @param <T1> the first argument type.
* @param <T2> the second argument type.
* @return this.
* @since 5.2
*/
public <T1, T2> JavaUtils acceptIfCondition(boolean condition, T1 t1, T2 t2, BiConsumer<T1, T2> consumer) {
if (condition) {
consumer.accept(t1, t2);
}
return this;
}
/**
* Invoke {@link BiConsumer#accept(Object, Object)} with the arguments if the t2
* argument is not null.
* @param t1 the first argument
* @param t2 the second consumer argument
* @param consumer the consumer.
* @param <T1> the first argument type.
* @param <T2> the second argument type.
* @return this.
* @since 5.2
*/
public <T1, T2> JavaUtils acceptIfNotNull(T1 t1, T2 t2, BiConsumer<T1, T2> consumer) {
if (t2 != null) {
consumer.accept(t1, t2);
}
return this;
}
/**
* Invoke {@link BiConsumer#accept(Object, Object)} with the arguments if the value
* argument is not null or empty.
* @param t1 the first consumer argument.
* @param value the second consumer argument
* @param <T> the first argument type.
* @param consumer the consumer.
* @return this.
* @since 5.2
*/
public <T> JavaUtils acceptIfHasText(T t1, String value, BiConsumer<T, String> consumer) {
if (StringUtils.hasText(value)) {
consumer.accept(t1, value);
}
return this;
}
}

View File

@@ -190,7 +190,7 @@ public class FilterParserTests {
public static class FooFilter 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 callback.execute();
}

View File

@@ -273,7 +273,7 @@ public class FilterAnnotationPostProcessorTests {
public static class TestAdvice extends AbstractRequestHandlerAdvice {
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
return callback.execute();
}

View File

@@ -395,7 +395,7 @@ public class MessagingAnnotationPostProcessorTests {
public static class ServiceActivatorAdvice extends AbstractRequestHandlerAdvice {
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
return callback.execute() + " advised";
}

View File

@@ -258,7 +258,7 @@ public class EnricherParserTests {
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 callback.execute();
}

View File

@@ -146,7 +146,7 @@ public class EnricherParserTests4 {
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 callback.execute();
}

View File

@@ -279,7 +279,7 @@ public class ServiceActivatorParserTests {
public static class BarAdvice extends AbstractRequestHandlerAdvice {
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
callback.execute();
return "bar";
}

View File

@@ -375,9 +375,7 @@ public class TransformerTests {
return new AbstractRequestHandlerAdvice() {
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message)
throws Exception {
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
adviceChannel().send(message);
return callback.execute();
}

View File

@@ -146,7 +146,7 @@ public class AdvisedMessageHandlerTests {
adviceChain.add(new AbstractRequestHandlerAdvice() {
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
compName.set(((AbstractReplyProducingMessageHandler.RequestHandler) target).getAdvisedHandler()
.getComponentName());
return callback.execute();
@@ -734,7 +734,7 @@ public class AdvisedMessageHandlerTests {
adviceChain.add(new AbstractRequestHandlerAdvice() {
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
outerCounter.incrementAndGet();
return callback.execute();
}
@@ -814,14 +814,18 @@ public class AdvisedMessageHandlerTests {
AbstractRequestHandlerAdvice advice = new AbstractRequestHandlerAdvice() {
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
Object result;
try {
result = callback.execute();
}
catch (Exception e) {
// should not be unwrapped because the cause is a Throwable
throw this.unwrapExceptionIfNecessary(e);
if (e instanceof ThrowableHolderException) {
throw (ThrowableHolderException) e;
}
else {
throw new ThrowableHolderException(e);
}
}
return result;
}
@@ -882,7 +886,7 @@ public class AdvisedMessageHandlerTests {
Advice advice = new AbstractRequestHandlerAdvice() {
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
called.set(true);
return callback.execute();
}
@@ -938,7 +942,7 @@ public class AdvisedMessageHandlerTests {
adviceChain.add(new AbstractRequestHandlerAdvice() {
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
Object result = callback.execute();
discardedWithinAdvice.set(discardChannel.receive(0));
return result;
@@ -963,7 +967,7 @@ public class AdvisedMessageHandlerTests {
adviceChain.add(new AbstractRequestHandlerAdvice() {
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
Object result = callback.execute();
discardedWithinAdvice.set(discardChannel.receive(0));
adviceCalled.set(true);
@@ -1015,9 +1019,8 @@ public class AdvisedMessageHandlerTests {
Map<Class<? extends Throwable>, Boolean> retryableExceptions = new HashMap<Class<? extends Throwable>, Boolean>();
retryableExceptions.put(MyException.class, retryForMyException);
retryableExceptions.put(MessagingException.class, true);
retryTemplate.setRetryPolicy(new SimpleRetryPolicy(3, retryableExceptions));
retryTemplate.setRetryPolicy(new SimpleRetryPolicy(3, retryableExceptions, true));
advice.setRetryTemplate(retryTemplate);

View File

@@ -161,7 +161,7 @@ public class IdempotentReceiverTests {
private int adviceCalled;
@Override
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) throws Exception {
protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
adviceCalled++;
return callback.execute();
}

View File

@@ -96,7 +96,7 @@ public class TransformerContextTests {
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 callback.execute();
}