Search in sources :

Example 6 with LogAccessor

use of org.springframework.core.log.LogAccessor in project spring-integration by spring-projects.

the class AdvisedMessageHandlerTests method testInappropriateAdvice.

@Test
public void testInappropriateAdvice() throws Exception {
    final AtomicBoolean called = new AtomicBoolean(false);
    Advice advice = new AbstractRequestHandlerAdvice() {

        @Override
        protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message) {
            called.set(true);
            return callback.execute();
        }
    };
    PollableChannel inputChannel = new QueueChannel();
    PollingConsumer consumer = new PollingConsumer(inputChannel, message -> {
    });
    consumer.setAdviceChain(Collections.singletonList(advice));
    ExecutorService exec = Executors.newSingleThreadExecutor();
    consumer.setTaskExecutor(new ErrorHandlingTaskExecutor(exec, t -> {
    }));
    consumer.setBeanFactory(mock(BeanFactory.class));
    consumer.afterPropertiesSet();
    consumer.setTaskScheduler(mock(TaskScheduler.class));
    consumer.start();
    Callable<?> pollingTask = TestUtils.getPropertyValue(consumer, "pollingTask", Callable.class);
    assertThat(AopUtils.isAopProxy(pollingTask)).isTrue();
    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(anyString());
    DirectFieldAccessor accessor = new DirectFieldAccessor(advice);
    accessor.setPropertyValue("logger", logger);
    pollingTask.call();
    assertThat(called.get()).isFalse();
    assertThat(logMessage.get()).isNotNull();
    assertThat(logMessage.get()).contains("can only be used for MessageHandlers; " + "an attempt to advise method 'call' in " + "'org.springframework.integration.endpoint.AbstractPollingEndpoint");
    consumer.stop();
    exec.shutdownNow();
}
Also used : DirtiesContext(org.springframework.test.annotation.DirtiesContext) DefaultRetryState(org.springframework.retry.support.DefaultRetryState) AopUtils(org.springframework.aop.support.AopUtils) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Autowired(org.springframework.beans.factory.annotation.Autowired) ErrorMessage(org.springframework.messaging.support.ErrorMessage) PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) SpringJUnitConfig(org.springframework.test.context.junit.jupiter.SpringJUnitConfig) MethodInvocation(org.aopalliance.intercept.MethodInvocation) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MessageHandlingException(org.springframework.messaging.MessageHandlingException) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Map(java.util.Map) PollableChannel(org.springframework.messaging.PollableChannel) Method(java.lang.reflect.Method) AdviceMessage(org.springframework.integration.message.AdviceMessage) TaskScheduler(org.springframework.scheduling.TaskScheduler) LogAccessor(org.springframework.core.log.LogAccessor) MessageChannel(org.springframework.messaging.MessageChannel) Executors(java.util.concurrent.Executors) Test(org.junit.jupiter.api.Test) List(java.util.List) Assertions.fail(org.assertj.core.api.Assertions.fail) Mockito.mock(org.mockito.Mockito.mock) QueueChannel(org.springframework.integration.channel.QueueChannel) MessagingException(org.springframework.messaging.MessagingException) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Mockito.spy(org.mockito.Mockito.spy) TestUtils(org.springframework.integration.test.util.TestUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) MessageFilter(org.springframework.integration.filter.MessageFilter) Advice(org.aopalliance.aop.Advice) Message(org.springframework.messaging.Message) ExecutorService(java.util.concurrent.ExecutorService) ErrorHandlingTaskExecutor(org.springframework.integration.util.ErrorHandlingTaskExecutor) MessageHandlingExpressionEvaluatingAdviceException(org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice.MessageHandlingExpressionEvaluatingAdviceException) SimpleRetryPolicy(org.springframework.retry.policy.SimpleRetryPolicy) Mockito.when(org.mockito.Mockito.when) MethodInterceptor(org.aopalliance.intercept.MethodInterceptor) RetryContext(org.springframework.retry.RetryContext) BeanFactory(org.springframework.beans.factory.BeanFactory) ProxyFactory(org.springframework.aop.framework.ProxyFactory) GenericMessage(org.springframework.messaging.support.GenericMessage) RetryTemplate(org.springframework.retry.support.RetryTemplate) Collections(java.util.Collections) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) ErrorMessage(org.springframework.messaging.support.ErrorMessage) AdviceMessage(org.springframework.integration.message.AdviceMessage) Message(org.springframework.messaging.Message) GenericMessage(org.springframework.messaging.support.GenericMessage) QueueChannel(org.springframework.integration.channel.QueueChannel) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) TaskScheduler(org.springframework.scheduling.TaskScheduler) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) PollableChannel(org.springframework.messaging.PollableChannel) ExecutorService(java.util.concurrent.ExecutorService) BeanFactory(org.springframework.beans.factory.BeanFactory) Advice(org.aopalliance.aop.Advice) LogAccessor(org.springframework.core.log.LogAccessor) ErrorHandlingTaskExecutor(org.springframework.integration.util.ErrorHandlingTaskExecutor) Test(org.junit.jupiter.api.Test)

