Search in sources :

Example 46 with Log

use of org.apache.commons.logging.Log in project spring-integration by spring-projects.

the class SourcePollingChannelAdapterFactoryBeanTests method testInterrupted.

@Test
public void testInterrupted() throws Exception {
    final CountDownLatch startLatch = new CountDownLatch(1);
    MessageSource<Object> ms = () -> {
        startLatch.countDown();
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new MessagingException("Interrupted awaiting stopLatch", e);
        }
        return null;
    };
    SourcePollingChannelAdapter pollingChannelAdapter = new SourcePollingChannelAdapter();
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
    taskScheduler.setAwaitTerminationSeconds(1);
    taskScheduler.afterPropertiesSet();
    pollingChannelAdapter.setTaskScheduler(taskScheduler);
    MessagePublishingErrorHandler errorHandler = new MessagePublishingErrorHandler();
    Log errorHandlerLogger = TestUtils.getPropertyValue(errorHandler, "logger", Log.class);
    errorHandlerLogger = spy(errorHandlerLogger);
    DirectFieldAccessor dfa = new DirectFieldAccessor(errorHandler);
    dfa.setPropertyValue("logger", errorHandlerLogger);
    pollingChannelAdapter.setErrorHandler(errorHandler);
    pollingChannelAdapter.setSource(ms);
    pollingChannelAdapter.setOutputChannel(new NullChannel());
    pollingChannelAdapter.setBeanFactory(mock(BeanFactory.class));
    pollingChannelAdapter.afterPropertiesSet();
    Log adapterLogger = TestUtils.getPropertyValue(pollingChannelAdapter, "logger", Log.class);
    adapterLogger = spy(adapterLogger);
    when(adapterLogger.isDebugEnabled()).thenReturn(true);
    dfa = new DirectFieldAccessor(pollingChannelAdapter);
    dfa.setPropertyValue("logger", adapterLogger);
    pollingChannelAdapter.start();
    assertTrue(startLatch.await(10, TimeUnit.SECONDS));
    pollingChannelAdapter.stop();
    taskScheduler.shutdown();
    verifyZeroInteractions(errorHandlerLogger);
    verify(adapterLogger).debug(contains("Poll interrupted - during stop()?"));
}
Also used : MessagePublishingErrorHandler(org.springframework.integration.channel.MessagePublishingErrorHandler) MessagingException(org.springframework.messaging.MessagingException) Log(org.apache.commons.logging.Log) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) BeanFactory(org.springframework.beans.factory.BeanFactory) SourcePollingChannelAdapter(org.springframework.integration.endpoint.SourcePollingChannelAdapter) CountDownLatch(java.util.concurrent.CountDownLatch) NullChannel(org.springframework.integration.channel.NullChannel) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) Test(org.junit.Test)

Example 47 with Log

use of org.apache.commons.logging.Log in project spring-integration by spring-projects.

the class P2pChannelTests method verifySubscriptions.

/**
 * @param channel
 */
private void verifySubscriptions(final AbstractSubscribableChannel channel) {
    final Log logger = mock(Log.class);
    when(logger.isInfoEnabled()).thenReturn(true);
    final List<String> logs = new ArrayList<>();
    doAnswer(invocation -> {
        logs.add(invocation.getArgument(0));
        return null;
    }).when(logger).info(Mockito.anyString());
    ReflectionUtils.doWithFields(AbstractMessageChannel.class, field -> {
        if ("logger".equals(field.getName())) {
            field.setAccessible(true);
            field.set(channel, logger);
        }
    });
    String log = "Channel '" + channel.getComponentName() + "' has " + "%d subscriber(s).";
    MessageHandler handler1 = mock(MessageHandler.class);
    channel.subscribe(handler1);
    assertEquals(1, channel.getSubscriberCount());
    assertEquals(String.format(log, 1), logs.remove(0));
    MessageHandler handler2 = mock(MessageHandler.class);
    channel.subscribe(handler2);
    assertEquals(2, channel.getSubscriberCount());
    assertEquals(String.format(log, 2), logs.remove(0));
    channel.unsubscribe(handler1);
    assertEquals(1, channel.getSubscriberCount());
    assertEquals(String.format(log, 1), logs.remove(0));
    channel.unsubscribe(handler1);
    assertEquals(1, channel.getSubscriberCount());
    assertEquals(0, logs.size());
    channel.unsubscribe(handler2);
    assertEquals(0, channel.getSubscriberCount());
    assertEquals(String.format(log, 0), logs.remove(0));
    verify(logger, times(4)).info(Mockito.anyString());
}
Also used : MessageHandler(org.springframework.messaging.MessageHandler) Log(org.apache.commons.logging.Log) ArrayList(java.util.ArrayList)

