Search in sources :

Example 46 with ThreadPoolTaskScheduler

use of org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler 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();
    LogAccessor adapterLogger = TestUtils.getPropertyValue(pollingChannelAdapter, "logger", LogAccessor.class);
    adapterLogger = spy(adapterLogger);
    when(adapterLogger.isDebugEnabled()).thenReturn(true);
    dfa = new DirectFieldAccessor(pollingChannelAdapter);
    dfa.setPropertyValue("logger", adapterLogger);
    pollingChannelAdapter.start();
    assertThat(startLatch.await(10, TimeUnit.SECONDS)).isTrue();
    pollingChannelAdapter.stop();
    taskScheduler.shutdown();
    verifyNoInteractions(errorHandlerLogger);
    verify(adapterLogger).debug(ArgumentMatchers.<Supplier<String>>argThat(logMessage -> logMessage.get().contains("Poll interrupted - during stop()?")));
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) QueueChannel(org.springframework.integration.channel.QueueChannel) MessagingException(org.springframework.messaging.MessagingException) ArgumentMatchers(org.mockito.ArgumentMatchers) PollerMetadata(org.springframework.integration.scheduling.PollerMetadata) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TestApplicationContext(org.springframework.integration.test.util.TestUtils.TestApplicationContext) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Mockito.spy(org.mockito.Mockito.spy) TestUtils(org.springframework.integration.test.util.TestUtils) Supplier(java.util.function.Supplier) MessagePublishingErrorHandler(org.springframework.integration.channel.MessagePublishingErrorHandler) MessageSource(org.springframework.integration.core.MessageSource) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) ArrayList(java.util.ArrayList) MethodInvocation(org.aopalliance.intercept.MethodInvocation) NullChannel(org.springframework.integration.channel.NullChannel) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Advice(org.aopalliance.aop.Advice) Message(org.springframework.messaging.Message) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) ClassUtils(org.springframework.util.ClassUtils) Trigger(org.springframework.scheduling.Trigger) Mockito.atLeastOnce(org.mockito.Mockito.atLeastOnce) SourcePollingChannelAdapter(org.springframework.integration.endpoint.SourcePollingChannelAdapter) TaskScheduler(org.springframework.scheduling.TaskScheduler) Mockito.when(org.mockito.Mockito.when) LogAccessor(org.springframework.core.log.LogAccessor) BDDMockito.willAnswer(org.mockito.BDDMockito.willAnswer) Mockito.verify(org.mockito.Mockito.verify) Lifecycle(org.springframework.context.Lifecycle) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) MethodInterceptor(org.aopalliance.intercept.MethodInterceptor) List(java.util.List) BeanFactory(org.springframework.beans.factory.BeanFactory) Log(org.apache.commons.logging.Log) GenericMessage(org.springframework.messaging.support.GenericMessage) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) MessagePublishingErrorHandler(org.springframework.integration.channel.MessagePublishingErrorHandler) MessagingException(org.springframework.messaging.MessagingException) Log(org.apache.commons.logging.Log) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CountDownLatch(java.util.concurrent.CountDownLatch) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) BeanFactory(org.springframework.beans.factory.BeanFactory) SourcePollingChannelAdapter(org.springframework.integration.endpoint.SourcePollingChannelAdapter) LogAccessor(org.springframework.core.log.LogAccessor) NullChannel(org.springframework.integration.channel.NullChannel) Test(org.junit.jupiter.api.Test)

Example 47 with ThreadPoolTaskScheduler

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

the class ExpressionEvaluatingMessageSourceIntegrationTests method test.