Example 7 with LogAccessor

use of org.springframework.core.log.LogAccessor in project spring-integration by spring-projects.

the class LoggingHandlerTests method testDontEvaluateIfNotEnabled.

@Test
public void testDontEvaluateIfNotEnabled() {
    LoggingHandler loggingHandler = new LoggingHandler("INFO");
    loggingHandler.setLoggerName("test.logging.handler");
    loggingHandler.setBeanFactory(mock(BeanFactory.class));
    loggingHandler.afterPropertiesSet();
    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(any(EvaluationContext.class), any(Message.class));
    loggingHandler.handleMessage(new GenericMessage<>("foo"));
    verify(expression, times(1)).getValue(any(EvaluationContext.class), any(Message.class));
}
Also used : Message(org.springframework.messaging.Message) GenericMessage(org.springframework.messaging.support.GenericMessage) Log(org.apache.commons.logging.Log) Expression(org.springframework.expression.Expression) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) BeanFactory(org.springframework.beans.factory.BeanFactory) LogAccessor(org.springframework.core.log.LogAccessor) EvaluationContext(org.springframework.expression.EvaluationContext) Test(org.junit.jupiter.api.Test)

Example 8 with LogAccessor

use of org.springframework.core.log.LogAccessor in project spring-integration by spring-projects.

the class LoggingHandlerTests method testUsageWithoutSpringInitialization.

@Test
public void testUsageWithoutSpringInitialization() {
    LoggingHandler loggingHandler = new LoggingHandler("ERROR");
    DirectFieldAccessor accessor = new DirectFieldAccessor(loggingHandler);
    LogAccessor log = (LogAccessor) accessor.getPropertyValue("messageLogger");
    log = spy(log);
    accessor.setPropertyValue("messageLogger", log);
    String testPayload = "TEST_PAYLOAD";
    Message<String> message = MessageBuilder.withPayload(testPayload).build();
    loggingHandler.handleMessage(message);
    verify(log).error(ArgumentMatchers.<Supplier<? extends CharSequence>>argThat(logMessage -> logMessage.get().equals(testPayload)));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ArgumentMatchers(org.mockito.ArgumentMatchers) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Autowired(org.springframework.beans.factory.annotation.Autowired) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Mockito.spy(org.mockito.Mockito.spy) TestUtils(org.springframework.integration.test.util.TestUtils) Supplier(java.util.function.Supplier) MessageBuilder(org.springframework.integration.support.MessageBuilder) SpringJUnitConfig(org.springframework.test.context.junit.jupiter.SpringJUnitConfig) Level(org.springframework.integration.handler.LoggingHandler.Level) Message(org.springframework.messaging.Message) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) LogAccessor(org.springframework.core.log.LogAccessor) MessageChannel(org.springframework.messaging.MessageChannel) Mockito.verify(org.mockito.Mockito.verify) EvaluationContext(org.springframework.expression.EvaluationContext) Test(org.junit.jupiter.api.Test) Mockito.never(org.mockito.Mockito.never) Assertions.fail(org.assertj.core.api.Assertions.fail) LogLevels(org.springframework.integration.test.condition.LogLevels) BeanFactory(org.springframework.beans.factory.BeanFactory) Expression(org.springframework.expression.Expression) Log(org.apache.commons.logging.Log) GenericMessage(org.springframework.messaging.support.GenericMessage) Mockito.mock(org.mockito.Mockito.mock) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) LogAccessor(org.springframework.core.log.LogAccessor) Test(org.junit.jupiter.api.Test)

Example 9 with LogAccessor

use of org.springframework.core.log.LogAccessor in project spring-integration by spring-projects.

the class FileWritingMessageHandlerTests method noFlushAppend.

