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

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

Introduction

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

Prototype

public GenericApplicationContext() 

Source Link

Document

Create a new GenericApplicationContext.

Usage

From source file:org.marketcetera.util.spring.SpringUtilsTest.java

@Test
public void stringBean() {
    GenericApplicationContext context = new GenericApplicationContext();
    SpringUtils.addStringBean(context, TEST_NAME_BEAN, TEST_VALUE);
    assertEquals(TEST_VALUE, context.getBean(TEST_NAME_BEAN));
}

From source file:org.openadaptor.spring.SpringAdaptor.java

/**
 * Returns the internal context./*w  w w . j  a  v a 2s . c om*/
 * 
 * @return The internal context.
 */
protected GenericApplicationContext getInternalContext() {
    if (internalContext == null) {
        // creates an empty generic application context, if the context is "null"
        internalContext = new GenericApplicationContext();
    } else {
        // When the same instance is used more as once, you could run in a refresh issue.
        // That requires a new created instance by using the default listable bean factory functionality.
        internalContext = new GenericApplicationContext(internalContext.getDefaultListableBeanFactory());
    }
    return internalContext;
}

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

/**
 * <p>install</p>//from ww w  .j  a v a2  s . c  o m
 *
 * @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  w  w  . j  a va2 s  .  co m*/
        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.opentripplanner.integration.benchmark.RunBenchmarkPlanMain.java

private GenericApplicationContext getApplicationContext() {

    GenericApplicationContext ctx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions(new ClassPathResource("org/opentripplanner/application-context.xml"));

    Map<String, BeanDefinition> additionalBeans = getAdditionalBeans();
    for (Map.Entry<String, BeanDefinition> entry : additionalBeans.entrySet())
        ctx.registerBeanDefinition(entry.getKey(), entry.getValue());

    ctx.refresh();//from   w w  w .  j av  a2 s  .  c om
    ctx.registerShutdownHook();
    return ctx;
}

From source file:org.pentaho.platform.plugin.services.pluginmgr.DefaultPluginManager.java

/**
 * The native bean factory is the bean factory that has had all of its bean definitions loaded natively. In other
 * words, the plugin manager will not add any further bean definitions (i.e. from a plugin.xml file) into this
 * factory. This factory represents the one responsible for holding bean definitions for plugin.spring.xml or, if in a
 * unit test environment, the unit test pre-loaded bean factory.
 *
 * @return a bean factory will preconfigured bean definitions or <code>null</code> if no bean definition source is
 * available//from  www. ja v  a2  s . co  m
 */
protected BeanFactory getNativeBeanFactory(final IPlatformPlugin plugin, final ClassLoader loader) {
    BeanFactory nativeFactory = null;
    if (plugin.getBeanFactory() != null) {
        // then we are probably in a unit test so just use the preconfigured one
        BeanFactory testFactory = plugin.getBeanFactory();
        if (testFactory instanceof ConfigurableBeanFactory) {
            ((ConfigurableBeanFactory) testFactory).setBeanClassLoader(loader);
        } else {
            logger.warn(Messages.getInstance().getString("PluginManager.WARN_WRONG_BEAN_FACTORY_TYPE")); //$NON-NLS-1$
        }
        nativeFactory = testFactory;
    } else {
        File f = new File(((PluginClassLoader) loader).getPluginDir(), "plugin.spring.xml"); //$NON-NLS-1$
        if (f.exists()) {
            logger.debug("Found plugin spring file @ " + f.getAbsolutePath()); //$NON-NLS-1$

            FileSystemResource fsr = new FileSystemResource(f);
            GenericApplicationContext appCtx = new GenericApplicationContext() {

                @Override
                protected void prepareBeanFactory(ConfigurableListableBeanFactory clBeanFactory) {
                    super.prepareBeanFactory(clBeanFactory);
                    clBeanFactory.setBeanClassLoader(loader);
                }

                @Override
                public ClassLoader getClassLoader() {
                    return loader;
                }

            };

            XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(appCtx);
            xmlReader.setBeanClassLoader(loader);
            xmlReader.loadBeanDefinitions(fsr);

            nativeFactory = appCtx;
        }
    }
    return nativeFactory;
}

From source file:org.pentaho.platform.plugin.services.pluginmgr.DefaultPluginManager.java

/**
 * Initializes a bean factory for serving up instance of plugin classes.
 *
 * @return an instance of the factory that allows callers to continue to define more beans on it programmatically
 *///w w  w  .j  a  v  a 2s.com
