Example usage for org.springframework.integration.endpoint SourcePollingChannelAdapter start

List of usage examples for org.springframework.integration.endpoint SourcePollingChannelAdapter start

Introduction

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

Prototype

@Override
    public final void start() 

Source Link

Usage

From source file:com.aeg.ims.ftp.SftpInboundReceiveSample.java

public void runDemo() {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:/META-INF/spring/integration/SftpInboundReceiveSample-context.xml");

    RemoteFileTemplate<LsEntry> template = null;
    String file1 = "a.txt";
    String file2 = "b.txt";
    String file3 = "c.bar";
    new File("local-dir", file1).delete();
    new File("local-dir", file2).delete();
    try {/*from   ww w.j  a  v  a  2 s . c om*/
        PollableChannel localFileChannel = context.getBean("receiveChannel", PollableChannel.class);
        @SuppressWarnings("unchecked")
        SessionFactory<LsEntry> sessionFactory = context.getBean(CachingSessionFactory.class);
        template = new RemoteFileTemplate<LsEntry>(sessionFactory);
        SftpTestUtils.createTestFiles(template, file1, file2, file3);

        SourcePollingChannelAdapter adapter = context.getBean(SourcePollingChannelAdapter.class);
        adapter.start();

        Message<?> received = localFileChannel.receive();
        assertNotNull("Expected file", received);
        System.out.println("Received first file message: " + received);
        received = localFileChannel.receive();
        assertNotNull("Expected file", received);
        System.out.println("Received second file message: " + received);
        received = localFileChannel.receive(1000);
        assertNull("Expected null", received);
        System.out.println("No third file was received as expected");
    } finally {
        SftpTestUtils.cleanUp(template, file1, file2, file3);
        context.close();
        assertTrue("Could note delete retrieved file", new File("local-dir", file1).delete());
        assertTrue("Could note delete retrieved file", new File("local-dir", file2).delete());
    }
}

From source file:eu.openanalytics.rsb.component.DirectoryDepositHandler.java

@PostConstruct
public void setupChannelAdapters() {
    final List<DepositDirectoryConfiguration> depositDirectoryConfigurations = getConfiguration()
            .getDepositRootDirectories();

    if ((depositDirectoryConfigurations == null) || (depositDirectoryConfigurations.isEmpty())) {
        return;/*from ww  w.  j a  v a  2 s  .com*/
    }

    final NioFileLocker nioFileLocker = new NioFileLocker();

    for (final DepositDirectoryConfiguration depositDirectoryConfiguration : depositDirectoryConfigurations) {
        final PeriodicTrigger fileTrigger = new PeriodicTrigger(
                depositDirectoryConfiguration.getPollingPeriod(), TimeUnit.MILLISECONDS);
        fileTrigger.setInitialDelay(5000L);

        final File depositRootDirectory = depositDirectoryConfiguration.getRootDirectory();

        final FileReadingMessageSource fileMessageSource = new FileReadingMessageSource();
        fileMessageSource.setAutoCreateDirectory(true);
        fileMessageSource.setBeanFactory(beanFactory);
        fileMessageSource.setBeanName("rsb-deposit-dir-ms-" + depositRootDirectory.getPath());
        fileMessageSource.setDirectory(new File(depositRootDirectory, Configuration.DEPOSIT_JOBS_SUBDIR));
        fileMessageSource.setFilter(zipJobFilter);
        fileMessageSource.setLocker(nioFileLocker);
        fileMessageSource.afterPropertiesSet();

        final HeaderSettingMessageSourceWrapper<File> messageSource = new HeaderSettingMessageSourceWrapper<File>(
                fileMessageSource, DIRECTORY_CONFIG_HEADER_NAME, depositDirectoryConfiguration);

        final SourcePollingChannelAdapter channelAdapter = new SourcePollingChannelAdapter();
        channelAdapter.setBeanFactory(beanFactory);
        channelAdapter.setBeanName("rsb-deposit-dir-ca-" + depositRootDirectory.getPath());
        channelAdapter.setOutputChannel(directoryDepositChannel);
        channelAdapter.setSource(messageSource);
        channelAdapter.setTrigger(fileTrigger);
        channelAdapter.afterPropertiesSet();
        channelAdapter.start();

        getLogger().info("Started channel adapter: " + channelAdapter);

        channelAdapters.add(channelAdapter);
    }
}

