Example usage for org.springframework.context.support FileSystemXmlApplicationContext FileSystemXmlApplicationContext

List of usage examples for org.springframework.context.support FileSystemXmlApplicationContext FileSystemXmlApplicationContext

Introduction

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

Prototype

public FileSystemXmlApplicationContext(String... configLocations) throws BeansException 

Source Link

Document

Create a new FileSystemXmlApplicationContext, loading the definitions from the given XML files and automatically refreshing the context.

Usage

From source file:jmona.driver.Main.java

/**
 * Run the {@link EvolutionContext#stepGeneration()} method until the
 * CompletionConditionon is met, executing any Processors after each
 * generation step./*from w w  w  .j a v a  2s .  c  o m*/
 * 
 * Provide the location of the Spring XML configuration file by using the
 * <em>--config</em> command line option, followed by the location of the
 * configuration file. By default, this program will look for a configuration
 * file at <code>./context.xml</code>.
 * 
 * @param args
 *          The command-line arguments to this program.
 */
@SuppressWarnings("unchecked")
public static void main(final String[] args) {
    // set up the list of options which the parser accepts
    setUpParser();

    // get the options from the command line arguments
    final OptionSet options = PARSER.parse(args);

    // get the location of the XML configuration file
    final String configFile = (String) options.valueOf(OPT_CONFIG_FILE);

    // create an application context from the specified XML configuration file
    final ApplicationContext applicationContext = new FileSystemXmlApplicationContext(configFile);

    // get the evolution contexts, completion criteria, and processors
    @SuppressWarnings("rawtypes")
    final Map<String, EvolutionContext> evolutionContextsMap = applicationContext
            .getBeansOfType(EvolutionContext.class);
    @SuppressWarnings("rawtypes")
    final Map<String, CompletionCondition> completionCriteriaMap = applicationContext
            .getBeansOfType(CompletionCondition.class);
    @SuppressWarnings("rawtypes")
    final Map<String, Processor> processorMap = applicationContext.getBeansOfType(Processor.class);

    // assert that there is only one evolution context bean in the app. context
    if (evolutionContextsMap.size() != 1) {
        throw new RuntimeException("Application context contains " + evolutionContextsMap.size()
                + " EvolutionContext beans, but must contain only 1.");
    }

    // assert that there is only one completion criteria bean in the app context
    if (completionCriteriaMap.size() != 1) {
        throw new RuntimeException("Application context contains " + completionCriteriaMap.size()
                + "CompletionCondition beans, but must contain only 1.");
    }

    // get the evolution context and completion condition from their maps
    @SuppressWarnings("rawtypes")
    final EvolutionContext evolutionContext = MapUtils.firstValue(evolutionContextsMap);
    @SuppressWarnings("rawtypes")
    final CompletionCondition completionCondition = MapUtils.firstValue(completionCriteriaMap);

    try {
        // while the criteria has not been satisfied, create the next generation
        while (!completionCondition.execute(evolutionContext)) {
            // create the next generation in the evolution
            evolutionContext.stepGeneration();

            // perform all post-processing on the evolution context
            for (@SuppressWarnings("rawtypes")
            final Processor processor : processorMap.values()) {
                processor.process(evolutionContext);
            }
        }
    } catch (final CompletionException exception) {
        throw new RuntimeException(exception);
    } catch (final EvolutionException exception) {
        throw new RuntimeException(exception);
    } catch (final ProcessingException exception) {
        throw new RuntimeException(exception);
    }
}

From source file:org.manalith.ircbot.ManalithBot.java

public static void main(String[] args) throws Exception {
    // ? /*from w  w  w .  j  a v a2  s  .  c o  m*/
    if (!Charset.defaultCharset().toString().equals("UTF-8")) {
        System.out.println("-Dfile.encoding=UTF-8   .");
        return;
    }

    //  ?
    Options options = new Options();
    options.addOption("c", true, "config file");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    String configFile = cmd.getOptionValue("c", "config.xml");

    // SSL/HTTPS 
    UrlUtils.setTrustAllHosts();

    //  
    ApplicationContext context = new FileSystemXmlApplicationContext(configFile);
    AppContextUtils.setApplicationContext(context);

    //  ?
    ManalithBot bot = context.getBean(ManalithBot.class);
    bot.startBot();
}