Example 48 with Log

use of org.apache.commons.logging.Log in project spring-integration by spring-projects.

the class TcpNetConnectionTests method testErrorLog.

@Test
public void testErrorLog() throws Exception {
    Socket socket = mock(Socket.class);
    InputStream stream = mock(InputStream.class);
    when(socket.getInputStream()).thenReturn(stream);
    when(stream.read()).thenReturn((int) 'x');
    TcpNetConnection connection = new TcpNetConnection(socket, true, false, e -> {
    }, null);
    connection.setDeserializer(new ByteArrayStxEtxSerializer());
    final AtomicReference<Object> log = new AtomicReference<Object>();
    Log logger = mock(Log.class);
    doAnswer(invocation -> {
        log.set(invocation.getArguments()[0]);
        return null;
    }).when(logger).error(Mockito.anyString());
    DirectFieldAccessor accessor = new DirectFieldAccessor(connection);
    accessor.setPropertyValue("logger", logger);
    connection.registerListener(mock(TcpListener.class));
    connection.setMapper(new TcpMessageMapper());
    connection.run();
    assertNotNull(log.get());
    assertEquals("Read exception " + connection.getConnectionId() + " MessageMappingException:Expected STX to begin message", log.get());
}
Also used : Log(org.apache.commons.logging.Log) PipedInputStream(java.io.PipedInputStream) ChannelInputStream(org.springframework.integration.ip.tcp.connection.TcpNioConnection.ChannelInputStream) InputStream(java.io.InputStream) ByteArrayStxEtxSerializer(org.springframework.integration.ip.tcp.serializer.ByteArrayStxEtxSerializer) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) AtomicReference(java.util.concurrent.atomic.AtomicReference) Socket(java.net.Socket) Test(org.junit.Test)

Example 49 with Log

use of org.apache.commons.logging.Log in project spring-integration by spring-projects.

the class ConnectionEventTests method testServerExceptionGuts.

