Example usage for org.springframework.context.support ClassPathXmlApplicationContext close

List of usage examples for org.springframework.context.support ClassPathXmlApplicationContext close

Introduction

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

Prototype

@Override
public void close() 

Source Link

Document

Close this application context, destroying all beans in its bean factory.

Usage

From source file:gr.seab.r2rml.beans.Main.java

public static void main(String[] args) {
    Calendar c0 = Calendar.getInstance();
    long t0 = c0.getTimeInMillis();

    CommandLineParser cmdParser = new PosixParser();

    Options cmdOptions = new Options();
    cmdOptions.addOption("p", "properties", true,
            "define the properties file. Example: r2rml-parser -p r2rml.properties");
    cmdOptions.addOption("h", "print help", false, "help");

    String propertiesFile = "r2rml.properties";

    try {//from   w w  w .  j a  v  a2 s  .c o m
        CommandLine line = cmdParser.parse(cmdOptions, args);

        if (line.hasOption("h")) {
            HelpFormatter help = new HelpFormatter();
            help.printHelp("r2rml-parser\n", cmdOptions);
            System.exit(0);
        }

        if (line.hasOption("p")) {
            propertiesFile = line.getOptionValue("p");
        }
    } catch (ParseException e1) {
        //e1.printStackTrace();
        log.error("Error parsing command line arguments.");
        System.exit(1);
    }

    try {
        if (StringUtils.isNotEmpty(propertiesFile)) {
            properties.load(new FileInputStream(propertiesFile));
            log.info("Loaded properties from " + propertiesFile);
        }
    } catch (FileNotFoundException e) {
        //e.printStackTrace();
        log.error("Properties file not found (" + propertiesFile + ").");
        System.exit(1);
    } catch (IOException e) {
        //e.printStackTrace();
        log.error("Error reading properties file (" + propertiesFile + ").");
        System.exit(1);
    }

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");

    Database db = (Database) context.getBean("db");
    db.setProperties(properties);

    Parser parser = (Parser) context.getBean("parser");
    parser.setProperties(properties);

    MappingDocument mappingDocument = parser.parse();

    mappingDocument.getTimestamps().add(t0); //0 Started
    mappingDocument.getTimestamps().add(Calendar.getInstance().getTimeInMillis()); //1 Finished parsing. Starting generating result model.

    Generator generator = (Generator) context.getBean("generator");
    generator.setProperties(properties);
    generator.setResultModel(parser.getResultModel());

    //Actually do the output
    generator.createTriples(mappingDocument);

    context.close();
    Calendar c1 = Calendar.getInstance();
    long t1 = c1.getTimeInMillis();
    log.info("Finished in " + (t1 - t0) + " milliseconds. Done.");
    mappingDocument.getTimestamps().add(Calendar.getInstance().getTimeInMillis()); //5 Finished.
    //log.info("5 Finished.");

    //output the result
    for (int i = 0; i < mappingDocument.getTimestamps().size(); i++) {
        if (i > 0) {
            long l = (mappingDocument.getTimestamps().get(i).longValue()
                    - mappingDocument.getTimestamps().get(i - 1).longValue());
            //System.out.println(l);
            log.info(String.valueOf(l));
        }
    }
    log.info("Parse. Generate in memory. Dump to disk/database. Log. - Alltogether in "
            + String.valueOf(mappingDocument.getTimestamps().get(5).longValue()
                    - mappingDocument.getTimestamps().get(0).longValue())
            + " msec.");
    log.info("Done.");
    System.out.println("Done.");
}

From source file:com.github.cmis4j.ws.CmisRepositoryMain.java