From source file:com.btisystems.pronx.ems.App.java

/**
 * Entrypoint method.//  w  w w . j  a v a2 s.  c  om
 *
 * @param args the args
 * @throws Exception the exception
 */
@SuppressWarnings("unchecked")
public static void main(final String[] args) throws Exception {

    final String configurationFile = processCommandLineOptions(args);

    LOG.info("Autogen running. configurationFile=" + configurationFile);

    if (configurationFile != null) {
        autogenContext = new FileSystemXmlApplicationContext(configurationFile);
        properties = (Properties) autogenContext.getBean("properties");
        LOG.info("properties=" + properties);

        final List<DeviceGroup> groupList = (List<DeviceGroup>) autogenContext.getBean("groupList");
        if (groupList != null) {

            processMibFiles(groupList);

            buildSourceFiles();

            deleteImportedSource();
        }
    }
    LOG.info("Autogen complete");
}

From source file:de.uniwue.dmir.heatmap.EntryPointIncremental.java

@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) throws IOException, ParseException {

    DateFormat df = new SimpleDateFormat(DATE_FORMAT);
    SimpleDateFormat backupDf = new SimpleDateFormat(BACKUP_DATE_FORMAT);

    String workDir = System.getProperty("workDir", ".");
    LOGGER.debug("Work dir: {}", workDir);
    String configDir = System.getProperty("configDir", ".");
    LOGGER.debug("Config dir: {}", configDir);

    File seedDir = new File(workDir, SEED_DIR);
    LOGGER.debug("Seed dir: {}", seedDir);
    File currentDir = new File(workDir, CURRENT_DIR);
    LOGGER.debug("Current dir: {}", currentDir);
    File backupDir = new File(workDir, BACKUP_DIR);
    LOGGER.debug("Backup dir: {}", backupDir);

    String initialMinTimeString = System.getProperty("minTime");
    LOGGER.debug("Initial minimal time parameter: {}", initialMinTimeString);
    Date initialMinTime = initialMinTimeString == null ? new Date(0) : df.parse(initialMinTimeString);
    LOGGER.debug("Initial minimal time: {}", df.format(initialMinTime));

    String absoluteMaxTimeString = System.getProperty("maxTime");
    LOGGER.debug("Absolute maximal time parameter: {}", absoluteMaxTimeString);
    Date absoluteMaxTime = absoluteMaxTimeString == null ? new Date()
            : new SimpleDateFormat(DATE_FORMAT).parse(absoluteMaxTimeString);
    LOGGER.debug("Absolute maximal time: {}", df.format(absoluteMaxTime));

    String incrementalFile = new File("file:" + configDir, INCREMENTAL_FILE).getPath();
    String settingsFile = new File("file:" + configDir, HEATMAP_PROCESSOR__FILE).getPath();

    LOGGER.debug("Initializing incremental control file: {}", incrementalFile);
    FileSystemXmlApplicationContext incrementalContext = new FileSystemXmlApplicationContext(incrementalFile);

    // get point limit
    int pointLimit = Integer
            .parseInt(incrementalContext.getBeanFactory().resolveEmbeddedValue("${point.limit}"));
    LOGGER.debug("Print limit: {}", pointLimit);

    // get backups to keep
    int backupsToKeep = Integer
            .parseInt(incrementalContext.getBeanFactory().resolveEmbeddedValue("${backups.to.keep}"));
    LOGGER.debug("Backups to keep: {}", pointLimit);

    LOGGER.debug("Initializing process components (manager and limiter).");
    IProcessManager processManager = incrementalContext.getBean(IProcessManager.class);
    IProcessLimiter processLimiter = incrementalContext.getBean(IProcessLimiter.class);

    LOGGER.debug("Starting incremental loop.");
    while (true) { // break as soon as no new points are available

        // cleanup --- just in case
        LOGGER.debug("Deleting \"current\" dir.");
        FileUtils.deleteDirectory(currentDir);

        // copy from seed to current
        LOGGER.debug("Copying seed.");
        seedDir.mkdirs();//from w ww .  j a va  2  s . c o m
        FileUtils.copyDirectory(seedDir, currentDir);

        // get min time
        LOGGER.debug("Getting minimal time ...");
        Date minTime = initialMinTime;
        ProcessManagerEntry entry = processManager.getEntry();
        if (entry != null && entry.getMaxTime() != null) {
            minTime = entry.getMaxTime();
        }
        LOGGER.debug("Minimal time: {}", new SimpleDateFormat(DATE_FORMAT).format(minTime));

        // break if we processed all available points (minTime is greater than or equal to absoluteMaxTime)
        if (minTime.getTime() >= absoluteMaxTime.getTime()) {
            LOGGER.debug("Processed all points.");
            break;
        }

        // get the maximal time
        LOGGER.debug("Get maximal time.");

        // get the time from the newest point in our point range (pointMaxTime) ...
        Date pointMaxTime = processLimiter.getMaxTime(minTime, pointLimit);

        // ... and possibly break the loop if no new points are available
        if (pointMaxTime == null)
            break;

        // set the max time and make sure we are not taking to many points 
        // (set max time to the minimum of pointMaxTime and absoluteMaxTime)
        Date maxTime = pointMaxTime.getTime() > absoluteMaxTime.getTime() ? absoluteMaxTime : pointMaxTime;

        LOGGER.debug("Maximal time: {}", new SimpleDateFormat(DATE_FORMAT).format(maxTime));

        // start process
        processManager.start(minTime);

        System.setProperty("minTimestamp", new SimpleDateFormat(DATE_FORMAT).format(minTime));

        System.setProperty("maxTimestamp", new SimpleDateFormat(DATE_FORMAT).format(maxTime));

        FileSystemXmlApplicationContext heatmapContext = new FileSystemXmlApplicationContext(settingsFile);

        IHeatmap heatmap = heatmapContext.getBean(HEATMAP_BEAN, IHeatmap.class);

        ITileProcessor tileProcessor = heatmapContext.getBean(WRITER_BEAN, ITileProcessor.class);

        heatmap.processTiles(tileProcessor);

        tileProcessor.close();
        heatmapContext.close();

        // finish process
        processManager.finish(maxTime);

        // move old seed
        if (backupsToKeep > 0) {
            FileUtils.moveDirectory(seedDir, new File(backupDir, backupDf.format(minTime))); // minTime is the maxTime of the seed

            // cleanup backups
            String[] backups = backupDir.list(DirectoryFileFilter.DIRECTORY);
            File oldestBackup = null;
            if (backups.length > backupsToKeep) {
                for (String bs : backups) {
                    File b = new File(backupDir, bs);
                    if (oldestBackup == null || oldestBackup.lastModified() > b.lastModified()) {
                        oldestBackup = b;
                    }
                }
                FileUtils.deleteDirectory(oldestBackup);
            }

        } else {
            FileUtils.deleteDirectory(seedDir);
        }

        // move new seed
        FileUtils.moveDirectory(currentDir, seedDir);

    }

    incrementalContext.close();

}

