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:net.radai.confusion.spring.SpringAnnotationConfigTest.java

@Test
public void testSpringAnnotationIntegration() throws Exception {
    Path dir = Files.createTempDirectory("test");
    Path targetFile = dir.resolve("confFile");
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("cats.ini");
            OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE_NEW)) {
        ByteStreams.copy(is, os);/*from   w  ww.ja v  a 2  s.c  o m*/
    }
    String absolutePath = targetFile.toFile().getCanonicalPath();
    System.setProperty("confFile", absolutePath);
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("annotationSpringContext.xml");
    //noinspection unchecked
    SpringAwareConfigurationService<Cats> confService = (SpringAwareConfigurationService<Cats>) context
            .getBean(ConfigurationService.class);
    Jsr330AnnotatedConfigurationConsumerBean consumer = context
            .getBean(Jsr330AnnotatedConfigurationConsumerBean.class);
    //noinspection unchecked
    Assert.assertNotNull(consumer.getConfService());
    Assert.assertNotNull(consumer.getInitialConf());
    Assert.assertTrue(consumer.getCats().isEmpty());

    try (InputStream is = getClass().getClassLoader().getResourceAsStream("cat.ini");
            OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE,
                    StandardOpenOption.TRUNCATE_EXISTING)) {
        ByteStreams.copy(is, os);
    }
    Thread.sleep(100);

    //verify event was received
    Assert.assertEquals(1, consumer.getCats().size());
    Assert.assertTrue(consumer.getInitialConf() != consumer.getCats().get(0));
    Assert.assertTrue(confService.getConfiguration() == consumer.getCats().get(0));

    context.close();
}

From source file:com.aeg.ims.transfer.protocol.ftp.OutboundChannelAdapter.java

public void runDemo() throws Exception {

    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
            "classpath:partners/CRH/OutboundChannelAdapter.xml");

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

    baseFolder.mkdirs();/*from ww w .  j  a  va 2  s.co  m*/

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

    final InputStream inputStreamA = OutboundChannelAdapter.class.getResourceAsStream("/test-files/a.txt");
    final InputStream inputStreamB = OutboundChannelAdapter.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());

    ctx.close();
}

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

@Test
public void testLsGetRm() throws Exception {
    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
            "classpath:/META-INF/spring/integration/SftpOutboundGatewaySample-context.xml");
    ToSftpFlowGateway toFtpFlow = ctx.getBean(ToSftpFlowGateway.class);
    RemoteFileTemplate<LsEntry> template = null;
    String file1 = "1.ftptest";
    String file2 = "2.ftptest";
    File tmpDir = new File(System.getProperty("java.io.tmpdir"));

    try {/*from www.  ja  va  2  s .c o  m*/
        // remove the previous output files if necessary
        new File(tmpDir, file1).delete();
        new File(tmpDir, file2).delete();

        @SuppressWarnings("unchecked")
        SessionFactory<LsEntry> sessionFactory = ctx.getBean(CachingSessionFactory.class);
        template = new RemoteFileTemplate<LsEntry>(sessionFactory);
        SftpTestUtils.createTestFiles(template, file1, file2);

        // execute the flow (ls, get, rm, aggregate results)
        List<Boolean> rmResults = toFtpFlow.lsGetAndRmFiles("si.sftp.sample");

        //Check everything went as expected, and clean up
        assertEquals(2, rmResults.size());
        for (Boolean result : rmResults) {
            assertTrue(result);
        }

    } finally {
        SftpTestUtils.cleanUp(template, file1, file2);
        ctx.close();
        assertTrue("Could note delete retrieved file", new File(tmpDir, file1).delete());
        assertTrue("Could note delete retrieved file", new File(tmpDir, file2).delete());
    }
}

From source file:org.huahinframework.emanager.Runner.java

/**
 * @param war/*from w  ww  . ja  v  a  2  s .c  o m*/
 * @param port
 * @param shutDownPort
 */
public void start(String war, int port, int shutDownPort) {
    log.info("huahin-emanager start");

    ConfigurableApplicationContext applicationContext = null;
    try {
        applicationContext = new ClassPathXmlApplicationContext("huahinEManagerProperties.xml",
                "huahinEManagerEMRProperties.xml");
        Properties properties = (Properties) applicationContext.getBean("properties");
        EMRProperties emrProperties = (EMRProperties) applicationContext.getBean("emrProperties");

        QueueManager queueManager = new QueueManager(properties, emrProperties);
        queueManager.start();

        SelectChannelConnector connector = new SelectChannelConnector();
        connector.setPort(port);

        Server server = new Server();
        server.setConnectors(new Connector[] { connector });

        WebAppContext web = new WebAppContext();
        web.setContextPath("/");
        web.setWar(war);

        ShutDowner shutDowner = new ShutDowner(shutDownPort, server, queueManager);
        shutDowner.start();

        server.addHandler(web);
        server.start();
        server.join();
        shutDowner.join();
        queueManager.join();
    } catch (Exception e) {
        log.error("huahin-emanager aborted", e);
        System.exit(-1);
    } finally {
        if (applicationContext != null) {
            applicationContext.close();
        }
    }

    log.info("huahin-emanager end");
}

