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

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

Introduction

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

Prototype

void setServletContext(@Nullable ServletContext servletContext);

Source Link

Document

Set the ServletContext for this web application context.

Usage

From source file:org.red5.server.winstone.WinstoneLoader.java

/**
 * Initialization./*from ww  w .  j av a  2 s .c om*/
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void init() {
    log.info("Loading Winstone context");
    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    // root location for servlet container
    String serverRoot = System.getProperty("red5.root");
    log.info("Server root: {}", serverRoot);
    String confRoot = System.getProperty("red5.config_root");
    log.info("Config root: {}", confRoot);
    // configure the webapps folder, make sure we have one
    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps");
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);
    // create one embedded (server) and use it everywhere
    Map args = new HashMap();
    //args.put("webroot", webappFolder + "/root");
    args.put("webappsDir", webappFolder);
    // Start server
    try {
        log.info("Starting Winstone servlet engine");
        Launcher.initLogger(args);
        // spawns threads, so your application doesn't block
        embedded = new StoneLauncher(args);
        log.trace("Classloader for embedded: {} TCL: {}", Launcher.class.getClassLoader(), originalClassLoader);
        // get the default host
        HostConfiguration host = embedded.getHostGroup().getHostByName(null);
        // set the primary application loader
        LoaderBase.setApplicationLoader(new WinstoneApplicationLoader(host, applicationContext));
        // get root first, we may want to start a spring config internally but for now skip it
        WebAppConfiguration root = host.getWebAppByURI("/");
        log.trace("Root: {}", root);
        // scan the sub directories to determine our context names
        buildContextNameList(webappFolder);
        // loop the other contexts
        for (String contextName : contextNames) {
            WebAppConfiguration ctx = host.getWebAppByURI(contextName);
            // get access to the servlet context
            final ServletContext servletContext = ctx.getContext(contextName);
            log.debug("Context initialized: {}", servletContext.getContextPath());
            //set the hosts id
            servletContext.setAttribute("red5.host.id", host.getHostname());
            // get the path
            String prefix = servletContext.getRealPath("/");
            log.debug("Path: {}", prefix);
            try {
                final ClassLoader cldr = ctx.getLoader();
                log.debug("Loader type: {}", cldr.getClass().getName());
                // get the (spring) config file path
                final String contextConfigLocation = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null
                                ? defaultSpringConfigLocation
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM);
                log.debug("Spring context config location: {}", contextConfigLocation);
                // get the (spring) parent context key
                final String parentContextKey = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null
                                ? defaultParentContextKey
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM);
                log.debug("Spring parent context key: {}", parentContextKey);
                //set current threads classloader to the webapp classloader
                Thread.currentThread().setContextClassLoader(cldr);
                //create a thread to speed-up application loading
                Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) {
                    public void run() {
                        //set thread context classloader to web classloader
                        Thread.currentThread().setContextClassLoader(cldr);
                        //get the web app's parent context
                        ApplicationContext parentContext = null;
                        if (applicationContext.containsBean(parentContextKey)) {
                            parentContext = (ApplicationContext) applicationContext.getBean(parentContextKey);
                        } else {
                            log.warn("Parent context was not found: {}", parentContextKey);
                        }
                        // create a spring web application context
                        final String contextClass = servletContext.getInitParameter(
                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null
                                        ? XmlWebApplicationContext.class.getName()
                                        : servletContext.getInitParameter(
                                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM);
                        //web app context (spring)
                        ConfigurableWebApplicationContext appctx = null;
                        try {
                            Class<?> clazz = Class.forName(contextClass, true, cldr);
                            appctx = (ConfigurableWebApplicationContext) clazz.newInstance();
                        } catch (Throwable e) {
                            throw new RuntimeException("Failed to load webapplication context class.", e);
                        }
                        appctx.setConfigLocations(new String[] { contextConfigLocation });
                        appctx.setServletContext(servletContext);
                        //set parent context or use current app context
                        if (parentContext != null) {
                            appctx.setParent(parentContext);
                        } else {
                            appctx.setParent(applicationContext);
                        }
                        // set the root webapp ctx attr on the each servlet context so spring can find it later
                        servletContext.setAttribute(
                                WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
                        //refresh the factory
                        log.trace("Classloader prior to refresh: {}", appctx.getClassLoader());
                        appctx.refresh();
                        if (log.isDebugEnabled()) {
                            log.debug("Red5 app is active: {} running: {}", appctx.isActive(),
                                    appctx.isRunning());
                        }
                    }
                };
                thread.setDaemon(true);
                thread.start();
            } catch (Throwable t) {
                log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(),
                        t.getMessage());
                t.printStackTrace();
            } finally {
                //reset the classloader
                Thread.currentThread().setContextClassLoader(originalClassLoader);
            }
        }
    } catch (Exception e) {
        if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) {
            log.error(
                    "Error loading Winstone, unable to bind connector. You may not have permission to use the selected port",
                    e);
        } else {
            log.error("Error loading Winstone", e);
        }
    } finally {
        registerJMX();
    }

}

