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:lcn.module.batch.core.launch.support.CommandLineRunner.java

/**
 * Batch Job? .//from  w  ww  .  j ava 2  s . c  o m
 * ?  , Job ? / JobExecutionID, Job Parameter
 *  CommandLineRunner Option ? .
 * 
 * @param jobPath : Job Context ? XML ?  
 * @param jobIdentifier : Job ? /JobExecutionID
 * @param parameters : Job Parameter 
 * @param opts : CommandLineRunner (-restart, -next, -stop, -abandon)
 */
public int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {
        //  ApplicationContext ?.
        context = new ClassPathXmlApplicationContext(jobPath);
        context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

        Assert.state(launcher != null, "A JobLauncher must be provided.  Please add one to the configuration.");
        // ? Batch Job? , ? Batch Job?  ? JobExplorer  ?.
        if (opts.contains("-restart") || opts.contains("-next")) {
            Assert.state(jobExplorer != null,
                    "A JobExplorer must be provided for a restart or start next operation.  Please add one to the configuration.");
        }

        // Job? ?? .
        String jobName = jobIdentifier;

        // JobParameters ?.
        JobParameters jobParameters = jobParametersConverter
                .getJobParameters(StringUtils.splitArrayElementsIntoProperties(parameters, "="));
        Assert.isTrue(parameters == null || parameters.length == 0 || !jobParameters.isEmpty(),
                "Invalid JobParameters " + Arrays.asList(parameters)
                        + ". If parameters are provided they should be in the form name=value (no whitespace).");

        // Batch Job? .
        if (opts.contains("-stop")) {
            List<JobExecution> jobExecutions = getRunningJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotRunningException(
                        "No running execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.STOPPING);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // ? Batch Job? ? abandon .
        if (opts.contains("-abandon")) {
            List<JobExecution> jobExecutions = getStoppedJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotStoppedException(
                        "No stopped execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.ABANDONED);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // Batch Job? .
        if (opts.contains("-restart")) {
            JobExecution jobExecution = getLastFailedJobExecution(jobIdentifier);
            if (jobExecution == null) {
                throw new JobExecutionNotFailedException(
                        "No failed or stopped execution found for job=" + jobIdentifier);
            }
            jobParameters = jobExecution.getJobInstance().getJobParameters();
            jobName = jobExecution.getJobInstance().getJobName();
        }

        Job job;

        // JobLocator  Job?  null? ApplicationContext? Job? .
        if (jobLocator != null) {
            job = jobLocator.getJob(jobName);
        } else {
            job = (Job) context.getBean(jobName);
        }

        // ? Batch Job?   Job Parameters ?.
        if (opts.contains("-next")) {
            JobParameters nextParameters = getNextJobParameters(job);
            Map<String, JobParameter> map = new HashMap<String, JobParameter>(nextParameters.getParameters());
            map.putAll(jobParameters.getParameters());
            jobParameters = new JobParameters(map);
        }

        // Batch Job? .
        JobExecution jobExecution = launcher.run(job, jobParameters);
        logger.warn("CommandLineRunner's Job Information");
        logger.warn("jobName=" + jobExecution.getJobInstance().getJobName());
        logger.warn("jobParamters=" + jobParameters.toString());
        logger.warn("jobExecutionTime="
                + (jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime()) / 1000f + "s");

        return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode());
    } catch (Throwable e) {
        String message = "Job Terminated in error: " + e.getMessage();
        logger.error(message, e);
        CommandLineRunner.message = message;
        return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode());
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

From source file:egovframework.rte.bat.core.launch.support.EgovCommandLineRunner.java

/**
 * Batch Job? ./*w  w w  .  j a v  a2s .c  o m*/
 * ?  , Job ? / JobExecutionID, Job Parameter
 *  CommandLineRunner Option ? .
 * 
 * @param jobPath : Job Context ? XML ?  
 * @param jobIdentifier : Job ? /JobExecutionID
 * @param parameters : Job Parameter 
 * @param opts : CommandLineRunner (-restart, -next, -stop, -abandon)
 */
public int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {
        //  ApplicationContext ?.
        context = new ClassPathXmlApplicationContext(jobPath);
        context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

        Assert.state(launcher != null, "A JobLauncher must be provided.  Please add one to the configuration.");
        // ? Batch Job? , ? Batch Job?  ? JobExplorer  ?.
        if (opts.contains("-restart") || opts.contains("-next")) {
            Assert.state(jobExplorer != null,
                    "A JobExplorer must be provided for a restart or start next operation.  Please add one to the configuration.");
        }

        // Job? ?? .
        String jobName = jobIdentifier;

        // JobParameters ?.
        JobParameters jobParameters = jobParametersConverter
                .getJobParameters(StringUtils.splitArrayElementsIntoProperties(parameters, "="));
        Assert.isTrue(parameters == null || parameters.length == 0 || !jobParameters.isEmpty(),
                "Invalid JobParameters " + Arrays.asList(parameters)
                        + ". If parameters are provided they should be in the form name=value (no whitespace).");

        // Batch Job? .
        if (opts.contains("-stop")) {
            List<JobExecution> jobExecutions = getRunningJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotRunningException(
                        "No running execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.STOPPING);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // ? Batch Job? ? abandon .
        if (opts.contains("-abandon")) {
            List<JobExecution> jobExecutions = getStoppedJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotStoppedException(
                        "No stopped execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.ABANDONED);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        // Batch Job? .
        if (opts.contains("-restart")) {
            JobExecution jobExecution = getLastFailedJobExecution(jobIdentifier);
            if (jobExecution == null) {
                throw new JobExecutionNotFailedException(
                        "No failed or stopped execution found for job=" + jobIdentifier);
            }
            jobParameters = jobExecution.getJobInstance().getJobParameters();
            jobName = jobExecution.getJobInstance().getJobName();
        }

        Job job;

        // JobLocator  Job?  null? ApplicationContext? Job? .
        if (jobLocator != null) {
            job = jobLocator.getJob(jobName);
        } else {
            job = (Job) context.getBean(jobName);
        }

        // ? Batch Job?   Job Parameters ?.
        if (opts.contains("-next")) {
            JobParameters nextParameters = getNextJobParameters(job);
            Map<String, JobParameter> map = new HashMap<String, JobParameter>(nextParameters.getParameters());
            map.putAll(jobParameters.getParameters());
            jobParameters = new JobParameters(map);
        }

        // Batch Job? .
        JobExecution jobExecution = launcher.run(job, jobParameters);
        logger.warn("EgovCommandLineRunner's Job Information");
        logger.warn("jobName=" + jobExecution.getJobInstance().getJobName());
        logger.warn("jobParamters=" + jobParameters.toString());
        logger.warn("jobExecutionTime="
                + (jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime()) / 1000f + "s");

        return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode());
    } catch (Throwable e) {
        String message = "Job Terminated in error: " + e.getMessage();
        logger.error(message, e);
        EgovCommandLineRunner.message = message;
        return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode());
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

From source file:com.jaspersoft.jasperserver.export.BaseExportImportCommand.java

protected boolean process(String[] args) throws IOException {
    Parameters exportParameters = parseArgs(args);
    ConfigurableApplicationContext ctx;
    if (exportParameters.hasParameter(ARG_HELP)) {
        ctx = createSpringContext(exportParameters, "helpApplicationContext-export-import*.xml");
    } else {//  w ww  . j  av a2s  .  co  m
        ctx = createSpringContext(exportParameters, "applicationContext*.xml");
    }
    try {
        boolean success = true;
        CommandMetadata metadataBean = getCommandMetadataBean(ctx);
        if (exportParameters.hasParameter(ARG_HELP)) {
            CommandHelp helpBean = getHelpBean(ctx);
            helpBean.printHelp(args[0], metadataBean, System.out);
        } else {
            CommandBean commandBean = getCommandBean(exportParameters, ctx);
            try {
                metadataBean.validateParameters(exportParameters);
                commandBean.process(exportParameters);
            } catch (JSExceptionWrapper e) {
                throw e;
            } catch (JSException e) {
                success = false;
                if (log.isInfoEnabled()) {
                    log.info(e.getMessage(), e);
                }

                String message = ctx.getMessage(e.getMessage(), e.getArgs(), Locale.getDefault());
                System.err.println(message);
            }
        }
        return success;
    } finally {
        ctx.close();
    }
}

From source file:com.opengamma.bbg.loader.BloombergHistoricalLoader.java

/**
 * @param args// w w w. ja va 2s. co m
 * @param options
 */
private static void processCommandLineOptions(String[] args, Options options) {
    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;
    }
    ConfigurableApplicationContext applicationContext = null;
    try {
        applicationContext = getApplicationContext();
        BloombergHistoricalLoader dataLoader = getDataHistoricalLoader(applicationContext);
        configureOptions(options, line, dataLoader);
        dataLoader.run();
        List<ExternalIdBundle> errors = dataLoader.getErrors();
        if (!errors.isEmpty()) {
            for (ExternalIdBundle bundle : errors) {
                s_logger.warn("Could not load historical data for {}", bundle);
            }
        }
    } finally {
        if (applicationContext != null) {
            applicationContext.close();
        }
    }

}

From source file:com.thinkbiganalytics.server.KyloServerApplication.java

public static void main(String[] args) {

    KyloVersion dbVersion = getDatabaseVersion();

    boolean skipUpgrade = KyloVersionUtil.isUpToDate(dbVersion);

    if (!skipUpgrade) {
        boolean upgradeComplete = false;
        do {//  ww  w .j  av  a  2  s.  c o m
            log.info("Upgrading...");
            System.setProperty(SpringApplication.BANNER_LOCATION_PROPERTY, "upgrade-banner.txt");
            ConfigurableApplicationContext cxt = SpringApplication.run(UpgradeKyloConfig.class);
            KyloUpgrader upgrader = cxt.getBean(KyloUpgrader.class);
            upgradeComplete = upgrader.upgrade();
            cxt.close();
        } while (!upgradeComplete);
        log.info("Upgrading complete");
    } else {
        log.info("Kylo v{} is up to date.  Starting the application.", dbVersion);
    }
    System.setProperty(SpringApplication.BANNER_LOCATION_PROPERTY, "banner.txt");
    SpringApplication.run("classpath:application-context.xml", args);
}

From source file:com.thinkbiganalytics.server.upgrade.KyloUpgrader.java

public void upgrade() {
    System.setProperty(SpringApplication.BANNER_LOCATION_PROPERTY, "upgrade-banner.txt");
    ConfigurableApplicationContext upgradeCxt = new SpringApplicationBuilder(KyloUpgradeConfig.class).web(true)
            .profiles(KYLO_UPGRADE).run();
    try {/*w ww  . j  a  v a  2s  . c om*/
        KyloUpgradeService upgradeService = upgradeCxt.getBean(KyloUpgradeService.class);
        // Keep upgrading until upgrade() returns true, i.e. we are up-to-date;
        while (!upgradeService.upgradeNext())
            ;
    } finally {
        upgradeCxt.close();
    }
}

From source file:de.iteratec.iteraplan.db.SchemaGenerationScriptCreator.java

public void generateDatabaseSchemaScript(String sqlOutputFilename) {
    ConfigurableApplicationContext context = LocalApplicationContextUtil.getApplicationContext();

    // potential starting point for further development - make printing to console configurable
    boolean printToConsole = true;

    LOGGER.info("Running hbm2ddl schema export");

    if (StringUtils.isNotBlank(sqlOutputFilename)) {
        outputFile = sqlOutputFilename;//from  w ww  . j  a  v a  2 s .c  o m
    }

    Writer outputFileWriter = null;

    try {
        if (outputFile != null) {
            LOGGER.info("writing generated schema to file: {0}", outputFile);
            System.out.println("writing generated schema to file: " + outputFile);
            outputFileWriter = new FileWriter(outputFile);
        }

        // retrieve Hibernate configuration object from Spring context
        AnnotationSessionFactoryBean sessionFactoryBean = context.getBean(AnnotationSessionFactoryBean.class);
        Configuration hibernateCfg = sessionFactoryBean.getConfiguration();
        Dialect dialect = Dialect.getDialect(hibernateCfg.getProperties());

        // generate drop SQL statements and write to file
        String[] dropSQL = hibernateCfg.generateDropSchemaScript(dialect);
        for (int i = 0; i < dropSQL.length; i++) {
            writeStatement(printToConsole, outputFileWriter, dropSQL[i]);
        }

        // generate create table SQL statements and write to file
        String[] createSQL = hibernateCfg.generateSchemaCreationScript(dialect);
        for (int j = 0; j < createSQL.length; j++) {
            writeStatement(printToConsole, outputFileWriter, createSQL[j]);
        }

        LOGGER.info("schema export complete");

    } catch (Exception e) {
        LOGGER.error("schema export unsuccessful", e);

    } finally {
        context.close();

        try {
            if (outputFileWriter != null) {
                outputFileWriter.close();
            }
        } catch (IOException ioe) {
            LOGGER.error("Error closing output file: " + outputFile, ioe);
        }
    }
}

From source file:de.iteratec.iteraplan.xmi.XmiImport.java

/**
 * Imports the XMI data.//from  w ww . j a v  a2 s .c om
 * 
 * @throws IOException if the {@code iteraplanData.xmi} file will be not found
 */
public void importData() throws IOException {
    LOGGER.info("Start Bank Data Import");

    ConfigurableApplicationContext context = prepareEnvironment(HistoryInitialization.USE_CONFIG_FILE);
    try {
        XmiImportService xmiDeserializer = context.getBean("xmiImportService", XmiImportService.class);

        Resource importFile = new ClassPathResource("de/iteratec/iteraplan/xmi/iteraplanData.xmi");
        xmiDeserializer.importXmi(importFile.getInputStream());

        LOGGER.info("XMI data imported successfuly");
    } finally {
        context.close();
    }
}

From source file:de.iteratec.iteraplan.xmi.XmiImport.java

/**
 * Imports the initial XMI data./*from  ww w .j  a va2  s . c o m*/
 * 
 * @param importAttributeTypes flag whether basic attribute types should be imported or not
 * @param initializeHistoryData Set to true if history base data should be initialized as well
 * @throws IOException if the {@code iteraplanData.xmi} file will be not found
 */
public void importInitialData(boolean importAttributeTypes, HistoryInitialization initializeHistoryData)
        throws IOException {
    LOGGER.info("Start Initial Data Import");

    ConfigurableApplicationContext context = prepareEnvironment(initializeHistoryData);
    try {
        XmiImportService xmiDeserializer = context.getBean(XmiImportService.class);

        Resource importFile = new ClassPathResource("de/iteratec/iteraplan/xmi/iteraplanData.xmi");
        xmiDeserializer.importInitialXmi(importFile.getInputStream(), importAttributeTypes);

        LOGGER.info("XMI data imported successfuly");
    } finally {
        context.close();
    }
}

From source file:fm.last.peyote.cacti.PeyoteCactiLauncher.java

public static void main(String[] args) throws JAXBException, IOException {
    if (args.length < 2 || args.length > 3) {
        printUsage();//from w  w  w.  j a  v a  2  s.c o m
    }
    String name = args[0];
    String url = args[1];
    ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring/peyote.xml");
    applicationContext.registerShutdownHook();
    try {
        InputData inputData = createInputData(args, applicationContext, name, url);
        PeyoteMarshaller marshaller = applicationContext.getBean(PeyoteMarshaller.class);
        marshaller.setInputData(inputData);
        log.info("Starting Peyote");
        File file = new File("datatemplate.xml");
        Writer outWriter = new FileWriter(file);
        marshaller.generateCactiDataTemplate(outWriter);
        outWriter.close();
        log.info("generated data template for '" + name + "' in " + file.getAbsolutePath());

        // file = new File("graphtemplate.xml");
        // outWriter = new FileWriter(file);
        // marshaller.generateCactiGraphTemplate(outWriter);
        // outWriter.close();
        // log.info("generated data template for '" + name + "' in " +
        // file.getAbsolutePath());

        log.info("Peyote finished.");
    } finally {
        applicationContext.close();
    }
}