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.cloud.stream.metrics.ApplicationMetricsExporterTests.java

@Test
public void propertiesWithPlaceholdersAndExpressions() throws Exception {
    ConfigurableApplicationContext applicationContext = SpringApplication.run(BinderExporterApplication.class,
            "--server.port=0", "--spring.jmx.enabled=false", "--PLATFORM_APP_NAME=123-name-foo",
            "--PLATFORM_APP_ID=123-id-bar",
            "--spring.cloud.application.guid=${PLATFORM_APP_NAME}.${PLATFORM_APP_ID}",
            "--spring.cloud.application.guid.expression=#{'${PLATFORM_APP_NAME}' + '..' + '${PLATFORM_APP_ID}'}",
            "--spring.cloud.application.guid.default.prop=${app.name.not.found:time-source}",
            "--spring.cloud.application.guid.default.env=${APP_NAME_NOT_FOUND:time-source}",
            "--spring.metrics.export.delay-millis=500",
            "--spring.cloud.stream.bindings." + Emitter.APPLICATION_METRICS + ".destination=foo",
            "--spring.metrics.export.includes=integration**",
            "--spring.cloud.stream.metrics.properties=spring**");
    Emitter emitterSource = applicationContext.getBean(Emitter.class);
    MessageCollector collector = applicationContext.getBean(MessageCollector.class);
    Message<?> message = collector.forChannel(emitterSource.applicationMetrics()).poll(10, TimeUnit.SECONDS);
    Assert.assertNotNull(message);/*from  w  ww .jav  a  2  s .  com*/
    ObjectMapper mapper = applicationContext.getBean(ObjectMapper.class);
    ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(),
            ApplicationMetrics.class);
    Assert.assertTrue(
            contains("integration.channel.errorChannel.errorRate.mean", applicationMetrics.getMetrics()));
    Assertions.assertThat(applicationMetrics.getProperties().get("spring.cloud.application.guid"))
            .isEqualTo("123-name-foo.123-id-bar");
    Assertions.assertThat(applicationMetrics.getProperties().get("spring.cloud.application.guid.expression"))
            .isEqualTo("123-name-foo..123-id-bar");
    Assertions.assertThat(applicationMetrics.getProperties().get("spring.cloud.application.guid.default.prop"))
            .isEqualTo("time-source");
    Assertions.assertThat(applicationMetrics.getProperties().get("spring.cloud.application.guid.default.env"))
            .isEqualTo("time-source");
    Assert.assertFalse(CollectionUtils.isEmpty(applicationMetrics.getProperties()));
    Assert.assertTrue(applicationMetrics.getProperties().get("spring.test.env.syntax").equals("testing"));
    applicationContext.close();
}

From source file:org.springframework.cloud.stream.metrics.ApplicationMetricsExporterTests.java

@Test
public void propertiesFromLowerPrioritySourcesOverridden() throws Exception {
    System.setProperty("spring.cloud.application.guid.test.metrics", "lowPriority");
    try {//from  w  w w.  j av a2s  . c  o  m
        ConfigurableApplicationContext applicationContext = SpringApplication.run(
                BinderExporterApplication.class, "--server.port=0", "--spring.jmx.enabled=false",
                "--spring.cloud.application.guid.test.metrics=highPriority",
                "--spring.metrics.export.delay-millis=500",
                "--spring.cloud.stream.bindings." + Emitter.APPLICATION_METRICS + ".destination=foo",
                "--spring.metrics.export.includes=integration**",
                "--spring.cloud.stream.metrics.properties=spring**");
        Emitter emitterSource = applicationContext.getBean(Emitter.class);
        MessageCollector collector = applicationContext.getBean(MessageCollector.class);
        Message<?> message = collector.forChannel(emitterSource.applicationMetrics()).poll(10,
                TimeUnit.SECONDS);
        Assert.assertNotNull(message);
        ObjectMapper mapper = applicationContext.getBean(ObjectMapper.class);
        ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(),
                ApplicationMetrics.class);
        Assert.assertTrue(
                contains("integration.channel.errorChannel.errorRate.mean", applicationMetrics.getMetrics()));
        Assertions
                .assertThat(
                        applicationMetrics.getProperties().get("spring.cloud.application.guid.test.metrics"))
                .isEqualTo("highPriority");
        applicationContext.close();
    } finally {
        System.clearProperty("spring.cloud.application.guid.test.metrics");
    }
}

