Example usage for org.springframework.context ConfigurableApplicationContext close

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

Introduction

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

Prototype

@Override
void close();

Source Link

Document

Close this application context, releasing all resources and locks that the implementation might hold.

Usage

From source file:org.springframework.integration.history.MessageHistoryIntegrationTests.java

@Test
public void testMessageHistoryWithoutHistoryWriter() {
    ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
            "messageHistoryWithoutHistoryWriter.xml", MessageHistoryIntegrationTests.class);
    SampleGateway gateway = ac.getBean("sampleGateway", SampleGateway.class);
    DirectChannel endOfThePipeChannel = ac.getBean("endOfThePipeChannel", DirectChannel.class);
    MessageHandler handler = Mockito.spy(new MessageHandler() {
        @Override//from w w  w . jav  a 2  s .com
        public void handleMessage(Message<?> message) {
            assertNull(message.getHeaders().get(MessageHistory.HEADER_NAME, MessageHistory.class));
            MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
            replyChannel.send(message);
        }
    });
    endOfThePipeChannel.subscribe(handler);
    gateway.echo("hello");
    Mockito.verify(handler, Mockito.times(1)).handleMessage(Mockito.any(Message.class));
    ac.close();
}

From source file:org.springframework.integration.history.MessageHistoryIntegrationTests.java

@Test
public void testMessageHistoryParser() {
    ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
            "messageHistoryWithHistoryWriterNamespace.xml", MessageHistoryIntegrationTests.class);
    SampleGateway gateway = ac.getBean("sampleGateway", SampleGateway.class);
    DirectChannel endOfThePipeChannel = ac.getBean("endOfThePipeChannel", DirectChannel.class);
    MessageHandler handler = Mockito.spy(new MessageHandler() {
        @Override/*from w  ww. ja v a  2s.  c o  m*/
        public void handleMessage(Message<?> message) {
            Iterator<Properties> historyIterator = message.getHeaders()
                    .get(MessageHistory.HEADER_NAME, MessageHistory.class).iterator();
            assertTrue(historyIterator.hasNext());
            MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
            replyChannel.send(message);
        }
    });
    endOfThePipeChannel.subscribe(handler);
    gateway.echo("hello");
    Mockito.verify(handler, Mockito.times(1)).handleMessage(Mockito.any(Message.class));
    ac.close();
}

From source file:org.springframework.integration.history.MessageHistoryIntegrationTests.java

@Test
public void testMessageHistoryParserWithNamePatterns() {
    ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
            "messageHistoryWithHistoryWriterNamespaceAndPatterns.xml", MessageHistoryIntegrationTests.class);
    SampleGateway gateway = ac.getBean("sampleGateway", SampleGateway.class);
    DirectChannel endOfThePipeChannel = ac.getBean("endOfThePipeChannel", DirectChannel.class);
    MessageHandler handler = Mockito.spy(new MessageHandler() {
        @Override//from   ww  w  .jav a  2s. c o  m
        public void handleMessage(Message<?> message) {
            Iterator<Properties> historyIterator = message.getHeaders()
                    .get(MessageHistory.HEADER_NAME, MessageHistory.class).iterator();
            assertTrue(historyIterator.hasNext());
            Properties gatewayHistory = historyIterator.next();
            assertEquals("sampleGateway", gatewayHistory.get("name"));
            assertTrue(historyIterator.hasNext());
            Properties chainHistory = historyIterator.next();
            assertEquals("sampleChain", chainHistory.get("name"));
            assertFalse(historyIterator.hasNext());
            MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
            replyChannel.send(message);
        }
    });
    endOfThePipeChannel.subscribe(handler);
    gateway.echo("hello");
    Mockito.verify(handler, Mockito.times(1)).handleMessage(Mockito.any(Message.class));
    ac.close();
}

From source file:org.springframework.integration.history.MessageHistoryIntegrationTests.java

@Test
@Ignore/*www . j av  a 2  s .c o m*/
public void testMessageHistoryWithHistoryPerformance() {
    ConfigurableApplicationContext acWithHistory = new ClassPathXmlApplicationContext(
            "perfWithMessageHistory.xml", MessageHistoryIntegrationTests.class);
    ConfigurableApplicationContext acWithoutHistory = new ClassPathXmlApplicationContext(
            "perfWithoutMessageHistory.xml", MessageHistoryIntegrationTests.class);

    SampleGateway gatewayHistory = acWithHistory.getBean("sampleGateway", SampleGateway.class);
    DirectChannel endOfThePipeChannelHistory = acWithHistory.getBean("endOfThePipeChannel",
            DirectChannel.class);
    endOfThePipeChannelHistory.subscribe(message -> {
        MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
        replyChannel.send(message);
    });

    SampleGateway gateway = acWithoutHistory.getBean("sampleGateway", SampleGateway.class);
    DirectChannel endOfThePipeChannel = acWithoutHistory.getBean("endOfThePipeChannel", DirectChannel.class);
    endOfThePipeChannel.subscribe(message -> {
        MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
        replyChannel.send(message);
    });

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    for (int i = 0; i < 10000; i++) {
        gatewayHistory.echo("hello");
    }
    stopWatch.stop();
    logger.info("Elapsed time with history 10000 calls: " + stopWatch.getTotalTimeSeconds());
    stopWatch = new StopWatch();
    stopWatch.start();
    for (int i = 0; i < 10000; i++) {
        gateway.echo("hello");
    }
    stopWatch.stop();
    logger.info("Elapsed time without history 10000 calls: " + stopWatch.getTotalTimeSeconds());
    acWithHistory.close();
    acWithoutHistory.close();
}

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

