Java Code Examples for javax.servlet.ServletContext#log()
The following examples show how to use
javax.servlet.ServletContext#log() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ContextLoader.java From spring-analysis-note with MIT License | 6 votes |
/** * Close Spring's web application context for the given servlet context. * <p>If overriding {@link #loadParentContext(ServletContext)}, you may have * to override this method as well. * @param servletContext the ServletContext that the WebApplicationContext runs in */ public void closeWebApplicationContext(ServletContext servletContext) { servletContext.log("Closing Spring root WebApplicationContext"); try { if (this.context instanceof ConfigurableWebApplicationContext) { ((ConfigurableWebApplicationContext) this.context).close(); } } finally { ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl == ContextLoader.class.getClassLoader()) { currentContext = null; } else if (ccl != null) { currentContextPerThread.remove(ccl); } servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); } }
Example 2
Source File: InitListener.java From white-label-event-app with Apache License 2.0 | 6 votes |
@Override public void contextInitialized(ServletContextEvent sce) { final ServletContext context = sce.getServletContext(); context.log("InitListener"); ResourcesConfigStrategy configStrategy = new ResourcesConfigStrategy(); try { configStrategy.configure(); } catch (ConfigException e) { throw new RuntimeException(e); } BackendSingletons.fdb = configStrategy.getFirebaseDatabase(); BackendSingletons.eventmobiConfig = configStrategy.getEventmobiConfig(); context.log("Firebase database: " + BackendSingletons.fdb.getReference()); context.log("Eventmobi API key: " + BackendSingletons.eventmobiConfig.getApiKey()); context.log("Eventmobi event name: " + BackendSingletons.eventmobiConfig.getEventName()); }
Example 3
Source File: NavigatorUtils.java From ontopia with Apache License 2.0 | 6 votes |
/** * INTERNAL: Gets the navigator application instance belonging to * the web application. */ public final static NavigatorApplicationIF getNavigatorApplication(ServletContext servletContext) { NavigatorApplicationIF navApp = (NavigatorApplicationIF) servletContext.getAttribute(NavigatorApplicationIF.NAV_APP_KEY); // If there is no current navigator application we need to create one. if (navApp == null) { // Initialise new configuration and register it with application context navApp = new NavigatorApplication(servletContext); servletContext.setAttribute(NavigatorApplicationIF.NAV_APP_KEY, navApp); servletContext.log("Setup navigator configuration and " + "assigned it to application context."); } return navApp; }
Example 4
Source File: ContextLoader.java From java-technology-stack with MIT License | 6 votes |
/** * Close Spring's web application context for the given servlet context. * <p>If overriding {@link #loadParentContext(ServletContext)}, you may have * to override this method as well. * @param servletContext the ServletContext that the WebApplicationContext runs in */ public void closeWebApplicationContext(ServletContext servletContext) { servletContext.log("Closing Spring root WebApplicationContext"); try { if (this.context instanceof ConfigurableWebApplicationContext) { ((ConfigurableWebApplicationContext) this.context).close(); } } finally { ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl == ContextLoader.class.getClassLoader()) { currentContext = null; } else if (ccl != null) { currentContextPerThread.remove(ccl); } servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); } }
Example 5
Source File: WebUtils.java From java-technology-stack with MIT License | 6 votes |
/** * Set a system property to the web application root directory. * The key of the system property can be defined with the "webAppRootKey" * context-param in {@code web.xml}. Default is "webapp.root". * <p>Can be used for tools that support substitution with {@code System.getProperty} * values, like log4j's "${key}" syntax within log file locations. * @param servletContext the servlet context of the web application * @throws IllegalStateException if the system property is already set, * or if the WAR file is not expanded * @see #WEB_APP_ROOT_KEY_PARAM * @see #DEFAULT_WEB_APP_ROOT_KEY * @see WebAppRootListener */ public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException { Assert.notNull(servletContext, "ServletContext must not be null"); String root = servletContext.getRealPath("/"); if (root == null) { throw new IllegalStateException( "Cannot set web app root system property when WAR file is not expanded"); } String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM); String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY); String oldValue = System.getProperty(key); if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) { throw new IllegalStateException("Web app root system property already set to different value: '" + key + "' = [" + oldValue + "] instead of [" + root + "] - " + "Choose unique values for the 'webAppRootKey' context-param in your web.xml files!"); } System.setProperty(key, root); servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]"); }
Example 6
Source File: ChartImageManager.java From birt with Eclipse Public License 1.0 | 6 votes |
/** * Deletes all files and sub-directories under directories. Returns true if * all deletions were successful. If a deletion fails, the method stops * attempting to delete and returns false. */ private static boolean deleteDir( File dir, ServletContext context ) { if ( dir.isDirectory( ) ) { String[] children = dir.list( ); for ( int i = 0; i < children.length; i++ ) { boolean success = deleteDir( new File( dir, children[i] ), context ); if ( !success ) { return false; } } } // The directory is now empty so delete it context.log( "Cleaned file: " + dir.getPath( ) ); //$NON-NLS-1$ return dir.delete( ); }
Example 7
Source File: WebUtils.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Set a system property to the web application root directory. * The key of the system property can be defined with the "webAppRootKey" * context-param in {@code web.xml}. Default is "webapp.root". * <p>Can be used for tools that support substitution with {@code System.getProperty} * values, like log4j's "${key}" syntax within log file locations. * @param servletContext the servlet context of the web application * @throws IllegalStateException if the system property is already set, * or if the WAR file is not expanded * @see #WEB_APP_ROOT_KEY_PARAM * @see #DEFAULT_WEB_APP_ROOT_KEY * @see WebAppRootListener * @see Log4jWebConfigurer */ public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException { Assert.notNull(servletContext, "ServletContext must not be null"); String root = servletContext.getRealPath("/"); if (root == null) { throw new IllegalStateException( "Cannot set web app root system property when WAR file is not expanded"); } String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM); String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY); String oldValue = System.getProperty(key); if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) { throw new IllegalStateException("Web app root system property already set to different value: '" + key + "' = [" + oldValue + "] instead of [" + root + "] - " + "Choose unique values for the 'webAppRootKey' context-param in your web.xml files!"); } System.setProperty(key, root); servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]"); }
Example 8
Source File: WebUtils.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * Set a system property to the web application root directory. * The key of the system property can be defined with the "webAppRootKey" * context-param in {@code web.xml}. Default is "webapp.root". * <p>Can be used for tools that support substitution with {@code System.getProperty} * values, like log4j's "${key}" syntax within log file locations. * @param servletContext the servlet context of the web application * @throws IllegalStateException if the system property is already set, * or if the WAR file is not expanded * @see #WEB_APP_ROOT_KEY_PARAM * @see #DEFAULT_WEB_APP_ROOT_KEY * @see WebAppRootListener * @see Log4jWebConfigurer */ public static void setWebAppRootSystemProperty(ServletContext servletContext) throws IllegalStateException { Assert.notNull(servletContext, "ServletContext must not be null"); String root = servletContext.getRealPath("/"); if (root == null) { throw new IllegalStateException( "Cannot set web app root system property when WAR file is not expanded"); } String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM); String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY); String oldValue = System.getProperty(key); if (oldValue != null && !StringUtils.pathEquals(oldValue, root)) { throw new IllegalStateException( "Web app root system property already set to different value: '" + key + "' = [" + oldValue + "] instead of [" + root + "] - " + "Choose unique values for the 'webAppRootKey' context-param in your web.xml files!"); } System.setProperty(key, root); servletContext.log("Set web app root system property: '" + key + "' = [" + root + "]"); }
Example 9
Source File: ContextLoader.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Close Spring's web application context for the given servlet context. If * the default {@link #loadParentContext(ServletContext)} implementation, * which uses ContextSingletonBeanFactoryLocator, has loaded any shared * parent context, release one reference to that shared parent context. * <p>If overriding {@link #loadParentContext(ServletContext)}, you may have * to override this method as well. * @param servletContext the ServletContext that the WebApplicationContext runs in */ public void closeWebApplicationContext(ServletContext servletContext) { servletContext.log("Closing Spring root WebApplicationContext"); try { if (this.context instanceof ConfigurableWebApplicationContext) { ((ConfigurableWebApplicationContext) this.context).close(); } } finally { ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl == ContextLoader.class.getClassLoader()) { currentContext = null; } else if (ccl != null) { currentContextPerThread.remove(ccl); } servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); if (this.parentContextRef != null) { this.parentContextRef.release(); } } }
Example 10
Source File: IbisApplicationInitializer.java From iaf with Apache License 2.0 | 5 votes |
@Override public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { WebApplicationContext wac = super.initWebApplicationContext(servletContext); SpringBus bus = (SpringBus) wac.getBean("cxf"); servletContext.log("Successfully started IBIS WebApplicationInitializer with SpringBus ["+bus.getId()+"]"); return wac; }
Example 11
Source File: SpringServletContainerInitializer.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Delegate the {@code ServletContext} to any {@link WebApplicationInitializer} * implementations present on the application classpath. * * <p>Because this class declares @{@code HandlesTypes(WebApplicationInitializer.class)}, * Servlet 3.0+ containers will automatically scan the classpath for implementations * of Spring's {@code WebApplicationInitializer} interface and provide the set of all * such types to the {@code webAppInitializerClasses} parameter of this method. * * <p>If no {@code WebApplicationInitializer} implementations are found on the * classpath, this method is effectively a no-op. An INFO-level log message will be * issued notifying the user that the {@code ServletContainerInitializer} has indeed * been invoked but that no {@code WebApplicationInitializer} implementations were * found. * * <p>Assuming that one or more {@code WebApplicationInitializer} types are detected, * they will be instantiated (and <em>sorted</em> if the @{@link * org.springframework.core.annotation.Order @Order} annotation is present or * the {@link org.springframework.core.Ordered Ordered} interface has been * implemented). Then the {@link WebApplicationInitializer#onStartup(ServletContext)} * method will be invoked on each instance, delegating the {@code ServletContext} such * that each instance may register and configure servlets such as Spring's * {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener}, * or any other Servlet API componentry such as filters. * * @param webAppInitializerClasses all implementations of * {@link WebApplicationInitializer} found on the application classpath * @param servletContext the servlet context to be initialized * @see WebApplicationInitializer#onStartup(ServletContext) * @see AnnotationAwareOrderComparator */ @Override public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException { List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>(); if (webAppInitializerClasses != null) { for (Class<?> waiClass : webAppInitializerClasses) { // Be defensive: Some servlet containers provide us with invalid classes, // no matter what @HandlesTypes says... if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(waiClass)) { try { initializers.add((WebApplicationInitializer) waiClass.newInstance()); } catch (Throwable ex) { throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex); } } } } if (initializers.isEmpty()) { servletContext.log("No Spring WebApplicationInitializer types detected on classpath"); return; } AnnotationAwareOrderComparator.sort(initializers); servletContext.log("Spring WebApplicationInitializers detected on classpath: " + initializers); for (WebApplicationInitializer initializer : initializers) { initializer.onStartup(servletContext); } }
Example 12
Source File: CsrfGuardServletContextListener.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Prints the configuration to the ServletContext log file with the given prefix. * Has no effect unless the CONFIG_PRINT_PARAM init parameter is "true." * @param context The ServletContext * @param prefix The string used as a prefix when printing the configuration to the log * @see javax.servlet.ServletContext#log(String) */ public static void printConfigIfConfigured(ServletContext context, String prefix) { String printConfig = context.getInitParameter(CONFIG_PRINT_PARAM); if (printConfig == null || "".equals(printConfig.trim())) { printConfig = CsrfGuard.getInstance().isPrintConfig() ? "true" : null; } if (printConfig != null && Boolean.parseBoolean(printConfig)) { context.log(prefix + CsrfGuard.getInstance().toString()); } }
Example 13
Source File: Log4jWebConfigurer.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Shut down log4j, properly releasing all file locks * and resetting the web app root system property. * @param servletContext the current ServletContext * @see WebUtils#removeWebAppRootSystemProperty */ public static void shutdownLogging(ServletContext servletContext) { servletContext.log("Shutting down log4j"); try { org.springframework.util.Log4jConfigurer.shutdownLogging(); } finally { // Remove the web app root system property. if (exposeWebAppRoot(servletContext)) { WebUtils.removeWebAppRootSystemProperty(servletContext); } } }
Example 14
Source File: SpringServletContainerInitializer.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Delegate the {@code ServletContext} to any {@link WebApplicationInitializer} * implementations present on the application classpath. * <p>Because this class declares @{@code HandlesTypes(WebApplicationInitializer.class)}, * Servlet 3.0+ containers will automatically scan the classpath for implementations * of Spring's {@code WebApplicationInitializer} interface and provide the set of all * such types to the {@code webAppInitializerClasses} parameter of this method. * <p>If no {@code WebApplicationInitializer} implementations are found on the classpath, * this method is effectively a no-op. An INFO-level log message will be issued notifying * the user that the {@code ServletContainerInitializer} has indeed been invoked but that * no {@code WebApplicationInitializer} implementations were found. * <p>Assuming that one or more {@code WebApplicationInitializer} types are detected, * they will be instantiated (and <em>sorted</em> if the @{@link * org.springframework.core.annotation.Order @Order} annotation is present or * the {@link org.springframework.core.Ordered Ordered} interface has been * implemented). Then the {@link WebApplicationInitializer#onStartup(ServletContext)} * method will be invoked on each instance, delegating the {@code ServletContext} such * that each instance may register and configure servlets such as Spring's * {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener}, * or any other Servlet API componentry such as filters. * @param webAppInitializerClasses all implementations of * {@link WebApplicationInitializer} found on the application classpath * @param servletContext the servlet context to be initialized * @see WebApplicationInitializer#onStartup(ServletContext) * @see AnnotationAwareOrderComparator */ @Override public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException { List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>(); if (webAppInitializerClasses != null) { for (Class<?> waiClass : webAppInitializerClasses) { // Be defensive: Some servlet containers provide us with invalid classes, // no matter what @HandlesTypes says... if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) && WebApplicationInitializer.class.isAssignableFrom(waiClass)) { try { initializers.add((WebApplicationInitializer) waiClass.newInstance()); } catch (Throwable ex) { throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex); } } } } if (initializers.isEmpty()) { servletContext.log("No Spring WebApplicationInitializer types detected on classpath"); return; } servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath"); AnnotationAwareOrderComparator.sort(initializers); for (WebApplicationInitializer initializer : initializers) { initializer.onStartup(servletContext); } }
Example 15
Source File: AgentWsContextListener.java From ats-framework with Apache License 2.0 | 5 votes |
@Override public void contextInitialized( ServletContextEvent servletEvent ) { ServletContext servletContext = servletEvent.getServletContext(); servletContext.log("Servlet context initialized event is received. Starting registering configurators"); try { new ClasspathUtils().logProblematicJars(); } catch (RuntimeException e) { log.warn("Error caught while trying to get all JARs in classpath", e); // do not rethrow exception as this will stop deployment on incompliant servers like JBoss } // create the default web service configurator String pathToConfigFile = servletContext.getRealPath("/WEB-INF"); AgentConfigurator defaultConfigurator = new AgentConfigurator(pathToConfigFile); TemplateActionsConfigurator templateActionsConfigurator = new TemplateActionsConfigurator(pathToConfigFile); List<Configurator> configurators = new ArrayList<Configurator>(); configurators.add(defaultConfigurator); configurators.add(templateActionsConfigurator); log.info("Initializing ATS Agent web service, start component registration"); try { MainComponentLoader.getInstance().initialize(configurators); } catch (AgentException ae) { throw new RuntimeException("Unable to initialize Agent component loader", ae); } }
Example 16
Source File: SafeDispatcherServlet.java From cas4.0.x-server-wechat with Apache License 2.0 | 5 votes |
public void init(final ServletConfig config) { try { this.delegate.init(config); } catch (final Throwable t) { // let the service method know initialization failed. this.initSuccess = false; /* * no matter what went wrong, our role is to capture this error and * prevent it from blocking initialization of the servlet. logging * overkill so that our deployer will find a record of this problem * even if unfamiliar with Commons Logging and properly configuring * it. */ final String message = "SafeDispatcherServlet: \n" + "The Spring DispatcherServlet we wrap threw on init.\n" + "But for our having caught this error, the servlet would not have initialized."; // logger it via Commons Logging LOGGER.error(message, t); // logger it to the ServletContext ServletContext context = config.getServletContext(); context.log(message, t); /* * record the error so that the application has access to later * display a proper error message based on the exception. */ context.setAttribute(CAUGHT_THROWABLE_KEY, t); } }
Example 17
Source File: Log4jWebConfigurer.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Shut down log4j, properly releasing all file locks * and resetting the web app root system property. * @param servletContext the current ServletContext * @see WebUtils#removeWebAppRootSystemProperty */ public static void shutdownLogging(ServletContext servletContext) { servletContext.log("Shutting down log4j"); try { org.springframework.util.Log4jConfigurer.shutdownLogging(); } finally { // Remove the web app root system property. if (exposeWebAppRoot(servletContext)) { WebUtils.removeWebAppRootSystemProperty(servletContext); } } }
Example 18
Source File: GatewayForwardingServletTest.java From knox with Apache License 2.0 | 5 votes |
@Test public void testRedirectDefaults() throws ServletException, IOException { IMocksControl mockControl = EasyMock.createControl(); ServletConfig config = mockControl.createMock(ServletConfig.class); ServletContext context = mockControl.createMock(ServletContext.class); HttpServletRequest request = mockControl.createMock(HttpServletRequest.class); HttpServletResponse response = mockControl.createMock(HttpServletResponse.class); RequestDispatcher dispatcher = mockControl.createMock(RequestDispatcher.class); // setup expectations EasyMock.expect(config.getServletName()).andStubReturn("default"); EasyMock.expect(config.getServletContext()).andStubReturn(context); EasyMock.expect(config.getInitParameter("redirectTo")).andReturn("/gateway/sandbox"); EasyMock.expect(request.getMethod()).andReturn("GET").anyTimes(); EasyMock.expect(request.getPathInfo()).andReturn("/webhdfs/v1/tmp").anyTimes(); EasyMock.expect(request.getQueryString()).andReturn("op=LISTSTATUS"); EasyMock.expect(response.getStatus()).andReturn(200).anyTimes(); EasyMock.expect(context.getContext("/gateway/sandbox")).andReturn(context); EasyMock.expect(context.getRequestDispatcher("/webhdfs/v1/tmp?op=LISTSTATUS")).andReturn(dispatcher); dispatcher.forward(request, response); EasyMock.expectLastCall().once(); // logging context.log(EasyMock.anyObject()); EasyMock.expectLastCall().anyTimes(); // run the test mockControl.replay(); GatewayForwardingServlet servlet = new GatewayForwardingServlet(); servlet.init(config); servlet.service(request, response); mockControl.verify(); }
Example 19
Source File: ContextLoader.java From lams with GNU General Public License v2.0 | 4 votes |
/** * 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 * @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; } }
Example 20
Source File: ContextLoader.java From spring4-understanding with Apache License 2.0 | 4 votes |
/** * 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 * @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; } }