Search in sources :

Example 26 with ThreadPoolTaskScheduler

use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler in project spring-integration by spring-projects.

the class ImapMailReceiverTests method testExecShutdown.

@Test
public void testExecShutdown() {
    ImapIdleChannelAdapter adapter = new ImapIdleChannelAdapter(new ImapMailReceiver());
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    adapter.setTaskScheduler(taskScheduler);
    adapter.start();
    ExecutorService exec = TestUtils.getPropertyValue(adapter, "sendingTaskExecutor", ExecutorService.class);
    adapter.stop();
    assertTrue(exec.isShutdown());
    adapter.start();
    exec = TestUtils.getPropertyValue(adapter, "sendingTaskExecutor", ExecutorService.class);
    adapter.stop();
    assertTrue(exec.isShutdown());
}
Also used : ExecutorService(java.util.concurrent.ExecutorService) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) LongRunningIntegrationTest(org.springframework.integration.test.support.LongRunningIntegrationTest) Test(org.junit.Test)

Example 27 with ThreadPoolTaskScheduler

use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler in project spring-integration by spring-projects.

the class ImapMailReceiverTests method testConnectionException.

@Test
public void testConnectionException() throws Exception {
    ImapMailReceiver mailReceiver = new ImapMailReceiver("imap:foo");
    ImapIdleChannelAdapter adapter = new ImapIdleChannelAdapter(mailReceiver);
    final AtomicReference<ImapIdleExceptionEvent> theEvent = new AtomicReference<ImapIdleExceptionEvent>();
    final CountDownLatch latch = new CountDownLatch(1);
    adapter.setApplicationEventPublisher(event -> {
        assertNull("only one event expected", theEvent.get());
        theEvent.set((ImapIdleExceptionEvent) event);
        latch.countDown();
    });
    ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.initialize();
    adapter.setTaskScheduler(taskScheduler);
    adapter.start();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    assertTrue(theEvent.get().toString().endsWith("cause=java.lang.IllegalStateException: Failure in 'idle' task. Will resubmit.]"));
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) ImapIdleExceptionEvent(org.springframework.integration.mail.ImapIdleChannelAdapter.ImapIdleExceptionEvent) CountDownLatch(java.util.concurrent.CountDownLatch) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) LongRunningIntegrationTest(org.springframework.integration.test.support.LongRunningIntegrationTest) Test(org.junit.Test)

Example 28 with ThreadPoolTaskScheduler

use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler 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 29 with ThreadPoolTaskScheduler

use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler in project spring-integration by spring-projects.

the class FileWritingMessageHandlerTests method lockForFlush.

@Test
public void lockForFlush() throws Exception {
    File tempFolder = this.temp.newFolder();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final BufferedOutputStream out = spy(new BufferedOutputStream(baos));
    FileWritingMessageHandler handler = new FileWritingMessageHandler(tempFolder) {

        @Override
        protected BufferedOutputStream createOutputStream(File fileToWriteTo, boolean append) {
            return out;
        }
    };
    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(10);
    handler.setFlushWhenIdle(false);
    handler.afterPropertiesSet();
    handler.start();
    final AtomicBoolean writing = new AtomicBoolean();
    final AtomicBoolean closeWhileWriting = new AtomicBoolean();
    willAnswer(i -> {
        writing.set(true);
        Thread.sleep(500);
        writing.set(false);
        return null;
    }).given(out).write(any(byte[].class), anyInt(), anyInt());
    willAnswer(i -> {
        closeWhileWriting.compareAndSet(false, writing.get());
        return null;
    }).given(out).close();
    handler.handleMessage(new GenericMessage<>("foo".getBytes()));
    verify(out).write(any(byte[].class), anyInt(), anyInt());
    assertFalse(closeWhileWriting.get());
    handler.stop();
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BeanFactory(org.springframework.beans.factory.BeanFactory) ByteArrayOutputStream(org.apache.commons.io.output.ByteArrayOutputStream) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) NullChannel(org.springframework.integration.channel.NullChannel) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) Test(org.junit.Test)

Example 30 with ThreadPoolTaskScheduler

use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler 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)

Aggregations

ThreadPoolTaskScheduler (org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler)122 Test (org.junit.Test)41 Bean (org.springframework.context.annotation.Bean)32 BeanFactory (org.springframework.beans.factory.BeanFactory)31 Test (org.junit.jupiter.api.Test)26 CountDownLatch (java.util.concurrent.CountDownLatch)19 QueueChannel (org.springframework.integration.channel.QueueChannel)19 GenericMessage (org.springframework.messaging.support.GenericMessage)13 AtomicReference (java.util.concurrent.atomic.AtomicReference)12 ExecutorService (java.util.concurrent.ExecutorService)10 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)8 MqttPahoMessageDrivenChannelAdapter (org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter)8 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 MqttPahoMessageHandler (org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler)6 JmsTemplate (org.springframework.jms.core.JmsTemplate)6 ArrayList (java.util.ArrayList)5 Log (org.apache.commons.logging.Log)5 MessageChannel (org.springframework.messaging.MessageChannel)5 File (java.io.File)4 ConnectionFactory (javax.jms.ConnectionFactory)4