From source file:com.china317.gmmp.gmmp_report_analysis.App.java

public static void main(String[] args) {
    log.info("[App main started]");
    String yyyyMMdd = "20150218";
    String beginTime = "20150211";

    // if (args != null && args.length > 0) {
    // yyyyMMdd = args[0];\
    // beginTime = args[0];
    // }/*  w w  w  .ja  va2 s. co  m*/

    log.info("[Spring init begin-------------]");
    // ApplicationContext context = new ClassPathXmlApplicationContext(new
    // String[]{"applicationContext.xml"});
    //ApplicationContext context = new FileSystemXmlApplicationContext(
    //      "//home/gmmp/lybc_reAnalySis/bin/applicationcontext.xml");

    ApplicationContext context = new FileSystemXmlApplicationContext(
            "//home/gmmp/repAnalysis4/bin/applicationcontext.xml");

    /*
     * ApplicationContext context = new FileSystemXmlApplicationContext(
     * "//home/gmmp/banche_reAnalysis/bin/applicationcontext.xml");
     */
    log.info("[Spring init end-------------]");

    log.info("AreaAddProcessor areaList init begin");
    AreaAddProcessor.init(context);
    PolyUtilityE2.getRules();
    List<Rule> list_rules = AreaAddProcessor.getRuleList();
    log.info("AreaAddProcessor areaList init end:" + list_rules.size() + "[PolyUtilityE2 rules:]"
            + PolyUtilityE2.getMapSize());

    for (int i = 0; i < dates.length; i++) {

        yyyyMMdd = dates[i];
        LineDenoterCache.getInstance().init(yyyyMMdd);
        log.info("LineDenoterCache size:" + LineDenoterCache.getInstance().getSize());
        try {
            // analysisBanche(yyyyMMdd, context);

            // analysisBaoChe(yyyyMMdd, context);

            analysisDgm(yyyyMMdd, context);
        } catch (Exception e) {
            log.error(e);
        }

        log.info("ONE DAY ANALYSIS ENDED:" + yyyyMMdd);

        /*
         * log.info("[Result:]"); log.info("ptm: offline:" +
         * PtmAnalysisImp.getInstance().getOfflineRecordsSize() +
         * "::: overspeed:" +
         * PtmAnalysisImp.getInstance().getOverSpeedRecordsSize());
         * 
         * log.info("lybc: offline:" +
         * BaocheAnalysisImp.getInstance().getOfflineRecordsSize() +
         * "::: overspeed:" +
         * BaocheAnalysisImp.getInstance().getOverSpeedRecordsSize());
         * 
         * log.info("dgm: fobbided:" +
         * DgmAnalysisImp.getInstance().getFobbidedSize() +
         * " ::: overspeed:" +
         * DgmAnalysisImp.getInstance().getOverSpeedRecordsSize() +
         * " ::: getIllegalParking:" +
         * DgmAnalysisImp.getInstance().getIllegalParking().size() +
         * " ::: getExitMap:" +
         * DgmAnalysisImp.getInstance().getExitMap().size() +
         * " ::: getFatigue:" +
         * DgmAnalysisImp.getInstance().getFatigueSize() + "::: offline:" +
         * DgmAnalysisImp.getInstance().getOfflineRecordsSize());
         */
    }

    log.info("[App ended]");

}

