Search in sources :

Example 11 with PeriodicTrigger

use of org.springframework.scheduling.support.PeriodicTrigger in project spring-integration by spring-projects.

the class AbstractMethodAnnotationPostProcessor method configurePollingEndpoint.

protected void configurePollingEndpoint(AbstractPollingEndpoint pollingEndpoint, List<Annotation> annotations) {
    PollerMetadata pollerMetadata = null;
    Poller[] pollers = MessagingAnnotationUtils.resolveAttribute(annotations, "poller", Poller[].class);
    if (!ObjectUtils.isEmpty(pollers)) {
        Assert.state(pollers.length == 1, "The 'poller' for an Annotation-based endpoint can have only one '@Poller'.");
        Poller poller = pollers[0];
        String ref = poller.value();
        String triggerRef = poller.trigger();
        String executorRef = poller.taskExecutor();
        String fixedDelayValue = this.beanFactory.resolveEmbeddedValue(poller.fixedDelay());
        String fixedRateValue = this.beanFactory.resolveEmbeddedValue(poller.fixedRate());
        String maxMessagesPerPollValue = this.beanFactory.resolveEmbeddedValue(poller.maxMessagesPerPoll());
        String cron = this.beanFactory.resolveEmbeddedValue(poller.cron());
        String errorChannel = this.beanFactory.resolveEmbeddedValue(poller.errorChannel());
        if (StringUtils.hasText(ref)) {
            Assert.state(!StringUtils.hasText(triggerRef) && !StringUtils.hasText(executorRef) && !StringUtils.hasText(cron) && !StringUtils.hasText(fixedDelayValue) && !StringUtils.hasText(fixedRateValue) && !StringUtils.hasText(maxMessagesPerPollValue), "The '@Poller' 'ref' attribute is mutually exclusive with other attributes.");
            pollerMetadata = this.beanFactory.getBean(ref, PollerMetadata.class);
        } else {
            pollerMetadata = new PollerMetadata();
            if (StringUtils.hasText(maxMessagesPerPollValue)) {
                pollerMetadata.setMaxMessagesPerPoll(Long.parseLong(maxMessagesPerPollValue));
            } else if (pollingEndpoint instanceof SourcePollingChannelAdapter) {
                // SPCAs default to 1 message per poll
                pollerMetadata.setMaxMessagesPerPoll(1);
            }
            if (StringUtils.hasText(executorRef)) {
                pollerMetadata.setTaskExecutor(this.beanFactory.getBean(executorRef, TaskExecutor.class));
            }
            Trigger trigger = null;
            if (StringUtils.hasText(triggerRef)) {
                Assert.state(!StringUtils.hasText(cron) && !StringUtils.hasText(fixedDelayValue) && !StringUtils.hasText(fixedRateValue), "The '@Poller' 'trigger' attribute is mutually exclusive with other attributes.");
                trigger = this.beanFactory.getBean(triggerRef, Trigger.class);
            } else if (StringUtils.hasText(cron)) {
                Assert.state(!StringUtils.hasText(fixedDelayValue) && !StringUtils.hasText(fixedRateValue), "The '@Poller' 'cron' attribute is mutually exclusive with other attributes.");
                trigger = new CronTrigger(cron);
            } else if (StringUtils.hasText(fixedDelayValue)) {
                Assert.state(!StringUtils.hasText(fixedRateValue), "The '@Poller' 'fixedDelay' attribute is mutually exclusive with other attributes.");
                trigger = new PeriodicTrigger(Long.parseLong(fixedDelayValue));
            } else if (StringUtils.hasText(fixedRateValue)) {
                trigger = new PeriodicTrigger(Long.parseLong(fixedRateValue));
                ((PeriodicTrigger) trigger).setFixedRate(true);
            }
            // 'Trigger' can be null. 'PollingConsumer' does fallback to the 'new PeriodicTrigger(10)'.
            pollerMetadata.setTrigger(trigger);
            if (StringUtils.hasText(errorChannel)) {
                MessagePublishingErrorHandler errorHandler = new MessagePublishingErrorHandler();
                errorHandler.setDefaultErrorChannelName(errorChannel);
                errorHandler.setBeanFactory(this.beanFactory);
                pollerMetadata.setErrorHandler(errorHandler);
            }
        }
    } else {
        pollerMetadata = PollerMetadata.getDefaultPollerMetadata(this.beanFactory);
        Assert.notNull(pollerMetadata, "No poller has been defined for Annotation-based endpoint, " + "and no default poller is available within the context.");
    }
    pollingEndpoint.setTaskExecutor(pollerMetadata.getTaskExecutor());
    pollingEndpoint.setTrigger(pollerMetadata.getTrigger());
    pollingEndpoint.setAdviceChain(pollerMetadata.getAdviceChain());
    pollingEndpoint.setMaxMessagesPerPoll(pollerMetadata.getMaxMessagesPerPoll());
    pollingEndpoint.setErrorHandler(pollerMetadata.getErrorHandler());
    if (pollingEndpoint instanceof PollingConsumer) {
        ((PollingConsumer) pollingEndpoint).setReceiveTimeout(pollerMetadata.getReceiveTimeout());
    }
    pollingEndpoint.setTransactionSynchronizationFactory(pollerMetadata.getTransactionSynchronizationFactory());
}
Also used : TaskExecutor(org.springframework.core.task.TaskExecutor) CronTrigger(org.springframework.scheduling.support.CronTrigger) MessagePublishingErrorHandler(org.springframework.integration.channel.MessagePublishingErrorHandler) PollingConsumer(org.springframework.integration.endpoint.PollingConsumer) Trigger(org.springframework.scheduling.Trigger) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) CronTrigger(org.springframework.scheduling.support.CronTrigger) SourcePollingChannelAdapter(org.springframework.integration.endpoint.SourcePollingChannelAdapter) PollerMetadata(org.springframework.integration.scheduling.PollerMetadata) Poller(org.springframework.integration.annotation.Poller) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger)