From source file:org.red5.server.undertow.UndertowLoader.java

/**
 * Initialization.// w  w w.j  a va 2  s  .com
 */
public void start() {
    log.info("Loading undertow context");
    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    // root location for servlet container
    String serverRoot = System.getProperty("red5.root");
    log.info("Server root: {}", serverRoot);
    String confRoot = System.getProperty("red5.config_root");
    log.info("Config root: {}", confRoot);
    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps");
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);
    // scan the sub directories to determine our context paths
    buildContextPathList(webappFolder);
    try {
        // create our servlet container
        container = ServletContainer.Factory.newInstance();
        // create a root path handler
        final PathHandler rootHandler = new PathHandler();
        // create one server and use it everywhere
        Undertow.Builder builder = Undertow.builder();
        // loop through connectors adding listeners to the builder
        for (UndertowConnector undertowConnector : connectors) {
            InetSocketAddress addr = undertowConnector.getSocketAddress();
            builder.addListener(addr.getPort(), addr.getHostName(),
                    (undertowConnector.isSecure() ? ListenerType.HTTPS : ListenerType.HTTP));
        }
        log.trace("Classloader for undertow: {} TCL: {}", Undertow.class.getClassLoader(), originalClassLoader);
        // create references for later lookup
        LoaderBase.setApplicationLoader(new UndertowApplicationLoader(container, applicationContext));
        // loop the other contexts
        for (String contextPath : contextPaths) {
            // create a class loader for the context
            ClassLoader classLoader = buildWebClassLoader(originalClassLoader, webappFolder, contextPath);
            // create deployment info
            DeploymentInfo info = deployment().setClassLoader(classLoader)
                    .setContextPath(contextPath.equalsIgnoreCase("/ROOT") ? "/" : contextPath)
                    .setDefaultEncoding("UTF-8").setDeploymentName(contextPath.substring(1) + ".war")
                    .setUrlEncoding("UTF-8");
            // parse the web.xml and configure the context
            parseWebXml(webappFolder, contextPath, info);
            if (log.isDebugEnabled()) {
                log.debug("Deployment info - name: {} servlets: {} filters: {}", new Object[] {
                        info.getDisplayName(), info.getServlets().size(), info.getFilters().size() });
            }
            // add the new deployment to the servlet container
            DeploymentManager manager = container.addDeployment(info);
            // set a reference to the manager and deploy the context
            LoaderBase.setRed5ApplicationContext(contextPath, new UndertowApplicationContext(manager));
            // deploy
            manager.deploy();
            // add path
            rootHandler.addPrefixPath(info.getContextPath(), manager.start());
            // get deployment
            Deployment deployment = manager.getDeployment();
            // get servlet context
            final ServletContext servletContext = deployment.getServletContext();
            log.debug("Context initialized: {}", servletContext.getContextPath());
            try {
                log.debug("Context: {}", servletContext);
                final ClassLoader webClassLoader = info.getClassLoader();
                log.debug("Webapp classloader: {}", webClassLoader);
                // get the (spring) config file path
                final String contextConfigLocation = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null
                                ? defaultSpringConfigLocation
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM);
                log.debug("Spring context config location: {}", contextConfigLocation);
                // get the (spring) parent context key
                final String parentContextKey = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null
                                ? defaultParentContextKey
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM);
                log.debug("Spring parent context key: {}", parentContextKey);
                // set current threads classloader to the webapp classloader
                Thread.currentThread().setContextClassLoader(webClassLoader);
                // create a thread to speed-up application loading
                Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) {
                    public void run() {
                        //set thread context classloader to web classloader
                        Thread.currentThread().setContextClassLoader(webClassLoader);
                        //get the web app's parent context
                        ApplicationContext parentContext = null;
                        if (applicationContext.containsBean(parentContextKey)) {
                            parentContext = (ApplicationContext) applicationContext.getBean(parentContextKey);
                        } else {
                            log.warn("Parent context was not found: {}", parentContextKey);
                        }
                        // create a spring web application context
                        final String contextClass = servletContext.getInitParameter(
                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null
                                        ? XmlWebApplicationContext.class.getName()
                                        : servletContext.getInitParameter(
                                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM);
                        // web app context (spring)
                        ConfigurableWebApplicationContext appctx = null;
                        try {
                            Class<?> clazz = Class.forName(contextClass, true, webClassLoader);
                            appctx = (ConfigurableWebApplicationContext) clazz.newInstance();
                            // set the root webapp ctx attr on the each servlet context so spring can find it later
                            servletContext.setAttribute(
                                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
                            appctx.setConfigLocations(new String[] { contextConfigLocation });
                            appctx.setServletContext(servletContext);
                            // set parent context or use current app context
                            if (parentContext != null) {
                                appctx.setParent(parentContext);
                            } else {
                                appctx.setParent(applicationContext);
                            }
                            // refresh the factory
                            log.trace("Classloader prior to refresh: {}", appctx.getClassLoader());
                            appctx.refresh();
                            if (log.isDebugEnabled()) {
                                log.debug("Red5 app is active: {} running: {}", appctx.isActive(),
                                        appctx.isRunning());
                            }
                            appctx.start();
                        } catch (Throwable e) {
                            throw new RuntimeException("Failed to load webapplication context class", e);
                        }
                    }
                };
                thread.setDaemon(true);
                thread.start();
            } catch (Throwable t) {
                log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(),
                        t.getMessage());
                t.printStackTrace();
            } finally {
                //reset the classloader
                Thread.currentThread().setContextClassLoader(originalClassLoader);
            }
        }
        // Dump deployments list
        if (log.isDebugEnabled()) {
            for (String deployment : container.listDeployments()) {
                log.debug("Container deployment: {}", deployment);
            }
        }
        // if everything is ok at this point then call the rtmpt and rtmps beans so they will init
        //         if (applicationContext.containsBean("rtmpt.server")) {
        //            log.debug("Initializing RTMPT");
        //            applicationContext.getBean("rtmpt.server");
        //            log.debug("Finished initializing RTMPT");
        //         } else {
        //            log.info("Dedicated RTMPT server configuration was not specified");
        //         }
        //         if (applicationContext.containsBean("rtmps.server")) {
        //            log.debug("Initializing RTMPS");
        //            applicationContext.getBean("rtmps.server");
        //            log.debug("Finished initializing RTMPS");
        //         } else {
        //            log.debug("Dedicated RTMPS server configuration was not specified");
        //         }
        // add a root handler
        builder.setHandler(rootHandler);
        // build the server instance
        server = builder.build();
        log.info("Starting Undertow");
        server.start();
    } catch (Exception e) {
        if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) {
            log.error(
                    "Error loading undertow, unable to bind connector. You may not have permission to use the selected port",
                    e);
        } else {
            log.error("Error loading undertow", e);
        }
    } finally {
        registerJMX();
    }
    log.debug("Undertow init exit");
}

