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

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

Introduction

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

Prototype

@Override
public void close() 

Source Link

Document

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

Usage

From source file:com.brienwheeler.lib.spring.beans.PropertyPlaceholderConfigurer.java

/**
 * Programatically process a single property file location, using System
 * properties in preference to included definitions for placeholder
 * resolution, and setting any resolved properties as System properties, if
 * no property by that name already exists.
 * /*from  ww w.j  ava2  s.c om*/
 * @param locationName String-encoded resource location for the properties file to process
 * @param placeholderPrefix the placeholder prefix String
 * @param placeholderSuffix the placeholder suffix String
 */
public static void processLocation(String locationName, String placeholderPrefix, String placeholderSuffix) {
    ResourceEditor resourceEditor = new ResourceEditor();
    resourceEditor.setAsText(locationName);

    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
    configurer.setLocation((Resource) resourceEditor.getValue());
    if (placeholderPrefix != null)
        configurer.setPlaceholderPrefix(placeholderPrefix);
    if (placeholderSuffix != null)
        configurer.setPlaceholderSuffix(placeholderSuffix);
    configurer.quiet = true;

    GenericApplicationContext context = new GenericApplicationContext();
    context.getBeanFactory().registerSingleton("propertyPlaceholderConfigurer", configurer);
    context.refresh();
    context.close();
}

From source file:edu.internet2.middleware.shibboleth.common.config.BaseService.java

/**
 * Loads the service context.//from  www.j ava 2  s.  co  m
 * 
 * @throws ServiceException thrown if the configuration for this service could not be loaded
 */
protected void loadContext() throws ServiceException {
    log.info("Loading new configuration for service {}", getId());

    if (serviceConfigurations == null || serviceConfigurations.isEmpty()) {
        setInitialized(true);
        return;
    }

    GenericApplicationContext newServiceContext = new GenericApplicationContext(getApplicationContext());
    newServiceContext.setDisplayName("ApplicationContext:" + getId());
    Lock writeLock = getReadWriteLock().writeLock();
    writeLock.lock();
    try {
        SpringConfigurationUtils.populateRegistry(newServiceContext, getServiceConfigurations());
        newServiceContext.refresh();

        GenericApplicationContext replacedServiceContext = serviceContext;
        onNewContextCreated(newServiceContext);
        setServiceContext(newServiceContext);
        setInitialized(true);
        if (replacedServiceContext != null) {
            replacedServiceContext.close();
        }
        log.info("{} service loaded new configuration", getId());
    } catch (Throwable e) {
        // Here we catch all the other exceptions thrown by Spring when it starts up the context
        setInitialized(false);
        Throwable rootCause = e;
        while (rootCause.getCause() != null) {
            rootCause = rootCause.getCause();
        }
        log.error("Configuration was not loaded for " + getId()
                + " service, error creating components.  The root cause of this error was: "
                + rootCause.getClass().getCanonicalName() + ": " + rootCause.getMessage());
        log.trace("Full stacktrace is: ", e);
        throw new ServiceException(
                "Configuration was not loaded for " + getId() + " service, error creating components.",
                rootCause);
    } finally {
        writeLock.unlock();
    }
}

From source file:com.paxxis.cornerstone.messaging.service.shell.ServiceShell.java

private void doDatabaseUpdate(String[] inputs) {
    GenericApplicationContext ctx = new GenericApplicationContext();
    ctx.registerShutdownHook();/*from   w  w w  .  j a  v a  2s. c  om*/
    ctx.refresh();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions(new FileSystemResource(inputs[0]));

    DatabaseUpdater updater = ctx.getBean(DatabaseUpdater.class);

    String target = null;
    if (inputs.length == 3) {
        target = inputs[2];
    }

    updater.update(inputs[1], target);

    ctx.close();
}

From source file:it.scoppelletti.programmerpower.console.spring.ConsoleApplicationRunner.java

/**
 * Inizializza il contesto dell’applicazione.
 * /*  ww w  .j a  v a 2 s.  co m*/
 * @param  ui Interfaccia utente.
 * @return    Oggetto.
 */