private void testServerExceptionGuts(AbstractServerConnectionFactory factory) throws Exception {
    ServerSocket ss = null;
    try {
        ss = ServerSocketFactory.getDefault().createServerSocket(0);
    } catch (Exception e) {
        fail("Failed to get a server socket");
    }
    factory.setPort(ss.getLocalPort());
    final AtomicReference<TcpConnectionServerExceptionEvent> theEvent = new AtomicReference<TcpConnectionServerExceptionEvent>();
    final CountDownLatch latch = new CountDownLatch(1);
    factory.setApplicationEventPublisher(new ApplicationEventPublisher() {

        @Override
        public void publishEvent(ApplicationEvent event) {
            theEvent.set((TcpConnectionServerExceptionEvent) event);
            latch.countDown();
        }

        @Override
        public void publishEvent(Object event) {
        }
    });
    factory.setBeanName("sf");
    factory.registerListener(message -> false);
    Log logger = spy(TestUtils.getPropertyValue(factory, "logger", Log.class));
    doNothing().when(logger).error(anyString(), any(Throwable.class));
    new DirectFieldAccessor(factory).setPropertyValue("logger", logger);
    factory.start();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    String actual = theEvent.toString();
    assertThat(actual, containsString("cause=java.net.BindException"));
    assertThat(actual, containsString("source=" + "sf, port=" + factory.getPort()));
    ArgumentCaptor<String> reasonCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<Throwable> throwableCaptor = ArgumentCaptor.forClass(Throwable.class);
    verify(logger).error(reasonCaptor.capture(), throwableCaptor.capture());
    assertThat(reasonCaptor.getValue(), startsWith("Error on Server"));
    assertThat(reasonCaptor.getValue(), endsWith("; port = " + factory.getPort()));
    assertThat(throwableCaptor.getValue(), instanceOf(BindException.class));
    ss.close();
}
Also used : Log(org.apache.commons.logging.Log) ApplicationEvent(org.springframework.context.ApplicationEvent) BindException(java.net.BindException) ServerSocket(java.net.ServerSocket) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.containsString(org.hamcrest.Matchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) MessageHandlingException(org.springframework.messaging.MessageHandlingException) MessagingException(org.springframework.messaging.MessagingException) BindException(java.net.BindException) UnknownHostException(java.net.UnknownHostException) ApplicationEventPublisher(org.springframework.context.ApplicationEventPublisher) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor)

Example 50 with Log

use of org.apache.commons.logging.Log in project spring-integration by spring-projects.

the class DownstreamExceptionTests method testNoErrorChannel.

@Test
public void testNoErrorChannel() throws Exception {
    service.n = 0;
    Log logger = spy(TestUtils.getPropertyValue(noErrorChannel, "logger", Log.class));
    final CountDownLatch latch = new CountDownLatch(1);
    doAnswer(invocation -> {
        if (((String) invocation.getArgument(0)).contains("Unhandled")) {
            latch.countDown();
        }
        return null;
    }).when(logger).error(anyString(), any(Throwable.class));
    new DirectFieldAccessor(noErrorChannel).setPropertyValue("logger", logger);
    MqttPahoMessageHandler adapter = new MqttPahoMessageHandler("tcp://localhost:1883", "si-test-out");
    adapter.setDefaultTopic("mqtt-fooEx1");
    adapter.setBeanFactory(mock(BeanFactory.class));
    adapter.afterPropertiesSet();
    adapter.start();
    adapter.handleMessage(new GenericMessage<String>("foo"));
    service.barrier.await(10, TimeUnit.SECONDS);
    service.barrier.reset();
    adapter.handleMessage(new GenericMessage<String>("foo"));
    service.barrier.await(10, TimeUnit.SECONDS);
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    verify(logger).error(contains("Unhandled exception for"), any(Throwable.class));
    service.barrier.reset();
    adapter.stop();
}
Also used : Log(org.apache.commons.logging.Log) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) MqttPahoMessageHandler(org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler) BeanFactory(org.springframework.beans.factory.BeanFactory) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Aggregations

Log (org.apache.commons.logging.Log)188 Test (org.junit.Test)51 Test (org.junit.jupiter.api.Test)40 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)35 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)19 BeanFactory (org.springframework.beans.factory.BeanFactory)17 CountDownLatch (java.util.concurrent.CountDownLatch)15 LogConfigurationException (org.apache.commons.logging.LogConfigurationException)15 ArrayList (java.util.ArrayList)12 File (java.io.File)11 QueueChannel (org.springframework.integration.channel.QueueChannel)11 MethodInvocation (org.aopalliance.intercept.MethodInvocation)10 IOException (java.io.IOException)9 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 Log4JLogger (org.apache.commons.logging.impl.Log4JLogger)9 Message (org.springframework.messaging.Message)8 List (java.util.List)7 ApplicationEventPublisher (org.springframework.context.ApplicationEventPublisher)7 InputStream (java.io.InputStream)6 LogFactory (org.apache.commons.logging.LogFactory)6