@SuppressWarnings("unused")
public static void main(String[] args) {
    try {//  w  w w .j av  a  2 s  .  co  m
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("cmis4j-ws-test.xml");
        ACLServicePort aclService = (ACLServicePort) ctx.getBean("aclService");
        DiscoveryServicePort discoveryService = (DiscoveryServicePort) ctx.getBean("discoveryService");
        MultiFilingServicePort multiFilingService = (MultiFilingServicePort) ctx.getBean("multiFilingService");
        NavigationServicePort navigationService = (NavigationServicePort) ctx.getBean("navigationService");
        ObjectServicePort objectService = (ObjectServicePort) ctx.getBean("objectService");
        PolicyServicePort policyService = (PolicyServicePort) ctx.getBean("policyService");
        RelationshipServicePort relationshipService = (RelationshipServicePort) ctx
                .getBean("relationshipService");
        RepositoryServicePort repositoryService = (RepositoryServicePort) ctx.getBean("repositoryService");
        VersioningServicePort versioningService = (VersioningServicePort) ctx.getBean("versioningService");
        ctx.close();
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:nats.client.spring.NatsApplicationEventTest.java

public static void main(String[] args) throws Exception {
    // TODO Make automated test that starts a NATS server and then runs test.

    // Nats server must running before running this test.
    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "natsApplicationEventContext.xml");
    try {/*w  w w .  j  ava  2  s  .c o m*/
        final Nats nats = context.getBean(Nats.class);
        Assert.assertNotNull(nats);

        final boolean invokedConnected = context.getBean("connected", ConnectListener.class).invoked.await(2,
                TimeUnit.SECONDS);
        Assert.assertTrue(invokedConnected, "The connected application event was never published.");
        final boolean invokedReady = context.getBean("ready", ReadyListener.class).invoked.await(2,
                TimeUnit.SECONDS);
        Assert.assertTrue(invokedReady, "The server ready application event was never published.");
        nats.close();
        final boolean invokedClosed = context.getBean("closed", ClosedListener.class).invoked.await(2,
                TimeUnit.SECONDS);
        Assert.assertTrue(invokedClosed, "The closed application event was never published.");
    } finally {
        context.close();
    }
}

From source file:org.excalibur.fm.configuration.Main2.java

public static void main(String[] args) {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath*:META-INF/applicationContext.xml");

    ProviderService providerService = context.getBean(ProviderService.class);

    // get all instance types offered at the North America region of all providers
    List<InstanceType> instanceTypes = providerService
            .getInstanceTypesAvailableOnRegion(GeographicRegions.NORTH_AMERICA.toType());

    // get all instance types of all regions of all providers
    instanceTypes = providerService.getAllInstanceTypesOfAllRegions();

    Constraint[] constraints = new Constraint[] { new Constraint(new Variable("cores", 9), Operator.GE),
            new Constraint(new Variable("memory", 8 * 1024), Operator.GE),
            new Constraint(new Variable("cost", 1000), Operator.LE) };

    List<InstanceType> allOptimalSolutions = new InstanceSelection2(instanceTypes)
            .findAllOptimalSolutions(constraints);

    System.out.format("\n%33s%17s%33s\n\n", " ", "Optimal solutions", " ");
    print(allOptimalSolutions);/*from   w ww  .  jav  a 2s .  c  o m*/

    context.close();
}

From source file:no.trank.openpipe.tutorial.intranet.Main.java

public static void main(String[] args) {
    if (args.length < 1) {
        usage();/*from w  w w.  j  a  v a2 s.c  o m*/
    } else {
        try {
            ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
                    "intranetApplicationContext.xml");
            try {
                FileDocumentReader directory = (FileDocumentReader) appContext.getBean("fileDocumentReader",
                        FileDocumentReader.class);
                directory.setDirectory(args[0]);

                if (args.length > 1) {
                    SolrHttpDocumentPoster solrDocumentPoster = (SolrHttpDocumentPoster) appContext
                            .getBean("solrDocumentPoster", SolrHttpDocumentPoster.class);
                    SolrDocumentProcessor solrDocumentProcessor = (SolrDocumentProcessor) appContext
                            .getBean("solrDocumentProcessor", SolrDocumentProcessor.class);

                    String solrUrl = args[1];
                    solrDocumentPoster.setPostUrl(solrUrl + "/update");
                    solrDocumentProcessor.setSolrSchemaUrl(solrUrl + "/admin/get-file.jsp?file=schema.xml");
                }

                Runnable pipelineApplication = (Runnable) appContext.getBean("pipelineApplicationBean",
                        Runnable.class);
                pipelineApplication.run();
            } finally {
                appContext.close();
            }
        } catch (BeansException e) {
            log.error("Spring error", e);
        }
    }
}