From source file:eu.openanalytics.rsb.component.EmailDepositHandler.java

@PostConstruct
public void setupChannelAdapters() throws URISyntaxException {
    final List<DepositEmailConfiguration> depositEmailConfigurations = getConfiguration()
            .getDepositEmailAccounts();// www . j  ava2s  .  co  m

    if ((depositEmailConfigurations == null) || (depositEmailConfigurations.isEmpty())) {
        return;
    }

    for (final DepositEmailConfiguration depositEmailConfiguration : depositEmailConfigurations) {
        final PeriodicTrigger trigger = new PeriodicTrigger(depositEmailConfiguration.getPollingPeriod(),
                TimeUnit.MILLISECONDS);
        trigger.setInitialDelay(5000L);

        AbstractMailReceiver mailReceiver = null;

        final URI emailAccountURI = depositEmailConfiguration.getAccountURI();
        if (StringUtils.equals(emailAccountURI.getScheme(), "pop3")) {
            mailReceiver = new Pop3MailReceiver(emailAccountURI.toString());
        } else if (StringUtils.equals(emailAccountURI.getScheme(), "imap")) {
            mailReceiver = new ImapMailReceiver(emailAccountURI.toString());
            ((ImapMailReceiver) mailReceiver).setShouldMarkMessagesAsRead(true);
        } else {
            throw new IllegalArgumentException("Invalid email account URI: " + emailAccountURI);
        }

        mailReceiver.setBeanFactory(beanFactory);
        mailReceiver.setBeanName("rsb-email-ms-" + emailAccountURI.getHost() + emailAccountURI.hashCode());
        mailReceiver.setShouldDeleteMessages(true);
        mailReceiver.setMaxFetchSize(1);
        mailReceiver.afterPropertiesSet();
        final MailReceivingMessageSource fileMessageSource = new MailReceivingMessageSource(mailReceiver);
        final HeaderSettingMessageSourceWrapper<javax.mail.Message> messageSource = new HeaderSettingMessageSourceWrapper<javax.mail.Message>(
                fileMessageSource, EMAIL_CONFIG_HEADER_NAME, depositEmailConfiguration);

        final SourcePollingChannelAdapter channelAdapter = new SourcePollingChannelAdapter();
        channelAdapter.setBeanFactory(beanFactory);
        channelAdapter.setBeanName("rsb-email-ca-" + emailAccountURI.getHost() + emailAccountURI.hashCode());
        channelAdapter.setOutputChannel(emailDepositChannel);
        channelAdapter.setSource(messageSource);
        channelAdapter.setTrigger(trigger);
        channelAdapter.afterPropertiesSet();
        channelAdapter.start();

        getLogger().info("Started channel adapter: " + channelAdapter);

        channelAdapters.add(channelAdapter);
    }
}

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