From source file:multibinder.RabbitAndKafkaBinderApplicationTests.java

@Test
public void messagingWorks() throws Exception {
    // passing connection arguments arguments to the embedded Kafka instance
    ConfigurableApplicationContext context = SpringApplication.run(MultibinderApplication.class,
            "--spring.cloud.stream.kafka.binder.brokers=" + kafkaEmbedded.getBrokersAsString(),
            "--spring.cloud.stream.kafka.binder.zkNodes=" + kafkaEmbedded.getZookeeperConnectionString(),
            "--spring.cloud.stream.bindings.output.producer.requiredGroups=" + this.randomGroup);
    DirectChannel dataProducer = new DirectChannel();
    BinderFactory<?> binderFactory = context.getBean(BinderFactory.class);

    QueueChannel dataConsumer = new QueueChannel();

    ((RabbitMessageChannelBinder) binderFactory.getBinder("rabbit")).bindConsumer("dataOut", this.randomGroup,
            dataConsumer, new ExtendedConsumerProperties<>(new RabbitConsumerProperties()));

    ((KafkaMessageChannelBinder) binderFactory.getBinder("kafka")).bindProducer("dataIn", dataProducer,
            new ExtendedProducerProperties<>(new KafkaProducerProperties()));

    String testPayload = "testFoo" + this.randomGroup;
    dataProducer.send(MessageBuilder.withPayload(testPayload).build());

    Message<?> receive = dataConsumer.receive(10000);
    Assert.assertThat(receive, Matchers.notNullValue());
    Assert.assertThat(receive.getPayload(), CoreMatchers.equalTo(testPayload));
    context.close();
}

From source file:net.radai.confusion.spring.SpringXmlConfTest.java

@Test
public void testSpringXmlIntegration() throws Exception {
    Path dir = Files.createTempDirectory("test");
    Path targetFile = dir.resolve("confFile");
    try (InputStream is = getClass().getClassLoader().getResourceAsStream("cats.ini");
            OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE,
                    StandardOpenOption.CREATE_NEW)) {
        ByteStreams.copy(is, os);/*w  w  w  . j  ava 2s .  c o  m*/
    }
    String absolutePath = targetFile.toFile().getCanonicalPath();
    System.setProperty("confFile", absolutePath);
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("xmlSpringContext.xml");
    //noinspection unchecked
    SpringAwareConfigurationService<Cats> confService = (SpringAwareConfigurationService<Cats>) context
            .getBean(ConfigurationService.class);
    TraditionalConfigurationConsumerBean consumer = context.getBean(TraditionalConfigurationConsumerBean.class);
    //noinspection unchecked
    SimpleConfigurationService<Cats> delegate = (SimpleConfigurationService<Cats>) ReflectionTestUtils
            .getField(confService, "delegate");
    Assert.assertNotNull(confService.getConfiguration());
    Assert.assertTrue(delegate.isStarted());
    Assert.assertTrue(consumer.getConf() == confService.getConfiguration());
    Assert.assertTrue(consumer.getConfService() == confService);
    Assert.assertTrue(consumer.getCats().isEmpty());

    try (InputStream is = getClass().getClassLoader().getResourceAsStream("cat.ini");
            OutputStream os = Files.newOutputStream(targetFile, StandardOpenOption.WRITE,
                    StandardOpenOption.TRUNCATE_EXISTING)) {
        ByteStreams.copy(is, os);
    }
    Thread.sleep(100);

    //verify event was received
    Assert.assertEquals(1, consumer.getCats().size());
    Assert.assertTrue(consumer.getConf() != consumer.getCats().get(0));
    Assert.assertTrue(confService.getConfiguration() == consumer.getCats().get(0));

    context.close();
    Assert.assertFalse(delegate.isStarted());
}

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  w  w  w  .j  ava 2 s  .c  o m*/
        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:com.github.exper0.efilecopier.ftp.FtpOutboundChannelAdapterSample.java

@Test
public void runDemo1() throws Exception {

    //        ConfigurableApplicationContext ctx =
    //            new ClassPathXmlApplicationContext("META-INF/spring/integration/FtpOutboundChannelAdapterSample-context.xml");
    ///*from   w  w  w  . j  a va2  s. co m*/
    //        MessageChannel ftpChannel = ctx.getBean("ftpChannel", MessageChannel.class);

    ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext(
            "META-INF/spring/integration/DynamicFtpOutboundChannelAdapterSample-context.xml");
    MessageChannel ftpChannel = ctx.getBean("toDynRouter", MessageChannel.class);

    baseFolder.mkdirs();

    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).setHeader("customer", "cust1")
            .build();
    final Message<File> messageB = MessageBuilder.withPayload(fileToSendB).setHeader("customer", "cust1")
            .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.kew.rmf.reconciliation.service.ReconciliationService.java

/**
 * Loads a single configuration./*from   www  .j a v a2  s.c o m*/
 */
