Use LogAccessor from SF

* Change main classes to use a `LogAccessor` API to simplify code flow
* Fix tests according `LogAccessor` property
* Fix some Sonar smells
This commit is contained in:
Artem Bilan
2020-10-06 13:56:50 -04:00
parent a66e82b0aa
commit c7ff99a4e8
95 changed files with 1165 additions and 1432 deletions

View File

@@ -506,9 +506,7 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP
Assert.state(correlationKey != null,
"Null correlation not allowed. Maybe the CorrelationStrategy is failing?");
if (this.logger.isDebugEnabled()) {
this.logger.debug("Handling message with correlationKey [" + correlationKey + "]: " + message);
}
this.logger.debug(() -> "Handling message with correlationKey [" + correlationKey + "]: " + message);
UUID groupIdUuid = UUIDConverter.getUUID(correlationKey);
Lock lock = this.lockRegistry.obtain(groupIdUuid.toString());
@@ -540,9 +538,8 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP
}
if (!messageGroup.isComplete() && messageGroup.canAdd(message)) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("Adding message to group [ " + messageGroup + "]");
}
MessageGroup messageGroupToLog = messageGroup;
this.logger.trace(() -> "Adding message to group [ " + messageGroupToLog + "]");
messageGroup = store(correlationKey, message);
if (this.releaseStrategy.canRelease(messageGroup)) {
@@ -575,9 +572,9 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP
ScheduledFuture<?> scheduledFuture = this.expireGroupScheduledFutures.remove(groupIdUuid);
if (scheduledFuture != null) {
boolean canceled = scheduledFuture.cancel(mayInterruptIfRunning);
if (canceled && this.logger.isDebugEnabled()) {
this.logger.debug("Cancel 'ScheduledFuture' for MessageGroup with Correlation Key [ "
+ correlationKey + "].");
if (canceled) {
this.logger.debug(() ->
"Cancel 'ScheduledFuture' for MessageGroup with Correlation Key [ " + correlationKey + "].");
}
}
}
@@ -607,9 +604,7 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP
groupNow.getLastModified()
<= (System.currentTimeMillis() - this.minimumTimeoutForEmptyGroups);
if (removeGroup) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Removing empty group: " + groupUuid);
}
this.logger.debug(() -> "Removing empty group: " + groupUuid);
remove(messageGroup);
}
}
@@ -619,18 +614,14 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Thread was interrupted while trying to obtain lock."
+ "Rescheduling empty MessageGroup [ " + groupId + "] for removal.");
}
this.logger.debug(() -> "Thread was interrupted while trying to obtain lock."
+ "Rescheduling empty MessageGroup [ " + groupId + "] for removal.");
removeEmptyGroupAfterTimeout(messageGroup, timeout);
}
}, new Date(System.currentTimeMillis() + timeout));
if (this.logger.isDebugEnabled()) {
this.logger.debug("Schedule empty MessageGroup [ " + groupId + "] for removal.");
}
this.logger.debug(() -> "Schedule empty MessageGroup [ " + groupId + "] for removal.");
this.expireGroupScheduledFutures.put(groupUuid, scheduledFuture);
}
@@ -651,18 +642,17 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP
try {
processForceRelease(groupId, timestamp, lastModified);
}
catch (MessageDeliveryException e) {
catch (MessageDeliveryException ex) {
if (AbstractCorrelatingMessageHandler.this.logger.isWarnEnabled()) {
AbstractCorrelatingMessageHandler.this.logger.warn("The MessageGroup ["
+ groupId + "] is rescheduled by the reason of:", e);
AbstractCorrelatingMessageHandler.this.logger.warn(ex,
() -> "The MessageGroup [" + groupId
+ "] is rescheduled by the reason of:");
}
scheduleGroupToForceComplete(groupId);
}
}, new Date(System.currentTimeMillis() + groupTimeout));
if (this.logger.isDebugEnabled()) {
this.logger.debug("Schedule MessageGroup [ " + messageGroup + "] to 'forceComplete'.");
}
this.logger.debug(() -> "Schedule MessageGroup [ " + messageGroup + "] to 'forceComplete'.");
this.expireGroupScheduledFutures.put(UUIDConverter.getUUID(groupId), scheduledFuture);
}
else {
@@ -774,26 +764,22 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP
*/
removeGroup =
lastModifiedNow <= (System.currentTimeMillis() - this.minimumTimeoutForEmptyGroups);
if (removeGroup && this.logger.isDebugEnabled()) {
this.logger.debug("Removing empty group: " + correlationKey);
if (removeGroup) {
this.logger.debug(() -> "Removing empty group: " + correlationKey);
}
}
}
else {
removeGroup = false;
if (this.logger.isDebugEnabled()) {
this.logger.debug("Group expiry candidate (" + correlationKey +
") has changed - it may be reconsidered for a future expiration");
}
this.logger.debug(() -> "Group expiry candidate (" + correlationKey +
") has changed - it may be reconsidered for a future expiration");
}
}
catch (MessageDeliveryException e) {
removeGroup = false;
if (this.logger.isDebugEnabled()) {
this.logger.debug("Group expiry candidate (" + correlationKey +
") has been affected by MessageDeliveryException - " +
"it may be reconsidered for a future expiration one more time");
}
this.logger.debug(() -> "Group expiry candidate (" + correlationKey +
") has been affected by MessageDeliveryException - " +
"it may be reconsidered for a future expiration one more time");
throw e;
}
finally {
@@ -832,22 +818,16 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP
}
protected void expireGroup(Object correlationKey, MessageGroup group, Lock lock) {
if (this.logger.isInfoEnabled()) {
this.logger.info("Expiring MessageGroup with correlationKey[" + correlationKey + "]");
}
this.logger.info(() -> "Expiring MessageGroup with correlationKey[" + correlationKey + "]");
if (this.sendPartialResultOnExpiry) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Prematurely releasing partially complete group with key ["
+ correlationKey + "] to: " + getOutputChannel());
}
this.logger.debug(() -> "Prematurely releasing partially complete group with key ["
+ correlationKey + "] to: " + getOutputChannel());
completeGroup(correlationKey, group, lock);
}
else {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Discarding messages of partially complete group with key ["
+ correlationKey + "] to: "
+ (this.discardChannelName != null ? this.discardChannelName : this.discardChannel));
}
this.logger.debug(() -> "Discarding messages of partially complete group with key ["
+ correlationKey + "] to: "
+ (this.discardChannelName != null ? this.discardChannelName : this.discardChannel));
if (this.releaseLockBeforeSend) {
lock.unlock();
}
@@ -876,9 +856,7 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP
Collection<Message<?>> partialSequence = null;
Object result;
try {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Completing group with correlationKey [" + correlationKey + "]");
}
this.logger.debug(() -> "Completing group with correlationKey [" + correlationKey + "]");
result = this.outputProcessor.processMessageGroup(group);
if (result instanceof Collection<?>) {
@@ -894,13 +872,13 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP
else if (!(result instanceof Message<?>)) {
messageBuilder =
getMessageBuilderFactory()
.withPayload(result)
.copyHeaders(message.getHeaders());
.withPayload(result)
.copyHeaders(message.getHeaders());
}
else if (compareSequences((Message<?>) result, message)) {
messageBuilder =
getMessageBuilderFactory()
.fromMessage((Message<?>) result);
.fromMessage((Message<?>) result);
}
result = messageBuilder != null ? messageBuilder.popSequenceDetails() : result;
}
@@ -923,7 +901,7 @@ public abstract class AbstractCorrelatingMessageHandler extends AbstractMessageP
protected void verifyResultCollectionConsistsOfMessages(Collection<?> elements) {
Class<?> commonElementType = CollectionUtils.findCommonElementType(elements);
Assert.isAssignable(Message.class, commonElementType,
Assert.isAssignable(Message.class, commonElementType, () ->
"The expected collection of Messages contains non-Message element: " + commonElementType);
}

View File

@@ -213,7 +213,7 @@ public abstract class AbstractExecutorChannel extends AbstractSubscribableChanne
this.delegate.getMessageHandler(), ex);
}
catch (Throwable ex2) { //NOSONAR
logger.error("Exception from afterMessageHandled in " + interceptor, ex2);
logger.error(ex2, () -> "Exception from afterMessageHandled in " + interceptor);
}
}
}

