1 /***
2 * Copyright 2003-2010 Terracotta, Inc.
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 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
22
23 import javax.servlet.ServletContextEvent;
24 import javax.servlet.ServletContextListener;
25
26
27
28
29 import java.util.List;
30
31 /***
32 * A ServletContextListener that shutsdown CacheManager. Use this when you want to shutdown
33 * ehcache automatically when the web application is shutdown.
34 * <p/>
35 * To receive notification events, this class must be configured in the deployment
36 * descriptor for the web application.
37 *
38 * To do so, add the following to web.xml in your web application:
39 * <pre>
40 * <listener>
41 * <listener-class>net.sf.ehcache.constructs.web.ShutdownListener</listener-class>
42 * </listener>
43 * <p/>
44 * </pre>
45 *
46 * @author Daniel Wiell
47 * @author Greg Luck
48 * @version $Id: ShutdownListener.html 13146 2011-08-01 17:12:39Z oletizi $
49 */
50 public class ShutdownListener implements ServletContextListener {
51
52 private static final Logger LOG = LoggerFactory.getLogger(ShutdownListener.class);
53
54 /***
55 * Notification that the web application is ready to process requests.
56 *
57 * @param servletContextEvent
58 */
59 public void contextInitialized(ServletContextEvent servletContextEvent) {
60
61 }
62
63 /***
64 * Notification that the servlet context is about to be shut down.
65 * <p/>
66 * Shuts down all cache managers known to {@link CacheManager#ALL_CACHE_MANAGERS}
67 *
68 * @param servletContextEvent
69 */
70 public void contextDestroyed(ServletContextEvent servletContextEvent) {
71 List knownCacheManagers = CacheManager.ALL_CACHE_MANAGERS;
72 if (LOG.isDebugEnabled()) {
73 LOG.debug("Shutting down " + knownCacheManagers.size() + " CacheManagers.");
74 }
75 while (!knownCacheManagers.isEmpty()) {
76 ((CacheManager) CacheManager.ALL_CACHE_MANAGERS.get(0)).shutdown();
77 }
78 }
79 }