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

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

Introduction

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

Prototype

void setConfigLocations(String... configLocations);

Source Link

Document

Set the config locations for this web application context.

Usage

From source file:nl.tue.gale.ae.config.GaleContextLoader.java

@Override
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext ac) {
    super.customizeContext(sc, ac);
    ArrayList<String> locations = new ArrayList<String>();
    locations.addAll(Arrays.asList(ac.getConfigLocations()));
    findLocations(sc, locations);/* ww  w .j av a 2s.c  om*/
    ac.setConfigLocations(locations.toArray(new String[] {}));
}

From source file:com.bstek.dorado.web.servlet.SpringContextLoaderListener.java

@Override
protected void customizeContext(ServletContext servletContext,
        ConfigurableWebApplicationContext applicationContext) {
    try {/*from  ww  w  .j  av  a2  s . co  m*/
        doradoLoader.preload(servletContext, true);
        List<String> doradoContextLocations = doradoLoader.getContextLocations(false);
        String[] realResourcesPath = doradoLoader.getRealResourcesPath(doradoContextLocations);
        applicationContext.setConfigLocations(realResourcesPath);
    } catch (Exception e) {
        logger.error(e, e);
    }
}

From source file:com.workingmouse.webservice.axis.SpringAxisServlet.java

/**
 * Instantiate the WebApplicationContext for the SpringAxisServlet, either a default
 * XmlWebApplicationContext or a custom context class if set. This implementation
 * expects custom contexts to implement ConfigurableWebApplicationContext.
 * Can be overridden in subclasses./* w ww .  j  av a2  s  . co  m*/
 *
 * @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 (LOG.isDebugEnabled()) {
        LOG.debug("Servlet with name '" + getServletName()
                + "' 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 servlet with name '"
                + getServletName() + "': custom WebApplicationContext class [" + getContextClass().getName()
                + "] is not of type ConfigurableWebApplicationContext");
    }

    ConfigurableWebApplicationContext wac = createContextInstance();
    wac.setParent(parent);
    wac.setServletContext(getServletContext());
    wac.setNamespace(getNamespace());

    if (this.contextConfigLocation != null) {
        wac.setConfigLocations(StringUtils.tokenizeToStringArray(this.contextConfigLocation,
                ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS, true, true));
    }
    wac.refresh();
    return wac;
}

From source file:net.sf.sail.webapp.spring.impl.CustomContextLoader.java

/**
 * The behaviour of this method is the same as the superclass except for
 * setting of the config locations.//from w ww .  ja v a 2s  .  c  om
 * 
 * @throws ClassNotFoundException
 * 
 * @see org.springframework.web.context.ContextLoader#createWebApplicationContext(javax.servlet.ServletContext,
 *      org.springframework.context.ApplicationContext)
 */
@Override
protected WebApplicationContext createWebApplicationContext(ServletContext servletContext,
        ApplicationContext parent) throws BeansException {

    Class<?> contextClass = determineContextClass(servletContext);
    if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
        throw new ApplicationContextException("Custom context class [" + contextClass.getName()
                + "] is not of type ConfigurableWebApplicationContext");
    }

    ConfigurableWebApplicationContext webApplicationContext = (ConfigurableWebApplicationContext) BeanUtils
            .instantiateClass(contextClass);
    webApplicationContext.setParent(parent);
    webApplicationContext.setServletContext(servletContext);

    String configClass = servletContext.getInitParameter(CONFIG_CLASS_PARAM);
    if (configClass != null) {
        try {
            SpringConfiguration springConfig = (SpringConfiguration) BeanUtils
                    .instantiateClass(Class.forName(configClass));
            webApplicationContext.setConfigLocations(springConfig.getRootApplicationContextConfigLocations());
        } catch (ClassNotFoundException e) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(CONFIG_CLASS_PARAM + " <" + configClass + "> not found.", e);
            }
            throw new InvalidParameterException("ClassNotFoundException: " + configClass);
        }
    } else {
        throw new InvalidParameterException("No value defined for the required: " + CONFIG_CLASS_PARAM);
    }

    webApplicationContext.refresh();
    return webApplicationContext;
}

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

/**
 * Initialization./*from www  .  ja  va2 s  .  c  o  m*/
 */
@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./*from w w w. java 2 s . co m*/
 */
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:org.red5.server.tomcat.TomcatLoader.java

/**
 * Initialization.//from w ww  .j a va  2s .  co 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  ww  .j  a  v  a 2 s  . co m
        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.openlegacy.web.OpenLegacyDispatcherServlet.java

@Override
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
    PluginsRegistry pluginsRegistry = DefaultPluginsLoader.create().load().getPluginsRegistry();

    if (!pluginsRegistry.isEmpty()) {
        List<String> locations = new LinkedList<String>(Arrays.asList(wac.getConfigLocations()));
        locations.addAll(pluginsRegistry.getSpringWebContextResources());
        wac.setConfigLocations(locations.toArray(new String[] {}));
        if (logger.isDebugEnabled()) {
            logger.debug("Modified config locations of web application context");
        }//from ww  w  . j a  v a  2  s .co m
    }

    super.configureAndRefreshWebApplicationContext(wac);
}