From source file:com.dhcc.framework.web.context.DhccContextLoader.java

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac,
        ServletContext sc) {/*from  ww  w.j  a  v  a 2 s  .c o  m*/
    Log logger = LogFactory.getLog(DhccContextLoader.class);
    if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
        // The application context id is still set to its original default value
        // -> assign a more useful id based on available information
        String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
        if (idParam != null) {
            wac.setId(idParam);
        } else {
            // Generate default id...
            if (sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) {
                // Servlet <= 2.4: resort to name specified in web.xml, if any.
                wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX
                        + ObjectUtils.getDisplayString(sc.getServletContextName()));
            } else {
                wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX
                        + ObjectUtils.getDisplayString(sc.getContextPath()));
            }
        }
    }

    wac.setServletContext(sc);
    String initParameter = sc.getInitParameter(CONFIG_LOCATION_PARAM);
    if (isMicrokernelStart(sc)) {
        initParameter = "classpath:codeTemplate/applicationSetupContext.xml";
        logger.error("because cant't  connect to db or setup flg is 0 so init application as  Microkernel ");
    } else {
        logger.info("initParameter==" + initParameter);
    }
    if (initParameter != null) {
        wac.setConfigLocation(initParameter);
    }
    customizeContext(sc, wac);
    wac.refresh();
}

