Search in sources :

Example 36 with LogAccessor

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

the class ChainParserTests method chainWithLoggingChannelAdapter.

@Test
@SuppressWarnings("unchecked")
public void chainWithLoggingChannelAdapter() {
    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(Supplier.class));
    @SuppressWarnings("unchecked") List<MessageHandler> handlers = TestUtils.getPropertyValue(this.logChain, "handlers", List.class);
    MessageHandler handler = handlers.get(2);
    assertThat(handler instanceof LoggingHandler).isTrue();
    DirectFieldAccessor dfa = new DirectFieldAccessor(handler);
    dfa.setPropertyValue("messageLogger", logger);
    this.loggingChannelAdapterChannel.send(MessageBuilder.withPayload(new byte[] { 116, 101, 115, 116 }).build());
    assertThat(log.get()).isNotNull();
    assertThat(log.get().get()).isEqualTo("TEST");
}
Also used : LoggingHandler(org.springframework.integration.handler.LoggingHandler) AbstractReplyProducingMessageHandler(org.springframework.integration.handler.AbstractReplyProducingMessageHandler) MessageHandler(org.springframework.messaging.MessageHandler) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Supplier(java.util.function.Supplier) AtomicReference(java.util.concurrent.atomic.AtomicReference) LogAccessor(org.springframework.core.log.LogAccessor) Test(org.junit.jupiter.api.Test)

Example 37 with LogAccessor

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

the class ConnectionFactoryTests method testEarlyClose.

private void testEarlyClose(final AbstractServerConnectionFactory factory, String property, String message) throws Exception {
    factory.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    factory.setBeanName("foo");
    factory.registerListener(mock(TcpListener.class));
    factory.afterPropertiesSet();
    LogAccessor logAccessor = TestUtils.getPropertyValue(factory, "logger", LogAccessor.class);
    Log logger = spy(logAccessor.getLog());
    new DirectFieldAccessor(logAccessor).setPropertyValue("log", logger);
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    final CountDownLatch latch3 = new CountDownLatch(1);
    when(logger.isInfoEnabled()).thenReturn(true);
    when(logger.isDebugEnabled()).thenReturn(true);
    doAnswer(invocation -> {
        latch1.countDown();
        // wait until the stop nulls the channel
        latch2.await(10, TimeUnit.SECONDS);
        return null;
    }).when(logger).info(argThat(logMessage -> logMessage.toString().contains("Listening")));
    doAnswer(invocation -> {
        latch3.countDown();
        return null;
    }).when(logger).debug(argThat(logMessage -> logMessage.toString().contains(message)));
    factory.start();
    assertThat(latch1.await(10, TimeUnit.SECONDS)).as("missing info log").isTrue();
    // stop on a different thread because it waits for the executor
    new SimpleAsyncTaskExecutor("testEarlyClose-").execute(factory::stop);
    int n = 0;
    DirectFieldAccessor accessor = new DirectFieldAccessor(factory);
    await("Stop was not invoked in time").atMost(Duration.ofSeconds(20)).until(() -> accessor.getPropertyValue(property) == null);
    latch2.countDown();
    assertThat(latch3.await(10, TimeUnit.SECONDS)).as("missing debug log").isTrue();
    String expected = "bean 'foo', port=" + factory.getPort() + message;
    ArgumentCaptor<LogMessage> captor = ArgumentCaptor.forClass(LogMessage.class);
    verify(logger, atLeast(1)).debug(captor.capture());
    assertThat(captor.getAllValues().stream().map(Object::toString).collect(Collectors.toList())).contains(expected);
    factory.stop();
}
Also used : Arrays(java.util.Arrays) SocketAddress(java.net.SocketAddress) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ErrorMessage(org.springframework.messaging.support.ErrorMessage) TcpConnectionFactoryFactoryBean(org.springframework.integration.ip.config.TcpConnectionFactoryFactoryBean) TcpReceivingChannelAdapter(org.springframework.integration.ip.tcp.TcpReceivingChannelAdapter) NullChannel(org.springframework.integration.channel.NullChannel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Duration(java.time.Duration) Mockito.atLeast(org.mockito.Mockito.atLeast) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) SimpleAsyncTaskExecutor(org.springframework.core.task.SimpleAsyncTaskExecutor) Awaitility.await(org.awaitility.Awaitility.await) TaskScheduler(org.springframework.scheduling.TaskScheduler) LogAccessor(org.springframework.core.log.LogAccessor) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) SocketFactory(javax.net.SocketFactory) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Assertions.fail(org.assertj.core.api.Assertions.fail) LogFactory(org.apache.commons.logging.LogFactory) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) QueueChannel(org.springframework.integration.channel.QueueChannel) MessagingException(org.springframework.messaging.MessagingException) Socket(java.net.Socket) IpIntegrationEvent(org.springframework.integration.ip.event.IpIntegrationEvent) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) 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) LogMessage(org.springframework.core.log.LogMessage) ArgumentCaptor(org.mockito.ArgumentCaptor) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) Message(org.springframework.messaging.Message) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) TcpOutboundGateway(org.springframework.integration.ip.tcp.TcpOutboundGateway) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) IntegrationContextUtils(org.springframework.integration.context.IntegrationContextUtils) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) BeanFactory(org.springframework.beans.factory.BeanFactory) Log(org.apache.commons.logging.Log) GenericMessage(org.springframework.messaging.support.GenericMessage) Collections(java.util.Collections) Log(org.apache.commons.logging.Log) SimpleAsyncTaskExecutor(org.springframework.core.task.SimpleAsyncTaskExecutor) CountDownLatch(java.util.concurrent.CountDownLatch) LogMessage(org.springframework.core.log.LogMessage) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) LogAccessor(org.springframework.core.log.LogAccessor)

