Example usage for org.springframework.integration.endpoint PollingConsumer PollingConsumer

List of usage examples for org.springframework.integration.endpoint PollingConsumer PollingConsumer

Introduction

In this page you can find the example usage for org.springframework.integration.endpoint PollingConsumer PollingConsumer.

Prototype

public PollingConsumer(PollableChannel inputChannel, MessageHandler handler) 

Source Link

Usage

From source file:com.apress.prospringintegration.endpoints.pollingconsumer.Main.java

public static void main(String[] args) {
    ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
            "polling-consumer.xml");
    applicationContext.start();//from w  w  w  . j av a  2s  .c  om

    ProblemReporter problemReporter = applicationContext.getBean(ProblemReporter.class);
    TicketMessageHandler ticketMessageHandler = applicationContext.getBean(TicketMessageHandler.class);
    TicketGenerator ticketGenerator = applicationContext.getBean(TicketGenerator.class);

    QueueChannel channel = applicationContext.getBean("ticketChannel", QueueChannel.class);

    // Define the polling consumer
    PollingConsumer ticketConsumer = new PollingConsumer(channel, ticketMessageHandler);
    ticketConsumer.setReceiveTimeout(RECEIVE_TIMEOUT);
    ticketConsumer.setBeanFactory(applicationContext);

    // Setup the poller using periodic trigger
    PeriodicTrigger periodicTrigger = new PeriodicTrigger(1000);
    periodicTrigger.setInitialDelay(5000);
    periodicTrigger.setFixedRate(false);

    PollerMetadata pollerMetadata = new PollerMetadata();
    pollerMetadata.setTrigger(periodicTrigger);
    pollerMetadata.setMaxMessagesPerPoll(3);

    ticketConsumer.setPollerMetadata(pollerMetadata);

    // Starts the polling consumer in the other thread
    ticketConsumer.start();

    // Generates messages and sends to the channel
    List<Ticket> tickets = ticketGenerator.createTickets();
    while (true) {
        for (Ticket ticket : tickets) {
            problemReporter.openTicket(ticket);
        }
    }
}

From source file:nhs.spring.integration.App.java

public static void main(String... args) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "spring-integration-context.xml");
    GameMessageHandler gameHandler = new GameMessageHandler();
    GameGenerator gameGenerator = context.getBean(GameGenerator.class);

    context.start();//from   w  ww.j  a  va  2s.c o  m

    //MessageChannel input = context.getBean("input-channel", MessageChannel.class);
    //PollableChannel output = context.getBean("output-channel", PollableChannel.class);
    QueueChannel qChannel = context.getBean("game-channel", QueueChannel.class);

    PollingConsumer gameConsumer = new PollingConsumer(qChannel, gameHandler);
    gameConsumer.setReceiveTimeout(RECEIVE_TIMEOUT);
    gameConsumer.setBeanFactory(context);

    // Set up the poller using periodic trigger
    PeriodicTrigger periodicTrigger = new PeriodicTrigger(1000);
    periodicTrigger.setInitialDelay(5000);
    periodicTrigger.setFixedRate(false);

    PollerMetadata pollerMetadata = new PollerMetadata();
    pollerMetadata.setTrigger(periodicTrigger);
    pollerMetadata.setMaxMessagesPerPoll(3);

    gameConsumer.setPollerMetadata(pollerMetadata);

    // Starts the polling consumer in the other thread
    gameConsumer.start();

    Date today = new Date();

    // Generates messages and sends to the channel
    Game game = gameGenerator.generateGame("League of legend", "Riot Games", today, "Tom", "Michael", "AOS");

    qChannel.send(MessageBuilder.withPayload(game).build());

    /*
    PublishSubscribeChannel pubsubChannel = null;
            
    pubsubChannel.subscribe(gameHandler);
            
    input.send(MessageBuilder.withPayload("Spring Integration / Hello NHS").build());
    Message<?> reply = output.receive();
            
    System.out.println("Received :" + reply);
    */
}

From source file:org.springframework.flex.messaging.integration.IntegrationAdapter.java

/**
 * {@inheritDoc}/*from w  w  w.jav a 2  s .  c o m*/
 */
public void afterPropertiesSet() {
    Assert.notNull(this.messageChannel, "MessageChannel must not be null");
    if (this.messageChannel instanceof PollableChannel) {
        this.consumerEndpoint = new PollingConsumer((PollableChannel) this.messageChannel, this);
    } else if (this.messageChannel instanceof SubscribableChannel) {
        this.consumerEndpoint = new EventDrivenConsumer((SubscribableChannel) this.messageChannel, this);
    }
}

From source file:org.springframework.integration.config.annotation.AbstractMethodAnnotationPostProcessor.java

protected AbstractEndpoint doCreateEndpoint(MessageHandler handler, MessageChannel inputChannel,
        List<Annotation> annotations) {
    AbstractEndpoint endpoint;/*  www.  j a va2 s  .c  o  m*/
    if (inputChannel instanceof PollableChannel) {
        PollingConsumer pollingConsumer = new PollingConsumer((PollableChannel) inputChannel, handler);
        configurePollingEndpoint(pollingConsumer, annotations);
        endpoint = pollingConsumer;
    } else {
        Poller[] pollers = MessagingAnnotationUtils.resolveAttribute(annotations, "poller", Poller[].class);
        Assert.state(ObjectUtils.isEmpty(pollers), "A '@Poller' should not be specified for Annotation-based "
                + "endpoint, since '" + inputChannel + "' is a SubscribableChannel (not pollable).");
        if (inputChannel instanceof Publisher) {
            endpoint = new ReactiveConsumer(inputChannel, handler);
        } else {
            endpoint = new EventDrivenConsumer((SubscribableChannel) inputChannel, handler);
        }
    }
    return endpoint;
}