From source file:org.red5.server.tomcat.TomcatLoader.java

/**
 * Initialization./*from  www  .  j a  v  a 2  s .  c o  m*/
 */
public void init() {
    log.info("Loading tomcat context");

    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();

    // root location for servlet container
    String serverRoot = System.getProperty("red5.root");
    log.info("Server root: {}", serverRoot);
    String confRoot = System.getProperty("red5.config_root");
    log.info("Config root: {}", confRoot);

    // create one embedded (server) and use it everywhere
    embedded = new Embedded();
    embedded.createLoader(originalClassLoader);
    embedded.setCatalinaBase(serverRoot);
    embedded.setCatalinaHome(serverRoot);
    embedded.setName(serviceEngineName);
    log.trace("Classloader for embedded: {} TCL: {}", Embedded.class.getClassLoader(), originalClassLoader);

    engine = embedded.createEngine();
    engine.setDefaultHost(host.getName());
    engine.setName(serviceEngineName);

    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps");
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);

    // scan for additional webapp contexts

    // Root applications directory
    File appDirBase = new File(webappFolder);
    // Subdirs of root apps dir
    File[] dirs = appDirBase.listFiles(new DirectoryFilter());
    // Search for additional context files
    for (File dir : dirs) {
        String dirName = '/' + dir.getName();
        // check to see if the directory is already mapped
        if (null == host.findChild(dirName)) {
            String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), dirName);
            log.debug("Webapp context directory (full path): {}", webappContextDir);
            Context ctx = null;
            if ("/root".equals(dirName) || "/root".equalsIgnoreCase(dirName)) {
                log.trace("Adding ROOT context");
                ctx = addContext("/", webappContextDir);
            } else {
                log.trace("Adding context from directory scan: {}", dirName);
                ctx = addContext(dirName, webappContextDir);
            }
            log.trace("Context: {}", ctx);

            //see if the application requests php support
            String enablePhp = ctx.findParameter("enable-php");
            //if its null try to read directly
            if (enablePhp == null) {
                File webxml = new File(webappContextDir + "/WEB-INF/", "web.xml");
                if (webxml.exists() && webxml.canRead()) {
                    try {
                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
                        Document doc = docBuilder.parse(webxml);
                        // normalize text representation
                        doc.getDocumentElement().normalize();
                        log.trace("Root element of the doc is {}", doc.getDocumentElement().getNodeName());
                        NodeList listOfElements = doc.getElementsByTagName("context-param");
                        int totalElements = listOfElements.getLength();
                        log.trace("Total no of elements: {}", totalElements);
                        for (int s = 0; s < totalElements; s++) {
                            Node fstNode = listOfElements.item(s);
                            if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
                                Element fstElmnt = (Element) fstNode;
                                NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("param-name");
                                Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
                                NodeList fstNm = fstNmElmnt.getChildNodes();
                                String pName = (fstNm.item(0)).getNodeValue();
                                log.trace("Param name: {}", pName);
                                if ("enable-php".equals(pName)) {
                                    NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("param-value");
                                    Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
                                    NodeList lstNm = lstNmElmnt.getChildNodes();
                                    String pValue = (lstNm.item(0)).getNodeValue();
                                    log.trace("Param value: {}", pValue);
                                    enablePhp = pValue;
                                    //
                                    break;
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.warn("Error reading web.xml", e);
                    }
                }
                webxml = null;
            }
            log.debug("Enable php: {}", enablePhp);
            if ("true".equals(enablePhp)) {
                log.info("Adding PHP (Quercus) servlet for context: {}", ctx.getName());
                // add servlet wrapper
                StandardWrapper wrapper = (StandardWrapper) ctx.createWrapper();
                wrapper.setServletName("QuercusServlet");
                wrapper.setServletClass("com.caucho.quercus.servlet.QuercusServlet");
                log.debug("Wrapper: {}", wrapper);
                ctx.addChild(wrapper);
                // add servlet mappings
                ctx.addServletMapping("*.php", "QuercusServlet");
            }

            webappContextDir = null;
        }
    }
    appDirBase = null;
    dirs = null;

    // Dump context list
    if (log.isDebugEnabled()) {
        for (Container cont : host.findChildren()) {
            log.debug("Context child name: {}", cont.getName());
        }
    }

    // Set a realm
    if (realm == null) {
        realm = new MemoryRealm();
    }
    embedded.setRealm(realm);

    // use Tomcat jndi or not
    if (System.getProperty("catalina.useNaming") != null) {
        embedded.setUseNaming(Boolean.valueOf(System.getProperty("catalina.useNaming")));
    }

    // add the valves to the host
    for (Valve valve : valves) {
        log.debug("Adding host valve: {}", valve);
        ((StandardHost) host).addValve(valve);
    }

    // baseHost = embedded.createHost(hostName, appRoot);
    engine.addChild(host);

    // add any additional hosts
    if (hosts != null && !hosts.isEmpty()) {
        // grab current contexts from base host
        Container[] currentContexts = host.findChildren();
        log.info("Adding {} additional hosts", hosts.size());
        for (Host h : hosts) {
            log.debug("Host - name: {} appBase: {} info: {}",
                    new Object[] { h.getName(), h.getAppBase(), h.getInfo() });
            //add the contexts to each host
            for (Container cont : currentContexts) {
                Context c = (Context) cont;
                addContext(c.getPath(), c.getDocBase(), h);
            }
            //add the host to the engine
            engine.addChild(h);
        }
    }

    // Add new Engine to set of Engine for embedded server
    embedded.addEngine(engine);

    // set connection properties
    for (String key : connectionProperties.keySet()) {
        log.debug("Setting connection property: {} = {}", key, connectionProperties.get(key));
        if (connectors == null || connectors.isEmpty()) {
            connector.setProperty(key, connectionProperties.get(key));
        } else {
            for (Connector ctr : connectors) {
                ctr.setProperty(key, connectionProperties.get(key));
            }
        }
    }

    // set the bind address
    if (address == null) {
        //bind locally
        address = InetSocketAddress.createUnresolved("127.0.0.1", connector.getPort()).getAddress();
    }
    // apply the bind address
    ProtocolHandler handler = connector.getProtocolHandler();
    if (handler instanceof Http11Protocol) {
        ((Http11Protocol) handler).setAddress(address);
    } else if (handler instanceof Http11NioProtocol) {
        ((Http11NioProtocol) handler).setAddress(address);
    } else {
        log.warn("Unknown handler type: {}", handler.getClass().getName());
    }

    // Start server
    try {
        // Add new Connector to set of Connectors for embedded server,
        // associated with Engine
        if (connectors == null || connectors.isEmpty()) {
            embedded.addConnector(connector);
            log.trace("Connector oName: {}", connector.getObjectName());
        } else {
            for (Connector ctr : connectors) {
                embedded.addConnector(ctr);
                log.trace("Connector oName: {}", ctr.getObjectName());
            }
        }

        log.info("Starting Tomcat servlet engine");
        embedded.start();

        LoaderBase.setApplicationLoader(new TomcatApplicationLoader(embedded, host, applicationContext));

        for (Container cont : host.findChildren()) {
            if (cont instanceof StandardContext) {
                StandardContext ctx = (StandardContext) cont;

                final ServletContext servletContext = ctx.getServletContext();
                log.debug("Context initialized: {}", servletContext.getContextPath());

                //set the hosts id
                servletContext.setAttribute("red5.host.id", getHostId());

                String prefix = servletContext.getRealPath("/");
                log.debug("Path: {}", prefix);

                try {
                    if (ctx.resourcesStart()) {
                        log.debug("Resources started");
                    }

                    log.debug("Context - available: {} privileged: {}, start time: {}, reloadable: {}",
                            new Object[] { ctx.getAvailable(), ctx.getPrivileged(), ctx.getStartTime(),
                                    ctx.getReloadable() });

                    Loader cldr = ctx.getLoader();
                    log.debug("Loader delegate: {} type: {}", cldr.getDelegate(), cldr.getClass().getName());
                    if (cldr instanceof WebappLoader) {
                        log.debug("WebappLoader class path: {}", ((WebappLoader) cldr).getClasspath());
                    }
                    final ClassLoader webClassLoader = cldr.getClassLoader();
                    log.debug("Webapp classloader: {}", webClassLoader);

                    // get the (spring) config file path
                    final String contextConfigLocation = servletContext.getInitParameter(
                            org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null
                                    ? defaultSpringConfigLocation
                                    : servletContext.getInitParameter(
                                            org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM);
                    log.debug("Spring context config location: {}", contextConfigLocation);

                    // get the (spring) parent context key
                    final String parentContextKey = servletContext.getInitParameter(
                            org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null
                                    ? defaultParentContextKey
                                    : servletContext.getInitParameter(
                                            org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM);
                    log.debug("Spring parent context key: {}", parentContextKey);

                    //set current threads classloader to the webapp classloader
                    Thread.currentThread().setContextClassLoader(webClassLoader);

                    //create a thread to speed-up application loading
                    Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) {
                        public void run() {
                            //set thread context classloader to web classloader
                            Thread.currentThread().setContextClassLoader(webClassLoader);
                            //get the web app's parent context
                            ApplicationContext parentContext = null;
                            if (applicationContext.containsBean(parentContextKey)) {
                                parentContext = (ApplicationContext) applicationContext
                                        .getBean(parentContextKey);
                            } else {
                                log.warn("Parent context was not found: {}", parentContextKey);
                            }
                            // create a spring web application context
                            final String contextClass = servletContext.getInitParameter(
                                    org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null
                                            ? XmlWebApplicationContext.class.getName()
                                            : servletContext.getInitParameter(
                                                    org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM);
                            //web app context (spring)
                            ConfigurableWebApplicationContext appctx = null;
                            try {
                                Class<?> clazz = Class.forName(contextClass, true, webClassLoader);
                                appctx = (ConfigurableWebApplicationContext) clazz.newInstance();
                            } catch (Throwable e) {
                                throw new RuntimeException("Failed to load webapplication context class.", e);
                            }
                            appctx.setConfigLocations(new String[] { contextConfigLocation });
                            appctx.setServletContext(servletContext);
                            //set parent context or use current app context
                            if (parentContext != null) {
                                appctx.setParent(parentContext);
                            } else {
                                appctx.setParent(applicationContext);
                            }
                            // set the root webapp ctx attr on the each servlet context so spring can find it later
                            servletContext.setAttribute(
                                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
                            //refresh the factory
                            log.trace("Classloader prior to refresh: {}", appctx.getClassLoader());
                            appctx.refresh();
                            if (log.isDebugEnabled()) {
                                log.debug("Red5 app is active: {} running: {}", appctx.isActive(),
                                        appctx.isRunning());
                            }
                        }
                    };
                    thread.setDaemon(true);
                    thread.start();

                } catch (Throwable t) {
                    log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(),
                            t.getMessage());
                    t.printStackTrace();
                } finally {
                    //reset the classloader
                    Thread.currentThread().setContextClassLoader(originalClassLoader);
                }
            }
        }

        // if everything is ok at this point then call the rtmpt and rtmps
        // beans so they will init
        if (applicationContext.containsBean("red5.core")) {
            ApplicationContext core = (ApplicationContext) applicationContext.getBean("red5.core");
            if (core.containsBean("rtmpt.server")) {
                log.debug("Initializing RTMPT");
                core.getBean("rtmpt.server");
                log.debug("Finished initializing RTMPT");
            } else {
                log.info("Dedicated RTMPT server configuration was not specified");
            }
            if (core.containsBean("rtmps.server")) {
                log.debug("Initializing RTMPS");
                core.getBean("rtmps.server");
                log.debug("Finished initializing RTMPS");
            } else {
                log.info("Dedicated RTMPS server configuration was not specified");
            }
        } else {
            log.info("Core context was not found");
        }
    } catch (Exception e) {
        if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) {
            log.error(
                    "Error loading tomcat, unable to bind connector. You may not have permission to use the selected port",
                    e);
        } else {
            log.error("Error loading tomcat", e);
        }
    } finally {
        registerJMX();
    }

}

