Search in sources :

Example 51 with Log

use of org.apache.commons.logging.Log 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();
    Log logger = spy(TestUtils.getPropertyValue(adapter, "logger", Log.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);
    Thread.sleep(1000);
    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("UTF-8");
    Socket socket = SocketFactory.getDefault().createSocket("localhost", connectionFactory.getPort());
    socket.getOutputStream().write(buf);
    socket.close();
    assertTrue(sawLog.await(10, TimeUnit.SECONDS));
    @SuppressWarnings("unchecked") Message<Map<String, ?>> message = (Message<Map<String, ?>>) outputChannel.receive(10000);
    assertNotNull(message);
    assertEquals("loggregator", message.getPayload().get("syslog_HOST"));
    adapter.stop();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
}
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) Log(org.apache.commons.logging.Log) 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) Map(java.util.Map) Socket(java.net.Socket) DatagramSocket(java.net.DatagramSocket) Test(org.junit.Test)

Example 52 with Log

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

the class ImapMailReceiverTests method testIdleWithServerGuts.

public void testIdleWithServerGuts(ImapMailReceiver receiver, boolean mapped, boolean simple) throws Exception {
    imapIdleServer.resetServer();
    Properties mailProps = new Properties();
    mailProps.put("mail.debug", "true");
    mailProps.put("mail.imap.connectionpool.debug", "true");
    receiver.setJavaMailProperties(mailProps);
    receiver.setMaxFetchSize(1);
    receiver.setShouldDeleteMessages(false);
    receiver.setShouldMarkMessagesAsRead(true);
    receiver.setCancelIdleInterval(8);
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    setUpScheduler(receiver, taskScheduler);
    receiver.setUserFlag("testSIUserFlag");
    receiver.afterPropertiesSet();
    Log logger = spy(TestUtils.getPropertyValue(receiver, "logger", Log.class));
    new DirectFieldAccessor(receiver).setPropertyValue("logger", logger);
    ImapIdleChannelAdapter adapter = new ImapIdleChannelAdapter(receiver);
    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);
    adapter.setTaskScheduler(taskScheduler);
    adapter.start();
    if (!mapped) {
        @SuppressWarnings("unchecked") org.springframework.messaging.Message<MimeMessage> received = (org.springframework.messaging.Message<MimeMessage>) channel.receive(10000);
        assertNotNull(received);
        assertNotNull(received.getPayload().getReceivedDate());
        assertTrue(received.getPayload().getLineCount() > -1);
        if (simple) {
            assertThat(received.getPayload().getContent(), equalTo(TestMailServer.MailServer.MailHandler.BODY + "\r\n"));
        } else {
            assertThat(received.getPayload().getContent(), equalTo(TestMailServer.MailServer.MailHandler.MESSAGE + "\r\n"));
        }
    } else {
        org.springframework.messaging.Message<?> received = channel.receive(10000);
        assertNotNull(received);
        MessageHeaders headers = received.getHeaders();
        assertNotNull(headers.get(MailHeaders.RAW_HEADERS));
        assertThat(headers.get(MailHeaders.CONTENT_TYPE), equalTo("TEXT/PLAIN; charset=ISO-8859-1"));
        assertThat(headers.get(MessageHeaders.CONTENT_TYPE), equalTo("TEXT/PLAIN; charset=ISO-8859-1"));
        assertThat(headers.get(MailHeaders.FROM), equalTo("Bar <bar@baz>"));
        assertThat((headers.get(MailHeaders.TO, String[].class))[0], equalTo("Foo <foo@bar>"));
        assertThat(Arrays.toString(headers.get(MailHeaders.CC, String[].class)), equalTo("[a@b, c@d]"));
        assertThat(Arrays.toString(headers.get(MailHeaders.BCC, String[].class)), equalTo("[e@f, g@h]"));
        assertThat(headers.get(MailHeaders.SUBJECT), equalTo("Test Email"));
        if (simple) {
            assertThat(received.getPayload(), equalTo(TestMailServer.MailServer.MailHandler.BODY + "\r\n"));
        } else {
            assertThat(received.getPayload(), equalTo(TestMailServer.MailServer.MailHandler.MESSAGE + "\r\n"));
        }
    }
    // new message after idle
    assertNotNull(channel.receive(10000));
    // no new message after second and third idle
    assertNull(channel.receive(10000));
    verify(logger).debug("Canceling IDLE");
    taskScheduler.shutdown();
    assertTrue(imapIdleServer.assertReceived("storeUserFlag"));
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Log(org.apache.commons.logging.Log) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Properties(java.util.Properties) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) MimeMessage(javax.mail.internet.MimeMessage) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) MessageHeaders(org.springframework.messaging.MessageHeaders)