Example 12 with PeriodicTrigger

use of org.springframework.scheduling.support.PeriodicTrigger 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 13 with PeriodicTrigger

use of org.springframework.scheduling.support.PeriodicTrigger in project spring-integration by spring-projects.

the class PollerAdviceTests method testCompoundTriggerAdvice.

@Test
public void testCompoundTriggerAdvice() throws Exception {
    SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter();
    final CountDownLatch latch = new CountDownLatch(5);
    final LinkedList<Object> overridePresent = new LinkedList<Object>();
    final CompoundTrigger compoundTrigger = new CompoundTrigger(new PeriodicTrigger(10));
    Trigger override = spy(new PeriodicTrigger(5));
    final CompoundTriggerAdvice advice = new CompoundTriggerAdvice(compoundTrigger, override);
    adapter.setSource(() -> {
        overridePresent.add(TestUtils.getPropertyValue(compoundTrigger, "override"));
        Message<Object> m = null;
        if (latch.getCount() % 2 == 0) {
            m = new GenericMessage<>("foo");
        }
        latch.countDown();
        return m;
    });
    adapter.setAdviceChain(Collections.singletonList(advice));
    adapter.setTrigger(compoundTrigger);
    configure(adapter);
    adapter.afterPropertiesSet();
    adapter.start();
    assertTrue(latch.await(10, TimeUnit.SECONDS));
    adapter.stop();
    while (overridePresent.size() > 5) {
        overridePresent.removeLast();
    }
    assertThat(overridePresent, contains(null, override, null, override, null));
    verify(override, atLeast(2)).nextExecutionTime(any(TriggerContext.class));
}
Also used : CompoundTrigger(org.springframework.integration.util.CompoundTrigger) DynamicPeriodicTrigger(org.springframework.integration.util.DynamicPeriodicTrigger) OnlyOnceTrigger(org.springframework.integration.test.util.OnlyOnceTrigger) Trigger(org.springframework.scheduling.Trigger) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) CompoundTrigger(org.springframework.integration.util.CompoundTrigger) TriggerContext(org.springframework.scheduling.TriggerContext) CountDownLatch(java.util.concurrent.CountDownLatch) LinkedList(java.util.LinkedList) CompoundTriggerAdvice(org.springframework.integration.aop.CompoundTriggerAdvice) DynamicPeriodicTrigger(org.springframework.integration.util.DynamicPeriodicTrigger) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) Test(org.junit.Test)

