Example usage for org.springframework.context ConfigurableApplicationContext getBean

List of usage examples for org.springframework.context ConfigurableApplicationContext getBean

Introduction

In this page you can find the example usage for org.springframework.context ConfigurableApplicationContext getBean.

Prototype

<T> T getBean(String name, Class<T> requiredType) throws BeansException;

Source Link

Document

Return an instance, which may be shared or independent, of the specified bean.

Usage

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

@SuppressWarnings("resource")
@Test/*ww w .j a v  a 2  s. c o m*/
public void testInitialIdleDelayWhenRecentIsSupported() throws Exception {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class);
    ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class);

    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);

    ImapMailReceiver receiver = new ImapMailReceiver("imap:foo");
    receiver = spy(receiver);
    receiver.setBeanFactory(mock(BeanFactory.class));
    receiver.afterPropertiesSet();

    final IMAPFolder folder = mock(IMAPFolder.class);
    given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.RECENT));
    given(folder.isOpen()).willReturn(false).willReturn(true);
    given(folder.exists()).willReturn(true);

    DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter);
    adapterAccessor.setPropertyValue("mailReceiver", receiver);

    Field storeField = AbstractMailReceiver.class.getDeclaredField("store");
    storeField.setAccessible(true);
    Store store = mock(Store.class);
    given(store.isConnected()).willReturn(true);
    given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder);
    storeField.set(receiver, store);

    willAnswer(invocation -> folder).given(receiver).getFolder();

    MimeMessage mailMessage = mock(MimeMessage.class);
    Flags flags = mock(Flags.class);
    given(mailMessage.getFlags()).willReturn(flags);
    final Message[] messages = new Message[] { mailMessage };

    willAnswer(invocation -> messages).given(receiver).searchForNewMessages();

    willAnswer(invocation -> null).given(receiver).fetchMessages(messages);

    final CountDownLatch idles = new CountDownLatch(2);
    willAnswer(invocation -> {
        idles.countDown();
        Thread.sleep(5000);
        return null;
    }).given(folder).idle();

    adapter.start();

    /*
     * Idle takes 5 seconds; since this server supports RECENT, we should
     * not receive any early messages.
     */
    assertNull(channel.receive(3000));
    assertNotNull(channel.receive(5000));
    assertTrue(idles.await(5, TimeUnit.SECONDS));
    adapter.stop();
    context.close();
}

From source file:org.springframework.integration.samples.async.gateway.AsyncGatewayTest.java

@Test
public void testAsyncGateway() throws Exception {
    ConfigurableApplicationContext ac = new FileSystemXmlApplicationContext(
            "src/main/resources/META-INF/spring/integration/*.xml");
    MathServiceGateway mathService = ac.getBean("mathService", MathServiceGateway.class);
    Map<Integer, Future<Integer>> results = new HashMap<Integer, Future<Integer>>();
    Random random = new Random();
    for (int i = 0; i < 100; i++) {
        int number = random.nextInt(200);
        Future<Integer> result = mathService.multiplyByTwo(number);
        results.put(number, result);/*from   w ww .  j  a v a 2 s  .  c  o  m*/
    }
    for (final Map.Entry<Integer, Future<Integer>> resultEntry : results.entrySet()) {
        executor.execute(() -> {
            int[] result = processFuture(resultEntry);

            if (result[1] == -1) {
                logger.info("Multiplying " + result[0]
                        + " should be easy. You should be able to multiply any number < 100 by 2 in your head");
            } else if (result[1] == -2) {
                logger.info("Multiplication of " + result[0] + " by 2 is can not be accomplished in " + timeout
                        + " seconds");
            } else {
                logger.info("Result of multiplication of " + result[0] + " by 2 is " + result[1]);
            }
        });
    }
    executor.shutdown();
    executor.awaitTermination(60, TimeUnit.SECONDS);
    logger.info("Finished");
    ac.close();
}

From source file:org.springframework.integration.samples.controlbus.ControlBusDemoTest.java

@Test
public void demoControlBus() {
    ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
            "/META-INF/spring/integration/ControlBusDemo-context.xml");
    MessageChannel controlChannel = ac.getBean("controlChannel", MessageChannel.class);
    PollableChannel adapterOutputChanel = ac.getBean("adapterOutputChanel", PollableChannel.class);
    logger.info("Received before adapter started: " + adapterOutputChanel.receive(1000));
    controlChannel.send(new GenericMessage<String>("@inboundAdapter.start()"));
    logger.info("Received before adapter started: " + adapterOutputChanel.receive(1000));
    controlChannel.send(new GenericMessage<String>("@inboundAdapter.stop()"));
    logger.info("Received after adapter stopped: " + adapterOutputChanel.receive(1000));
    ac.close();/*from  w  ww  .  ja  v a 2 s  .c o m*/
}

From source file:org.springframework.integration.samples.fileprocessing.FileProcessingTest.java

@Test
public void testSequentialFileProcessing() throws Exception {
    logger.info("\n\n#### Starting Sequential processing test ####");
    logger.info("Populating directory with files");
    for (int i = 0; i < fileCount; i++) {
        File file = new File("input/file_" + i + ".txt");
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        out.write("hello " + i);
        out.close();//from   www  .j  a  v a 2s. co m
    }
    logger.info("Populated directory with files");
    Thread.sleep(2000);
    logger.info("Starting Spring Integration Sequential File processing");
    ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
            "META-INF/spring/integration/sequentialFileProcessing-config.xml");
    PollableChannel filesOutChannel = ac.getBean("filesOutChannel", PollableChannel.class);
    for (int i = 0; i < fileCount; i++) {
        logger.info("Finished processing " + filesOutChannel.receive(10000).getPayload());
    }
    ac.stop();
}

