Example usage for org.springframework.web.context ConfigurableWebApplicationContext getBeanFactory

List of usage examples for org.springframework.web.context ConfigurableWebApplicationContext getBeanFactory

Introduction

In this page you can find the example usage for org.springframework.web.context ConfigurableWebApplicationContext getBeanFactory.

Prototype

ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;

Source Link

Document

Return the internal bean factory of this application context.

Usage

From source file:org.red5.server.war.RootContextLoaderServlet.java

/**
 * Clearing the in-memory configuration parameters, we will receive
 * notification that the servlet context is about to be shut down
 *//* w ww .  ja va  2 s .c  om*/
@Override
public void contextDestroyed(ServletContextEvent sce) {
    synchronized (instance) {
        logger.info("Webapp shutdown");
        // XXX Paul: grabbed this from
        // http://opensource.atlassian.com/confluence/spring/display/DISC/Memory+leak+-+classloader+won%27t+let+go
        // in hopes that we can clear all the issues with J2EE containers
        // during shutdown
        try {
            ServletContext ctx = sce.getServletContext();
            // if the ctx being destroyed is root then kill the timer
            if (ctx.getContextPath().equals("/ROOT")) {
                timer.cancel();
            } else {
                // remove from registered list
                registeredContexts.remove(ctx);
            }
            // prepare spring for shutdown
            Introspector.flushCaches();
            // dereg any drivers
            for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements();) {
                Driver driver = (Driver) e.nextElement();
                if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {
                    DriverManager.deregisterDriver(driver);
                }
            }
            // shutdown jmx
            JMXAgent.shutdown();
            // shutdown spring
            Object attr = ctx.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            if (attr != null) {
                // get web application context from the servlet context
                ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) attr;
                ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
                // for (String scope : factory.getRegisteredScopeNames()) {
                // logger.debug("Registered scope: " + scope);
                // }
                try {
                    for (String singleton : factory.getSingletonNames()) {
                        logger.debug("Registered singleton: " + singleton);
                        factory.destroyScopedBean(singleton);
                    }
                } catch (RuntimeException e) {
                }
                factory.destroySingletons();

                ctx.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
                applicationContext.close();
            }
            instance.getContextLoader().closeWebApplicationContext(ctx);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            // http://jakarta.apache.org/commons/logging/guide.html#Classloader_and_Memory_Management
            // http://wiki.apache.org/jakarta-commons/Logging/UndeployMemoryLeak?action=print
            LogFactory.release(Thread.currentThread().getContextClassLoader());
        }
    }
}

From source file:org.red5.server.war.RootContextLoaderServlet.java

public void registerSubContext(String webAppKey) {
    // get the sub contexts - servlet context
    ServletContext ctx = servletContext.getContext(webAppKey);
    logger.info("Registering subcontext for servlet context: " + ctx.getContextPath());
    if (registeredContexts.contains(ctx)) {
        logger.debug("Context is already registered: " + webAppKey);
        return;/*from ww  w  .  ja v  a 2s  .  com*/
    }

    ContextLoader loader = new ContextLoader();

    ConfigurableWebApplicationContext appCtx = (ConfigurableWebApplicationContext) loader
            .initWebApplicationContext(ctx);
    appCtx.setParent(applicationContext);
    appCtx.refresh();

    ctx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appCtx);

    ConfigurableBeanFactory appFactory = appCtx.getBeanFactory();

    logger.debug("About to grab Webcontext bean for " + webAppKey);
    Context webContext = (Context) appCtx.getBean("web.context");
    webContext.setCoreBeanFactory(parentFactory);
    webContext.setClientRegistry(clientRegistry);
    webContext.setServiceInvoker(globalInvoker);
    webContext.setScopeResolver(globalResolver);
    webContext.setMappingStrategy(globalStrategy);

    WebScope scope = (WebScope) appFactory.getBean("web.scope");
    scope.setServer(server);
    scope.setParent(global);
    scope.register();
    scope.start();

    // register the context so we dont try to reinitialize it
    registeredContexts.add(ctx);

}

From source file:org.red5.server.war.MainServlet.java

/**
 * Main entry point for the Red5 Server as a war
 *///from w w w.j a v a  2 s  .c o  m