Example 14 with PeriodicTrigger

use of org.springframework.scheduling.support.PeriodicTrigger in project spring-integration by spring-projects.

the class PollingLifecycleTests method ensurePollerTaskStops.

@Test
public void ensurePollerTaskStops() throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    QueueChannel channel = new QueueChannel();
    channel.send(new GenericMessage<String>("foo"));
    MessageHandler handler = Mockito.spy(new MessageHandler() {

        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            latch.countDown();
        }
    });
    PollingConsumer consumer = new PollingConsumer(channel, handler);
    consumer.setTrigger(new PeriodicTrigger(0));
    consumer.setErrorHandler(errorHandler);
    consumer.setTaskScheduler(taskScheduler);
    consumer.setBeanFactory(mock(BeanFactory.class));
    consumer.afterPropertiesSet();
    consumer.start();
    assertTrue(latch.await(2, TimeUnit.SECONDS));
    Mockito.verify(handler, times(1)).handleMessage(Mockito.any(Message.class));
    consumer.stop();
    for (int i = 0; i < 10; i++) {
        channel.send(new GenericMessage<String>("foo"));
    }
    // give enough time for poller to kick in if it didn't stop properly
    Thread.sleep(2000);
    // we'll still have a natural race condition between call to stop() and poller polling
    // so what we really have to assert is that it doesn't poll for more then once after stop() was called
    Mockito.reset(handler);
    Mockito.verify(handler, atMost(1)).handleMessage(Mockito.any(Message.class));
}
Also used : QueueChannel(org.springframework.integration.channel.QueueChannel) MessageHandler(org.springframework.messaging.MessageHandler) Message(org.springframework.messaging.Message) GenericMessage(org.springframework.messaging.support.GenericMessage) MessagingException(org.springframework.messaging.MessagingException) CountDownLatch(java.util.concurrent.CountDownLatch) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) BeanFactory(org.springframework.beans.factory.BeanFactory) ConfigurableBeanFactory(org.springframework.beans.factory.config.ConfigurableBeanFactory) Test(org.junit.Test)

Example 15 with PeriodicTrigger

use of org.springframework.scheduling.support.PeriodicTrigger in project spring-integration by spring-projects.

the class SourcePollingChannelAdapterFactoryBeanTests method testTransactionalAdviceChain.