protected void initializeBeanFactory(final IPlatformPlugin plugin, final ClassLoader loader)
        throws PlatformPluginRegistrationException {

    if (!(loader instanceof PluginClassLoader)) {
        logger.warn(
                "Can't determine plugin dir to load spring file because classloader is not of type PluginClassLoader.  "
                        //$NON-NLS-1$
                        + "This is since we are probably in a unit test"); //$NON-NLS-1$
        return;
    }

    //
    // Get the native factory (the factory that comes preconfigured via either Spring bean files or via JUnit test
    //
    BeanFactory nativeBeanFactory = getNativeBeanFactory(plugin, loader);

    //
    // Now create the definable factory for accepting old style bean definitions from IPluginProvider
    //

    GenericApplicationContext beanFactory = null;
    if (nativeBeanFactory != null && nativeBeanFactory instanceof GenericApplicationContext) {
        beanFactory = (GenericApplicationContext) nativeBeanFactory;
    } else {
        beanFactory = new GenericApplicationContext();
        beanFactory.setClassLoader(loader);
        beanFactory.getBeanFactory().setBeanClassLoader(loader);

        if (nativeBeanFactory != null) {
            beanFactory.getBeanFactory().setParentBeanFactory(nativeBeanFactory);
        }
    }

    beanFactoryMap.put(plugin.getId(), beanFactory);

    //
    // Register any beans defined via the pluginProvider
    //

    // we do not have to synchronize on the bean set here because the
    // map that backs the set is never modified after the plugin has
    // been made available to the plugin manager
    for (PluginBeanDefinition def : plugin.getBeans()) {
        // register by classname if id is null
        def.setBeanId((def.getBeanId() == null) ? def.getClassname() : def.getBeanId());
        assertUnique(plugin.getId(), def.getBeanId());
        // defining plugin beans the old way through the plugin provider ifc supports only prototype scope
        BeanDefinition beanDef = BeanDefinitionBuilder.rootBeanDefinition(def.getClassname())
                .setScope(BeanDefinition.SCOPE_PROTOTYPE).getBeanDefinition();
        beanFactory.registerBeanDefinition(def.getBeanId(), beanDef);
    }

    StandaloneSpringPentahoObjectFactory pentahoFactory = new StandaloneSpringPentahoObjectFactory(
            "Plugin Factory ( " + plugin.getId() + " )");
    pentahoFactory.init(null, beanFactory);

}

From source file:org.pentaho.platform.repository2.unified.DefaultUnifiedRepositoryBase.java

@BeforeClass
public static void setUpClass() throws Exception {
    // folder cannot be deleted at teardown shutdown hooks have not yet necessarily completed
    // parent folder must match jcrRepository.homeDir bean property in repository-test-override.spring.xml
    FileUtils.deleteDirectory(new File("/tmp/jackrabbit-test-TRUNK"));
    PentahoSessionHolder.setStrategyName(PentahoSessionHolder.MODE_GLOBAL);

    // register repository spring context for correct work of <pen:list>
    final StandaloneSpringPentahoObjectFactory pentahoObjectFactory = new StandaloneSpringPentahoObjectFactory();
    GenericApplicationContext appCtx = new GenericApplicationContext();
    XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(appCtx);
    xmlReader.loadBeanDefinitions(new ClassPathResource("repository.spring.xml"));
    xmlReader.loadBeanDefinitions(new ClassPathResource("repository-test-override.spring.xml"));
    pentahoObjectFactory.init(null, appCtx);
    PentahoSystem.registerObjectFactory(pentahoObjectFactory);
}

From source file:org.springframework.amqp.rabbit.core.RabbitAdminTests.java

@Test
public void testNoFailOnStartupWithMissingBroker() throws Exception {
    SingleConnectionFactory connectionFactory = new SingleConnectionFactory("foo");
    connectionFactory.setPort(434343);/*from  w  w w.  j a v  a  2s . com*/
    GenericApplicationContext applicationContext = new GenericApplicationContext();
    applicationContext.getBeanFactory().registerSingleton("foo", new Queue("queue"));
    RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
    rabbitAdmin.setApplicationContext(applicationContext);
    rabbitAdmin.setAutoStartup(true);
    rabbitAdmin.afterPropertiesSet();
    connectionFactory.destroy();
}

From source file:org.springframework.amqp.rabbit.core.RabbitAdminTests.java

@Test
public void testFailOnFirstUseWithMissingBroker() throws Exception {
    SingleConnectionFactory connectionFactory = new SingleConnectionFactory("localhost");
    connectionFactory.setPort(434343);/*from  w  w w .j  av  a  2 s .c  o  m*/
    GenericApplicationContext applicationContext = new GenericApplicationContext();
    applicationContext.getBeanFactory().registerSingleton("foo", new Queue("queue"));
    RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
    rabbitAdmin.setApplicationContext(applicationContext);
    rabbitAdmin.setAutoStartup(true);
    rabbitAdmin.afterPropertiesSet();
    exception.expect(IllegalArgumentException.class);
    rabbitAdmin.declareQueue();
    connectionFactory.destroy();
}