private GenericApplicationContext initApplicationContext(UserInterfaceProvider ui) {
    SingletonBeanRegistry beanRegistry;
    GenericApplicationContext ctx = null;
    GenericApplicationContext applCtx;
    XmlBeanDefinitionReader reader;
    ConfigurableEnvironment env;
    PropertySource<?> propSource;
    MutablePropertySources propSources;

    try {
        ctx = new GenericApplicationContext();
        reader = new XmlBeanDefinitionReader(ctx);
        reader.loadBeanDefinitions(ConsoleApplicationRunner.CONSOLE_CONTEXT);
        reader.loadBeanDefinitions(initApplicationContextResourceName());

        beanRegistry = ctx.getBeanFactory();
        beanRegistry.registerSingleton(ConsoleApplicationRunner.BEAN_NAME, this);
        beanRegistry.registerSingleton(UserInterfaceProvider.BEAN_NAME, ui);

        env = ctx.getEnvironment();

        // Acquisisco gli eventuali profili configurati prima di aggiungere
        // quello di Programmer Power
        env.getActiveProfiles();

        env.addActiveProfile(ConsoleApplicationRunner.PROFILE);

        propSources = env.getPropertySources();

        propSources.addFirst(new ConsolePropertySource(ConsolePropertySource.class.getName(), this));

        propSource = BeanConfigUtils.loadPropertySource();
        if (propSource != null) {
            propSources.addFirst(propSource);
        }

        ctx.refresh();
        applCtx = ctx;
        ctx = null;
    } finally {
        if (ctx != null) {
            ctx.close();
            ctx = null;
        }
    }

    return applCtx;
}

From source file:org.opennms.install.Installer.java

/**
 * <p>install</p>/* www .  j  a v a 2  s .  com*/
 *
 * @param argv an array of {@link java.lang.String} objects.
 * @throws java.lang.Exception if any.
 */