From source file:com.opengamma.bbg.referencedata.cache.MongoDBReferenceDataCacheRefresher.java

/**
 * Runs the tool./*from   ww w  .j a  v  a 2  s . c o  m*/
 * 
 * @param args  empty arguments
 * @throws Exception 
 */
public static void main(final String[] args) throws Exception { // CSIGNORE
    PlatformConfigUtils.configureSystemProperties();
    System.out.println("Starting connections");
    String configLocation = "com/opengamma/bbg/bbg-reference-data-context.xml";

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(configLocation);
    try {
        context.start();
        MongoDBValueCachingReferenceDataProvider mongoProvider = context
                .getBean("bloombergReferenceDataProvider", MongoDBValueCachingReferenceDataProvider.class);
        MongoDBReferenceDataCacheRefresher refresher = new MongoDBReferenceDataCacheRefresher(mongoProvider);

        Options options = createOptions();
        CommandLineParser parser = new PosixParser();
        CommandLine line = null;
        try {
            line = parser.parse(options, args);
        } catch (ParseException e) {
            usage(options);
            return;
        }
        if (line.hasOption(HELP_OPTION)) {
            usage(options);
            return;
        }

        //TODO other options, e.g. explicitly specify security 
        int numberOfSecurities = Integer.parseInt(line.getArgs()[0]);
        int id = Integer.parseInt(line.getArgs()[1]);
        System.out.println("Refreshing " + numberOfSecurities + " securities, id " + id);
        refresher.refreshCaches(numberOfSecurities, id);
        System.out.println("Done refreshing");
    } catch (Exception ex) {
        context.close();
        throw ex;
    }
}

From source file:nz.co.jsrsolutions.ds3.DataScraper3.java

public static void main(String[] args) {

    logger.info("Starting application [ ds3 ] ...");

    ClassPathXmlApplicationContext context = null;

    try {/*from ww  w .  java2  s.  co  m*/

        CommandLineParser parser = new GnuParser();

        CommandLine commandLine = parser.parse(CommandLineOptions.Options, args);

        if (commandLine.getOptions().length > 0 && !commandLine.hasOption(CommandLineOptions.HELP)) {

            StringBuffer environment = new StringBuffer();
            environment.append(SPRING_CONFIG_PREFIX);
            environment.append(commandLine.getOptionValue(CommandLineOptions.ENVIRONMENT));
            environment.append(SPRING_CONFIG_SUFFIX);

            context = new ClassPathXmlApplicationContext(environment.toString());
            context.registerShutdownHook();

            if (commandLine.hasOption(CommandLineOptions.SCHEDULED)) {

                Scheduler scheduler = context.getBean(SCHEDULER_BEAN_ID, Scheduler.class);
                scheduler.start();

                Object lock = new Object();
                synchronized (lock) {
                    lock.wait();
                }

            } else {
                DataScraper3Controller controller = context.getBean(CONTROLLER_BEAN_ID,
                        DataScraper3Controller.class);
                controller.executeCommandLine(commandLine);
            }

        } else {

            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("ds3", CommandLineOptions.Options);

        }

    } catch (DataScraper3Exception ds3e) {
        logger.error("Failed to execute command", ds3e);
    } catch (ParseException pe) {

        logger.error("Failed to parse command line", pe);

    } catch (Exception e) {

        logger.error("Failed to execute command", e);

    } finally {
        if (context != null) {
            context.close();
        }
    }

    logger.info("Exiting application [ ds3 ] ...");

}

From source file:cn.webank.ecif.index.server.EcifIndexServer.java

/**
 * @param args/*  w  w w .  j a v  a 2  s  . c  om*/
 */