// Notification that the web application is ready to process requests
public void contextInitialized(ServletContextEvent sce) {
    System.setProperty("red5.deployment.type", "war");

    if (null != servletContext) {
        return;
    }
    servletContext = sce.getServletContext();
    String prefix = servletContext.getRealPath("/");

    long time = System.currentTimeMillis();

    logger.info("RED5 Server (http://www.osflash.org/red5)");
    logger.info("Loading red5 global context from: " + red5Config);
    logger.info("Path: " + prefix);

    try {
        // Detect root of Red5 configuration and set as system property
        String root;
        String classpath = System.getProperty("java.class.path");
        File fp = new File(prefix + red5Config);
        fp = fp.getCanonicalFile();
        if (!fp.isFile()) {
            // Given file does not exist, search it on the classpath
            String[] paths = classpath.split(System.getProperty("path.separator"));
            for (String element : paths) {
                fp = new File(element + "/" + red5Config);
                fp = fp.getCanonicalFile();
                if (fp.isFile()) {
                    break;
                }
            }
        }
        if (!fp.isFile()) {
            throw new Exception(
                    "could not find configuration file " + red5Config + " on your classpath " + classpath);
        }

        root = fp.getAbsolutePath();
        root = root.replace('\\', '/');
        int idx = root.lastIndexOf('/');
        root = root.substring(0, idx);
        // update classpath
        System.setProperty("java.class.path",
                classpath + File.pathSeparatorChar + root + File.pathSeparatorChar + root + "/classes");
        logger.debug("New classpath: " + System.getProperty("java.class.path"));
        // set configuration root
        System.setProperty("red5.config_root", root);
        logger.info("Setting configuation root to " + root);

        // Setup system properties so they can be evaluated
        Properties props = new Properties();
        props.load(new FileInputStream(root + "/red5.properties"));
        for (Object o : props.keySet()) {
            String key = (String) o;
            if (StringUtils.isNotBlank(key)) {
                System.setProperty(key, props.getProperty(key));
            }
        }

        // Store root directory of Red5
        idx = root.lastIndexOf('/');
        root = root.substring(0, idx);
        if (System.getProperty("file.separator").equals("/")) {
            // Workaround for linux systems
            root = "/" + root;
        }
        System.setProperty("red5.root", root);
        logger.info("Setting Red5 root to " + root);

        Class contextClass = org.springframework.web.context.support.XmlWebApplicationContext.class;
        ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) BeanUtils
                .instantiateClass(contextClass);

        String[] strArray = servletContext.getInitParameter(ContextLoader.CONFIG_LOCATION_PARAM)
                .split("[,\\s]");
        logger.info("Config location files: " + strArray.length);
        applicationContext.setConfigLocations(strArray);
        applicationContext.setServletContext(servletContext);
        applicationContext.refresh();

        // set web application context as an attribute of the servlet
        // context so that it may be located via Springs
        // WebApplicationContextUtils
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                applicationContext);

        ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
        // register default
        // add the context to the parent
        factory.registerSingleton("default.context", applicationContext);

    } catch (Throwable e) {
        logger.error("", e);
    }

    long startupIn = System.currentTimeMillis() - time;
    logger.info("Startup done in: " + startupIn + " ms");

}

From source file:org.red5.server.war.MainServlet.java

/**
 * Clearing the in-memory configuration parameters, we will receive
 * notification that the servlet context is about to be shut down
 *///  w  ww  .j a  v a  2 s.  c o m
public void contextDestroyed(ServletContextEvent sce) {
    logger.info("Webapp shutdown");
    // XXX Paul: grabbed this from
    // http://opensource.atlassian.com/confluence/spring/display/DISC/Memory+leak+-+classloader+won%27t+let+go
    // in hopes that we can clear all the issues with J2EE containers during
    // shutdown
    try {
        // prepare spring for shutdown
        Introspector.flushCaches();
        // dereg any drivers
        for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements();) {
            Driver driver = (Driver) e.nextElement();
            if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {
                DriverManager.deregisterDriver(driver);
            }
        }
        // shutdown jmx
        JMXAgent.shutdown();
        // shutdown spring
        // get web application context from the servlet context
        ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) servletContext
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
        if (factory.containsSingleton("default.context")) {
            for (String scope : factory.getRegisteredScopeNames()) {
                logger.debug("Registered scope: " + scope);
            }
            for (String singleton : factory.getSingletonNames()) {
                logger.debug("Registered singleton: " + singleton);
                // factory.destroyScopedBean(singleton);
            }
            factory.destroySingletons();
        }
        servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        applicationContext.close();
        // http://jakarta.apache.org/commons/logging/guide.html#Classloader_and_Memory_Management
        // http://wiki.apache.org/jakarta-commons/Logging/UndeployMemoryLeak?action=print
        // LogFactory.release(Thread.currentThread().getContextClassLoader());
    } catch (Throwable e) {
        // may get a java.lang.StackOverflowError when shutting appcontext
        // down in jboss
        e.printStackTrace();
    }
}

From source file:org.red5.server.war.WarLoaderServlet.java

public void registerSubContext(String webAppKey) {
    // get the sub contexts - servlet context
    ServletContext ctx = servletContext.getContext(webAppKey);
    if (ctx == null) {
        ctx = servletContext;//  ww  w.java 2  s . com
    }
    ContextLoader loader = new ContextLoader();
    ConfigurableWebApplicationContext appCtx = (ConfigurableWebApplicationContext) loader
            .initWebApplicationContext(ctx);
    appCtx.setParent(applicationContext);
    appCtx.refresh();

    ctx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appCtx);

    ConfigurableBeanFactory appFactory = appCtx.getBeanFactory();

    logger.debug("About to grab Webcontext bean for " + webAppKey);
    Context webContext = (Context) appCtx.getBean("web.context");
    webContext.setCoreBeanFactory(parentFactory);
    webContext.setClientRegistry(clientRegistry);
    webContext.setServiceInvoker(globalInvoker);
    webContext.setScopeResolver(globalResolver);
    webContext.setMappingStrategy(globalStrategy);

    WebScope scope = (WebScope) appFactory.getBean("web.scope");
    scope.setServer(server);
    scope.setParent(global);
    scope.register();
    scope.start();

    // register the context so we dont try to reinitialize it
    registeredContexts.add(ctx);

}