public void install(final String[] argv) throws Exception {
    printHeader();
    loadProperties();
    parseArguments(argv);

    final boolean doDatabase = (m_update_database || m_do_inserts || m_update_iplike || m_update_unicode
            || m_fix_constraint);

    if (!doDatabase && m_tomcat_conf == null && !m_install_webapp && m_library_search_path == null) {
        usage(options, m_commandLine, "Nothing to do.  Use -h for help.", null);
        System.exit(1);
    }

    if (doDatabase) {
        final File cfgFile = ConfigFileConstants
                .getFile(ConfigFileConstants.OPENNMS_DATASOURCE_CONFIG_FILE_NAME);

        InputStream is = new FileInputStream(cfgFile);
        final JdbcDataSource adminDsConfig = new DataSourceConfigurationFactory(is)
                .getJdbcDataSource(ADMIN_DATA_SOURCE_NAME);
        final DataSource adminDs = new SimpleDataSource(adminDsConfig);
        is.close();

        is = new FileInputStream(cfgFile);
        final JdbcDataSource dsConfig = new DataSourceConfigurationFactory(is)
                .getJdbcDataSource(OPENNMS_DATA_SOURCE_NAME);
        final DataSource ds = new SimpleDataSource(dsConfig);
        is.close();

        m_installerDb.setForce(m_force);
        m_installerDb.setIgnoreNotNull(m_ignore_not_null);
        m_installerDb.setNoRevert(m_do_not_revert);
        m_installerDb.setAdminDataSource(adminDs);
        m_installerDb.setPostgresOpennmsUser(dsConfig.getUserName());
        m_installerDb.setDataSource(ds);
        m_installerDb.setDatabaseName(dsConfig.getDatabaseName());

        m_migrator.setDataSource(ds);
        m_migrator.setAdminDataSource(adminDs);
        m_migrator.setValidateDatabaseVersion(!m_ignore_database_version);

        m_migration.setDatabaseName(dsConfig.getDatabaseName());
        m_migration.setSchemaName(dsConfig.getSchemaName());
        m_migration.setAdminUser(adminDsConfig.getUserName());
        m_migration.setAdminPassword(adminDsConfig.getPassword());
        m_migration.setDatabaseUser(dsConfig.getUserName());
        m_migration.setDatabasePassword(dsConfig.getPassword());
        m_migration.setChangeLog("changelog.xml");
    }

    checkIPv6();

    /*
     * Make sure we can execute the rrdtool binary when the
     * JniRrdStrategy is enabled.
     */

    boolean using_jni_rrd_strategy = System.getProperty("org.opennms.rrd.strategyClass", "")
            .contains("JniRrdStrategy");

    if (using_jni_rrd_strategy) {
        File rrd_binary = new File(System.getProperty("rrd.binary"));
        if (!rrd_binary.canExecute()) {
            throw new Exception("Cannot execute the rrdtool binary '" + rrd_binary.getAbsolutePath()
                    + "' required by the current RRD strategy. Update the rrd.binary field in opennms.properties appropriately.");
        }
    }

    /*
     * make sure we can load the ICMP library before we go any farther
     */

    if (!Boolean.getBoolean("skip-native")) {
        String icmp_path = findLibrary("jicmp", m_library_search_path, false);
        String icmp6_path = findLibrary("jicmp6", m_library_search_path, false);
        String jrrd_path = findLibrary("jrrd", m_library_search_path, false);
        String jrrd2_path = findLibrary("jrrd2", m_library_search_path, false);
        writeLibraryConfig(icmp_path, icmp6_path, jrrd_path, jrrd2_path);
    }

    /*
     * Everything needs to use the administrative data source until we
     * verify that the opennms database is created below (and where we
     * create it if it doesn't already exist).
     */

    verifyFilesAndDirectories();

    if (m_install_webapp) {
        checkWebappOldOpennmsDir();
        checkServerXmlOldOpennmsContext();
    }

    if (m_update_database || m_fix_constraint) {
        // OLDINSTALL m_installerDb.readTables();
    }

    m_installerDb.disconnect();
    if (doDatabase) {
        m_migrator.validateDatabaseVersion();

        System.out.println(
                String.format("* using '%s' as the PostgreSQL user for OpenNMS", m_migration.getAdminUser()));
        System.out.println(String.format("* using '%s' as the PostgreSQL database name for OpenNMS",
                m_migration.getDatabaseName()));
        if (m_migration.getSchemaName() != null) {
            System.out.println(String.format("* using '%s' as the PostgreSQL schema name for OpenNMS",
                    m_migration.getSchemaName()));
        }
    }

    if (m_update_database) {
        m_migrator.prepareDatabase(m_migration);
    }

    if (doDatabase) {
        m_installerDb.checkUnicode();
    }

    handleConfigurationChanges();

    final GenericApplicationContext context = new GenericApplicationContext();
    context.setClassLoader(Bootstrap.loadClasses(new File(m_opennms_home), true));

    if (m_update_database) {
        m_installerDb.databaseSetUser();
        m_installerDb.disconnect();

        for (final Resource resource : context.getResources("classpath*:/changelog.xml")) {
            System.out.println("- Running migration for changelog: " + resource.getDescription());
            m_migration.setAccessor(new ExistingResourceAccessor(resource));
            m_migrator.migrate(m_migration);
        }
    }

    if (m_update_unicode) {
        System.out.println("WARNING: the -U option is deprecated, it does nothing now");
    }

    if (m_do_vacuum) {
        m_installerDb.vacuumDatabase(m_do_full_vacuum);
    }

    if (m_install_webapp) {
        installWebApp();
    }

    if (m_tomcat_conf != null) {
        updateTomcatConf();
    }

    if (m_update_iplike) {
        m_installerDb.updateIplike();
    }

    if (m_update_database && m_remove_database) {
        m_installerDb.disconnect();
        m_installerDb.databaseRemoveDB();
    }

    if (doDatabase) {
        m_installerDb.disconnect();
    }

    if (m_update_database) {
        createConfiguredFile();
    }

    System.out.println();
    System.out.println("Installer completed successfully!");

    if (!m_skip_upgrade_tools) {
        System.setProperty("opennms.manager.class", "org.opennms.upgrade.support.Upgrade");
        Bootstrap.main(new String[] {});
    }

    context.close();
}

From source file:org.openspaces.admin.application.ApplicationFileDeployment.java