From source file:cn.com.inhand.devicenetworks.ap.mq.rabbitmq.TaskNotificationConsumer.java

public static void main(String[] agrs) throws Exception {
    String path = "file:/home/han/myworks/workroom/NetBeansProjects/WSAP/RabbitMQDemo/RabbitMQDemo/src/main/webapp/WEB-INF/MQXMLApplicationContext.xml";
    AbstractApplicationContext ctx = new FileSystemXmlApplicationContext(path);
    RabbitTemplate template = ctx.getBean(RabbitTemplate.class);
    template.convertAndSend("Hello, world!");
    Thread.sleep(1000);//from  w  ww .  jav  a  2s.  c o  m
    ctx.destroy();
}

From source file:org.openspaces.focalserver.FocalServer.java

public static void main(String[] args) throws IOException {
    if (args.length < 1) {
        printUsage();/*  ww  w .  j  a  va  2 s. c o  m*/
        System.exit(1);
    }
    LOGGER.info("\n==================================================\n"
            + "GigaSpaces Focal Server starting using " + Arrays.asList(args) + " \n" + "Log created by <"
            + System.getProperty("user.name") + "> on " + new Date().toString() + "\n"
            + "==================================================");
    ApplicationContext applicationContext;
    try {
        applicationContext = new FileSystemXmlApplicationContext(args);
    } catch (Exception e) {
        LOGGER.fine("Failed starting GigaSpaces Focal Server using " + Arrays.asList(args)
                + ", will try to load from classpath. " + e.getMessage());
        applicationContext = new ClassPathXmlApplicationContext(args);
    }

}

