Search in sources :

Example 16 with LogAccessor

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

the class ChannelPublishingJmsMessageListenerTests method testBadConversion.

@Test
public void testBadConversion() throws Exception {
    final QueueChannel requestChannel = new QueueChannel();
    ChannelPublishingJmsMessageListener listener = new ChannelPublishingJmsMessageListener();
    LogAccessor logger = spy(TestUtils.getPropertyValue(listener, "logger", LogAccessor.class));
    doNothing().when(logger).error(any(Throwable.class), anyString());
    new DirectFieldAccessor(listener).setPropertyValue("logger", logger);
    listener.setRequestChannel(requestChannel);
    QueueChannel errorChannel = new QueueChannel();
    listener.setErrorChannel(errorChannel);
    listener.setBeanFactory(mock(BeanFactory.class));
    listener.setMessageConverter(new TestMessageConverter() {

        @Override
        public Object fromMessage(jakarta.jms.Message message) throws MessageConversionException {
            return null;
        }
    });
    listener.afterPropertiesSet();
    jakarta.jms.Message jmsMessage = session.createTextMessage("test");
    listener.onMessage(jmsMessage, mock(Session.class));
    ErrorMessage received = (ErrorMessage) errorChannel.receive(0);
    assertThat(received).isNotNull();
    assertThat(received.getPayload().getMessage()).startsWith("Inbound conversion failed");
    listener.stop();
}
Also used : MessageConversionException(org.springframework.jms.support.converter.MessageConversionException) QueueChannel(org.springframework.integration.channel.QueueChannel) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) BeanFactory(org.springframework.beans.factory.BeanFactory) LogAccessor(org.springframework.core.log.LogAccessor) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Session(jakarta.jms.Session) Test(org.junit.jupiter.api.Test)

Example 17 with LogAccessor

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

the class SyslogReceivingChannelAdapterTests method testTcpRFC5424.

@Test
public void testTcpRFC5424() throws Exception {
    SyslogReceivingChannelAdapterFactoryBean factory = new SyslogReceivingChannelAdapterFactoryBean(SyslogReceivingChannelAdapterFactoryBean.Protocol.tcp);
    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.setBeanFactory(mock(BeanFactory.class));
    AbstractServerConnectionFactory connectionFactory = new TcpNioServerConnectionFactory(0);
    connectionFactory.setDeserializer(new RFC6587SyslogDeserializer());
    connectionFactory.setApplicationEventPublisher(publisher);
    factory.setConnectionFactory(connectionFactory);
    factory.setConverter(new RFC5424MessageConverter());
    factory.afterPropertiesSet();
    factory.start();
    TestingUtilities.waitListening(connectionFactory, 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 = ("253 <14>1 2014-06-20T09:14:07+00:00 loggregator d0602076-b14a-4c55-852a-981e7afeed38 DEA - " + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"]" + "[exampleSDID@32473 iut=\\\"3\\\" eventSource=\\\"Application\\\" eventID=\\\"1011\\\"] Removing instance").getBytes(StandardCharsets.UTF_8);
    Socket socket = SocketFactory.getDefault().createSocket("localhost", connectionFactory.getPort());
    socket.getOutputStream().write(buf);
    socket.close();
    assertThat(sawLog.await(10, TimeUnit.SECONDS)).isTrue();
    @SuppressWarnings("unchecked") Message<Map<String, ?>> message = (Message<Map<String, ?>>) outputChannel.receive(10000);
    assertThat(message).isNotNull();
    assertThat(message.getPayload().get("syslog_HOST")).isEqualTo("loggregator");
    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) RFC5424MessageConverter(org.springframework.integration.syslog.RFC5424MessageConverter) Message(org.springframework.messaging.Message) TcpNioServerConnectionFactory(org.springframework.integration.ip.tcp.connection.TcpNioServerConnectionFactory) 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) Map(java.util.Map) Socket(java.net.Socket) DatagramSocket(java.net.DatagramSocket) Test(org.junit.jupiter.api.Test)

Example 18 with LogAccessor

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

the class SourcePollingChannelAdapterFactoryBeanTests method testZeroForMaxMessagesPerPoll.

@Test
public void testZeroForMaxMessagesPerPoll() throws InterruptedException {
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.afterPropertiesSet();
    SourcePollingChannelAdapter pollingChannelAdapter = new SourcePollingChannelAdapter();
    pollingChannelAdapter.setTaskScheduler(taskScheduler);
    pollingChannelAdapter.setSource(() -> new GenericMessage<>("test"));
    pollingChannelAdapter.setTrigger(new PeriodicTrigger(1));
    pollingChannelAdapter.setMaxMessagesPerPoll(0);
    QueueChannel outputChannel = new QueueChannel();
    pollingChannelAdapter.setOutputChannel(outputChannel);
    pollingChannelAdapter.setBeanFactory(mock(BeanFactory.class));
    LogAccessor logger = spy(TestUtils.getPropertyValue(pollingChannelAdapter, "logger", LogAccessor.class));
    new DirectFieldAccessor(pollingChannelAdapter).setPropertyValue("logger", logger);
    CountDownLatch logCalledLatch = new CountDownLatch(1);
    willAnswer(invocation -> {
        logCalledLatch.countDown();
        return invocation.callRealMethod();
    }).given(logger).info(anyString());
    pollingChannelAdapter.afterPropertiesSet();
    pollingChannelAdapter.start();
    assertThat(logCalledLatch.await(10, TimeUnit.SECONDS)).isTrue();
    verify(logger, atLeastOnce()).info("Polling disabled while 'maxMessagesPerPoll == 0'");
    pollingChannelAdapter.setMaxMessagesPerPoll(1);
    Message<?> receive = outputChannel.receive(10_000);
    assertThat(receive).isNotNull();
    assertThat(receive.getPayload()).isEqualTo("test");
    pollingChannelAdapter.stop();
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) BeanFactory(org.springframework.beans.factory.BeanFactory) SourcePollingChannelAdapter(org.springframework.integration.endpoint.SourcePollingChannelAdapter) LogAccessor(org.springframework.core.log.LogAccessor) CountDownLatch(java.util.concurrent.CountDownLatch) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) Test(org.junit.jupiter.api.Test)