@Test
public void test() throws Exception {
    QueueChannel channel = new QueueChannel();
    String payloadExpression = "'test-' + T(org.springframework.integration.endpoint.ExpressionEvaluatingMessageSourceIntegrationTests).next()";
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.afterPropertiesSet();
    Map<String, Expression> headerExpressions = new HashMap<String, Expression>();
    headerExpressions.put("foo", new LiteralExpression("x"));
    headerExpressions.put("bar", new SpelExpressionParser().parseExpression("7 * 6"));
    ExpressionFactoryBean factoryBean = new ExpressionFactoryBean(payloadExpression);
    factoryBean.afterPropertiesSet();
    Expression expression = factoryBean.getObject();
    ExpressionEvaluatingMessageSource<Object> source = new ExpressionEvaluatingMessageSource<Object>(expression, Object.class);
    source.setBeanFactory(mock(BeanFactory.class));
    source.setHeaderExpressions(headerExpressions);
    SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter();
    adapter.setSource(source);
    adapter.setTaskScheduler(scheduler);
    adapter.setMaxMessagesPerPoll(3);
    adapter.setTrigger(new PeriodicTrigger(60000));
    adapter.setOutputChannel(channel);
    adapter.setErrorHandler(t -> {
        throw new IllegalStateException("unexpected exception in test", t);
    });
    adapter.start();
    List<Message<?>> messages = new ArrayList<Message<?>>();
    for (int i = 0; i < 3; i++) {
        messages.add(channel.receive(1000));
    }
    scheduler.destroy();
    Message<?> message1 = messages.get(0);
    assertThat(message1.getPayload()).isEqualTo("test-1");
    assertThat(message1.getHeaders().get("foo")).isEqualTo("x");
    assertThat(message1.getHeaders().get("bar")).isEqualTo(42);
    Message<?> message2 = messages.get(1);
    assertThat(message2.getPayload()).isEqualTo("test-2");
    assertThat(message2.getHeaders().get("foo")).isEqualTo("x");
    assertThat(message2.getHeaders().get("bar")).isEqualTo(42);
    Message<?> message3 = messages.get(2);
    assertThat(message3.getPayload()).isEqualTo("test-3");
    assertThat(message3.getHeaders().get("foo")).isEqualTo("x");
    assertThat(message3.getHeaders().get("bar")).isEqualTo(42);
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) Message(org.springframework.messaging.Message) HashMap(java.util.HashMap) LiteralExpression(org.springframework.expression.common.LiteralExpression) ArrayList(java.util.ArrayList) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) SpelExpressionParser(org.springframework.expression.spel.standard.SpelExpressionParser) ExpressionFactoryBean(org.springframework.integration.config.ExpressionFactoryBean) LiteralExpression(org.springframework.expression.common.LiteralExpression) Expression(org.springframework.expression.Expression) BeanFactory(org.springframework.beans.factory.BeanFactory) Test(org.junit.Test)

Example 48 with ThreadPoolTaskScheduler

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

the class DelayHandlerTests method setup.

@BeforeEach
public void setup() {
    input.setBeanName("input");
    output.setBeanName("output");
    taskScheduler = new ThreadPoolTaskScheduler();
    taskScheduler.afterPropertiesSet();
    delayHandler = new DelayHandler(DELAYER_MESSAGE_GROUP_ID, taskScheduler);
    delayHandler.setOutputChannel(output);
    delayHandler.setBeanFactory(mock(BeanFactory.class));
    input.subscribe(delayHandler);
    output.subscribe(resultHandler);
}
Also used : BeanFactory(org.springframework.beans.factory.BeanFactory) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 49 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 = new File(tempDir, UUID.randomUUID().toString());
    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());
    assertThat(closeWhileWriting.get()).isFalse();
    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.jupiter.api.Test)

Example 50 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 = new File(tempDir, UUID.randomUUID().toString());
    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<>("foo"));
    handler.handleMessage(new GenericMessage<>("bar"));
    handler.handleMessage(new GenericMessage<>("baz"));
    // change of payload type forces flush
    handler.handleMessage(new GenericMessage<>("qux".getBytes()));
    assertThat(file.length()).isGreaterThanOrEqualTo(9L);
    // forces flush
    handler.stop();
    assertThat(file.length()).isEqualTo(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()).isEqualTo(15L);
    handler.handleMessage(new GenericMessage<InputStream>(new ByteArrayInputStream("buz".getBytes())));
    handler.trigger(new GenericMessage<>(Matcher.quoteReplacement(file.getAbsolutePath())));
    assertThat(file.length()).isEqualTo(18L);
    assertThat(TestUtils.getPropertyValue(handler, "fileStates", Map.class).size()).isEqualTo(0);
    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<>("foo"));
    assertThat(file.length()).isEqualTo(21L);
    assertThat(called.get()).isTrue();
    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()).isEqualTo(24L);
    assertThat(called.get()).isTrue();
    handler.stop();
    LogAccessor logger = spy(TestUtils.getPropertyValue(handler, "logger", LogAccessor.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<>("foo"));
        Thread.sleep(5);
    }
    assertThat(flushes.get()).isGreaterThanOrEqualTo(2);
    handler.stop();
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) 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) LogAccessor(org.springframework.core.log.LogAccessor) File(java.io.File) NullChannel(org.springframework.integration.channel.NullChannel) Map(java.util.Map) Test(org.junit.jupiter.api.Test)

Aggregations

ThreadPoolTaskScheduler (org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler)259 Bean (org.springframework.context.annotation.Bean)117 Test (org.junit.jupiter.api.Test)73 BeanFactory (org.springframework.beans.factory.BeanFactory)33 CountDownLatch (java.util.concurrent.CountDownLatch)24 QueueChannel (org.springframework.integration.channel.QueueChannel)23 AtomicReference (java.util.concurrent.atomic.AtomicReference)18 Test (org.junit.Test)18 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)18 ConditionalOnMissingBean (org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean)15 GenericMessage (org.springframework.messaging.support.GenericMessage)14 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)13 ExecutorService (java.util.concurrent.ExecutorService)12 ArrayList (java.util.ArrayList)11 Message (org.springframework.messaging.Message)9 MessageChannel (org.springframework.messaging.MessageChannel)9 LogAccessor (org.springframework.core.log.LogAccessor)8 MessagingException (org.springframework.messaging.MessagingException)8 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)7 IOException (java.io.IOException)6