View File

@@ -26,10 +26,9 @@ import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.commons.logging.Log;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.core.OrderComparator;
import org.springframework.core.log.LogAccessor;
import org.springframework.integration.IntegrationPattern;
import org.springframework.integration.IntegrationPatternType;
import org.springframework.integration.context.IntegrationContextUtils;
@@ -68,7 +67,7 @@ import org.springframework.util.StringUtils;
public abstract class AbstractMessageChannel extends IntegrationObjectSupport
implements MessageChannel, TrackableComponent, InterceptableChannel, IntegrationManagement, IntegrationPattern {
protected final ChannelInterceptorList interceptors = new ChannelInterceptorList(logger); // NOSONAR
protected final ChannelInterceptorList interceptors = new ChannelInterceptorList(this.logger); // NOSONAR
private final Comparator<Object> orderComparator = new OrderComparator();
@@ -152,7 +151,7 @@ public abstract class AbstractMessageChannel extends IntegrationObjectSupport
*/
@Override
public void setInterceptors(List<ChannelInterceptor> interceptors) {
Collections.sort(interceptors, this.orderComparator);
interceptors.sort(this.orderComparator);
this.interceptors.set(interceptors);
}
@@ -270,7 +269,7 @@ public abstract class AbstractMessageChannel extends IntegrationObjectSupport
*/
@Override
public boolean send(Message<?> message) {
return this.send(message, -1);
return send(message, -1);
}
/**
@@ -301,7 +300,7 @@ public abstract class AbstractMessageChannel extends IntegrationObjectSupport
SampleFacade sample = null;
try {
message = convertPayloadIfNecessary(message);
boolean debugEnabled = this.loggingEnabled && logger.isDebugEnabled();
boolean debugEnabled = this.loggingEnabled && this.logger.isDebugEnabled();
if (debugEnabled) {
logger.debug("preSend on channel '" + this + "', message: " + message);
}
@@ -338,7 +337,7 @@ public abstract class AbstractMessageChannel extends IntegrationObjectSupport
interceptorList.afterSendCompletion(message, this, sent, ex, interceptorStack);
}
throw IntegrationUtils.wrapInDeliveryExceptionIfNecessary(message,
() -> "failed to send Message to channel '" + this.getComponentName() + "'", ex);
() -> "failed to send Message to channel '" + getComponentName() + "'", ex);
}
}
@@ -394,7 +393,7 @@ public abstract class AbstractMessageChannel extends IntegrationObjectSupport
}
}
}
throw new MessageDeliveryException(message, "Channel '" + this.getComponentName() +
throw new MessageDeliveryException(message, "Channel '" + getComponentName() +
"' expected one of the following data types [" +
StringUtils.arrayToCommaDelimitedString(this.datatypes) +
"], but received [" + message.getPayload().getClass() + "]");
@@ -429,11 +428,11 @@ public abstract class AbstractMessageChannel extends IntegrationObjectSupport
protected final List<ChannelInterceptor> interceptors = new CopyOnWriteArrayList<>(); // NOSONAR
private final Log logger;
private final LogAccessor logger;
private int size;
public ChannelInterceptorList(Log logger) {
public ChannelInterceptorList(LogAccessor logger) {
this.logger = logger;
}
@@ -469,10 +468,8 @@ public abstract class AbstractMessageChannel extends IntegrationObjectSupport
Message<?> previous = message;
message = interceptor.preSend(message, channel);
if (message == null) {
if (this.logger.isDebugEnabled()) {
this.logger.debug(interceptor.getClass().getSimpleName()
+ " returned null from preSend, i.e. precluding the send.");
}
this.logger.debug(() -> interceptor.getClass().getSimpleName()
+ " returned null from preSend, i.e. precluding the send.");
afterSendCompletion(previous, channel, false, null, interceptorStack);
return null;
}
@@ -499,7 +496,7 @@ public abstract class AbstractMessageChannel extends IntegrationObjectSupport
interceptor.afterSendCompletion(message, channel, sent, ex);
}
catch (Exception ex2) {
this.logger.error("Exception from afterSendCompletion in " + interceptor, ex2);
this.logger.error(ex2, () -> "Exception from afterSendCompletion in " + interceptor);
}
}
}
@@ -535,14 +532,13 @@ public abstract class AbstractMessageChannel extends IntegrationObjectSupport
@Nullable Exception ex, @Nullable Deque<ChannelInterceptor> interceptorStack) {
if (interceptorStack != null) {
for (Iterator<ChannelInterceptor> iterator = interceptorStack.descendingIterator(); iterator
.hasNext(); ) {
ChannelInterceptor interceptor = iterator.next();
for (Iterator<ChannelInterceptor> iter = interceptorStack.descendingIterator(); iter.hasNext(); ) {
ChannelInterceptor interceptor = iter.next();
try {
interceptor.afterReceiveCompletion(message, channel, ex);
}
catch (Exception ex2) {
this.logger.error("Exception from afterReceiveCompletion in " + interceptor, ex2);
this.logger.error(ex2, () -> "Exception from afterReceiveCompletion in " + interceptor);
}
}
}

View File

@@ -122,7 +122,7 @@ public class FluxMessageChannel extends AbstractMessageChannel
}
}
catch (Exception ex) {
logger.warn("Error during processing event: " + message, ex);
logger.warn(ex, () -> "Error during processing event: " + message);
}
})
.subscribe());

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.
@@ -19,9 +19,6 @@ package org.springframework.integration.context;
import java.util.Properties;
import java.util.UUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
@@ -34,6 +31,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.support.DefaultConversionService;
import org.springframework.core.log.LogAccessor;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
@@ -77,7 +75,7 @@ public abstract class IntegrationObjectSupport implements BeanNameAware, NamedCo
/**
* Logger that is available to subclasses
*/
protected final Log logger = LogFactory.getLog(getClass()); // NOSONAR protected
protected final LogAccessor logger = new LogAccessor(getClass()); // NOSONAR protected
private final ConversionService defaultConversionService = DefaultConversionService.getSharedInstance();
@@ -264,8 +262,8 @@ public abstract class IntegrationObjectSupport implements BeanNameAware, NamedCo
public ConversionService getConversionService() {
if (this.conversionService == null && this.beanFactory != null) {
this.conversionService = IntegrationUtils.getConversionService(this.beanFactory);
if (this.conversionService == null && this.logger.isDebugEnabled()) {
this.logger.debug("Unable to attempt conversion of Message payload types. Component '" +
if (this.conversionService == null) {
this.logger.debug(() -> "Unable to attempt conversion of Message payload types. Component '" +
getComponentName() + "' has no explicit ConversionService reference, " +
"and there is no 'integrationConversionService' bean within the context.");
}

View File

@@ -234,7 +234,7 @@ public abstract class MessageProducerSupport extends AbstractEndpoint implements
sendMessage(message);
}
catch (Exception ex) {
logger.error("Error sending a message: " + message, ex);
logger.error(ex, () -> "Error sending a message: " + message);
}
})
.subscribe();

View File

@@ -184,11 +184,9 @@ public class PollingConsumer extends AbstractPollingEndpoint implements Integrat
if (interceptor instanceof ExecutorChannelInterceptor) {
ExecutorChannelInterceptor executorInterceptor = (ExecutorChannelInterceptor) interceptor;
theMessage = executorInterceptor.beforeHandle(theMessage, this.inputChannel, this.handler);
if (message == null) {
if (logger.isDebugEnabled()) {
logger.debug(executorInterceptor.getClass().getSimpleName()
+ " returned null from beforeHandle, i.e. precluding the send.");
}
if (theMessage == null) {
logger.debug(() -> executorInterceptor.getClass().getSimpleName()
+ " returned null from beforeHandle, i.e. precluding the send.");
triggerAfterMessageHandled(null, null, interceptorStack);
return null;
}
@@ -200,6 +198,7 @@ public class PollingConsumer extends AbstractPollingEndpoint implements Integrat
private void triggerAfterMessageHandled(Message<?> message, Exception ex,
Deque<ExecutorChannelInterceptor> interceptorStack) {
Iterator<ExecutorChannelInterceptor> iterator = interceptorStack.descendingIterator();
while (iterator.hasNext()) {
ExecutorChannelInterceptor interceptor = iterator.next();
@@ -207,7 +206,7 @@ public class PollingConsumer extends AbstractPollingEndpoint implements Integrat
interceptor.afterMessageHandled(message, this.inputChannel, this.handler, ex);
}
catch (Throwable ex2) { //NOSONAR
logger.error("Exception from afterMessageHandled in " + interceptor, ex2);
logger.error(ex2, () -> "Exception from afterMessageHandled in " + interceptor);
}
}
}

View File

@@ -481,8 +481,8 @@ public abstract class AbstractMessageProducingHandler extends AbstractMessageHan
result = new MessageHandlingException(requestMessage, ex);
}
if (errorChannel == null) {
logger.error("Async exception received and no 'errorChannel' header exists and no default "
+ "'errorChannel' found", result);
logger.error(result,
"Async exception received and no 'errorChannel' header exists and no default 'errorChannel' found");
}
else {
try {
@@ -492,7 +492,7 @@ public abstract class AbstractMessageProducingHandler extends AbstractMessageHan
Exception exceptionToLog =
IntegrationUtils.wrapInHandlingExceptionIfNecessary(requestMessage,
() -> "failed to send error message in the [" + this + ']', e);
logger.error("Failed to send async reply", exceptionToLog);
logger.error(exceptionToLog, "Failed to send async reply");
}
}
}
@@ -538,7 +538,7 @@ public abstract class AbstractMessageProducingHandler extends AbstractMessageHan
exceptionToLogAndSend = new MessagingException(replyMessage, exceptionToLogAndSend);
}
}
logger.error("Failed to send async reply: " + result.toString(), exceptionToLogAndSend);
logger.error(exceptionToLogAndSend, () -> "Failed to send async reply: " + result.toString());
onFailure(exceptionToLogAndSend);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2019 the original author or authors.
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -49,8 +49,8 @@ public abstract class AbstractReactiveMessageHandler extends MessageHandlerSuppo
messageToUse = message;
}
return handleMessageInternal(messageToUse)
.doOnError(e -> this.logger.error(
"An error occurred in message handler [" + this + "] on message [" + messageToUse + "]", e));
.doOnError((ex) -> this.logger.error(ex, () ->
"An error occurred in message handler [" + this + "] on message [" + messageToUse + "]"));
}
protected abstract Mono<Void> handleMessageInternal(Message<?> message);