From source file:org.devproof.portal.test.MockContextLoader.java

@Override
public ConfigurableApplicationContext loadContext(String... locations) throws Exception {
    registerResource(CommonConstants.JNDI_MAIL_SESSION, Session.getDefaultInstance(new Properties()));
    registerResource(CommonConstants.JNDI_PROP_EMAIL_DISABLED, "true");
    registerResource(CommonConstants.JNDI_PROP_HIBERNATE_DIALECT, "org.hibernate.dialect.H2Dialect");
    registerResource(CommonConstants.JNDI_PROP_HIBERNATE_SECOND_LEVEL_CACHE, "false");
    registerResource(CommonConstants.JNDI_PROP_HIBERNATE_QUERY_CACHE, "false");
    ConfigurableWebApplicationContext context = new XmlWebApplicationContext();
    MockServletContext servletContext = new MockServletContext("") {
        @Override/* w w  w. j a v a  2 s  .  c om*/
        public String getRealPath(String arg0) {
            return System.getProperty("java.io.tmpdir");
        }
    };
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
    context.setServletContext(servletContext);
    String[] configLocations = PortalContextLoaderListener.locateConfigLocations(locations);
    context.setConfigLocations(configLocations);
    context.refresh();
    context.registerShutdownHook();
    return context;
}