Example 38 with LogAccessor

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

the class SyslogReceivingChannelAdapterTests method testTcp.

@Test
public void testTcp() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(SyslogReceivingChannelAdapterFactoryBean.Protocol.tcp);
    factory.setPort(0);
    PollableChannel outputChannel = new QueueChannel();
    factory.setOutputChannel(outputChannel);
    ApplicationEventPublisher publisher = mock(ApplicationEventPublisher.class);
    final CountDownLatch latch = new CountDownLatch(2);
    doAnswer(invocation -> {
        latch.countDown();
        return null;
    }).when(publisher).publishEvent(any(ApplicationEvent.class));
    factory.setApplicationEventPublisher(publisher);
    factory.setBeanFactory(mock(BeanFactory.class));
    factory.afterPropertiesSet();
    factory.start();
    AbstractServerConnectionFactory server = TestUtils.getPropertyValue(factory, "syslogAdapter.connectionFactory", AbstractServerConnectionFactory.class);
    TestingUtilities.waitListening(server, null);
    TcpSyslogReceivingChannelAdapter adapter = (TcpSyslogReceivingChannelAdapter) factory.getObject();
    LogAccessor logger = spy(TestUtils.getPropertyValue(adapter, "logger", LogAccessor.class));
    doReturn(true).when(logger).isDebugEnabled();
    final CountDownLatch sawLog = new CountDownLatch(1);
    doAnswer(invocation -> {
        if (((String) invocation.getArgument(0)).contains("Error on syslog socket")) {
            sawLog.countDown();
        }
        invocation.callRealMethod();
        return null;
    }).when(logger).debug(anyString());
    new DirectFieldAccessor(adapter).setPropertyValue("logger", logger);
    byte[] buf = "<157>JUL 26 22:08:35 WEBERN TESTING[70729]: TEST SYSLOG MESSAGE\n".getBytes(StandardCharsets.UTF_8);
    Socket socket = SocketFactory.getDefault().createSocket("localhost", server.getPort());
    socket.getOutputStream().write(buf);
    socket.close();
    assertThat(sawLog.await(10, TimeUnit.SECONDS)).isTrue();
    Message<?> message = outputChannel.receive(10000);
    assertThat(message).isNotNull();
    assertThat(message.getHeaders().get("syslog_HOST")).isEqualTo("WEBERN");
    assertThat(message.getHeaders().get(IpHeaders.IP_ADDRESS)).isNotNull();
    adapter.stop();
    assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) ApplicationEvent(org.springframework.context.ApplicationEvent) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) SyslogReceivingChannelAdapterFactoryBean(org.springframework.integration.syslog.config.SyslogReceivingChannelAdapterFactoryBean) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) PollableChannel(org.springframework.messaging.PollableChannel) BeanFactory(org.springframework.beans.factory.BeanFactory) AbstractServerConnectionFactory(org.springframework.integration.ip.tcp.connection.AbstractServerConnectionFactory) LogAccessor(org.springframework.core.log.LogAccessor) Socket(java.net.Socket) DatagramSocket(java.net.DatagramSocket) 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