View File

@@ -298,8 +298,8 @@ public class DelayHandler extends AbstractReplyProducingMessageHandler implement
else {
Assert.isInstanceOf(MessageStore.class, this.messageStore);
}
this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(this.getBeanFactory());
this.releaseHandler = this.createReleaseMessageTask();
this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory());
this.releaseHandler = createReleaseMessageTask();
}
private MessageHandler createReleaseMessageTask() {
@@ -343,7 +343,9 @@ public class DelayHandler extends AbstractReplyProducingMessageHandler implement
}
// no delay
return delayed ? ((DelayedMessageWrapper) requestMessage.getPayload()).getOriginal() : requestMessage;
return delayed
? ((DelayedMessageWrapper) requestMessage.getPayload()).getOriginal()
: requestMessage;
}
private long determineDelayForMessage(Message<?> message) {
@@ -365,15 +367,18 @@ public class DelayHandler extends AbstractReplyProducingMessageHandler implement
Object delayValue = null;
try {
delayValue = this.delayExpression.getValue(this.evaluationContext,
delayedMessageWrapper != null ? delayedMessageWrapper.getOriginal() : message);
delayedMessageWrapper != null
? delayedMessageWrapper.getOriginal()
: message);
}
catch (EvaluationException e) {
delayValueException = e;
}
if (delayValue instanceof Date) {
long current = delayedMessageWrapper != null
? delayedMessageWrapper.getRequestDate()
: System.currentTimeMillis();
long current =
delayedMessageWrapper != null
? delayedMessageWrapper.getRequestDate()
: System.currentTimeMillis();
delay = ((Date) delayValue).getTime() - current;
}
else if (delayValue != null) {
@@ -392,22 +397,19 @@ public class DelayHandler extends AbstractReplyProducingMessageHandler implement
private void handleDelayValueException(Exception delayValueException) {
if (this.ignoreExpressionFailures) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to get delay value from 'delayExpression': " +
delayValueException.getMessage() +
". Will fall back to default delay: " + this.defaultDelay);
}
logger.debug(() -> "Failed to get delay value from 'delayExpression': " +
delayValueException.getMessage() +
". Will fall back to default delay: " + this.defaultDelay);
}
else {
throw new IllegalStateException("Error occurred during 'delay' value determination",
delayValueException);
throw new IllegalStateException("Error occurred during 'delay' value determination", delayValueException);
}
}
private void releaseMessageAfterDelay(final Message<?> message, long delay) {
Message<?> delayedMessage = message;
DelayedMessageWrapper messageWrapper = null;
DelayedMessageWrapper messageWrapper;
if (message.getPayload() instanceof DelayedMessageWrapper) {
messageWrapper = (DelayedMessageWrapper) message.getPayload();
}
@@ -445,10 +447,8 @@ public class DelayHandler extends AbstractReplyProducingMessageHandler implement
Message<?> theMessage = ((MessageStore) this.messageStore).getMessage(messageId);
if (theMessage == null) {
if (logger.isDebugEnabled()) {
logger.debug("No message in the Message Store for id: " + messageId +
". Likely another instance has already released it.");
}
logger.debug(() -> "No message in the Message Store for id: " + messageId +
". Likely another instance has already released it.");
return null;
}
else {
@@ -471,9 +471,7 @@ public class DelayHandler extends AbstractReplyProducingMessageHandler implement
message);
try {
if (!(getErrorChannel().send(errorMessage))) {
if (this.logger.isDebugEnabled()) {
this.logger.debug("Failed to send error message: " + errorMessage);
}
this.logger.debug(() -> "Failed to send error message: " + errorMessage);
rescheduleForRetry(message, identity);
}
else {
@@ -481,16 +479,12 @@ public class DelayHandler extends AbstractReplyProducingMessageHandler implement
}
}
catch (Exception e1) {
if (this.logger.isDebugEnabled()) {
logger.debug("Error flow threw an exception for message: " + message, e1);
}
logger.debug(e1, () -> "Error flow threw an exception for message: " + message);
rescheduleForRetry(message, identity);
}
}
else {
if (this.logger.isDebugEnabled()) {
logger.debug("Release flow threw an exception for message: " + message, e);
}
logger.debug(e, () -> "Release flow threw an exception for message: " + message);
if (!rescheduleForRetry(message, identity)) {
throw e; // there might be an error handler on the scheduler
}
@@ -500,7 +494,7 @@ public class DelayHandler extends AbstractReplyProducingMessageHandler implement
private boolean rescheduleForRetry(Message<?> message, String identity) {
if (this.deliveries.get(identity).incrementAndGet() >= this.maxAttempts) {
this.logger.error("Discarding; maximum release attempts reached for: " + message);
this.logger.error(() -> "Discarding; maximum release attempts reached for: " + message);
this.deliveries.remove(identity);
return false;
}
@@ -530,8 +524,8 @@ public class DelayHandler extends AbstractReplyProducingMessageHandler implement
}
handleMessageInternal(message);
}
else if (logger.isDebugEnabled()) {
logger.debug("No message in the Message Store to release: " + message +
else {
logger.debug(() -> "No message in the Message Store to release: " + message +
". Likely another instance has already released it.");
}
}

View File

@@ -19,11 +19,11 @@ package org.springframework.integration.handler;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.log.LogAccessor;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.integration.dispatcher.AggregateMessageDeliveryException;
@@ -65,7 +65,7 @@ public class LoggingHandler extends AbstractMessageHandler {
private boolean shouldLogFullMessageSet;
private Log messageLogger = this.logger;
private LogAccessor messageLogger = this.logger;
/**
* Create a LoggingHandler with the given log level (case-insensitive).
@@ -146,7 +146,7 @@ public class LoggingHandler extends AbstractMessageHandler {
public void setLoggerName(String loggerName) {
Assert.hasText(loggerName, "loggerName must not be empty");
this.messageLogger = LogFactory.getLog(loggerName);
this.messageLogger = new LogAccessor(loggerName);
}
/**
@@ -174,38 +174,27 @@ public class LoggingHandler extends AbstractMessageHandler {
this.evaluationContext = ExpressionUtils.createStandardEvaluationContext(getBeanFactory());
}
@Override // NOSONAR
@Override
protected void handleMessageInternal(Message<?> message) {
Supplier<CharSequence> logMessage = () -> createLogMessage(message);
switch (this.level) {
case FATAL:
if (this.messageLogger.isFatalEnabled()) {
this.messageLogger.fatal(createLogMessage(message));
}
this.messageLogger.fatal(logMessage);
break;
case ERROR:
if (this.messageLogger.isErrorEnabled()) {
this.messageLogger.error(createLogMessage(message));
}
this.messageLogger.error(logMessage);
break;
case WARN:
if (this.messageLogger.isWarnEnabled()) {
this.messageLogger.warn(createLogMessage(message));
}
this.messageLogger.warn(logMessage);
break;
case INFO:
if (this.messageLogger.isInfoEnabled()) {
this.messageLogger.info(createLogMessage(message));
}
this.messageLogger.info(logMessage);
break;
case DEBUG:
if (this.messageLogger.isDebugEnabled()) {
this.messageLogger.debug(createLogMessage(message));
}
this.messageLogger.debug(logMessage);
break;
case TRACE:
if (this.messageLogger.isTraceEnabled()) {
this.messageLogger.trace(createLogMessage(message));
}
this.messageLogger.trace(logMessage);
break;
default:
throw new IllegalStateException("Level '" + this.level + "' is not supported");
@@ -213,11 +202,11 @@ public class LoggingHandler extends AbstractMessageHandler {
}
@Nullable
private Object createLogMessage(Message<?> message) {
private String createLogMessage(Message<?> message) {
Object logMessage = this.expression.getValue(this.evaluationContext, message);
return logMessage instanceof Throwable
? createLogMessage((Throwable) logMessage)
: logMessage;
: Objects.toString(logMessage);
}
private String createLogMessage(Throwable throwable) {

View File

@@ -172,7 +172,6 @@ public class JsonToObjectTransformer extends AbstractTransformer implements Bean
Object result;
try {
result = this.jsonObjectMapper.fromJson(message.getPayload(), valueType);
}
catch (IOException e) {
throw new UncheckedIOException(e);
@@ -197,8 +196,8 @@ public class JsonToObjectTransformer extends AbstractTransformer implements Bean
}
catch (Exception ex) {
if (ex.getCause() instanceof ClassNotFoundException) {
logger.debug("Cannot build a ResolvableType from the request message '" + message +
"' evaluating expression '" + this.valueTypeExpression.getExpressionString() + "'", ex);
logger.debug(ex, () -> "Cannot build a ResolvableType from the request message '" + message +
"' evaluating expression '" + this.valueTypeExpression.getExpressionString() + "'");
return null;
}
else {

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.
@@ -213,11 +213,11 @@ public abstract class AbstractMessageRouter extends AbstractMessageHandler imple
this.messagingTemplate.send(channel, messageToSend);
return true;
}
catch (MessagingException e) {
catch (MessagingException ex) {
if (!this.ignoreSendFailures) {
throw e;
throw ex;
}
this.logger.debug("Send failure ignored", e);
this.logger.debug(ex, "Send failure ignored");
return false;
}
}

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.
@@ -136,33 +136,27 @@ public class ExpressionEvaluatingTransactionSynchronizationProcessor extends Int
Message<?> message = holder.getMessage();
if (message != null) {
if (expression != null) {
if (logger.isDebugEnabled()) {
logger.debug("Evaluating " + expressionType + " expression: '" + expression.getExpressionString()
+ "' on " + message);
}
logger.debug(() -> "Evaluating " + expressionType + " expression: '" + expression.getExpressionString()
+ "' on " + message);
EvaluationContext evaluationContextToUse = prepareEvaluationContextToUse(holder);
Object value = expression.getValue(evaluationContextToUse, message);
if (value != null && messageChannel != null) {
sendMessageForExpressionResult(value, message.getHeaders(), messageChannel, expressionType);
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Expression evaluation returned null");
}
logger.trace("Expression evaluation returned null");
}
}
else if (messageChannel != null) {
if (logger.isDebugEnabled()) {
logger.debug("Sending received message to " + messageChannel + " as part of '" +
expressionType + "' transaction synchronization");
}
logger.debug(() -> "Sending received message to " + messageChannel + " as part of '" +
expressionType + "' transaction synchronization");
try {
// rollback will be initiated if any of the previous sync operations fail (e.g., beforeCommit)
// this means that this method will be called without explicit configuration thus no channel
sendMessage(messageChannel, message);
}
catch (Exception e) {
logger.error("Failed to send " + message, e);
catch (Exception ex) {
logger.error(ex, () -> "Failed to send " + message);
}
}
@@ -172,12 +166,9 @@ public class ExpressionEvaluatingTransactionSynchronizationProcessor extends Int
private void sendMessageForExpressionResult(Object value, Map<String, ?> headers,
MessageChannel messageChannel, String expressionType) {
if (logger.isDebugEnabled()) {
logger.debug("Sending expression result message to " + messageChannel + " " +
"as part of '" + expressionType + "' transaction synchronization");
}
Message<?> spelResultMessage = null;
try {
logger.debug(() -> "Sending expression result message to " + messageChannel + " " +
"as part of '" + expressionType + "' transaction synchronization");
Message<?> spelResultMessage;
if (value instanceof Message<?>) {
spelResultMessage = (Message<?>) value;
}
@@ -188,11 +179,11 @@ public class ExpressionEvaluatingTransactionSynchronizationProcessor extends Int
.copyHeaders(headers)
.build();
}
try {
sendMessage(messageChannel, spelResultMessage);
}
catch (Exception e) {
logger.error("Failed to send " + expressionType + " evaluation result " + spelResultMessage, e);
catch (Exception ex) {
logger.error(ex, () -> "Failed to send " + expressionType + " evaluation result " + spelResultMessage);
}
}

View File

@@ -86,9 +86,7 @@ public class SyslogToMapTransformer extends AbstractPayloadTransformer<Object, M
parseMatcherToMap(payload, matcher, map);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Could not decode: " + payload);
}
logger.debug(() -> "Could not decode: " + payload);
map.put(UNDECODED, payload);
}
return map;
@@ -111,10 +109,8 @@ public class SyslogToMapTransformer extends AbstractPayloadTransformer<Object, M
}
map.put(MESSAGE, matcher.group(5)); // NOSONAR
}
catch (Exception e) {
if (logger.isDebugEnabled()) {
logger.debug("Could not decode: " + payload, e);
}
catch (Exception ex) {
logger.debug(ex, () -> "Could not decode: " + payload);
map.clear();
map.put(UNDECODED, payload);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2013-2019 the original author or authors.
* Copyright 2013-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -28,12 +28,13 @@ import org.springframework.messaging.Message;
/**
* @author Mark Fisher
* @author Artem Bilan
*
* @since 3.0
*/
public class ExpressionEvaluatingHeaderValueMessageProcessor<T> extends AbstractHeaderValueMessageProcessor<T>
implements BeanFactoryAware {
private static final ExpressionParser expressionParser = new SpelExpressionParser(new SpelParserConfiguration(
private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser(new SpelParserConfiguration(
true, true));
private final ExpressionEvaluatingMessageProcessor<T> targetProcessor;
@@ -42,7 +43,6 @@ public class ExpressionEvaluatingHeaderValueMessageProcessor<T> extends Abstract
* Create a header value processor for the given Expression and the
* expected type of the expression evaluation result. The expectedType
* may be null if unknown.
*
* @param expression the {@link Expression} to evaluate.
* @param expectedType the type for return value of {@code expression} evaluation result.
*/
@@ -54,12 +54,11 @@ public class ExpressionEvaluatingHeaderValueMessageProcessor<T> extends Abstract
* Create a header value processor for the given expression string and
* the expected type of the expression evaluation result. The
* expectedType may be null if unknown.
*
* @param expressionString the {@link java.lang.String} expression presentation to evaluate.
* @param expectedType the type for return value of {@code expression} evaluation result.
*/
public ExpressionEvaluatingHeaderValueMessageProcessor(String expressionString, Class<T> expectedType) {
Expression expression = expressionParser.parseExpression(expressionString);
Expression expression = EXPRESSION_PARSER.parseExpression(expressionString);
this.targetProcessor = new ExpressionEvaluatingMessageProcessor<T>(expression, expectedType);
}

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.
@@ -16,14 +16,12 @@
package org.springframework.integration.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.expression.BeanFactoryResolver;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.log.LogAccessor;
import org.springframework.expression.EvaluationException;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
@@ -47,7 +45,7 @@ import org.springframework.messaging.Message;
*/
public abstract class AbstractExpressionEvaluator implements BeanFactoryAware, InitializingBean {
protected final Log logger = LogFactory.getLog(this.getClass()); // NOSONAR final
protected final LogAccessor logger = new LogAccessor(this.getClass()); // NOSONAR final
protected static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser();
@@ -129,7 +127,7 @@ public abstract class AbstractExpressionEvaluator implements BeanFactoryAware, I
return evaluateExpression(expression, (Object) message, expectedType);
}
catch (Exception ex) {
this.logger.debug("SpEL Expression evaluation failed with Exception.", ex);
this.logger.debug(ex, "SpEL Expression evaluation failed with Exception.");
Throwable cause = null;
if (ex instanceof EvaluationException) { // NOSONAR
cause = ex.getCause();

View File

@@ -96,7 +96,7 @@ public class BeanFactoryTypeConverter implements TypeConverter, BeanFactoryAware
return canConvert(sourceType, targetType);
}
@Override
@Override // NOSONAR
public Object convertValue(Object value, TypeDescriptor sourceType, TypeDescriptor targetType) {
// Echoes org.springframework.expression.common.ExpressionUtils.convertTypedValue()
if ((targetType.getType() == Void.class || targetType.getType() == Void.TYPE) && value == null) {

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.
@@ -31,9 +31,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.DirectFieldAccessor;
@@ -41,6 +39,7 @@ import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.log.LogAccessor;
import org.springframework.integration.annotation.Poller;
import org.springframework.integration.annotation.Publisher;
import org.springframework.integration.annotation.ServiceActivator;
@@ -58,8 +57,7 @@ import org.springframework.messaging.MessagingException;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
@@ -69,8 +67,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
* @since 4.2
*
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class BarrierMessageHandlerTests {
@@ -173,7 +170,7 @@ public class BarrierMessageHandlerTests {
Map<?, ?> suspensions = TestUtils.getPropertyValue(handler, "suspensions", Map.class);
assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
assertThat(suspensions.size()).as("suspension not removed").isEqualTo(0);
Log logger = spy(TestUtils.getPropertyValue(handler, "logger", Log.class));
LogAccessor logger = spy(TestUtils.getPropertyValue(handler, "logger", LogAccessor.class));
new DirectFieldAccessor(handler).setPropertyValue("logger", logger);
final Message<String> triggerMessage = MessageBuilder.withPayload("bar").setCorrelationId("foo").build();
handler.trigger(triggerMessage);

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,12 +28,12 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.logging.Log;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.log.LogAccessor;
import org.springframework.integration.dispatcher.RoundRobinLoadBalancingStrategy;
import org.springframework.integration.dispatcher.UnicastingDispatcher;
import org.springframework.integration.endpoint.EventDrivenConsumer;
@@ -56,7 +56,7 @@ class DirectChannelTests {
@Test
void testSend() {
DirectChannel channel = new DirectChannel();
Log logger = spy(TestUtils.getPropertyValue(channel, "logger", Log.class));
LogAccessor logger = spy(TestUtils.getPropertyValue(channel, "logger", LogAccessor.class));
when(logger.isDebugEnabled()).thenReturn(true);
new DirectFieldAccessor(channel).setPropertyValue("logger", logger);
ThreadNameExtractingTestTarget target = new ThreadNameExtractingTestTarget();

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.
@@ -27,16 +27,17 @@ import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import org.apache.commons.logging.Log;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.core.log.LogAccessor;
import org.springframework.messaging.MessageHandler;
import org.springframework.util.ReflectionUtils;
/**
* @author Oleg Zhurakousky
* @author Gary Russell
* @author Artem Bilan
*
*/
public class P2pChannelTests {
@@ -53,7 +54,7 @@ public class P2pChannelTests {
* @param channel
*/
private void verifySubscriptions(final AbstractSubscribableChannel channel) {
final Log logger = mock(Log.class);
final LogAccessor logger = mock(LogAccessor.class);
when(logger.isInfoEnabled()).thenReturn(true);
final List<String> logs = new ArrayList<>();
doAnswer(invocation -> {
@@ -96,7 +97,7 @@ public class P2pChannelTests {
final ExecutorChannel channel = new ExecutorChannel(mock(Executor.class));
channel.setBeanName("executorChannel");
final Log logger = mock(Log.class);
final LogAccessor logger = mock(LogAccessor.class);
when(logger.isInfoEnabled()).thenReturn(true);
ReflectionUtils.doWithFields(AbstractMessageChannel.class, field -> {
if ("logger".equals(field.getName())) {
@@ -114,7 +115,7 @@ public class P2pChannelTests {
final PublishSubscribeChannel channel = new PublishSubscribeChannel();
channel.setBeanName("pubSubChannel");
final Log logger = mock(Log.class);
final LogAccessor logger = mock(LogAccessor.class);
when(logger.isInfoEnabled()).thenReturn(true);
ReflectionUtils.doWithFields(AbstractMessageChannel.class, field -> {
if ("logger".equals(field.getName())) {

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.
@@ -17,6 +17,7 @@
package org.springframework.integration.config;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
@@ -25,12 +26,10 @@ import static org.mockito.Mockito.when;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import org.apache.commons.logging.Log;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanFactory;
@@ -38,6 +37,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.log.LogAccessor;
import org.springframework.expression.Expression;
import org.springframework.integration.IntegrationMessageHeaderAccessor;
import org.springframework.integration.MessageRejectedException;
@@ -60,8 +60,7 @@ import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.PollableChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import org.springframework.util.StringUtils;
/**
@@ -72,8 +71,7 @@ import org.springframework.util.StringUtils;
* @author Gunnar Hillert
* @author Gary Russell
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
public class ChainParserTests {
@Autowired
@@ -296,13 +294,13 @@ public class ChainParserTests {
@Test //INT-2275, INT-2958
public void chainWithLoggingChannelAdapter() {
Log logger = mock(Log.class);
final AtomicReference<String> log = new AtomicReference<>();
LogAccessor logger = mock(LogAccessor.class);
final AtomicReference<Supplier<? extends CharSequence>> log = new AtomicReference<>();
when(logger.isWarnEnabled()).thenReturn(true);
doAnswer(invocation -> {
log.set(invocation.getArgument(0));
return null;
}).when(logger).warn(any());
}).when(logger).warn(any(Supplier.class));
@SuppressWarnings("unchecked")
List<MessageHandler> handlers = TestUtils.getPropertyValue(this.logChain, "handlers", List.class);
@@ -311,24 +309,20 @@ public class ChainParserTests {
DirectFieldAccessor dfa = new DirectFieldAccessor(handler);
dfa.setPropertyValue("messageLogger", logger);
this.loggingChannelAdapterChannel.send(MessageBuilder.withPayload(new byte[] { 116, 101, 115, 116 }).build());
this.loggingChannelAdapterChannel.send(MessageBuilder.withPayload(new byte[]{ 116, 101, 115, 116 }).build());
assertThat(log.get()).isNotNull();
assertThat(log.get()).isEqualTo("TEST");
assertThat(log.get().get()).isEqualTo("TEST");
}
@Test(expected = BeanCreationException.class) //INT-2275
@Test
public void invalidNestedChainWithLoggingChannelAdapter() {
try {
new ClassPathXmlApplicationContext("invalidNestedChainWithOutboundChannelAdapter-context.xml",
this.getClass()).close();
fail("BeanCreationException is expected!");
}
catch (BeansException e) {
assertThat(e.getCause().getClass()).isEqualTo(IllegalArgumentException.class);
assertThat(e.getMessage()).contains("output channel was provided");
assertThat(e.getMessage()).contains("does not implement the MessageProducer");
throw e;
}
assertThatExceptionOfType(BeanCreationException.class)
.isThrownBy(() ->
new ClassPathXmlApplicationContext("invalidNestedChainWithOutboundChannelAdapter-context.xml",
getClass()))
.withCauseInstanceOf(IllegalArgumentException.class)
.withMessageContaining("output channel was provided")
.withMessageContaining("does not implement the MessageProducer");
}
@Test //INT-2605

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,11 +37,12 @@ import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.Lifecycle;
import org.springframework.core.log.LogAccessor;
import org.springframework.integration.channel.MessagePublishingErrorHandler;
import org.springframework.integration.channel.NullChannel;
import org.springframework.integration.channel.QueueChannel;
@@ -172,7 +173,7 @@ public class SourcePollingChannelAdapterFactoryBeanTests {
pollingChannelAdapter.setBeanFactory(mock(BeanFactory.class));
pollingChannelAdapter.afterPropertiesSet();
Log adapterLogger = TestUtils.getPropertyValue(pollingChannelAdapter, "logger", Log.class);
LogAccessor adapterLogger = TestUtils.getPropertyValue(pollingChannelAdapter, "logger", LogAccessor.class);
adapterLogger = spy(adapterLogger);
when(adapterLogger.isDebugEnabled()).thenReturn(true);

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.
@@ -30,10 +30,9 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.List;
import java.util.function.Supplier;
import org.apache.commons.logging.Log;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.beans.DirectFieldAccessor;
@@ -42,6 +41,7 @@ import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.log.LogAccessor;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.context.IntegrationContextUtils;
import org.springframework.integration.expression.FunctionExpression;
@@ -53,14 +53,14 @@ import org.springframework.integration.util.MessagingAnnotationUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Artem Bilan
*
* @since 4.3.8
*/
@RunWith(SpringRunner.class)
@SpringJUnitConfig
public class CustomMessagingAnnotationTests {
@Autowired(required = false)
@@ -74,7 +74,7 @@ public class CustomMessagingAnnotationTests {
public void testLogAnnotation() {
assertThat(this.loggingHandler).isNotNull();
Log log = spy(TestUtils.getPropertyValue(this.loggingHandler, "messageLogger", Log.class));
LogAccessor log = spy(TestUtils.getPropertyValue(this.loggingHandler, "messageLogger", LogAccessor.class));
given(log.isWarnEnabled())
.willReturn(true);
@@ -86,12 +86,13 @@ public class CustomMessagingAnnotationTests {
.setHeader("bar", "baz")
.build());
ArgumentCaptor<Object> argumentCaptor = ArgumentCaptor.forClass(Object.class);
@SuppressWarnings("unchecked")
ArgumentCaptor<Supplier<? extends CharSequence>> argumentCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(log)
.warn(argumentCaptor.capture());
assertThat(argumentCaptor.getValue()).isEqualTo("foo for baz");
assertThat(argumentCaptor.getValue().get()).isEqualTo("foo for baz");
}
@Configuration

View File

@@ -30,7 +30,6 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log;
import org.junit.jupiter.api.Test;
import org.springframework.beans.DirectFieldAccessor;
@@ -40,6 +39,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.core.log.LogAccessor;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.expression.Expression;
import org.springframework.integration.channel.QueueChannel;
@@ -274,7 +274,7 @@ public class GatewayParserTests {
@Test
public void testCustomCompletableNoAsyncAttemptAsync() throws Exception {
Object gateway = context.getBean("&customCompletableAttemptAsync");
Log logger = spy(TestUtils.getPropertyValue(gateway, "logger", Log.class));
LogAccessor logger = spy(TestUtils.getPropertyValue(gateway, "logger", LogAccessor.class));
when(logger.isDebugEnabled()).thenReturn(true);
new DirectFieldAccessor(gateway).setPropertyValue("logger", logger);
QueueChannel requestChannel = (QueueChannel) context.getBean("requestChannel");
@@ -423,7 +423,7 @@ public class GatewayParserTests {
}
@Override
@SuppressWarnings({"rawtypes", "unchecked"})
@SuppressWarnings({ "rawtypes", "unchecked" })
public <T> Future<T> submit(Callable<T> task) {
try {
Future<?> result = super.submit(task);

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.
@@ -19,8 +19,7 @@ package org.springframework.integration.config.xml;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
@@ -31,7 +30,7 @@ import org.springframework.integration.endpoint.EventDrivenConsumer;
import org.springframework.integration.expression.FunctionExpression;
import org.springframework.integration.handler.LoggingHandler;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Mark Fisher
@@ -40,7 +39,7 @@ import org.springframework.test.context.junit4.SpringRunner;
*
* @since 2.1
*/
@RunWith(SpringRunner.class)
@SpringJUnitConfig
public class LoggingChannelAdapterParserTests {
@Autowired
@@ -55,7 +54,7 @@ public class LoggingChannelAdapterParserTests {
@Test
public void verifyConfig() {
LoggingHandler loggingHandler = TestUtils.getPropertyValue(loggerConsumer, "handler", LoggingHandler.class);
assertThat(TestUtils.getPropertyValue(loggingHandler, "messageLogger.logger.name"))
assertThat(TestUtils.getPropertyValue(loggingHandler, "messageLogger.log.logger.name"))
.isEqualTo("org.springframework.integration.test.logger");
assertThat(TestUtils.getPropertyValue(loggingHandler, "order")).isEqualTo(1);
assertThat(TestUtils.getPropertyValue(loggingHandler, "level")).isEqualTo(LoggingHandler.Level.WARN);
@@ -66,7 +65,7 @@ public class LoggingChannelAdapterParserTests {
public void verifyExpressionAndOtherDefaultConfig() {
LoggingHandler loggingHandler =
TestUtils.getPropertyValue(loggerWithExpression, "handler", LoggingHandler.class);
assertThat(TestUtils.getPropertyValue(loggingHandler, "messageLogger.logger.name"))
assertThat(TestUtils.getPropertyValue(loggingHandler, "messageLogger.log.logger.name"))
.isEqualTo("org.springframework.integration.handler.LoggingHandler");
assertThat(TestUtils.getPropertyValue(loggingHandler, "order")).isEqualTo(Ordered.LOWEST_PRECEDENCE);
assertThat(TestUtils.getPropertyValue(loggingHandler, "level")).isEqualTo(LoggingHandler.Level.INFO);

View File

@@ -39,7 +39,6 @@ import java.util.concurrent.atomic.AtomicReference;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.apache.commons.logging.Log;
import org.junit.jupiter.api.Test;
import org.springframework.beans.DirectFieldAccessor;
@@ -64,6 +63,7 @@ import org.springframework.context.annotation.Lazy;
import org.springframework.context.expression.EnvironmentAccessor;
import org.springframework.context.expression.MapAccessor;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.log.LogAccessor;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.expression.EvaluationContext;
@@ -313,7 +313,7 @@ public class EnableIntegrationTests {
assertThat(TestUtils.getPropertyValue(trigger, "fixedRate", Boolean.class)).isFalse();
assertThat(this.annotationTestService.isRunning()).isTrue();
Log logger = spy(TestUtils.getPropertyValue(this.serviceActivatorEndpoint, "logger", Log.class));
LogAccessor logger = spy(TestUtils.getPropertyValue(this.serviceActivatorEndpoint, "logger", LogAccessor.class));
when(logger.isDebugEnabled()).thenReturn(true);
final CountDownLatch pollerInterruptedLatch = new CountDownLatch(1);
doAnswer(invocation -> {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2016-2019 the original author or authors.
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,7 +18,6 @@ package org.springframework.integration.handler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
@@ -29,12 +28,13 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.core.log.LogAccessor;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.endpoint.EventDrivenConsumer;
@@ -73,7 +73,7 @@ public class AsyncHandlerTests {
private ExecutorService executor;
@Before
@BeforeEach
public void setup() {
this.executor = Executors.newSingleThreadExecutor();
this.handler = new AbstractReplyProducingMessageHandler() {
@@ -107,17 +107,18 @@ public class AsyncHandlerTests {
this.handler.setOutputChannel(this.output);
this.handler.setBeanFactory(mock(BeanFactory.class));
this.latch = new CountDownLatch(1);
Log logger = spy(TestUtils.getPropertyValue(this.handler, "logger", Log.class));
new DirectFieldAccessor(this.handler).setPropertyValue("logger", logger);
LogAccessor logAccessor = TestUtils.getPropertyValue(this.handler, "logger", LogAccessor.class);
Log log = spy(logAccessor.getLog());
new DirectFieldAccessor(logAccessor).setPropertyValue("log", log);
doAnswer(invocation -> {
failedCallbackMessage = invocation.getArgument(0);
failedCallbackMessage = invocation.getArgument(0).toString();
failedCallbackException = invocation.getArgument(1);
exceptionLatch.countDown();
return null;
}).when(logger).error(anyString(), any(Throwable.class));
}).when(log).error(any(), any(Throwable.class));
}
@After
@AfterEach
public void tearDown() {
this.executor.shutdownNow();
}

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.handler;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
@@ -25,32 +26,36 @@ import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.function.Supplier;
import org.apache.commons.logging.Log;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.log.LogAccessor;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.integration.handler.LoggingHandler.Level;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.test.condition.LogLevels;
import org.springframework.integration.test.util.TestUtils;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Mark Fisher
* @author Artem Bilan
* @author Andriy Kryvtsun
*
* @since 2.0
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
@LogLevels(categories = "test.logging.handler")
public class LoggingHandlerTests {
@Autowired
@@ -88,51 +93,49 @@ public class LoggingHandlerTests {
@Test
public void testDontEvaluateIfNotEnabled() {
LoggingHandler loggingHandler = new LoggingHandler("INFO");
loggingHandler.setLoggerName("test.logging.handler");
loggingHandler.setBeanFactory(mock(BeanFactory.class));
loggingHandler.afterPropertiesSet();
DirectFieldAccessor accessor = new DirectFieldAccessor(loggingHandler);
Log log = (Log) accessor.getPropertyValue("messageLogger");
log = spy(log);
accessor.setPropertyValue("messageLogger", log);
Expression expression = (Expression) accessor.getPropertyValue("expression");
expression = spy(expression);
accessor.setPropertyValue("expression", expression);
when(log.isInfoEnabled()).thenReturn(false);
LogAccessor logAccessor = TestUtils.getPropertyValue(loggingHandler, "messageLogger", LogAccessor.class);
Log log = spy(logAccessor.getLog());
when(log.isInfoEnabled()).thenReturn(false, true);
new DirectFieldAccessor(logAccessor).setPropertyValue("log", log);
Expression expression = spy(TestUtils.getPropertyValue(loggingHandler, "expression", Expression.class));
loggingHandler.setLogExpression(expression);
loggingHandler.handleMessage(new GenericMessage<>("foo"));
verify(expression, never()).getValue(Mockito.any(EvaluationContext.class), Mockito.any(Message.class));
when(log.isInfoEnabled()).thenReturn(true);
verify(expression, never()).getValue(any(EvaluationContext.class), any(Message.class));
loggingHandler.handleMessage(new GenericMessage<>("foo"));
verify(expression, times(1)).getValue(Mockito.any(EvaluationContext.class), Mockito.any(Message.class));
verify(expression, times(1)).getValue(any(EvaluationContext.class), any(Message.class));
}
@Test
@SuppressWarnings("unchecked")
public void testChangeLevel() {
LoggingHandler loggingHandler = new LoggingHandler(Level.INFO);
loggingHandler.setBeanFactory(mock(BeanFactory.class));
loggingHandler.afterPropertiesSet();
DirectFieldAccessor accessor = new DirectFieldAccessor(loggingHandler);
Log log = (Log) accessor.getPropertyValue("messageLogger");
LogAccessor log = (LogAccessor) accessor.getPropertyValue("messageLogger");
log = spy(log);
accessor.setPropertyValue("messageLogger", log);
when(log.isInfoEnabled()).thenReturn(true);
loggingHandler.handleMessage(new GenericMessage<>("foo"));
verify(log, times(1)).info(Mockito.anyString());
verify(log, never()).warn(Mockito.anyString());
verify(log, times(1)).info(any(Supplier.class));
verify(log, never()).warn(any(Supplier.class));
loggingHandler.setLevel(Level.WARN);
loggingHandler.handleMessage(new GenericMessage<>("foo"));
verify(log, times(1)).info(Mockito.anyString());
verify(log, times(1)).warn(Mockito.anyString());
verify(log, times(1)).info(any(Supplier.class));
verify(log, times(1)).warn(any(Supplier.class));
}
@Test
public void testUsageWithoutSpringInitialization() {
LoggingHandler loggingHandler = new LoggingHandler("ERROR");
DirectFieldAccessor accessor = new DirectFieldAccessor(loggingHandler);
Log log = (Log) accessor.getPropertyValue("messageLogger");
LogAccessor log = (LogAccessor) accessor.getPropertyValue("messageLogger");
log = spy(log);
accessor.setPropertyValue("messageLogger", log);
@@ -141,7 +144,9 @@ public class LoggingHandlerTests {
loggingHandler.handleMessage(message);
verify(log).error(testPayload);
verify(log)
.error(ArgumentMatchers.<Supplier<? extends CharSequence>>argThat(logMessage ->
logMessage.get().equals(testPayload)));
}
public static class TestBean {

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.handler.advice;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
@@ -39,16 +40,14 @@ import java.util.concurrent.atomic.AtomicReference;
import org.aopalliance.aop.Advice;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.logging.Log;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.junit.jupiter.api.Test;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.log.LogAccessor;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.endpoint.PollingConsumer;
import org.springframework.integration.filter.MessageFilter;
@@ -70,8 +69,7 @@ import org.springframework.retry.support.DefaultRetryState;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
/**
* @author Gary Russell
@@ -79,8 +77,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
*
* @since 2.2
*/
@ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@SpringJUnitConfig
@DirtiesContext
public class AdvisedMessageHandlerTests {
@@ -836,7 +833,7 @@ public class AdvisedMessageHandlerTests {
Method method = AbstractReplyProducingMessageHandler.class.getDeclaredMethod("handleRequestMessage",
Message.class);
when(methodInvocation.getMethod()).thenReturn(method);
when(methodInvocation.getArguments()).thenReturn(new Object[] { new GenericMessage<>("foo") });
when(methodInvocation.getArguments()).thenReturn(new Object[]{ new GenericMessage<>("foo") });
try {
doAnswer(invocation -> {
throw theThrowable;
@@ -903,14 +900,13 @@ public class AdvisedMessageHandlerTests {
Callable<?> pollingTask = TestUtils.getPropertyValue(consumer, "pollingTask", Callable.class);
assertThat(AopUtils.isAopProxy(pollingTask)).isTrue();
Log logger = TestUtils.getPropertyValue(advice, "logger", Log.class);
logger = spy(logger);
LogAccessor logger = spy(TestUtils.getPropertyValue(advice, "logger", LogAccessor.class));
when(logger.isWarnEnabled()).thenReturn(Boolean.TRUE);
final AtomicReference<String> logMessage = new AtomicReference<>();
doAnswer(invocation -> {
logMessage.set(invocation.getArgument(0));
return null;
}).when(logger).warn(Mockito.anyString());
}).when(logger).warn(anyString());
DirectFieldAccessor accessor = new DirectFieldAccessor(advice);
accessor.setPropertyValue("logger", logger);

View File

@@ -21,7 +21,8 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import org.apache.commons.logging.Log;
import java.util.function.Supplier;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -29,6 +30,7 @@ import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.ResolvableType;
import org.springframework.core.log.LogAccessor;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.support.json.Jackson2JsonObjectMapper;
@@ -66,6 +68,7 @@ public class JsonToObjectTransformerParserTests {
private JsonObjectMapper<?, ?> jsonObjectMapper;
@Test
@SuppressWarnings("unchecked")
public void testDefaultObjectMapper() {
Object jsonToObjectTransformer =
TestUtils.getPropertyValue(this.defaultJacksonMapperTransformer, "transformer");
@@ -73,7 +76,7 @@ public class JsonToObjectTransformerParserTests {
.isEqualTo(Jackson2JsonObjectMapper.class);
DirectFieldAccessor dfa = new DirectFieldAccessor(jsonToObjectTransformer);
Log logger = (Log) spy(dfa.getPropertyValue("logger"));
LogAccessor logger = (LogAccessor) spy(dfa.getPropertyValue("logger"));
dfa.setPropertyValue("logger", logger);
String jsonString =
@@ -92,9 +95,9 @@ public class JsonToObjectTransformerParserTests {
assertThat(person.getAge()).isEqualTo(42);
assertThat(person.getAddress().toString()).isEqualTo("123 Main Street");
ArgumentCaptor<String> stringArgumentCaptor = ArgumentCaptor.forClass(String.class);
verify(logger).debug(stringArgumentCaptor.capture(), any(Exception.class));
String logMessage = stringArgumentCaptor.getValue();
ArgumentCaptor<Supplier<String>> argumentCaptor = ArgumentCaptor.forClass(Supplier.class);
verify(logger).debug(any(Exception.class), argumentCaptor.capture());
String logMessage = argumentCaptor.getValue().get();
assertThat(logMessage).startsWith("Cannot build a ResolvableType from the request message");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2019 the original author or authors.
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +21,6 @@ import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import org.apache.commons.logging.Log;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
@@ -29,6 +28,7 @@ import org.springframework.beans.DirectFieldAccessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.log.LogAccessor;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.channel.QueueChannel;
import org.springframework.integration.config.EnableIntegration;
@@ -55,19 +55,19 @@ public class AvroTests {
@LogLevels(classes = DirectChannel.class, categories = "bar", level = "DEBUG")
void testTransformers(@Autowired Config config) {
AvroTestClass1 test = new AvroTestClass1("baz", "fiz");
Log spied = spy(TestUtils.getPropertyValue(config.in1(), "logger", Log.class));
LogAccessor spied = spy(TestUtils.getPropertyValue(config.in1(), "logger", LogAccessor.class));
new DirectFieldAccessor(config.in1()).setPropertyValue("logger", spied);
config.in1().send(new GenericMessage<>(test));
assertThat(config.tapped().receive(0))
.isNotNull()
.extracting(msg -> msg.getPayload())
.isInstanceOf(byte[].class);
.isNotNull()
.extracting(msg -> msg.getPayload())
.isInstanceOf(byte[].class);
Message<?> received = config.out().receive(0);
assertThat(received)
.isNotNull()
.extracting(msg -> msg.getPayload())
.isEqualTo(test)
.isNotSameAs(test);
.isNotNull()
.extracting(msg -> msg.getPayload())
.isEqualTo(test)
.isNotSameAs(test);
assertThat(received.getHeaders().get("flow")).isEqualTo("flow1");
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
verify(spied, atLeastOnce()).debug(captor.capture());
@@ -80,15 +80,15 @@ public class AvroTests {
AvroTestClass1 test = new AvroTestClass1("baz", "fiz");
config.in2().send(new GenericMessage<>(test));
assertThat(config.tapped().receive(0))
.isNotNull()
.extracting(msg -> msg.getPayload())
.isInstanceOf(byte[].class);
.isNotNull()
.extracting(msg -> msg.getPayload())
.isInstanceOf(byte[].class);
Message<?> received = config.out().receive(0);
assertThat(received)
.isNotNull()
.extracting(msg -> msg.getPayload())
.isNotEqualTo(test)
.isInstanceOf(AvroTestClass2.class);
.isNotNull()
.extracting(msg -> msg.getPayload())
.isNotEqualTo(test)
.isInstanceOf(AvroTestClass2.class);
assertThat(received.getHeaders().get("flow")).isEqualTo("flow2");
}
@@ -97,15 +97,15 @@ public class AvroTests {
AvroTestClass1 test = new AvroTestClass1("baz", "fiz");
config.in3().send(new GenericMessage<>(test));
assertThat(config.tapped().receive(0))
.isNotNull()
.extracting(msg -> msg.getPayload())
.isInstanceOf(byte[].class);
.isNotNull()
.extracting(msg -> msg.getPayload())
.isInstanceOf(byte[].class);
Message<?> received = config.out().receive(0);
assertThat(received)
.isNotNull()
.extracting(msg -> msg.getPayload())
.isNotEqualTo(test)
.isInstanceOf(AvroTestClass2.class);
.isNotNull()
.extracting(msg -> msg.getPayload())
.isNotEqualTo(test)
.isInstanceOf(AvroTestClass2.class);
assertThat(received.getHeaders().get("flow")).isEqualTo("flow3");
}
@@ -114,15 +114,15 @@ public class AvroTests {
AvroTestClass1 test = new AvroTestClass1("baz", "fiz");
config.in4().send(new GenericMessage<>(test));
assertThat(config.tapped().receive(0))
.isNotNull()
.extracting(msg -> msg.getPayload())
.isInstanceOf(byte[].class);
.isNotNull()
.extracting(msg -> msg.getPayload())
.isInstanceOf(byte[].class);
Message<?> received = config.out().receive(0);
assertThat(received)
.isNotNull()
.extracting(msg -> msg.getPayload())
.isEqualTo(test)
.isNotSameAs(test);
.isNotNull()
.extracting(msg -> msg.getPayload())
.isEqualTo(test)
.isNotSameAs(test);
assertThat(received.getHeaders().get("flow")).isEqualTo("flow4");
}
@@ -131,15 +131,15 @@ public class AvroTests {
AvroTestClass1 test = new AvroTestClass1("baz", "fiz");
config.in5().send(new GenericMessage<>(test));
assertThat(config.tapped().receive(0))
.isNotNull()
.extracting(msg -> msg.getPayload())
.isInstanceOf(byte[].class);
.isNotNull()
.extracting(msg -> msg.getPayload())
.isInstanceOf(byte[].class);
Message<?> received = config.out().receive(0);
assertThat(received)
.isNotNull()
.extracting(msg -> msg.getPayload())
.isNotEqualTo(test)
.isInstanceOf(AvroTestClass2.class);
.isNotNull()
.extracting(msg -> msg.getPayload())
.isNotEqualTo(test)
.isInstanceOf(AvroTestClass2.class);
assertThat(received.getHeaders().get("flow")).isEqualTo("flow5");
}
@@ -148,15 +148,15 @@ public class AvroTests {
AvroTestClass1 test = new AvroTestClass1("baz", "fiz");
config.in6().send(new GenericMessage<>(test));
assertThat(config.tapped().receive(0))
.isNotNull()
.extracting(msg -> msg.getPayload())
.isInstanceOf(byte[].class);
.isNotNull()
.extracting(msg -> msg.getPayload())
.isInstanceOf(byte[].class);
Message<?> received = config.out().receive(0);
assertThat(received)
.isNotNull()
.extracting(msg -> msg.getPayload())
.isEqualTo(test)
.isNotSameAs(test);
.isNotNull()
.extracting(msg -> msg.getPayload())
.isEqualTo(test)
.isNotSameAs(test);
assertThat(received.getHeaders().get("flow")).isEqualTo("flow6");
}
@@ -219,7 +219,7 @@ public class AvroTests {
.wireTap(tapped())
.transform(new SimpleFromAvroTransformer(AvroTestClass1.class)
.typeExpression("'avroTest' == headers[avro_type] ? '"
+ AvroTestClass2.class.getName() + "' : null"))
+ AvroTestClass2.class.getName() + "' : null"))
.enrichHeaders(h -> h.header("flow", "flow5"))
.channel(out())
.get();
@@ -232,7 +232,7 @@ public class AvroTests {
.wireTap(tapped())
.transform(new SimpleFromAvroTransformer(AvroTestClass1.class)
.typeExpression("'avroTest' == headers[avro_type] ? '"
+ AvroTestClass2.class.getName() + "' : null"))
+ AvroTestClass2.class.getName() + "' : null"))
.enrichHeaders(h -> h.header("flow", "flow6"))
.channel(out())
.get();