1 /**
2 * Copyright 2003-2007 Greg Luck
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package net.sf.ehcache.constructs.web;
18
19 import net.sf.ehcache.CacheManager;
20
21 import javax.servlet.ServletContextEvent;
22 import javax.servlet.ServletContextListener;
23
24 import org.apache.commons.logging.Log;
25 import org.apache.commons.logging.LogFactory;
26
27 import java.util.List;
28
29 /**
30 * A ServletContextListener that shutsdown CacheManager. Use this when you want to shutdown
31 * ehcache automatically when the web application is shutdown. If the web application is in
32 * a VM which is being shutdown, the ehcache shutdown hooks will do the work and this class
33 * is not required.
34 * <p/>
35 * To receive notification events, this class must be configured in the deployment descriptor for the web application.
36 * To do so, add the following to web.xml in your web application:
37 * <pre>
38 * <listener>
39 * <listener-class>net.sf.ehcache.constructs.web.ShutdownListener</listener-class>
40 * </listener>
41 * <p/>
42 * </pre>
43 *
44 * @author Daniel Wiell
45 * @author Greg Luck
46 * @version $Id: ShutdownListener.java 512 2007-07-10 09:18:45Z gregluck $
47 */
48 public class ShutdownListener implements ServletContextListener {
49
50 private static final Log LOG = LogFactory.getLog(ShutdownListener.class.getName());
51
52 /**
53 * Notification that the web application is ready to process requests.
54 *
55 * @param servletContextEvent
56 */
57 public void contextInitialized(ServletContextEvent servletContextEvent) {
58 //nothing required
59 }
60
61 /**
62 * Notification that the servlet context is about to be shut down.
63 * <p/>
64 * Shuts down all cache managers known to {@link CacheManager#ALL_CACHE_MANAGERS}
65 *
66 * @param servletContextEvent
67 */
68 public void contextDestroyed(ServletContextEvent servletContextEvent) {
69 List knownCacheManagers = CacheManager.ALL_CACHE_MANAGERS;
70 if (LOG.isDebugEnabled()) {
71 LOG.debug("Shutting down " + knownCacheManagers.size() + " CacheManagers.");
72 }
73 while (!knownCacheManagers.isEmpty()) {
74 ((CacheManager) CacheManager.ALL_CACHE_MANAGERS.get(0)).shutdown();
75 }
76 }
77 }