From source file:org.springframework.integration.config.ConsumerEndpointFactoryBean.java

private void initializeEndpoint() throws Exception {
    synchronized (this.initializationMonitor) {
        if (this.initialized) {
            return;
        }//from   www  .java2s.c om
        MessageChannel channel = null;
        if (StringUtils.hasText(this.inputChannelName)) {
            Assert.isTrue(this.beanFactory.containsBean(this.inputChannelName), "no such input channel '"
                    + this.inputChannelName + "' for endpoint '" + this.beanName + "'");
            channel = this.beanFactory.getBean(this.inputChannelName, MessageChannel.class);
        }
        if (this.inputChannel != null) {
            channel = this.inputChannel;
        }
        Assert.state(channel != null, "one of inputChannelName or inputChannel is required");
        if (channel instanceof SubscribableChannel) {
            Assert.isNull(this.pollerMetadata, "A poller should not be specified for endpoint '" + this.beanName
                    + "', since '" + channel + "' is a SubscribableChannel (not pollable).");
            this.endpoint = new EventDrivenConsumer((SubscribableChannel) channel, this.handler);
        } else if (channel instanceof PollableChannel) {
            PollingConsumer pollingConsumer = new PollingConsumer((PollableChannel) channel, this.handler);
            if (this.pollerMetadata == null) {
                this.pollerMetadata = PollerMetadata.getDefaultPollerMetadata(this.beanFactory);
                Assert.notNull(this.pollerMetadata, "No poller has been defined for endpoint '" + this.beanName
                        + "', and no default poller is available within the context.");
            }
            pollingConsumer.setTaskExecutor(this.pollerMetadata.getTaskExecutor());
            pollingConsumer.setTrigger(this.pollerMetadata.getTrigger());
            pollingConsumer.setAdviceChain(this.pollerMetadata.getAdviceChain());
            pollingConsumer.setMaxMessagesPerPoll(this.pollerMetadata.getMaxMessagesPerPoll());

            pollingConsumer.setErrorHandler(this.pollerMetadata.getErrorHandler());

            pollingConsumer.setReceiveTimeout(this.pollerMetadata.getReceiveTimeout());
            pollingConsumer.setTransactionSynchronizationFactory(
                    this.pollerMetadata.getTransactionSynchronizationFactory());
            pollingConsumer.setBeanClassLoader(beanClassLoader);
            pollingConsumer.setBeanFactory(beanFactory);
            this.endpoint = pollingConsumer;
        } else {
            throw new IllegalArgumentException("unsupported channel type: [" + channel.getClass() + "]");
        }
        this.endpoint.setBeanName(this.beanName);
        this.endpoint.setBeanFactory(this.beanFactory);
        this.endpoint.setAutoStartup(this.autoStartup);
        this.endpoint.afterPropertiesSet();
        this.initialized = true;
    }
}

From source file:org.springframework.integration.handler.advice.AdvisedMessageHandlerTests.java

@Test
public void testInappropriateAdvice() throws Exception {
    final AtomicBoolean called = new AtomicBoolean(false);
    Advice advice = new AbstractRequestHandlerAdvice() {
        @Override/*w ww .j  a  v a  2 s .  c  o  m*/
        protected Object doInvoke(ExecutionCallback callback, Object target, Message<?> message)
                throws Exception {
            called.set(true);
            return callback.execute();
        }
    };
    PollableChannel inputChannel = new QueueChannel();
    PollingConsumer consumer = new PollingConsumer(inputChannel, new MessageHandler() {
        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
        }
    });
    consumer.setAdviceChain(Collections.singletonList(advice));
    consumer.setTaskExecutor(
            new ErrorHandlingTaskExecutor(Executors.newSingleThreadExecutor(), new ErrorHandler() {
                @Override
                public void handleError(Throwable t) {
                }
            }));
    consumer.afterPropertiesSet();

    Callable<?> pollingTask = TestUtils.getPropertyValue(consumer, "poller.pollingTask", Callable.class);
    assertTrue(AopUtils.isAopProxy(pollingTask));
    Log logger = TestUtils.getPropertyValue(advice, "logger", Log.class);
    logger = spy(logger);
    when(logger.isWarnEnabled()).thenReturn(Boolean.TRUE);
    final AtomicReference<String> logMessage = new AtomicReference<String>();
    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            logMessage.set((String) invocation.getArguments()[0]);
            return null;
        }
    }).when(logger).warn(Mockito.anyString());
    DirectFieldAccessor accessor = new DirectFieldAccessor(advice);
    accessor.setPropertyValue("logger", logger);

    pollingTask.call();
    assertFalse(called.get());
    assertNotNull(logMessage.get());
    assertTrue(logMessage.get()
            .endsWith("can only be used for MessageHandlers; " + "an attempt to advise method 'call' in "
                    + "'org.springframework.integration.endpoint.AbstractPollingEndpoint$1' is ignored"));
}