Example 19 with LogAccessor

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

the class CustomMessagingAnnotationTests method testLogAnnotation.

@Test
public void testLogAnnotation() {
    assertThat(this.loggingHandler).isNotNull();
    LogAccessor log = spy(TestUtils.getPropertyValue(this.loggingHandler, "messageLogger", LogAccessor.class));
    given(log.isWarnEnabled()).willReturn(true);
    new DirectFieldAccessor(this.loggingHandler).setPropertyValue("messageLogger", log);
    this.loggingChannel.send(MessageBuilder.withPayload("foo").setHeader("bar", "baz").build());
    @SuppressWarnings("unchecked") ArgumentCaptor<Supplier<? extends CharSequence>> argumentCaptor = ArgumentCaptor.forClass(Supplier.class);
    verify(log).warn(argumentCaptor.capture());
    assertThat(argumentCaptor.getValue().get()).isEqualTo("foo for baz");
}
Also used : DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Supplier(java.util.function.Supplier) LogAccessor(org.springframework.core.log.LogAccessor) Test(org.junit.jupiter.api.Test)

Example 20 with LogAccessor

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

the class CachingClientConnectionFactoryTests method testGatewayRelease.

@SuppressWarnings("unchecked")
// INT-3722
@Test
public void testGatewayRelease() {
    TcpNetServerConnectionFactory in = new TcpNetServerConnectionFactory(0);
    in.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    final TcpSendingMessageHandler handler = new TcpSendingMessageHandler();
    handler.setConnectionFactory(in);
    final AtomicInteger count = new AtomicInteger(2);
    in.registerListener(message -> {
        if (!(message instanceof ErrorMessage)) {
            if (count.decrementAndGet() < 1) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            handler.handleMessage(message);
        }
        return false;
    });
    handler.setBeanFactory(mock(BeanFactory.class));
    handler.afterPropertiesSet();
    handler.start();
    TestingUtilities.waitListening(in, null);
    int port = in.getPort();
    TcpNetClientConnectionFactory out = new TcpNetClientConnectionFactory("localhost", port);
    out.setApplicationEventPublisher(mock(ApplicationEventPublisher.class));
    CachingClientConnectionFactory cache = new CachingClientConnectionFactory(out, 2);
    TcpOutboundGateway gate = new TcpOutboundGateway();
    gate.setConnectionFactory(cache);
    QueueChannel outputChannel = new QueueChannel();
    gate.setOutputChannel(outputChannel);
    gate.setBeanFactory(mock(BeanFactory.class));
    gate.setRemoteTimeout(20_000);
    gate.afterPropertiesSet();
    LogAccessor logger = spy(TestUtils.getPropertyValue(gate, "logger", LogAccessor.class));
    new DirectFieldAccessor(gate).setPropertyValue("logger", logger);
    when(logger.isDebugEnabled()).thenReturn(true);
    doAnswer(new Answer<Void>() {

        private final CountDownLatch latch = new CountDownLatch(2);

        private final AtomicBoolean first = new AtomicBoolean(true);

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            invocation.callRealMethod();
            String log = ((Supplier<String>) invocation.getArgument(0)).get();
            if (log.startsWith("Response") && this.first.getAndSet(false)) {
                new SimpleAsyncTaskExecutor("testGatewayRelease-").execute(() -> gate.handleMessage(new GenericMessage<>("bar")));
                // hold up the first thread until the second has added its pending reply
                this.latch.await(20, TimeUnit.SECONDS);
            } else if (log.startsWith("Added")) {
                this.latch.countDown();
            }
            return null;
        }
    }).when(logger).debug(any(Supplier.class));
    gate.start();
    gate.handleMessage(new GenericMessage<>("foo"));
    Message<byte[]> result = (Message<byte[]>) outputChannel.receive(10000);
    assertThat(result).isNotNull();
    assertThat(new String(result.getPayload())).isEqualTo("foo");
    result = (Message<byte[]>) outputChannel.receive(10000);
    assertThat(result).isNotNull();
    assertThat(new String(result.getPayload())).isEqualTo("bar");
    handler.stop();
    gate.stop();
    verify(logger, never()).error(anyString());
    cache.stop();
    in.stop();
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Message(org.springframework.messaging.Message) GenericMessage(org.springframework.messaging.support.GenericMessage) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) BeanFactory(org.springframework.beans.factory.BeanFactory) Supplier(java.util.function.Supplier) TcpSendingMessageHandler(org.springframework.integration.ip.tcp.TcpSendingMessageHandler) SimpleAsyncTaskExecutor(org.springframework.core.task.SimpleAsyncTaskExecutor) CountDownLatch(java.util.concurrent.CountDownLatch) TcpOutboundGateway(org.springframework.integration.ip.tcp.TcpOutboundGateway) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InvocationOnMock(org.mockito.invocation.InvocationOnMock) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) LogAccessor(org.springframework.core.log.LogAccessor) ErrorMessage(org.springframework.messaging.support.ErrorMessage) 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