@SuppressWarnings("resource")
@Test//w w  w. j a  va 2  s  . co  m
@Ignore
public void testMessageHistory() throws Exception {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class);
    ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class);

    AbstractMailReceiver receiver = new ImapMailReceiver();
    receiver = spy(receiver);
    receiver.setBeanFactory(mock(BeanFactory.class));
    receiver.afterPropertiesSet();

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

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

    willAnswer(invocation -> {
        DirectFieldAccessor accessor = new DirectFieldAccessor((invocation.getMock()));
        IMAPFolder folder = mock(IMAPFolder.class);
        accessor.setPropertyValue("folder", folder);
        given(folder.hasNewMessages()).willReturn(true);
        return null;
    }).given(receiver).openFolder();

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

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

    PollableChannel channel = context.getBean("channel", PollableChannel.class);

    adapter.start();
    org.springframework.messaging.Message<?> replMessage = channel.receive(10000);
    MessageHistory history = MessageHistory.read(replMessage);
    assertNotNull(history);
    Properties componentHistoryRecord = TestUtils.locateComponentInHistory(history, "simpleAdapter", 0);
    assertNotNull(componentHistoryRecord);
    assertEquals("mail:imap-idle-channel-adapter", componentHistoryRecord.get("type"));
    adapter.stop();
    context.close();
}

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

@Test
public void testIdleChannelAdapterException() throws Exception {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class);
    ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class);

    //ImapMailReceiver receiver = (ImapMailReceiver) TestUtils.getPropertyValue(adapter, "mailReceiver");

    DirectChannel channel = new DirectChannel();
    channel.subscribe(new AbstractReplyProducingMessageHandler() {

        @Override/*from w ww  . j a va 2  s . c om*/
        protected Object handleRequestMessage(org.springframework.messaging.Message<?> requestMessage) {
            throw new RuntimeException("Failed");
        }
    });
    adapter.setOutputChannel(channel);
    QueueChannel errorChannel = new QueueChannel();
    adapter.setErrorChannel(errorChannel);

    AbstractMailReceiver receiver = new ImapMailReceiver();
    receiver = spy(receiver);
    receiver.setBeanFactory(mock(BeanFactory.class));
    receiver.afterPropertiesSet();

    Field folderField = AbstractMailReceiver.class.getDeclaredField("folder");
    folderField.setAccessible(true);
    Folder folder = mock(IMAPFolder.class);
    given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.USER));
    folderField.set(receiver, folder);

    willAnswer(invocation -> true).given(folder).isOpen();

    willAnswer(invocation -> null).given(receiver).openFolder();

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

    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);

    adapter.start();
    org.springframework.messaging.Message<?> replMessage = errorChannel.receive(10000);
    assertNotNull(replMessage);
    assertEquals("Failed", ((Exception) replMessage.getPayload()).getCause().getMessage());
    adapter.stop();
    context.close();
}

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

@SuppressWarnings("resource")
@Test/*from w  ww . j a v  a  2 s. co m*/
public void testNoInitialIdleDelayWhenRecentNotSupported() 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.USER));
    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 };

    final AtomicInteger shouldFindMessagesCounter = new AtomicInteger(2);
    willAnswer(invocation -> {
        /*
         * Return the message from first invocation of waitForMessages()
         * and in receive(); then return false in the next call to
         * waitForMessages() so we enter idle(); counter will be reset
         * to 1 in the mocked idle().
         */
        if (shouldFindMessagesCounter.decrementAndGet() >= 0) {
            return messages;
        } else {
            return new Message[0];
        }
    }).given(receiver).searchForNewMessages();

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

    willAnswer(invocation -> {
        Thread.sleep(5000);
        shouldFindMessagesCounter.set(1);
        return null;
    }).given(folder).idle();

    adapter.start();

    /*
     * Idle takes 5 seconds; if all is well, we should receive the first message
     * before then.
     */
    assertNotNull(channel.receive(3000));
    // We should not receive any more until the next idle elapses
    assertNull(channel.receive(3000));
    assertNotNull(channel.receive(6000));
    adapter.stop();
    context.close();
}

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

@SuppressWarnings("resource")
@Test//from   ww  w .j av  a 2s .com
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);/*w w w  . j  a va2 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();
}