List of usage examples for org.springframework.web.context ConfigurableWebApplicationContext isActive
boolean isActive();
From source file:org.springsource.sinspctr.InspctrServer.java
public InspctrServer(ConfigurableWebApplicationContext webApplicationContext, int port) { Assert.notNull(webApplicationContext, "context must not be null"); Assert.isTrue(!webApplicationContext.isActive(), "context must not have been started"); this.webApplicationContext = webApplicationContext; this.port = port; }
From source file:org.red5.server.winstone.WinstoneApplicationContext.java
public void stop() { log.debug("stop"); try {//from w w w. ja v a 2s .c o m Object o = context.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (o != null) { log.debug("Spring context for {} was found", context.getContextName()); ConfigurableWebApplicationContext appCtx = (ConfigurableWebApplicationContext) o; //close the red5 app if (appCtx.isRunning()) { log.debug("Context was running, attempting to stop"); appCtx.stop(); } if (appCtx.isActive()) { log.debug("Context is active, attempting to close"); appCtx.close(); } } else { log.warn("Spring context for {} was not found", context.getContextName()); } } catch (Exception e) { log.error("Could not stop spring context", e); } context.destroy(); }
From source file:org.red5.server.undertow.UndertowApplicationContext.java
/** * Stop the application and servlet contexts. *//* www . j a v a 2s. co m*/ public void stop() { log.debug("stop"); try { Deployment deployment = manager.getDeployment(); ServletContextImpl servlet = deployment.getServletContext(); Object o = servlet.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (o != null) { log.debug("Spring context for {} was found", deployment.getDeploymentInfo().getContextPath()); ConfigurableWebApplicationContext appCtx = (ConfigurableWebApplicationContext) o; // close the red5 app if (appCtx.isRunning()) { log.debug("Context was running, attempting to stop"); appCtx.stop(); } if (appCtx.isActive()) { log.debug("Context is active, attempting to close"); appCtx.close(); } } else { log.warn("Spring context for {} was not found", deployment.getDeploymentInfo().getContextPath()); } } catch (Exception e) { log.error("Could not stop spring context", e); } manager.undeploy(); }
From source file:org.red5.server.tomcat.TomcatApplicationContext.java
public void stop() { log.debug("stop"); try {// w w w .j a v a 2s .c o m ServletContext servlet = context.getServletContext(); Object o = servlet.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (o != null) { log.debug("Spring context for {} was found", context.getName()); ConfigurableWebApplicationContext appCtx = (ConfigurableWebApplicationContext) o; //close the red5 app if (appCtx.isRunning()) { log.debug("Context was running, attempting to stop"); appCtx.stop(); } if (appCtx.isActive()) { log.debug("Context is active, attempting to close"); appCtx.close(); } } else { log.warn("Spring context for {} was not found", context.getName()); } } catch (Exception e) { log.error("Could not stop spring context", e); } context.getParent().removeChild(context); if (context instanceof StandardContext) { StandardContext ctx = (StandardContext) context; try { //stop the tomcat context ctx.stop(); } catch (Exception e) { log.error("Could not stop context", e); } finally { try { ctx.destroy(); } catch (Exception e) { log.error("Could not destroy context", e); } } } }
From source file:com.dhcc.framework.web.context.DhccContextLoader.java
/** * Initialize Spring's web application context for the given servlet context, * using the application context provided at construction time, or creating a new one * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params. * @param servletContext current servlet context * @return the new WebApplicationContext * @see #ContextLoader(WebApplicationContext) * @see #CONTEXT_CLASS_PARAM// ww w . ja v a2s .com * @see #CONFIG_LOCATION_PARAM */ public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { throw new IllegalStateException( "Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader* definitions in your web.xml!"); } Log logger = LogFactory.getLog(DhccContextLoader.class); servletContext.log("Initializing Spring root WebApplicationContext"); if (logger.isInfoEnabled()) { logger.info("Root WebApplicationContext: initialization started"); } long startTime = System.currentTimeMillis(); try { // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. if (this.context == null) { this.context = createWebApplicationContext(servletContext); } if (this.context instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; if (!cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> // determine parent for root web application context, if any. ApplicationContext parent = loadParentContext(servletContext); cwac.setParent(parent); } configureAndRefreshWebApplicationContext(cwac, servletContext); } } servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl == DhccContextLoader.class.getClassLoader()) { currentContext = this.context; } else if (ccl != null) { currentContextPerThread.put(ccl, this.context); } if (logger.isDebugEnabled()) { logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } return this.context; } catch (RuntimeException ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } catch (Error err) { logger.error("Context initialization failed", err); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); throw err; } }
From source file:org.red5.server.winstone.WinstoneLoader.java
/** * Initialization.//from w ww . j a v a2 s .com */ @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./* ww w. j a va 2s . c om*/ */ 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 ww w . j a va 2s.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.springframework.web.context.ContextLoader.java
/** * Initialize Spring's web application context for the given servlet context, * using the application context provided at construction time, or creating a new one * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params. * @param servletContext current servlet context * @return the new WebApplicationContext * @see #ContextLoader(WebApplicationContext) * @see #CONTEXT_CLASS_PARAM/*from w w w . ja v a2 s .c om*/ * @see #CONFIG_LOCATION_PARAM */ public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { throw new IllegalStateException( "Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader* definitions in your web.xml!"); } Log logger = LogFactory.getLog(ContextLoader.class); servletContext.log("Initializing Spring root WebApplicationContext"); if (logger.isInfoEnabled()) { logger.info("Root WebApplicationContext: initialization started"); } long startTime = System.currentTimeMillis(); try { // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. if (this.context == null) { this.context = createWebApplicationContext(servletContext); } if (this.context instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; if (!cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> // determine parent for root web application context, if any. ApplicationContext parent = loadParentContext(servletContext); cwac.setParent(parent); } configureAndRefreshWebApplicationContext(cwac, servletContext); } } servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl == ContextLoader.class.getClassLoader()) { currentContext = this.context; } else if (ccl != null) { currentContextPerThread.put(ccl, this.context); } if (logger.isDebugEnabled()) { logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } return this.context; } catch (RuntimeException ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } catch (Error err) { logger.error("Context initialization failed", err); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); throw err; } }
From source file:org.springframework.xd.dirt.stream.StreamServer.java
public StreamServer(ConfigurableWebApplicationContext webApplicationContext, int port) { Assert.notNull(webApplicationContext, "context must not be null"); Assert.isTrue(!webApplicationContext.isActive(), "context must not have been started"); this.webApplicationContext = webApplicationContext; this.port = port; }