Example usage for org.springframework.context ConfigurableApplicationContext getBean

List of usage examples for org.springframework.context ConfigurableApplicationContext getBean

Introduction

In this page you can find the example usage for org.springframework.context ConfigurableApplicationContext getBean.

Prototype

Object getBean(String name) throws BeansException;

Source Link

Document

Return an instance, which may be shared or independent, of the specified bean.

Usage

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 {/*from ww  w  .  j  a  va  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:com.vilt.minium.app.MiniumApp.java

protected static void launchBrowser(final ConfigurableApplicationContext context) throws IOException {
    final EmbeddedBrowser browser = context.getBean(EmbeddedBrowser.class);
    browser.addListener(new Listener() {

        @Override//from w w w . j  a v a  2s  .c o  m
        public void closed() {
            SpringApplication.exit(context);
        }
    });
    browser.start();
}

From source file:com.vilt.minium.app.MiniumApp.java

public static ConfigurableApplicationContext launchService(String... args) throws IOException {
    final ConfigurableApplicationContext context = new SpringApplicationBuilder(MiniumAppWebConfig.class)
            .headless(false).showBanner(true).run(args);

    final AppPreferences appPreferences = context.getBean(AppPreferences.class);
    final WebConsolePreferences webConsolePreferences = WebConsolePreferences.from(appPreferences);

    webConsolePreferences.validate();/*from  w ww.j  ava  2 s.  com*/
    return context;
}

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;//w  w w. j  av a  2 s . c om
    }

    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 initial XMI data./*from  ww w . java  2  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:de.iteratec.iteraplan.xmi.XmiImport.java

private ConfigurableApplicationContext prepareEnvironment(HistoryInitialization initializeHistoryData) {
    createTempUserContext();/* w  ww  .  j a  v  a2s . c o  m*/
    ConfigurableApplicationContext context = LocalApplicationContextUtil.getApplicationContext();

    HistoryEventListener historyListener = context.getBean(HistoryEventListener.class);
    switch (initializeHistoryData) {
    case FORCE_INITIALIZE:
        historyListener.setHistoryEnabled(true);
        break;
    case FORCE_DONT_INITIALIZE:
        historyListener.setHistoryEnabled(false);
        break;
    default:
        // do nothing
    }

    return context;
}

From source file:de.micromata.genome.gwiki.model.config.GWikiAbstractSpringContextBootstrapConfigLoader.java

@Override
public GWikiDAOContext loadConfig(ServletConfig config) {
    if (config != null && StringUtils.isBlank(fileName) == true) {
        fileName = config/*from  www  .  ja  v  a  2 s .c o m*/
                .getInitParameter("de.micromata.genome.gwiki.model.config.GWikiBootstrapConfigLoader.fileName");
        supportsJndi = StringUtils.equals(config.getInitParameter("de.micromata.genome.gwiki.supportsJndi"),
                "true");
    }
    ConfigurableApplicationContext actx = createApplicationContext(config, getApplicationContextName());
    actx.addBeanFactoryPostProcessor(new GWikiDAOContextPropertyPlaceholderConfigurer(config, supportsJndi));
    actx.refresh();
    beanFactory = actx;
    GWikiDAOContext daoContext = (GWikiDAOContext) actx.getBean("GWikiBootstrapConfig");

    daoContext.setBeanFactory(beanFactory);
    return daoContext;
}

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  a2  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();
    }
}

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

private static InputData createInputData(String[] args, ConfigurableApplicationContext applicationContext,
        String name, String url) throws ClientProtocolException, IOException {
    InputData inputData;/*from ww w.j a  v a  2  s. c om*/
    if (args.length == 3) {
        inputData = new InputData();
        String[] dataItems = args[2].split(",");
        inputData.setCactiDataItems(dataItems);
        inputData.setName(name);
        inputData.setUrl(url);
    } else {
        JmxInputProcessor jmxProcessor = applicationContext.getBean(JmxInputProcessor.class);
        inputData = jmxProcessor.getInputDataFromJmx(name, url);
    }
    return inputData;
}

From source file:grails.util.RunTests.java

public static void main(String[] args) {
    int exitCode = 0;
    try {//  w ww.j ava 2  s .co m
        log.info("Bootstrapping Grails from classpath");
        ConfigurableApplicationContext appCtx = (ConfigurableApplicationContext) GrailsUtil
                .bootstrapGrailsFromClassPath();
        GrailsApplication application = (GrailsApplication) appCtx.getBean(GrailsApplication.APPLICATION_ID);

        Class[] allClasses = application.getAllClasses();
        log.debug("Going through [" + allClasses.length + "] classes");
        TestSuite s = new TestSuite();
        for (int i = 0; i < allClasses.length; i++) {
            Class clazz = allClasses[i];
            if (TestCase.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())) {
                log.debug("Adding test [" + clazz.getName() + "]");
                s.addTest(new GrailsTestSuite(appCtx, clazz));
            } else {
                log.debug("[" + clazz.getName() + "] is not a test case.");
            }
        }
        String[] beanNames = appCtx.getBeanNamesForType(PersistenceContextInterceptor.class);
        PersistenceContextInterceptor interceptor = null;
        if (beanNames.length > 0) {
            interceptor = (PersistenceContextInterceptor) appCtx.getBean(beanNames[0]);
        }

        try {
            if (interceptor != null) {
                interceptor.init();
            }
            TestResult r = TestRunner.run(s);
            exitCode = r.errorCount() + r.failureCount();
            if (exitCode > 0) {
                System.err.println("Tests failed!");
            }
            if (interceptor != null)
                interceptor.flush();
        } finally {
            if (interceptor != null)
                interceptor.destroy();
        }
    } catch (Exception e) {
        log.error("Error executing tests: " + e.getMessage(), e);
        exitCode = 1;
    } finally {
        System.exit(exitCode);
    }
}