From source file:org.springframework.integration.samples.fileprocessing.FileProcessingTest.java

@Test
public void testConcurrentFileProcessing() throws Exception {
    logger.info("\n\n#### Starting Concurrent processing test #### ");
    logger.info("Populating directory with files");
    for (int i = 0; i < fileCount; i++) {
        File file = new File("input/file_" + i + ".txt");
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        out.write("hello " + i);
        out.close();//from w  w  w  .j  a  v a  2 s  . c  o  m
    }
    logger.info("Populated directory with files");
    Thread.sleep(2000);
    logger.info("Starting Spring Integration Sequential File processing");
    ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
            "/META-INF/spring/integration/concurrentFileProcessing-config.xml");
    PollableChannel filesOutChannel = ac.getBean("filesOutChannel", PollableChannel.class);
    for (int i = 0; i < fileCount; i++) {
        logger.info("Finished processing " + filesOutChannel.receive(10000).getPayload());
    }
    ac.close();
}

From source file:org.springframework.integration.samples.ftp.FtpInboundChannelAdapterSample.java

@Test
public void runDemo() throws Exception {
    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
            "META-INF/spring/integration/FtpInboundChannelAdapterSample-context.xml");

    PollableChannel ftpChannel = ctx.getBean("ftpChannel", PollableChannel.class);

    Message<?> message1 = ftpChannel.receive(2000);
    Message<?> message2 = ftpChannel.receive(2000);
    Message<?> message3 = ftpChannel.receive(1000);

    LOGGER.info("Received first file message: {}.", message1);
    LOGGER.info("Received second file message: {}.", message2);
    LOGGER.info("Received nothing else: {}.", message3);

    assertNotNull(message1);//w  w  w.j a v a 2  s .c  o  m
    assertNotNull(message2);
    assertNull("Was NOT expecting a third message.", message3);

}

From source file:org.springframework.integration.samples.ftp.FtpOutboundChannelAdapterSample.java

@Test
public void runDemo() throws Exception {

    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
            "META-INF/spring/integration/FtpOutboundChannelAdapterSample-context.xml");

    MessageChannel ftpChannel = ctx.getBean("ftpChannel", MessageChannel.class);

    baseFolder.mkdirs();/*from   www  . j a  v a 2 s .c  om*/

    final File fileToSendA = new File(baseFolder, "a.txt");
    final File fileToSendB = new File(baseFolder, "b.txt");

    final InputStream inputStreamA = FtpOutboundChannelAdapterSample.class
            .getResourceAsStream("/test-files/a.txt");
    final InputStream inputStreamB = FtpOutboundChannelAdapterSample.class
            .getResourceAsStream("/test-files/b.txt");

    FileUtils.copyInputStreamToFile(inputStreamA, fileToSendA);
    FileUtils.copyInputStreamToFile(inputStreamB, fileToSendB);

    assertTrue(fileToSendA.exists());
    assertTrue(fileToSendB.exists());

    final Message<File> messageA = MessageBuilder.withPayload(fileToSendA).build();
    final Message<File> messageB = MessageBuilder.withPayload(fileToSendB).build();

    ftpChannel.send(messageA);
    ftpChannel.send(messageB);

    Thread.sleep(2000);

    assertTrue(new File(TestSuite.FTP_ROOT_DIR + File.separator + "a.txt").exists());
    assertTrue(new File(TestSuite.FTP_ROOT_DIR + File.separator + "b.txt").exists());

    LOGGER.info("Successfully transfered file 'a.txt' and 'b.txt' to a remote FTP location.");
    ctx.close();
}

From source file:org.springframework.integration.samples.http.HttpClientDemo.java

public static void main(String[] args) {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "/META-INF/spring/integration/http-outbound-config.xml");
    RequestGateway requestGateway = context.getBean("requestGateway", RequestGateway.class);
    String reply = requestGateway.echo("Hello");
    logger.info("\n\n++++++++++++ Replied with: " + reply + " ++++++++++++\n");
    context.close();/*from   ww w.  j  av  a  2 s .c o  m*/
}

From source file:org.springframework.integration.samples.loanbroker.demo.LoanBrokerSharkDetectorDemo.java

public static void main(String[] args) {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "META-INF/spring/integration/bootstrap-config/stubbed-loan-broker-multicast.xml");
    LoanBrokerGateway broker = context.getBean("loanBrokerGateway", LoanBrokerGateway.class);
    LoanRequest loanRequest = new LoanRequest();
    loanRequest.setCustomer(new Customer());
    LoanQuote loan = broker.getBestLoanQuote(loanRequest);
    logger.info("\n********* Best Quote: " + loan);
    List<LoanQuote> loanQuotes = broker.getAllLoanQuotes(loanRequest);
    logger.info("\n********* All Quotes: ");
    for (LoanQuote loanQuote : loanQuotes) {
        logger.info(loanQuote);/*from   ww  w  .  j a  va 2  s. c om*/
    }
    context.close();
}