public static void main(String[] args) {
    final EcifIndexServer server = new EcifIndexServer();
    // start spring context;
    final ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();

    context.getEnvironment().setActiveProfiles("product");
    context.setConfigLocation("application.xml");
    context.refresh();
    context.start();

    // thread pool construct
    ThreadPoolTaskExecutor taskThreadPool = context.getBean("taskExecutor", ThreadPoolTaskExecutor.class);

    server.setTaskThreadPool(taskThreadPool);

    ExecutorService fixedThreadPool = context.getBean("fixedTaskExecutor", ExecutorService.class);

    server.setSchedulerThreadPool(fixedThreadPool);

    EcifThreadFactory threadFactory = context.getBean("cn.webank.ecif.index.async.EcifThreadFactory",
            EcifThreadFactory.class);

    server.setThreadFactory(threadFactory);

    Properties props = context.getBean("ecifProperties", java.util.Properties.class);

    WeBankServiceDispatcher serviceDispatcher = context.getBean(
            "cn.webank.framework.biz.service.support.WeBankServiceDispatcher", WeBankServiceDispatcher.class);

    ReloadableResourceBundleMessageSource bundleMessageSource = context.getBean("messageSource",
            ReloadableResourceBundleMessageSource.class);

    String topics = props.getProperty("listener.topics");
    String[] splits = topics.split(",");

    SolaceManager solaceManager = context.getBean("cn.webank.framework.message.SolaceManager",
            SolaceManager.class);
    MessageListener messageLisener = new MessageListener(
            // props.getProperty("listener.queue"),
            Arrays.asList(splits), Integer.parseInt(props.getProperty("listener.scanintervalseconds", "5")),
            taskThreadPool, Integer.parseInt(props.getProperty("listener.timeoutseconds", "5")),
            serviceDispatcher, solaceManager, bundleMessageSource);
    server.addListenerOnSchedule(messageLisener);

    // register shutdownhook
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                // close resource
                if (context != null) {
                    context.close();
                }

            } catch (Exception e) {
                LOG.error("shutdown error", e);
            }
        }
    });

    // hold server
    try {
        LOG.info("ecif-index server start ok!");
        server.start();
    } catch (Exception e) {
        try {
            // close resource
            server.shutDown();
            if (context != null) {
                context.close();
            }

        } catch (Exception ex) {
            LOG.error("shutdown error", ex);
        }
    }

    LOG.info("ecif-index server stop !");
}

From source file:easycare.util.db.TestData.java

public static void main(String[] args) {
    boolean success = true;
    ClassPathXmlApplicationContext context = null;
    try {//from  ww w. ja v a2  s.com
        context = new ClassPathXmlApplicationContext("classpath:easycare-properties.xml",
                "classpath:easycare-dataloader.xml", "classpath:easycare-builder.xml",
                "classpath:easycare-model.xml", "classpath:easycare-service.xml",
                "classpath:easycare-email.xml", "classpath:easycare-security.xml", "classpath:easycare-ids.xml",
                "classpath:easycare-util.xml", "classpath:easycare-report.xml",
                "classpath:easycare-conversions.xml", "classpath:alc-services.xml",
                "classpath:easycare-tibco-demo.xml", "classpath:easycare-activemq-demo.xml");
        TestData testData = context.getBean(TestData.class);
        parseArguments(args, testData);
        testData.setupTestData();
    } catch (Exception e) {
        log.error("Exception running DbTool", e);
        success = false;
    } finally {
        if (context != null) {
            context.close();
        }
    }

    if (!success) {
        System.exit(1);
    }
}

From source file:edu.mayo.cts2.uriresolver.dao.DAOUtiltities.java

public static UriDAO connectDB(UriDAO uriDAO) {
    if (uriDAO != null && uriDAO.isConnected()) {
        return uriDAO;
    }//from  www . jav a 2s .com

    DataSource ds;
    boolean inMemoryDBrequired = false;
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

    uriDAO = (UriDAOJdbc) context.getBean("uriJDBCTemplate");
    ds = (DataSource) context.getBean("dataSource");
    context.close();

    int connectionCode = uriDAO.checkDataSource(ds);

    if (connectionCode != 0) {
        inMemoryDBrequired = true;
        logConnectionError(connectionCode);
    } else if (!checkTablesExist(ds)) {
        inMemoryDBrequired = true;
    }

    // TODO: test data exists?  and correct columns ??

    if (inMemoryDBrequired) {
        ds = createInMemoryDatabase(uriDAO);
        if (ds == null) {
            return null;
        }
    }

    uriDAO.setDataSource(ds);
    return uriDAO;
}