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

@@ -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();