@Test
public void noFlushAppend() throws Exception {
    File tempFolder = new File(tempDir, UUID.randomUUID().toString());
    FileWritingMessageHandler handler = new FileWritingMessageHandler(tempFolder);
    handler.setFileExistsMode(FileExistsMode.APPEND_NO_FLUSH);
    handler.setFileNameGenerator(message -> "foo.txt");
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.afterPropertiesSet();
    handler.setTaskScheduler(taskScheduler);
    handler.setOutputChannel(new NullChannel());
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.setFlushInterval(30000);
    handler.afterPropertiesSet();
    handler.start();
    File file = new File(tempFolder, "foo.txt");
    handler.handleMessage(new GenericMessage<>("foo"));
    handler.handleMessage(new GenericMessage<>("bar"));
    handler.handleMessage(new GenericMessage<>("baz"));
    // change of payload type forces flush
    handler.handleMessage(new GenericMessage<>("qux".getBytes()));
    assertThat(file.length()).isGreaterThanOrEqualTo(9L);
    // forces flush
    handler.stop();
    assertThat(file.length()).isEqualTo(12L);
    handler.setFlushInterval(100);
    handler.start();
    handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("fiz".getBytes())));
    int n = 0;
    while (n++ < 100 && file.length() < 15) {
        Thread.sleep(100);
    }
    assertThat(file.length()).isEqualTo(15L);
    handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("buz".getBytes())));
    handler.trigger(new GenericMessage<>(Matcher.quoteReplacement(file.getAbsolutePath())));
    assertThat(file.length()).isEqualTo(18L);
    assertThat(TestUtils.getPropertyValue(handler, "fileStates", Map.class).size()).isEqualTo(0);
    handler.setFlushInterval(30000);
    final AtomicBoolean called = new AtomicBoolean();
    handler.setFlushPredicate((fileAbsolutePath, firstWrite, lastWrite, triggerMessage) -> {
        called.set(true);
        return true;
    });
    handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("box".getBytes())));
    handler.trigger(new GenericMessage<>("foo"));
    assertThat(file.length()).isEqualTo(21L);
    assertThat(called.get()).isTrue();
    handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("bux".getBytes())));
    called.set(false);
    handler.flushIfNeeded((fileAbsolutePath, firstWrite, lastWrite) -> {
        called.set(true);
        return true;
    });
    assertThat(file.length()).isEqualTo(24L);
    assertThat(called.get()).isTrue();
    handler.stop();
    LogAccessor logger = spy(TestUtils.getPropertyValue(handler, "logger", LogAccessor.class));
    new DirectFieldAccessor(handler).setPropertyValue("logger", logger);
    when(logger.isDebugEnabled()).thenReturn(true);
    final AtomicInteger flushes = new AtomicInteger();
    doAnswer(i -> {
        flushes.incrementAndGet();
        return null;
    }).when(logger).debug(startsWith("Flushed:"));
    handler.setFlushInterval(50);
    handler.setFlushWhenIdle(false);
    handler.start();
    for (int i = 0; i < 40; i++) {
        handler.handleMessage(new GenericMessage<>("foo"));
        Thread.sleep(5);
    }
    assertThat(flushes.get()).isGreaterThanOrEqualTo(2);
    handler.stop();
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) BeanFactory(org.springframework.beans.factory.BeanFactory) LogAccessor(org.springframework.core.log.LogAccessor) File(java.io.File) NullChannel(org.springframework.integration.channel.NullChannel) Map(java.util.Map) Test(org.junit.jupiter.api.Test)

Example 10 with LogAccessor

use of org.springframework.core.log.LogAccessor in project spring-integration by spring-projects.

the class BarrierMessageHandlerTests method testLateReply.

@Test
public void testLateReply() throws Exception {
    final BarrierMessageHandler handler = new BarrierMessageHandler(0);
    QueueChannel outputChannel = new QueueChannel();
    QueueChannel discardChannel = new QueueChannel();
    handler.setOutputChannel(outputChannel);
    handler.setDiscardChannelName("discards");
    handler.setChannelResolver(s -> discardChannel);
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    final CountDownLatch latch = new CountDownLatch(1);
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.execute(() -> {
        handler.handleMessage(MessageBuilder.withPayload("foo").setCorrelationId("foo").build());
        latch.countDown();
    });
    Map<?, ?> suspensions = TestUtils.getPropertyValue(handler, "suspensions", Map.class);
    assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
    assertThat(suspensions.size()).as("suspension not removed").isEqualTo(0);
    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);
    ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
    verify(logger).error(captor.capture());
    assertThat(captor.getValue()).contains("Suspending thread timed out or did not arrive within timeout for:").contains("payload=bar");
    assertThat(suspensions.size()).isEqualTo(0);
    Message<?> discard = discardChannel.receive(0);
    assertThat(triggerMessage).isSameAs(discard);
    handler.handleMessage(MessageBuilder.withPayload("foo").setCorrelationId("foo").build());
    assertThat(suspensions.size()).isEqualTo(0);
    exec.shutdownNow();
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) BeanFactory(org.springframework.beans.factory.BeanFactory) ExecutorService(java.util.concurrent.ExecutorService) LogAccessor(org.springframework.core.log.LogAccessor) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.jupiter.api.Test)

Aggregations

LogAccessor (org.springframework.core.log.LogAccessor)38 Test (org.junit.jupiter.api.Test)34 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)34 BeanFactory (org.springframework.beans.factory.BeanFactory)19 CountDownLatch (java.util.concurrent.CountDownLatch)16 QueueChannel (org.springframework.integration.channel.QueueChannel)15 Supplier (java.util.function.Supplier)11 Message (org.springframework.messaging.Message)11 GenericMessage (org.springframework.messaging.support.GenericMessage)11 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)9 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)9 Mockito.spy (org.mockito.Mockito.spy)9 TestUtils (org.springframework.integration.test.util.TestUtils)8 ThreadPoolTaskScheduler (org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7 AtomicReference (java.util.concurrent.atomic.AtomicReference)7 Mockito.mock (org.mockito.Mockito.mock)7 Mockito.verify (org.mockito.Mockito.verify)7 TimeUnit (java.util.concurrent.TimeUnit)6 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6