@Test
public void testTransactionalAdviceChain() throws Throwable {
    SourcePollingChannelAdapterFactoryBean factoryBean = new SourcePollingChannelAdapterFactoryBean();
    QueueChannel outputChannel = new QueueChannel();
    TestApplicationContext context = TestUtils.createTestApplicationContext();
    factoryBean.setBeanFactory(context.getBeanFactory());
    factoryBean.setBeanClassLoader(ClassUtils.getDefaultClassLoader());
    factoryBean.setOutputChannel(outputChannel);
    factoryBean.setSource(() -> new GenericMessage<>("test"));
    PollerMetadata pollerMetadata = new PollerMetadata();
    List<Advice> adviceChain = new ArrayList<Advice>();
    final AtomicBoolean adviceApplied = new AtomicBoolean(false);
    adviceChain.add((MethodInterceptor) invocation -> {
        adviceApplied.set(true);
        return invocation.proceed();
    });
    pollerMetadata.setTrigger(new PeriodicTrigger(5000));
    pollerMetadata.setMaxMessagesPerPoll(1);
    final AtomicInteger count = new AtomicInteger();
    final MethodInterceptor txAdvice = mock(MethodInterceptor.class);
    adviceChain.add((MethodInterceptor) invocation -> {
        count.incrementAndGet();
        return invocation.proceed();
    });
    when(txAdvice.invoke(any(MethodInvocation.class))).thenAnswer(invocation -> {
        count.incrementAndGet();
        return ((MethodInvocation) invocation.getArgument(0)).proceed();
    });
    pollerMetadata.setAdviceChain(adviceChain);
    factoryBean.setPollerMetadata(pollerMetadata);
    factoryBean.setAutoStartup(true);
    factoryBean.afterPropertiesSet();
    context.registerEndpoint("testPollingEndpoint", factoryBean.getObject());
    context.refresh();
    Message<?> message = outputChannel.receive(5000);
    assertEquals("test", message.getPayload());
    assertEquals(1, count.get());
    assertTrue("adviceChain was not applied", adviceApplied.get());
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) QueueChannel(org.springframework.integration.channel.QueueChannel) MessagingException(org.springframework.messaging.MessagingException) PollerMetadata(org.springframework.integration.scheduling.PollerMetadata) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TestApplicationContext(org.springframework.integration.test.util.TestUtils.TestApplicationContext) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) ArgumentMatchers.contains(org.mockito.ArgumentMatchers.contains) Mockito.spy(org.mockito.Mockito.spy) TestUtils(org.springframework.integration.test.util.TestUtils) MessagePublishingErrorHandler(org.springframework.integration.channel.MessagePublishingErrorHandler) MessageSource(org.springframework.integration.core.MessageSource) Mockito.verifyZeroInteractions(org.mockito.Mockito.verifyZeroInteractions) 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) Assert.assertNotNull(org.junit.Assert.assertNotNull) Assert.assertTrue(org.junit.Assert.assertTrue) SourcePollingChannelAdapter(org.springframework.integration.endpoint.SourcePollingChannelAdapter) TaskScheduler(org.springframework.scheduling.TaskScheduler) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) BDDMockito.willAnswer(org.mockito.BDDMockito.willAnswer) Mockito.verify(org.mockito.Mockito.verify) Lifecycle(org.springframework.context.Lifecycle) TimeUnit(java.util.concurrent.TimeUnit) 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) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) QueueChannel(org.springframework.integration.channel.QueueChannel) ArrayList(java.util.ArrayList) MethodInvocation(org.aopalliance.intercept.MethodInvocation) PeriodicTrigger(org.springframework.scheduling.support.PeriodicTrigger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MethodInterceptor(org.aopalliance.intercept.MethodInterceptor) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Advice(org.aopalliance.aop.Advice) PollerMetadata(org.springframework.integration.scheduling.PollerMetadata) TestApplicationContext(org.springframework.integration.test.util.TestUtils.TestApplicationContext) Test(org.junit.Test)

Aggregations

PeriodicTrigger (org.springframework.scheduling.support.PeriodicTrigger)42 AutowireCapableBeanFactory (org.springframework.beans.factory.config.AutowireCapableBeanFactory)20 Before (org.junit.Before)19 BrokenBarrierException (java.util.concurrent.BrokenBarrierException)14 Test (org.junit.Test)14 QueueChannel (org.springframework.integration.channel.QueueChannel)10 PollerMetadata (org.springframework.integration.scheduling.PollerMetadata)10 CountDownLatch (java.util.concurrent.CountDownLatch)8 BeanFactory (org.springframework.beans.factory.BeanFactory)6 Message (org.springframework.messaging.Message)6 SourcePollingChannelAdapter (org.springframework.integration.endpoint.SourcePollingChannelAdapter)5 GenericMessage (org.springframework.messaging.support.GenericMessage)5 NullChannel (org.springframework.integration.channel.NullChannel)4 TestApplicationContext (org.springframework.integration.test.util.TestUtils.TestApplicationContext)4 Trigger (org.springframework.scheduling.Trigger)4 ThreadPoolTaskScheduler (org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler)4 ArrayList (java.util.ArrayList)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)3 ConfigurableBeanFactory (org.springframework.beans.factory.config.ConfigurableBeanFactory)3