From source file:org.openvpms.tools.data.loader.StaxArchetypeDataLoader.java

/**
 * The main line//from  w w w.ja  v a  2  s .co  m
 *
 * @param args the command line arguments
 */
public static void main(String[] args) {
    try {
        JSAP parser = createParser();
        JSAPResult config = parser.parse(args);
        String[] files = config.getStringArray("file");
        String dir = config.getString("dir");
        if (!config.success() || (files.length == 0 && dir == null)) {
            displayUsage(parser, config);
        } else {
            String contextPath = config.getString("context");

            ApplicationContext context;
            if (!new File(contextPath).exists()) {
                context = new ClassPathXmlApplicationContext(contextPath);
            } else {
                context = new FileSystemXmlApplicationContext(contextPath);
            }

            IArchetypeService service = (IArchetypeService) context.getBean("archetypeService");
            StaxArchetypeDataLoader loader = new StaxArchetypeDataLoader(service);
            loader.setVerbose(config.getBoolean("verbose"));
            loader.setValidateOnly(config.getBoolean("validateOnly"));
            loader.setBatchSize(config.getInt("batchSaveSize"));
            if (files.length != 0) {
                loader.load(files);
            } else if (dir != null) {
                loader.load(dir);
            }
        }
    } catch (Throwable throwable) {
        log.error(throwable, throwable);
    }
}

From source file:sample.contact.ClientApplication.java

public static void main(String[] args) {
    String username = System.getProperty("username", "");
    String password = System.getProperty("password", "");
    String nrOfCallsString = System.getProperty("nrOfCalls", "");

    if ("".equals(username) || "".equals(password)) {
        System.out.println(/*from w ww.  j ava  2 s . c o m*/
                "You need to specify the user ID to use, the password to use, and optionally a number of calls "
                        + "using the username, password, and nrOfCalls system properties respectively. eg for user rod, "
                        + "use: -Dusername=rod -Dpassword=koala' for a single call per service and "
                        + "use: -Dusername=rod -Dpassword=koala -DnrOfCalls=10 for ten calls per service.");
        System.exit(-1);
    } else {
        int nrOfCalls = 1;

        if (!"".equals(nrOfCallsString)) {
            nrOfCalls = Integer.parseInt(nrOfCallsString);
        }

        ListableBeanFactory beanFactory = new FileSystemXmlApplicationContext("clientContext.xml");
        ClientApplication client = new ClientApplication(beanFactory);

        client.invokeContactService(new UsernamePasswordAuthenticationToken(username, password), nrOfCalls);
        System.exit(0);
    }
}

From source file:eu.scape_project.archiventory.Archiventory.java

/**
 * Main entry point.//w  w  w  . ja va 2s .c  o m
 *
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    Configuration conf = new Configuration();
    // Command line interface
    config = new CliConfig();
    CommandLineParser cmdParser = new PosixParser();
    GenericOptionsParser gop = new GenericOptionsParser(conf, args);
    CommandLine cmd = cmdParser.parse(Options.OPTIONS, gop.getRemainingArgs());
    if ((args.length == 0) || (cmd.hasOption(Options.HELP_OPT))) {
        Options.exit("Usage", 0);
    } else {
        Options.initOptions(cmd, config);
    }
    // Trying to load spring configuration from local file system (same
    // directory where the application is executed). If the spring 
    // configuration is not given as a parameter, it is loaded as a 
    // resource from the class path. 
    if (config.getSpringConfig() != null && (new File(config.getSpringConfig()).exists())) {
        ctx = new FileSystemXmlApplicationContext("file://" + config.getSpringConfig());
    } else {
        ctx = new ClassPathXmlApplicationContext(SPRING_CONFIG_RESOURCE_PATH);
    }
    if (config.isMapReduceJob()) {
        startHadoopJob(conf);
    } else {
        startApplication();
    }
}