From source file:org.springframework.cloud.stream.metrics.ApplicationMetricsExporterTests.java

@Test
public void overrideAppName() throws Exception {
    ConfigurableApplicationContext applicationContext = SpringApplication.run(BinderExporterApplication.class,
            "--server.port=0", "--spring.jmx.enabled=false", "--spring.metrics.export.delay-millis=500",
            "--spring.application.name=foo",
            "--spring.cloud.stream.bindings." + Emitter.APPLICATION_METRICS + ".destination=foo",
            "--spring.cloud.stream.metrics.key=foobarfoo");
    Emitter emitterSource = applicationContext.getBean(Emitter.class);
    MessageCollector collector = applicationContext.getBean(MessageCollector.class);
    Message<?> message = collector.forChannel(emitterSource.applicationMetrics()).poll(10, TimeUnit.SECONDS);
    Assert.assertNotNull(message);//from   w ww.  ja  va2s .  c om
    ObjectMapper mapper = applicationContext.getBean(ObjectMapper.class);
    ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(),
            ApplicationMetrics.class);
    Assert.assertTrue(
            contains("integration.channel.errorChannel.errorRate.mean", applicationMetrics.getMetrics()));
    Assert.assertTrue(contains("mem", applicationMetrics.getMetrics()));
    Assert.assertEquals("foobarfoo", applicationMetrics.getName());
    Assert.assertTrue(CollectionUtils.isEmpty(applicationMetrics.getProperties()));
    applicationContext.close();
}

From source file:org.springframework.data.hadoop.examples.CommonMain.java

public static void main(String args[]) {

    ConfigurableApplicationContext context = null;

    try {/* w  w w  .  ja  v a 2s . co  m*/
        System.out.println("Running example");
        context = new ClassPathXmlApplicationContext("application-context.xml");
        JobRunner runner = (JobRunner) context.getBean("runner");
        runner.call();
        System.out.println("Complete example");
    } catch (Throwable e) {
        log.error("Error in main method", e);
    } finally {
        if (context != null) {
            context.close();
        }
    }

}

From source file:org.springframework.integration.dsl.test.IntegrationFlowTests.java