From source file:org.impalaframework.web.spring.loader.BaseImpalaContextLoader.java

/**
 * Creates the <code>WebApplicationContext</code> by bootstrapping Impala, retrieving the <code>ModuleDefinitionSource</code>
 * for loading the module metadata. It then instantiates the application context and returns it for further processing by
 * <code>ContextLoader</code>.
 *//*from  w  w w.j  a va2  s  . c o m*/
@Override
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext,
        ApplicationContext parent) throws BeansException {

    final WebApplicationContext newContext;

    //this method is supported for 3.1 and above
    Method configurableMethod = ReflectionUtils.findMethod(super.getClass(),
            "configureAndRefreshWebApplicationContext",
            new Class[] { ConfigurableWebApplicationContext.class, ServletContext.class });

    if (configurableMethod != null) {

        newContext = super.createWebApplicationContext(servletContext);

        //use the configure method to do configuration on the web application context
        if (newContext instanceof ConfigurableWebApplicationContext) {

            ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) newContext;
            if (configurableMethod != null) {

                ReflectionUtils.invokeMethod(configurableMethod, this, new Object[] { parent, servletContext });
            }

            wac.setParent(parent);
            wac.setServletContext(servletContext);
        }

    } else {

        //for 3.0 and below
        newContext = legacyCreateContext(servletContext, parent);
    }

    return newContext;
}

