Search in sources :

Example 11 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);
    assertEquals("test-1", message1.getPayload());
    assertEquals("x", message1.getHeaders().get("foo"));
    assertEquals(42, message1.getHeaders().get("bar"));
    Message<?> message2 = messages.get(1);
    assertEquals("test-2", message2.getPayload());
    assertEquals("x", message2.getHeaders().get("foo"));
    assertEquals(42, message2.getHeaders().get("bar"));
    Message<?> message3 = messages.get(2);
    assertEquals("test-3", message3.getPayload());
    assertEquals("x", message3.getHeaders().get("foo"));
    assertEquals(42, message3.getHeaders().get("bar"));
}
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 12 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();
    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 13 with ThreadPoolTaskScheduler

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

the class DefaultConfiguringBeanFactoryPostProcessor method registerTaskScheduler.

/**
 * Register a TaskScheduler in the given BeanDefinitionRegistry.
 */
private void registerTaskScheduler(BeanDefinitionRegistry registry) {
    if (this.logger.isInfoEnabled()) {
        this.logger.info("No bean named '" + IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME + "' has been explicitly defined. Therefore, a default ThreadPoolTaskScheduler will be created.");
    }
    BeanDefinition scheduler = BeanDefinitionBuilder.genericBeanDefinition(ThreadPoolTaskScheduler.class).addPropertyValue("poolSize", IntegrationProperties.getExpressionFor(IntegrationProperties.TASK_SCHEDULER_POOL_SIZE)).addPropertyValue("threadNamePrefix", "task-scheduler-").addPropertyValue("rejectedExecutionHandler", new CallerRunsPolicy()).addPropertyValue("errorHandler", new RootBeanDefinition(MessagePublishingErrorHandler.class)).getBeanDefinition();
    registry.registerBeanDefinition(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, scheduler);
}
Also used : CallerRunsPolicy(java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) RootBeanDefinition(org.springframework.beans.factory.support.RootBeanDefinition) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler)

Example 14 with ThreadPoolTaskScheduler

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

the class OutboundGatewayFunctionTests method testContainerWithDestNoCorrelation.

@Test
public void testContainerWithDestNoCorrelation() throws Exception {
    BeanFactory beanFactory = mock(BeanFactory.class);
    when(beanFactory.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)).thenReturn(true);
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.initialize();
    when(beanFactory.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class)).thenReturn(scheduler);
    final JmsOutboundGateway gateway = new JmsOutboundGateway();
    gateway.setBeanFactory(beanFactory);
    gateway.setConnectionFactory(getConnectionFactory());
    gateway.setRequestDestination(requestQueue2);
    gateway.setReplyDestination(replyQueue2);
    gateway.setUseReplyContainer(true);
    gateway.afterPropertiesSet();
    gateway.start();
    final AtomicReference<Object> reply = new AtomicReference<Object>();
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.execute(() -> {
        latch1.countDown();
        try {
            reply.set(gateway.handleRequestMessage(new GenericMessage<String>("foo")));
        } finally {
            latch2.countDown();
        }
    });
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    JmsTemplate template = new JmsTemplate();
    template.setConnectionFactory(getConnectionFactory());
    template.setReceiveTimeout(10000);
    javax.jms.Message request = template.receive(requestQueue2);
    assertNotNull(request);
    final javax.jms.Message jmsReply = request;
    template.send(request.getJMSReplyTo(), (MessageCreator) session -> {
        jmsReply.setJMSCorrelationID(jmsReply.getJMSMessageID());
        return jmsReply;
    });
    assertTrue(latch2.await(20, TimeUnit.SECONDS));
    assertNotNull(reply.get());
    gateway.stop();
    scheduler.destroy();
    exec.shutdownNow();
}
Also used : DefaultMessageListenerContainer(org.springframework.jms.listener.DefaultMessageListenerContainer) ActiveMQQueue(org.apache.activemq.command.ActiveMQQueue) TestUtils(org.springframework.integration.test.util.TestUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) CachingConnectionFactory(org.springframework.jms.connection.CachingConnectionFactory) JmsTemplate(org.springframework.jms.core.JmsTemplate) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) ExecutorService(java.util.concurrent.ExecutorService) JmsException(org.springframework.jms.JmsException) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) TaskScheduler(org.springframework.scheduling.TaskScheduler) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) JMSException(javax.jms.JMSException) Executors(java.util.concurrent.Executors) IntegrationContextUtils(org.springframework.integration.context.IntegrationContextUtils) ActiveMQConnectionFactory(org.apache.activemq.ActiveMQConnectionFactory) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) MessageCreator(org.springframework.jms.core.MessageCreator) Rule(org.junit.Rule) Log4j2LevelAdjuster(org.springframework.integration.test.rule.Log4j2LevelAdjuster) Destination(javax.jms.Destination) Assert.assertFalse(org.junit.Assert.assertFalse) BeanFactory(org.springframework.beans.factory.BeanFactory) GenericMessage(org.springframework.messaging.support.GenericMessage) ConnectionFactory(javax.jms.ConnectionFactory) Mockito.mock(org.mockito.Mockito.mock) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) GenericMessage(org.springframework.messaging.support.GenericMessage) BeanFactory(org.springframework.beans.factory.BeanFactory) ExecutorService(java.util.concurrent.ExecutorService) JmsTemplate(org.springframework.jms.core.JmsTemplate) Test(org.junit.Test)