Example 53 with Log

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

the class FileWritingMessageHandlerTests method noFlushAppend.

@Test
public void noFlushAppend() throws Exception {
    File tempFolder = this.temp.newFolder();
    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<String>("foo"));
    handler.handleMessage(new GenericMessage<String>("bar"));
    handler.handleMessage(new GenericMessage<String>("baz"));
    // change of payload type forces flush
    handler.handleMessage(new GenericMessage<byte[]>("qux".getBytes()));
    assertThat(file.length(), greaterThanOrEqualTo(9L));
    // forces flush
    handler.stop();
    assertThat(file.length(), equalTo(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(), equalTo(15L));
    handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("buz".getBytes())));
    handler.trigger(new GenericMessage<String>(Matcher.quoteReplacement(file.getAbsolutePath())));
    assertThat(file.length(), equalTo(18L));
    assertEquals(0, TestUtils.getPropertyValue(handler, "fileStates", Map.class).size());
    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<String>("foo"));
    assertThat(file.length(), equalTo(21L));
    assertTrue(called.get());
    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(), equalTo(24L));
    assertTrue(called.get());
    handler.stop();
    Log logger = spy(TestUtils.getPropertyValue(handler, "logger", Log.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<String>("foo"));
        Thread.sleep(5);
    }
    assertThat(flushes.get(), greaterThanOrEqualTo(2));
    handler.stop();
}
Also used : Log(org.apache.commons.logging.Log) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) 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) File(java.io.File) NullChannel(org.springframework.integration.channel.NullChannel) Test(org.junit.Test)

Example 54 with Log

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

the class JmsOutboundGateway method onMessageSync.

private void onMessageSync(javax.jms.Message message, String correlationId) {
    try {
        LinkedBlockingQueue<javax.jms.Message> queue = this.replies.get(correlationId);
        if (queue == null) {
            if (this.correlationKey != null) {
                Log debugLogger = LogFactory.getLog("si.jmsgateway.debug");
                if (debugLogger.isDebugEnabled()) {
                    Object siMessage = this.messageConverter.fromMessage(message);
                    debugLogger.debug("No pending reply for " + siMessage + " with correlationId: " + correlationId + " pending replies: " + this.replies.keySet());
                }
                throw new RuntimeException("No sender waiting for reply");
            }
            synchronized (this.earlyOrLateReplies) {
                queue = this.replies.get(correlationId);
                if (queue == null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Reply for correlationId " + correlationId + " received early or late");
                    }
                    this.earlyOrLateReplies.put(correlationId, new TimedReply(message));
                }
            }
        }
        if (queue != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Received reply with correlationId " + correlationId);
            }
            queue.add(message);
        }
    } catch (Exception e) {
        if (logger.isWarnEnabled()) {
            logger.warn("Failed to consume reply with correlationId " + correlationId, e);
        }
    }
}
Also used : Message(org.springframework.messaging.Message) Log(org.apache.commons.logging.Log) MessageTimeoutException(org.springframework.integration.MessageTimeoutException) MessageHandlingException(org.springframework.messaging.MessageHandlingException) JMSException(javax.jms.JMSException) MessageDeliveryException(org.springframework.messaging.MessageDeliveryException)

Example 55 with Log

use of org.apache.commons.logging.Log 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();
    Log logger = spy(TestUtils.getPropertyValue(listener, "logger", Log.class));
    doNothing().when(logger).error(anyString(), any(Throwable.class));
    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(javax.jms.Message message) throws JMSException, MessageConversionException {
            return null;
        }
    });
    listener.afterPropertiesSet();
    javax.jms.Message jmsMessage = session.createTextMessage("test");
    listener.onMessage(jmsMessage, mock(Session.class));
    ErrorMessage received = (ErrorMessage) errorChannel.receive(0);
    assertNotNull(received);
    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) Log(org.apache.commons.logging.Log) JMSException(javax.jms.JMSException) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) BeanFactory(org.springframework.beans.factory.BeanFactory) ErrorMessage(org.springframework.messaging.support.ErrorMessage) Session(javax.jms.Session) 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