private void loadConfiguration(String configFileName) throws ReconciliationServiceException {
    synchronized (configurationStatuses) {
        ConfigurationStatus status = configurationStatuses.get(configFileName);
        assert (status == ConfigurationStatus.LOADING);
    }

    StopWatch sw = new Slf4JStopWatch(timingLogger);

    String configurationFile = CONFIG_BASE + configFileName;
    logger.info("{}: Loading configuration from file {}", configFileName, configurationFile);

    ConfigurableApplicationContext context = new GenericXmlApplicationContext(configurationFile);
    context.registerShutdownHook();

    LuceneMatcher matcher = context.getBean("engine", LuceneMatcher.class);
    String configName = matcher.getConfig().getName();

    contexts.put(configFileName, context);
    matchers.put(configName, matcher);

    try {
        matcher.loadData();
        totals.put(configName, matcher.getIndexReader().numDocs());
        logger.debug("{}: Loaded data", configName);

        // Append " (environment)" to Metadata name, to help with interactive testing
        Metadata metadata = getMetadata(configName);
        if (metadata != null) {
            if (!"prod".equals(environment)) {
                metadata.setName(metadata.getName() + " (" + environment + ")");
            }
        }

        synchronized (configurationStatuses) {
            ConfigurationStatus status = configurationStatuses.get(configFileName);
            if (status != ConfigurationStatus.LOADING) {
                logger.error(
                        "Unexpected configuration status '" + status + "' after loading " + configFileName);
            }
            configurationStatuses.put(configFileName, ConfigurationStatus.LOADED);
        }
    } catch (Exception e) {
        logger.error("Problem loading configuration " + configFileName, e);

        context.close();
        totals.remove(configName);
        matchers.remove(configName);
        contexts.remove(configFileName);

        synchronized (configurationStatuses) {
            ConfigurationStatus status = configurationStatuses.get(configFileName);
            if (status != ConfigurationStatus.LOADING) {
                logger.error(
                        "Unexpected configuration status '" + status + "' after loading " + configFileName);
            }
            configurationStatuses.remove(configFileName);
        }

        sw.stop("LoadConfiguration:" + configFileName + ".failure");
        throw new ReconciliationServiceException("Problem loading configuration " + configFileName, e);
    }

    sw.stop("LoadConfiguration:" + configFileName + ".success");
}

From source file:cl.vmetrix.operation.channels.OperationCh.java

@Override
public boolean processMessage(String msg) throws VMWebServiceException {

    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    OperationService operationService = (OperationService) context.getBean("operationService");
    logger.debug("Getting object from XML...");
    XmlValidator xmlv = new XmlValidator();

    try {/*w  ww. ja  v  a2 s  .c  o  m*/
        if (xmlv.validateXMLstg(msg)) {

            try {
                logger.debug("XML Validation...OK!.");
                logger.debug("String XML is valid...start process...");
                operation = ObjectFromXMLstg.createOperationObj(msg);

            } catch (JAXBException e) {
                logger.error("JAXBException in ObjectFromXMLstg.operation", e);
                logger.error("JAXBException unmarshaller the xml: " + msg);
                throw new VMWebServiceException("Exception processing this xml: " + msg, e);
            } catch (Exception e) {
                logger.error("Exception in ObjectFromXMLstg.operation", e);
                logger.error("Exception unmarshaller the xml: " + msg);
                throw new VMWebServiceException("Exception processing this xml: " + msg, e);
            }

            logger.debug("Start persistent process....");

            origin = operation.getOrigin();
            processDate = operation.getProcessDate();
            dealNum = operation.getDealNum();

            try {
                if (operation.getCashFlow() != null && operation.getCashFlow().size() > 0)
                    operationService.persistCashflow(mappingCasflow(operation.getCashFlow()));

                if (operation.getInterest() != null && operation.getInterest().size() > 0)
                    operationService.persistInterest(mappingInterest(operation.getInterest()));

                operationService.persistEquivCred(mappingEquivCred(operation.getEquivalenteCredito()));

                operationService.persistPricing(mappingPricing(operation.getPricing()));

                operationService.persistProfit(mappingProfit(operation.getProfit()));

                operationService.persistSide(mappingSide(operation.getSide()));

                operationService.persistTranInfo(mappingTranInfo(operation.getTransactionInfo()));

                operationService.persistTranSaction(mappingTransaction(operation.getTransaction()));

            } catch (Exception e) {
                logger.error("Exception saving operation. Could not process message", e);
                rollbackDB(operationService, operation);
                throw new VMWebServiceException("Exception processing this xml: " + msg, e);
            }

            return true;

        } else {
            logger.debug("XML is not valid...stop process.");
            throw new VMWebServiceException("XML is not valid...stop process.");
        }

    } catch (Exception e) {
        logger.error("Exception processing the operation. Could not process message", e);
        throw new VMWebServiceException("Exception processing this xml: " + msg, e);
    } finally {
        if (context != null) {
            logger.debug("Closing context..");
            context.close();
        }
        operationService = null;
        xmlv = null;
        operation = null;
        logger.debug("End persistent operation.");
    }

}