List of usage examples for org.springframework.web.context WebApplicationContext ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
To view the source code for org.springframework.web.context WebApplicationContext ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE.
Click Source Link
From source file:org.red5.server.winstone.WinstoneLoader.java
/** * Initialization./*from w w w . j a va 2 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.atomserver.utils.test.TestingAtomServer.java
private Server createServer(int port, String atomserverServletContext) { // set up the server and the atomserver web application context Server server = new Server(port); Context context = new Context(server, "/" + atomserverServletContext, true /*sessions*/, false /*no security*/); // we need to hard-code certain system properties to get the behavior we want here - we // will re-set them when we're done Properties properties = (Properties) System.getProperties().clone(); System.setProperty("atomserver.env", "asdev-hsql-mem"); System.setProperty("atomserver.servlet.context", atomserverServletContext); // TODO: this should be removed System.setProperty("atomserver.servlet.mapping", "v1"); // our Spring application context will start off by loading the basic built-in bean // definitions appContext = new GenericWebApplicationContext(); XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(appContext); xmlReader.loadBeanDefinitions(new ClassPathResource("org/atomserver/spring/propertyConfigurerBeans.xml")); xmlReader.loadBeanDefinitions(new ClassPathResource("org/atomserver/spring/databaseBeans.xml")); xmlReader.loadBeanDefinitions(new ClassPathResource("org/atomserver/spring/logBeans.xml")); xmlReader.loadBeanDefinitions(new ClassPathResource("org/atomserver/spring/storageBeans.xml")); xmlReader.loadBeanDefinitions(new ClassPathResource("org/atomserver/spring/abderaBeans.xml")); // if we were given a Spring config location, we use that -- otherwise we configure the // workspaces that were set up through the API if (springBeansLocation != null) { xmlReader.loadBeanDefinitions(new ClassPathResource(springBeansLocation)); } else {/* w ww. ja v a2s . c o m*/ RootBeanDefinition workspaces = new RootBeanDefinition(HashSet.class); ConstructorArgumentValues constructorArgumentValues = new ConstructorArgumentValues(); constructorArgumentValues.addGenericArgumentValue(workspaceSet); workspaces.setConstructorArgumentValues(constructorArgumentValues); appContext.registerBeanDefinition("org.atomserver-workspaces", workspaces); } // override the base content storage to use DB-based storage RootBeanDefinition storage = new RootBeanDefinition(DBBasedContentStorage.class); MutablePropertyValues propertyValues = new MutablePropertyValues(); propertyValues.addPropertyValue("contentDAO", new RuntimeBeanReference("org.atomserver-contentDAO")); propertyValues.addPropertyValue("entriesDAO", new RuntimeBeanReference("org.atomserver-entriesDAO")); storage.setPropertyValues(propertyValues); appContext.registerBeanDefinition("org.atomserver-contentStorage", storage); // clear the existing ENV ConfigurationAwareClassLoader.invalidateENV(); // refresh the context to actually instantiate everything. appContext.refresh(); // re-set the system properties System.setProperties(properties); // clear the update ENV ConfigurationAwareClassLoader.invalidateENV(); // put our app context into the servlet context context.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appContext); // load and init the service context for v1 final ServiceContext serviceContext = (ServiceContext) appContext.getBean(ServiceContext.class.getName()); serviceContext.init(new Abdera(), Collections.EMPTY_MAP); // create a new AtomServerServlet - but override the createServiceContext method AtomServerServlet servlet = new AtomServerServlet() { protected ServiceContext createServiceContext() { return serviceContext; } }; // load and init the service context for v2 final ServiceContext serviceContextV2 = (ServiceContext) appContext .getBean("org.atomserver-serviceContext.v2"); serviceContextV2.init(new Abdera(), Collections.EMPTY_MAP); // create a new AtomServerServlet - but override the createServiceContext method AtomServerServlet servletV2 = new AtomServerServlet() { protected ServiceContext createServiceContext() { return serviceContextV2; } }; // register the servlets context.addServlet(new ServletHolder(servlet), "/v1/*"); context.addServlet(new ServletHolder(servletV2), "/v2/*"); EntriesDAOiBatisImpl entriesDAO = (EntriesDAOiBatisImpl) appContext.getBean("org.atomserver-entriesDAO"); entriesDAO.setUseWorkspaceCollectionCache(false); // ready to be started return server; }
From source file:com.thoughtworks.go.server.web.UrlRewriterIntegrationTest.java
@BeforeClass public static void beforeClass() throws Exception { ServletHelper.init();/*from ww w . j av a 2 s . c o m*/ httpUtil = new HttpTestUtil(new HttpTestUtil.ContextCustomizer() { public void customize(WebAppContext ctx) throws Exception { wac = mock(WebApplicationContext.class); ctx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); URL resource = getClass().getClassLoader().getResource("WEB-INF/urlrewrite.xml"); if (resource == null) { throw new RuntimeException("Cannot load WEB-INF/urlrewrite.xml"); } ctx.setBaseResource(Resource.newResource(new File(resource.getFile()).getParent())); ctx.addFilter(UrlRewriteFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST)) .setInitParameter("confPath", "/urlrewrite.xml"); ctx.addServlet(HttpTestUtil.EchoServlet.class, "/*"); } }); httpUtil.httpConnector(HTTP); httpUtil.httpsConnector(HTTPS); when(wac.getBean("serverConfigService")).thenReturn(new BaseUrlProvider() { public boolean hasAnyUrlConfigured() { return useConfiguredUrls; } public String siteUrlFor(String url, boolean forceSsl) throws URISyntaxException { ServerSiteUrlConfig siteUrl = forceSsl ? new ServerSiteUrlConfig(HTTPS_SITE_URL) : new ServerSiteUrlConfig(HTTP_SITE_URL); return siteUrl.siteUrlFor(url); } }); httpUtil.start(); originalSslPort = System.getProperty(SystemEnvironment.CRUISE_SERVER_SSL_PORT); System.setProperty(SystemEnvironment.CRUISE_SERVER_SSL_PORT, String.valueOf(HTTPS)); FeatureToggleService featureToggleService = mock(FeatureToggleService.class); when(featureToggleService.isToggleOn(anyString())).thenReturn(true); Toggles.initializeWith(featureToggleService); }
From source file:org.intalio.tempo.web.AlfrescoFacesPortlet.java
/** * @see org.apache.myfaces.portlet.MyFacesGenericPortlet#facesRender(javax.portlet.RenderRequest, * javax.portlet.RenderResponse)//from w w w.jav a 2 s .com */ protected void facesRender(RenderRequest request, RenderResponse response) throws PortletException, IOException { try { User user = (User) request.getPortletSession().getAttribute(AuthenticationHelper.AUTHENTICATION_USER); if (user == null) { Method getHttpServletRequest = request.getClass().getMethod("getHttpServletRequest"); HttpServletRequest hsr = (HttpServletRequest) getHttpServletRequest.invoke(request); Long userID = (Long) hsr.getSession().getAttribute("USER_ID"); com.liferay.portal.model.User liferayUser = UserServiceUtil.getUserById(userID); String userName = liferayUser.getScreenName(); logger.debug("user name for alfresco is:" + userName); getPortletContext().removeAttribute("loggedin"); setAuthenticatedUser(request, userName); } else { logger.debug("User got from portlet session is: " + user.getUserName()); } } catch (Throwable e) { // do nothing } Application.setInPortalServer(true); // Set the current locale I18NUtil.setLocale(Application.getLanguage(request.getPortletSession())); if (request.getParameter(ERROR_OCCURRED) != null) { String errorPage = Application.getErrorPage(getPortletContext()); if (logger.isDebugEnabled()) logger.debug("An error has occurred, redirecting to error page: " + errorPage); response.setContentType("text/html"); PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher(errorPage); dispatcher.include(request, response); } else { WebApplicationContext ctx = (WebApplicationContext) getPortletContext() .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); AuthenticationService auth = (AuthenticationService) ctx.getBean("AuthenticationService"); // if we have no User object in the session then an HTTP Session // timeout must have occured // use the viewId to check that we are not already on the login page PortletSession session = request.getPortletSession(); String viewId = request.getParameter(VIEW_ID); logger.debug("View ID is:" + viewId); // keep track of last view id so we can use it as return page from // multi-part requests request.getPortletSession().setAttribute(SESSION_LAST_VIEW_ID, viewId); User user = (User) request.getPortletSession().getAttribute(AuthenticationHelper.AUTHENTICATION_USER); if (user == null && (viewId == null || viewId.equals(getLoginPage()) == false)) { if (AuthenticationHelper.portalGuestAuthenticate(ctx, session, auth) == AuthenticationStatus.Guest) { if (logger.isDebugEnabled()) logger.debug("Guest access successful."); // perform the forward to the page processed by the Faces // servlet response.setContentType("text/html"); request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true"); // get the start location as configured by the web-client // config ConfigService configService = (ConfigService) ctx.getBean("webClientConfigService"); ClientConfigElement configElement = (ClientConfigElement) configService.getGlobalConfig() .getConfigElement("client"); if (NavigationBean.LOCATION_MYALFRESCO.equals(configElement.getInitialLocation())) { nonFacesRequest(request, response, "/jsp/dashboards/container.jsp"); } else { nonFacesRequest(request, response, "/jsp/browse/browse.jsp"); } } else { if (logger.isDebugEnabled()) logger.debug("No valid User login, requesting login page. ViewId: " + viewId); // set last used username as special session value used by // the LoginBean session.setAttribute(AuthenticationHelper.SESSION_USERNAME, request.getPreferences().getValue(PREF_ALF_USERNAME, null)); // login page is the default portal page response.setContentType("text/html"); request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true"); nonFacesRequest(request, response); } } else { if (session.getAttribute(AuthenticationHelper.SESSION_INVALIDATED) != null) { // remove the username preference value as explicit logout // was requested by the user if (request.getPreferences().isReadOnly(PREF_ALF_USERNAME) == false) { request.getPreferences().reset(PREF_ALF_USERNAME); } session.removeAttribute(AuthenticationHelper.SESSION_INVALIDATED); } try { if (user != null) { if (logger.isDebugEnabled()) logger.debug("Validating ticket: " + user.getTicket()); // setup the authentication context auth.validate(user.getTicket()); } // do the normal JSF processing String loggedin = (String) getPortletContext().getAttribute("loggedin"); logger.debug("logged in?:" + loggedin); if (loggedin != null && loggedin.equalsIgnoreCase("true") && viewId != null) { super.facesRender(request, response); } else { getPortletContext().setAttribute("loggedin", "true"); response.setContentType("text/html"); request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true"); nonFacesRequest(request, response, "/jsp/browse/browse.jsp"); } } catch (AuthenticationException authErr) { // ticket is no longer valid! if (logger.isDebugEnabled()) logger.debug("Invalid ticket, requesting login page."); // remove User object as it's now useless request.getPortletSession().removeAttribute(AuthenticationHelper.AUTHENTICATION_USER); // login page is the default portal page response.setContentType("text/html"); request.getPortletSession().setAttribute(PortletUtil.PORTLET_REQUEST_FLAG, "true"); nonFacesRequest(request, response); } catch (Throwable e) { if (getErrorPage() != null) { handleError(request, response, e); } else { logger.warn("No error page configured, re-throwing exception"); if (e instanceof PortletException) { throw (PortletException) e; } else if (e instanceof IOException) { throw (IOException) e; } else { throw new PortletException(e); } } } } } }
From source file:org.red5.server.undertow.UndertowLoader.java
/** * Initialization.// ww w. j a va 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: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//from w w w. j a v a 2s. 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(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.tomcat.TomcatVHostLoader.java
/** * Starts a web application and its red5 (spring) component. This is basically a stripped down * version of init()./* w ww. j a va 2s .c o m*/ * * @return true on success */ @SuppressWarnings("cast") public boolean startWebApplication(String applicationName) { boolean result = false; log.info("Starting Tomcat virtual host - Web application"); log.info("Virtual host root: {}", webappRoot); log.info("Virtual host context id: {}", defaultApplicationContextId); // application directory String contextName = '/' + applicationName; Container cont = null; //check if the context already exists for the host if ((cont = host.findChild(contextName)) == null) { log.debug("Context did not exist in host"); String webappContextDir = FileUtil.formatPath(webappRoot, applicationName); //prepend slash Context ctx = addContext(contextName, webappContextDir); //set the newly created context as the current container cont = ctx; } else { log.debug("Context already exists in host"); } try { ServletContext servletContext = ((Context) cont).getServletContext(); log.debug("Context initialized: {}", servletContext.getContextPath()); String prefix = servletContext.getRealPath("/"); log.debug("Path: {}", prefix); Loader cldr = cont.getLoader(); log.debug("Loader type: {}", cldr.getClass().getName()); ClassLoader webClassLoader = cldr.getClassLoader(); log.debug("Webapp classloader: {}", webClassLoader); //create a spring web application context XmlWebApplicationContext appctx = new XmlWebApplicationContext(); appctx.setClassLoader(webClassLoader); appctx.setConfigLocations(new String[] { "/WEB-INF/red5-*.xml" }); //check for red5 context bean if (applicationContext.containsBean(defaultApplicationContextId)) { appctx.setParent((ApplicationContext) applicationContext.getBean(defaultApplicationContextId)); } else { log.warn("{} bean was not found in context: {}", defaultApplicationContextId, applicationContext.getDisplayName()); //lookup context loader and attempt to get what we need from it if (applicationContext.containsBean("context.loader")) { ContextLoader contextLoader = (ContextLoader) applicationContext.getBean("context.loader"); appctx.setParent(contextLoader.getContext(defaultApplicationContextId)); } else { log.debug("Context loader was not found, trying JMX"); MBeanServer mbs = JMXFactory.getMBeanServer(); //get the ContextLoader from jmx ObjectName oName = JMXFactory.createObjectName("type", "ContextLoader"); ContextLoaderMBean proxy = null; if (mbs.isRegistered(oName)) { proxy = (ContextLoaderMBean) MBeanServerInvocationHandler.newProxyInstance(mbs, oName, ContextLoaderMBean.class, true); log.debug("Context loader was found"); appctx.setParent(proxy.getContext(defaultApplicationContextId)); } else { log.warn("Context loader was not found"); } } } if (log.isDebugEnabled()) { if (appctx.getParent() != null) { log.debug("Parent application context: {}", appctx.getParent().getDisplayName()); } } // appctx.setServletContext(servletContext); //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.refresh(); result = true; } catch (Throwable t) { log.error("Error setting up context: {}", applicationName, t); if (log.isDebugEnabled()) { t.printStackTrace(); } } return result; }
From source file:org.intalio.tempo.web.AlfrescoFacesPortlet.java
private void setAuthenticatedUser(PortletRequest req, String userName) { WebApplicationContext ctx = (WebApplicationContext) getPortletContext() .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY); TransactionService transactionService = serviceRegistry.getTransactionService(); NodeService nodeService = serviceRegistry.getNodeService(); AuthenticationComponent authComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent"); AuthenticationService authService = (AuthenticationService) ctx.getBean("authenticationService"); PersonService personService = (PersonService) ctx.getBean("personService"); // Get a list of the available locales ConfigService configServiceService = (ConfigService) ctx.getBean("webClientConfigService"); LanguagesConfigElement configElement = (LanguagesConfigElement) configServiceService.getConfig("Languages") .getConfigElement(LanguagesConfigElement.CONFIG_ELEMENT_ID); m_languages = configElement.getLanguages(); // Set up the user information UserTransaction tx = transactionService.getUserTransaction(); NodeRef homeSpaceRef = null;// w ww . ja v a2 s . c om User user; try { tx.begin(); // Set the authentication authComponent.setCurrentUser(userName); user = new User(userName, authService.getCurrentTicket(), personService.getPerson(userName)); homeSpaceRef = (NodeRef) nodeService.getProperty(personService.getPerson(userName), ContentModel.PROP_HOMEFOLDER); if (homeSpaceRef == null) { logger.warn("Home Folder is null for user '" + userName + "', using company_home."); homeSpaceRef = (NodeRef) nodeService.getRootNode(Repository.getStoreRef()); } user.setHomeSpaceId(homeSpaceRef.getId()); tx.commit(); } catch (Throwable ex) { logger.error(ex); try { tx.rollback(); } catch (Exception ex2) { logger.error("Failed to rollback transaction", ex2); } if (ex instanceof RuntimeException) { throw (RuntimeException) ex; } else { throw new RuntimeException("Failed to set authenticated user", ex); } } // Store the user req.getPortletSession().setAttribute(AuthenticationHelper.AUTHENTICATION_USER, user); req.getPortletSession().setAttribute(LoginBean.LOGIN_EXTERNAL_AUTH, Boolean.TRUE); logger.debug("...authenticated user is: " + user.getUserName() + user.getTicket()); }
From source file:org.red5.server.tomcat.TomcatLoader.java
/** * Initialization./*from w w w. j a v a 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(); } }