From source file:org.pentaho.platform.web.servlet.JAXRSServlet.java

protected ApplicationContext getAppContext() {

    ConfigurableWebApplicationContext wac = new XmlWebApplicationContext() {
        @Override/*www .j  a  v  a 2  s .  co  m*/
        protected Resource getResourceByPath(String path) {
            return new FileSystemResource(new File(path));
        }
    };

    wac.setServletContext(getServletContext());
    wac.setServletConfig(getServletConfig());
    wac.setNamespace(getServletName());
    String springFile = PentahoSystem.getApplicationContext()
            .getSolutionPath("system" + File.separator + "pentahoServices.spring.xml"); //$NON-NLS-1$ //$NON-NLS-2$
    wac.setConfigLocations(new String[] { springFile });
    wac.refresh();

    return wac;
}

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

/**
 * Main entry point for the Red5 Server as a war
 *///from  w ww .  j  ava2s  .  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.springframework.web.context.ContextLoader.java

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac,
        ServletContext sc) {//ww  w  .j  a v a  2s. co m
    if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
        // The application context id is still set to its original default value
        // -> assign a more useful id based on available information
        String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
        if (idParam != null) {
            wac.setId(idParam);
        } else {
            // Generate default id...
            wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX
                    + ObjectUtils.getDisplayString(sc.getContextPath()));
        }
    }

    wac.setServletContext(sc);
    String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
    if (configLocationParam != null) {
        wac.setConfigLocation(configLocationParam);
    }

    // The wac environment's #initPropertySources will be called in any case when the context
    // is refreshed; do it eagerly here to ensure servlet property sources are in place for
    // use in any post-processing or initialization that occurs below prior to #refresh
    ConfigurableEnvironment env = wac.getEnvironment();
    if (env instanceof ConfigurableWebEnvironment) {
        ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
    }

    customizeContext(sc, wac);
    wac.refresh();
}