Example 15 with ThreadPoolTaskScheduler

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

the class OutboundGatewayFunctionTests method testContainerWithDest.

@Test
public void testContainerWithDest() throws Exception {
    BeanFactory beanFactory = mock(BeanFactory.class);
    when(beanFactory.containsBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME)).thenReturn(true);
    ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
    scheduler.initialize();
    when(beanFactory.getBean(IntegrationContextUtils.TASK_SCHEDULER_BEAN_NAME, TaskScheduler.class)).thenReturn(scheduler);
    final JmsOutboundGateway gateway = new JmsOutboundGateway();
    gateway.setBeanFactory(beanFactory);
    ConnectionFactory connectionFactory = getConnectionFactory();
    gateway.setConnectionFactory(connectionFactory);
    gateway.setRequestDestination(requestQueue1);
    gateway.setReplyDestination(replyQueue1);
    gateway.setCorrelationKey("JMSCorrelationID");
    gateway.setUseReplyContainer(true);
    gateway.afterPropertiesSet();
    gateway.start();
    final AtomicReference<Object> reply = new AtomicReference<Object>();
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    ExecutorService exec = Executors.newSingleThreadExecutor();
    exec.execute(() -> {
        latch1.countDown();
        try {
            reply.set(gateway.handleRequestMessage(new GenericMessage<String>("foo")));
        } finally {
            latch2.countDown();
        }
    });
    assertTrue(latch1.await(10, TimeUnit.SECONDS));
    JmsTemplate template = new JmsTemplate();
    template.setConnectionFactory(connectionFactory);
    template.setReceiveTimeout(10000);
    javax.jms.Message request = template.receive(requestQueue1);
    assertNotNull(request);
    final javax.jms.Message jmsReply = request;
    template.send(request.getJMSReplyTo(), (MessageCreator) session -> jmsReply);
    assertTrue(latch2.await(10, TimeUnit.SECONDS));
    assertNotNull(reply.get());
    gateway.stop();
    scheduler.destroy();
    exec.shutdown();
}
Also used : DefaultMessageListenerContainer(org.springframework.jms.listener.DefaultMessageListenerContainer) ActiveMQQueue(org.apache.activemq.command.ActiveMQQueue) TestUtils(org.springframework.integration.test.util.TestUtils) AtomicReference(java.util.concurrent.atomic.AtomicReference) CachingConnectionFactory(org.springframework.jms.connection.CachingConnectionFactory) JmsTemplate(org.springframework.jms.core.JmsTemplate) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) ExecutorService(java.util.concurrent.ExecutorService) JmsException(org.springframework.jms.JmsException) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) TaskScheduler(org.springframework.scheduling.TaskScheduler) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) JMSException(javax.jms.JMSException) Executors(java.util.concurrent.Executors) IntegrationContextUtils(org.springframework.integration.context.IntegrationContextUtils) ActiveMQConnectionFactory(org.apache.activemq.ActiveMQConnectionFactory) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) MessageCreator(org.springframework.jms.core.MessageCreator) Rule(org.junit.Rule) Log4j2LevelAdjuster(org.springframework.integration.test.rule.Log4j2LevelAdjuster) Destination(javax.jms.Destination) Assert.assertFalse(org.junit.Assert.assertFalse) BeanFactory(org.springframework.beans.factory.BeanFactory) GenericMessage(org.springframework.messaging.support.GenericMessage) ConnectionFactory(javax.jms.ConnectionFactory) Mockito.mock(org.mockito.Mockito.mock) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ThreadPoolTaskScheduler(org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler) GenericMessage(org.springframework.messaging.support.GenericMessage) CachingConnectionFactory(org.springframework.jms.connection.CachingConnectionFactory) ActiveMQConnectionFactory(org.apache.activemq.ActiveMQConnectionFactory) ConnectionFactory(javax.jms.ConnectionFactory) BeanFactory(org.springframework.beans.factory.BeanFactory) ExecutorService(java.util.concurrent.ExecutorService) JmsTemplate(org.springframework.jms.core.JmsTemplate) 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