@Test
public void testInterrupted() throws Exception {
    final CountDownLatch startLatch = new CountDownLatch(1);

    MessageSource<Object> ms = () -> {
        startLatch.countDown();/*from  w w w.j a  v a  2 s  .co m*/
        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()?"));
}

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

@Test
public void testStartSourceBeforeRunPollingTask() {
    TaskScheduler taskScheduler = mock(TaskScheduler.class);

    willAnswer(invocation -> {// w ww  . ja va2 s  . c o m
        Runnable task = invocation.getArgument(0);
        task.run();
        return null;
    }).given(taskScheduler).schedule(any(Runnable.class), any(Trigger.class));

    SourcePollingChannelAdapter pollingChannelAdapter = new SourcePollingChannelAdapter();
    pollingChannelAdapter.setTaskScheduler(taskScheduler);
    pollingChannelAdapter.setSource(new LifecycleMessageSource());
    pollingChannelAdapter.setMaxMessagesPerPoll(1);
    QueueChannel outputChannel = new QueueChannel();
    pollingChannelAdapter.setOutputChannel(outputChannel);
    pollingChannelAdapter.setBeanFactory(mock(BeanFactory.class));
    pollingChannelAdapter.afterPropertiesSet();
    pollingChannelAdapter.start();

    Message<?> receive = outputChannel.receive(10_000);
    assertNotNull(receive);
    assertEquals(true, receive.getPayload());
    pollingChannelAdapter.stop();
}

From source file:org.springframework.integration.samples.advice.FileTransferDeleteAfterSuccessDemo.java

public static void main(String[] args) throws Exception {
    LOGGER.info("\n========================================================="
            + "\n                                                         "
            + "\n          Welcome to Spring Integration!                 "
            + "\n                                                         "
            + "\n    For more information please visit:                   "
            + "\n    http://www.springsource.org/spring-integration       "
            + "\n                                                         "
            + "\n=========================================================");

    final AbstractApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:META-INF/spring/integration/expression-advice-context.xml");

    context.registerShutdownHook();// w w w.  j  ava 2s. c  o m

    @SuppressWarnings("unchecked")
    SessionFactory<FTPFile> sessionFactory = context.getBean(SessionFactory.class);
    SourcePollingChannelAdapter fileInbound = context.getBean(SourcePollingChannelAdapter.class);

    @SuppressWarnings("unchecked")
    Session<FTPFile> session = mock(Session.class);
    when(sessionFactory.getSession()).thenReturn(session);
    fileInbound.start();

    LOGGER.info("\n========================================================="
            + "\n                                                          "
            + "\n    This is the Expression Advice Sample -                "
            + "\n                                                          "
            + "\n    Press 'Enter' to terminate.                           "
            + "\n                                                          "
            + "\n    Place a file in ${java.io.tmpdir}/adviceDemo ending   "
            + "\n    with .txt                                             "
            + "\n    The demo simulates a file transfer followed by the    "
            + "\n    Advice deleting the file; the result of the deletion  "
            + "\n    is logged.                                            "
            + "\n                                                          "
            + "\n=========================================================");

    System.in.read();
    System.exit(0);
}

From source file:org.springframework.integration.samples.advice.FileTransferRenameAfterFailureDemo.java

public static void main(String[] args) throws Exception {
    LOGGER.info("\n========================================================="
            + "\n                                                         "
            + "\n          Welcome to Spring Integration!                 "
            + "\n                                                         "
            + "\n    For more information please visit:                   "
            + "\n    http://www.springsource.org/spring-integration       "
            + "\n                                                         "
            + "\n=========================================================");

    final AbstractApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:META-INF/spring/integration/expression-advice-context.xml");

    context.registerShutdownHook();//  www .ja v a 2 s  . c  o m

    @SuppressWarnings("unchecked")
    SessionFactory<FTPFile> sessionFactory = context.getBean(SessionFactory.class);
    SourcePollingChannelAdapter fileInbound = context.getBean(SourcePollingChannelAdapter.class);

    when(sessionFactory.getSession()).thenThrow(new RuntimeException("Force Failure"));
    fileInbound.start();

    LOGGER.info("\n========================================================="
            + "\n                                                          "
            + "\n    This is the Expression Advice Sample -                "
            + "\n                                                          "
            + "\n    Press 'Enter' to terminate.                           "
            + "\n                                                          "
            + "\n    Place a file in ${java.io.tmpdir}/adviceDemo ending   "
            + "\n    with .txt                                             "
            + "\n    The demo simulates a file transfer failure followed   "
            + "\n    by the Advice renaming the file; the result of the    "
            + "\n    rename is logged.                                     "
            + "\n                                                          "
            + "\n=========================================================");

    System.in.read();
    System.exit(0);
}