private static <T> T getSpringBeanFromResource(Resource resource, Class<T> type) throws BeansException {
    final GenericApplicationContext context = new GenericApplicationContext();
    try {/* w  ww. j ava  2  s .  c  om*/
        final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(context);
        xmlReader.loadBeanDefinitions(resource);
        context.refresh();
        return context.getBean(type);
    } finally {
        if (context.isActive()) {
            context.close();
        }
    }
}

From source file:org.springframework.boot.context.logging.LoggingApplicationListenerTests.java

@Test
public void closingChildContextDoesNotCleanUpLoggingSystem() {
    System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName());
    multicastEvent(new ApplicationStartingEvent(this.springApplication, new String[0]));
    TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils
            .getField(this.initializer, "loggingSystem");
    assertThat(loggingSystem.cleanedUp).isFalse();
    GenericApplicationContext childContext = new GenericApplicationContext();
    childContext.setParent(this.context);
    multicastEvent(new ContextClosedEvent(childContext));
    assertThat(loggingSystem.cleanedUp).isFalse();
    multicastEvent(new ContextClosedEvent(this.context));
    assertThat(loggingSystem.cleanedUp).isTrue();
    childContext.close();
}

From source file:org.springframework.test.context.junit.jupiter.AbstractExpressionEvaluatingCondition.java

private <A extends Annotation> boolean evaluateExpression(String expression, boolean loadContext,
        Class<A> annotationType, ExtensionContext context) {

    Assert.state(context.getElement().isPresent(), "No AnnotatedElement");
    AnnotatedElement element = context.getElement().get();
    GenericApplicationContext gac = null;
    ApplicationContext applicationContext;

    if (loadContext) {
        applicationContext = SpringExtension.getApplicationContext(context);
    } else {/*from   ww w.j a  v  a2  s  .c om*/
        gac = new GenericApplicationContext();
        gac.refresh();
        applicationContext = gac;
    }

    if (!(applicationContext instanceof ConfigurableApplicationContext)) {
        if (logger.isWarnEnabled()) {
            String contextType = applicationContext.getClass().getName();
            logger.warn(String.format(
                    "@%s(\"%s\") could not be evaluated on [%s] since the test "
                            + "ApplicationContext [%s] is not a ConfigurableApplicationContext",
                    annotationType.getSimpleName(), expression, element, contextType));
        }
        return false;
    }

    ConfigurableBeanFactory configurableBeanFactory = ((ConfigurableApplicationContext) applicationContext)
            .getBeanFactory();
    BeanExpressionResolver expressionResolver = configurableBeanFactory.getBeanExpressionResolver();
    Assert.state(expressionResolver != null, "No BeanExpressionResolver");
    BeanExpressionContext beanExpressionContext = new BeanExpressionContext(configurableBeanFactory, null);

    Object result = expressionResolver.evaluate(configurableBeanFactory.resolveEmbeddedValue(expression),
            beanExpressionContext);

    if (gac != null) {
        gac.close();
    }

    if (result instanceof Boolean) {
        return (Boolean) result;
    } else if (result instanceof String) {
        String str = ((String) result).trim().toLowerCase();
        if ("true".equals(str)) {
            return true;
        }
        Assert.state("false".equals(str),
                () -> String.format("@%s(\"%s\") on %s must evaluate to \"true\" or \"false\", not \"%s\"",
                        annotationType.getSimpleName(), expression, element, result));
        return false;
    } else {
        String message = String.format("@%s(\"%s\") on %s must evaluate to a String or a Boolean, not %s",
                annotationType.getSimpleName(), expression, element,
                (result != null ? result.getClass().getName() : "null"));
        throw new IllegalStateException(message);
    }
}

From source file:uk.co.modularaudio.util.spring.SpringComponentHelper.java

public void destroyAppContext(final GenericApplicationContext gac) {
    // Preshutdown calls
    for (final SpringContextHelper helper : contextHelpers) {
        try {// w  ww.  j  av  a 2  s.  c o  m
            helper.preShutdownDoThings(gac, beanInstantiationList);
        } catch (final DatastoreException e) {
            final String msg = "Exception caught calling preshutdown of helper " + helper.getClass() + ": "
                    + e.toString();
            log.error(msg, e);
            // We don't halt as the destroy should try and carry on
        }
    }
    gac.close();
}