@Test
public void testWrongLastComponent() {
    ConfigurableApplicationContext context = null;
    try {//from  ww w  . j  a v  a2 s. c  o  m
        context = new AnnotationConfigApplicationContext(InvalidLastComponentFlowContext.class);
        fail("BeanCreationException expected");
    } catch (Exception e) {
        assertThat(e, instanceOf(BeanCreationException.class));
        assertThat(e.getMessage(), containsString("is a one-way 'MessageHandler'"));
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

From source file:org.springframework.integration.dsl.test.IntegrationFlowTests.java

@Test
public void testWrongLastMessageChannel() {
    ConfigurableApplicationContext context = null;
    try {//from   w  ww . j  a  v a 2 s .c o m
        context = new AnnotationConfigApplicationContext(InvalidLastMessageChannelFlowContext.class);
        fail("BeanCreationException expected");
    } catch (Exception e) {
        assertThat(e, instanceOf(BeanCreationException.class));
        assertThat(e.getMessage(), containsString("'.fixedSubscriberChannel()' "
                + "can't be the last EIP-method in the IntegrationFlow definition"));
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

From source file:org.springframework.integration.dsl.test.IntegrationFlowTests.java

@Test
public void testWrongConfigurationWithSpecBean() {
    ConfigurableApplicationContext context = null;
    try {/*from ww w  . j  a v a 2  s .  c o  m*/
        context = new AnnotationConfigApplicationContext(InvalidConfigurationWithSpec.class);
        fail("BeanCreationException expected");
    } catch (Exception e) {
        assertThat(e, instanceOf(IllegalArgumentException.class));
        assertThat(e.getCause(), instanceOf(BeanCreationException.class));
        assertThat(e.getCause().getMessage(),
                containsString("must be populated to target objects via 'get()' method call"));
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

From source file:org.springframework.integration.endpoint.PseudoTransactionalMessageSourceTests.java

@Test
public void testTransactionSynchronizationFactoryBean() {
    ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(TestTxSyncConfiguration.class);

    TransactionSynchronizationFactory syncFactory = ctx.getBean(TransactionSynchronizationFactory.class);

    PollableChannel queueChannel = ctx.getBean("outputChannel", PollableChannel.class);

    SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter();

    adapter.setTransactionSynchronizationFactory(syncFactory);

    QueueChannel outputChannel = new QueueChannel();
    adapter.setOutputChannel(outputChannel);
    adapter.setSource(new MessageSource<String>() {

        @Override//  w  ww  . ja  v a 2  s .c om
        public Message<String> receive() {
            GenericMessage<String> message = new GenericMessage<String>("foo");
            IntegrationResourceHolder holder = (IntegrationResourceHolder) TransactionSynchronizationManager
                    .getResource(this);
            holder.addAttribute("baz", "qux");
            holder.addAttribute("bix", "qox");
            return message;
        }
    });

    TransactionSynchronizationManager.initSynchronization();
    TransactionSynchronizationManager.setActualTransactionActive(true);
    doPoll(adapter);
    TransactionSynchronizationUtils.triggerBeforeCommit(false);
    TransactionSynchronizationUtils.triggerAfterCommit();
    Message<?> beforeCommitMessage = queueChannel.receive(1000);
    assertNotNull(beforeCommitMessage);
    assertEquals("qox", beforeCommitMessage.getPayload());
    Message<?> afterCommitMessage = queueChannel.receive(1000);
    assertNotNull(afterCommitMessage);
    assertEquals("qux", afterCommitMessage.getPayload());
    TransactionSynchronizationUtils.triggerAfterCompletion(TransactionSynchronization.STATUS_COMMITTED);
    TransactionSynchronizationManager.clearSynchronization();
    TransactionSynchronizationManager.setActualTransactionActive(false);
    ctx.close();
}

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

@Test
public void testNoHistoryAwareMessageHandler() {
    ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
            "messageHistoryWithoutHistoryWriter.xml", MessageHistoryIntegrationTests.class);
    Map<String, ConsumerEndpointFactoryBean> cefBeans = ac.getBeansOfType(ConsumerEndpointFactoryBean.class);
    for (ConsumerEndpointFactoryBean cefBean : cefBeans.values()) {
        DirectFieldAccessor bridgeAccessor = new DirectFieldAccessor(cefBean);
        String handlerClassName = bridgeAccessor.getPropertyValue("handler").getClass().getName();
        assertFalse("org.springframework.integration.config.MessageHistoryWritingMessageHandler"
                .equals(handlerClassName));
    }/*from   w  w  w . j  a v  a2  s.c  om*/
    ac.close();
}

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

@Test
public void testMessageHistoryWithHistoryWriter() {
    ConfigurableApplicationContext ac = new ClassPathXmlApplicationContext(
            "messageHistoryWithHistoryWriter.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 .j a va2  s  . c  o m
        public void handleMessage(Message<?> message) {
            Iterator<Properties> historyIterator = message.getHeaders()
                    .get(MessageHistory.HEADER_NAME, MessageHistory.class).iterator();

            Properties event = historyIterator.next();
            assertEquals("sampleGateway", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("gateway", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("bridgeInChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("testBridge", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("bridge", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("headerEnricherChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("testHeaderEnricher", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("transformer", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("chainChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("sampleChain", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("chain", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("sampleChain$child.service-activator-within-chain",
                    event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("service-activator", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("filterChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("testFilter", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("filter", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("splitterChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("testSplitter", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("splitter", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("aggregatorChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("testAggregator", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("aggregator", event.getProperty(MessageHistory.TYPE_PROPERTY));

            event = historyIterator.next();
            assertEquals("endOfThePipeChannel", event.getProperty(MessageHistory.NAME_PROPERTY));
            assertEquals("channel", event.getProperty(MessageHistory.TYPE_PROPERTY));

            MessageChannel replyChannel = (MessageChannel) message.getHeaders().getReplyChannel();
            replyChannel.send(message);
        }
    });
    endOfThePipeChannel.subscribe(handler);
    Message<?> result = gateway.echo("hello");
    Mockito.verify(handler, Mockito.times(1)).handleMessage(Mockito.any(Message.class));
    assertNotNull(result);
    //assertEquals("hello", result);
    ac.close();
}