From source file:org.red5.server.war.WarLoaderServlet.java

/**
 * Clearing the in-memory configuration parameters, we will receive
 * notification that the servlet context is about to be shut down
 *///w  w  w. j av  a2  s . c  om
@Override
public void contextDestroyed(ServletContextEvent sce) {
    synchronized (servletContext) {
        logger.info("Webapp shutdown");
        // XXX Paul: grabbed this from
        // http://opensource.atlassian.com/confluence/spring/display/DISC/Memory+leak+-+classloader+won%27t+let+go
        // in hopes that we can clear all the issues with J2EE containers
        // during shutdown
        try {
            ServletContext ctx = sce.getServletContext();
            // prepare spring for shutdown
            Introspector.flushCaches();
            // dereg any drivers
            for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements();) {
                Driver driver = (Driver) e.nextElement();
                if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {
                    DriverManager.deregisterDriver(driver);
                }
            }
            // shutdown jmx
            JMXAgent.shutdown();
            // shutdown the persistence thread
            FilePersistenceThread persistenceThread = FilePersistenceThread.getInstance();
            if (persistenceThread != null) {
                persistenceThread.shutdown();
            }
            // shutdown spring
            Object attr = ctx.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            if (attr != null) {
                // get web application context from the servlet context
                ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) attr;
                ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
                // for (String scope : factory.getRegisteredScopeNames()) {
                // logger.debug("Registered scope: " + scope);
                // }
                try {
                    for (String singleton : factory.getSingletonNames()) {
                        logger.debug("Registered singleton: " + singleton);
                        factory.destroyScopedBean(singleton);
                    }
                } catch (RuntimeException e) {
                }
                factory.destroySingletons();
                ctx.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
                applicationContext.close();
            }
            getContextLoader().closeWebApplicationContext(ctx);
            //            org.apache.commons.logging.LogFactory.releaseAll();
            //            org.apache.log4j.LogManager.getLoggerRepository().shutdown();
            //            org.apache.log4j.LogManager.shutdown();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

From source file:org.sakaiproject.component.impl.SakaiContextLoader.java

/**
  * Allows loading/override of custom bean definitions from sakai.home
  */*ww w.j  a v  a 2  s .  c o  m*/
  * <p>The pattern is the 'servlet_name-context.xml'</p>
  *
  * @param servletContext current servlet context
  * @return the new WebApplicationContext
  * @throws org.springframework.beans.BeansException
  *          if the context couldn't be initialized
  */
@Override
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) throws BeansException {

    ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) super.initWebApplicationContext(
            servletContext);
    // optionally look in sakai home for additional bean deifinitions to load
    if (cwac != null) {
        final String servletName = servletContext.getServletContextName();
        String location = getHomeBeanDefinitionIfExists(servletName);
        if (StringUtils.isNotBlank(location)) {
            log.debug("Servlet " + servletName + " is attempting to load bean definition [" + location + "]");
            XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(
                    (BeanDefinitionRegistry) cwac.getBeanFactory());
            try {
                int loaded = reader.loadBeanDefinitions(new FileSystemResource(location));
                log.info("Servlet " + servletName + " loaded " + loaded + " beans from [" + location + "]");
                AnnotationConfigUtils.registerAnnotationConfigProcessors(reader.getRegistry());
                cwac.getBeanFactory().preInstantiateSingletons();
            } catch (BeanDefinitionStoreException bdse) {
                log.warn("Failure loading beans from [" + location + "]", bdse);
            } catch (BeanCreationException bce) {
                log.warn("Failure instantiating beans from [" + location + "]", bce);
            }
        }
    }
    return cwac;
}

From source file:org.springframework.boot.SpringApplication.java

/**
 * Apply any relevant post processing the {@link ApplicationContext}. Subclasses can
 * apply additional processing as required.
 * @param context the application context
 *//*from w  w  w.  ja va2 s.  c om*/
protected void postProcessApplicationContext(ConfigurableApplicationContext context) {
    if (this.webEnvironment) {
        if (context instanceof ConfigurableWebApplicationContext) {
            ConfigurableWebApplicationContext configurableContext = (ConfigurableWebApplicationContext) context;
            if (this.beanNameGenerator != null) {
                configurableContext.getBeanFactory().registerSingleton(
                        AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, this.beanNameGenerator);
            }
        }
    }

    if (this.resourceLoader != null) {
        if (context instanceof GenericApplicationContext) {
            ((GenericApplicationContext) context).setResourceLoader(this.resourceLoader);
        }
        if (context instanceof DefaultResourceLoader) {
            ((DefaultResourceLoader) context).setClassLoader(this.resourceLoader.getClassLoader());
        }
    }
}