From source file:org.springframework.web.struts.ContextLoaderPlugIn.java

/**
 * Instantiate the WebApplicationContext for the ActionServlet, either a default
 * XmlWebApplicationContext or a custom context class if set. This implementation
 * expects custom contexts to implement ConfigurableWebApplicationContext.
 * Can be overridden in subclasses.// www .jav  a2s  . com
 * @throws org.springframework.beans.BeansException if the context couldn't be initialized
 * @see #setContextClass
 * @see org.springframework.web.context.support.XmlWebApplicationContext
 */
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent)
        throws BeansException {

    if (logger.isDebugEnabled()) {
        logger.debug("ContextLoaderPlugIn for Struts ActionServlet '" + getServletName() + "', module '"
                + getModulePrefix() + "' will try to create custom WebApplicationContext "
                + "context of class '" + getContextClass().getName() + "', using parent context [" + parent
                + "]");
    }
    if (!ConfigurableWebApplicationContext.class.isAssignableFrom(getContextClass())) {
        throw new ApplicationContextException(
                "Fatal initialization error in ContextLoaderPlugIn for Struts ActionServlet '"
                        + getServletName() + "', module '" + getModulePrefix()
                        + "': custom WebApplicationContext class [" + getContextClass().getName()
                        + "] is not of type ConfigurableWebApplicationContext");
    }

    ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils
            .instantiateClass(getContextClass());
    wac.setParent(parent);
    wac.setServletContext(getServletContext());
    wac.setNamespace(getNamespace());
    if (getContextConfigLocation() != null) {
        wac.setConfigLocations(StringUtils.tokenizeToStringArray(getContextConfigLocation(),
                ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS));
    }
    wac.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            beanFactory.addBeanPostProcessor(new ActionServletAwareProcessor(getActionServlet()));
        }
    });
    wac.refresh();
    return wac;
}