KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > appserv > web > cache > CacheManager


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.appserv.web.cache;
25
26 import java.text.MessageFormat JavaDoc;
27
28 import java.util.ArrayList JavaDoc;
29 import java.util.Collections JavaDoc;
30 import java.util.Enumeration JavaDoc;
31 import java.util.HashMap JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Properties JavaDoc;
35 import java.util.Set JavaDoc;
36 import java.io.PrintWriter JavaDoc;
37 import java.io.StringWriter JavaDoc;
38
39 import java.util.logging.Logger JavaDoc;
40 import java.util.logging.Level JavaDoc;
41 import java.util.ResourceBundle JavaDoc;
42
43 import javax.servlet.ServletContext JavaDoc;
44 import org.apache.catalina.LifecycleException;
45
46 import com.sun.appserv.util.cache.Cache;
47 import com.sun.appserv.web.cache.mapping.CacheMapping;
48
49 import com.sun.enterprise.web.logging.pwc.LogDomains;
50
51 public class CacheManager {
52
53     public static final String JavaDoc CACHE_MANAGER_ATTR_NAME =
54                             "com.sun.appserv.web.CacheManager";
55     public static final int DEFAULT_CACHE_MAX_ENTRIES = 4096;
56     public static final int DEFAULT_CACHE_TIMEOUT = 30;
57     public static final String JavaDoc DEFAULT_CACHE_CLASSNAME =
58                                         "com.sun.appserv.util.cache.LruCache";
59
60     // PWC_LOGGER
61
private static Logger JavaDoc _logger;
62     /**
63      * The resource bundle containing the localized message strings.
64      */

65     private static ResourceBundle JavaDoc _rb = null;
66
67     // default max maximum number of entries in the cache
68
int maxEntries = DEFAULT_CACHE_MAX_ENTRIES;
69     int defaultTimeout = DEFAULT_CACHE_TIMEOUT;
70     String JavaDoc cacheClassName = DEFAULT_CACHE_CLASSNAME;
71     
72     boolean enabled = false;
73
74     // application servlet context
75
ServletContext JavaDoc context;
76
77     // XXX: potentially zero or more caches?
78
Properties JavaDoc cacheProps;
79     Cache defaultCache;
80
81     // cache mappings indexed by the filter name
82
HashMap JavaDoc cacheMappings = new HashMap JavaDoc();
83
84     // default-helper, its properties
85
Map JavaDoc defaultHelperProps;
86     DefaultCacheHelper defaultHelper;
87
88     // cache helpers indexed by their name and filter name
89
HashMap JavaDoc helperDefs = new HashMap JavaDoc();
90     HashMap JavaDoc cacheHelpers = new HashMap JavaDoc();
91     HashMap JavaDoc cacheHelpersByFilterName = new HashMap JavaDoc();
92
93     // CacheManagerListener classes
94
ArrayList JavaDoc listeners = new ArrayList JavaDoc();
95
96     /**
97      * default constructor
98      */

99     public CacheManager() { }
100
101     /**
102      * set the maximum number of entries of this cache
103      * @param maxEntries number of entries the cache should carry
104      */

105     public void setMaxEntries(int maxEntries) {
106         this.maxEntries = maxEntries;
107     }
108
109     /**
110      * set the defaultTimeout of this cache
111      * @param defaultTimeout in seconds
112      */

113     public void setDefaultTimeout(int defaultTimeout) {
114         this.defaultTimeout = defaultTimeout;
115     }
116
117     /**
118      * set the whether this is enabled
119      * @param enabled is this enabled?
120      */

121     public void setEnabled(boolean enabled) {
122         this.enabled = enabled;
123     }
124
125     /**
126      * @return whether this is enabled
127      */

128     public boolean isEnabled() {
129         return enabled;
130     }
131
132     /**
133      * add generic property
134      * @param name named property
135      * @param value value
136      */

137     public void addProperty(String JavaDoc name, String JavaDoc value) {
138         if (name.equalsIgnoreCase("cacheClassName")) {
139            cacheClassName = value;
140         } else {
141             if (cacheProps == null) {
142                 cacheProps = new Properties JavaDoc();
143             }
144             cacheProps.setProperty(name, value);
145         }
146     }
147
148     /**
149      * add a CacheHelper definition
150      * @param name CacheHelper name
151      * @param helperDef CacheHelper definition
152      */

153     public void addCacheHelperDef(String JavaDoc name, HashMap JavaDoc helperDef) {
154         helperDefs.put(name, helperDef);
155     }
156
157     /**
158      * set the default-helper's properties
159      * @param map a HashMap of properties
160      */

161     public void setDefaultHelperProps(Map JavaDoc map) {
162         this.defaultHelperProps = map;
163     }
164
165     /**
166      * set the ServletContext of this application
167      * @param context ServletContext
168      */

169     public void setServletContext(ServletContext JavaDoc context) {
170         this.context = context;
171     }
172     
173     /**
174      * load the helper class
175      * @param className of the helper
176      * @return CacheHelper instance
177      */

178     private CacheHelper loadCacheHelper(String JavaDoc className)
179         throws Exception JavaDoc {
180
181         // use the context class loader to load class so that any
182
// user-defined classes in WEB-INF can also be loaded.
183
ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader();
184         Class JavaDoc helperClass = cl.loadClass(className);
185
186         CacheHelper helper = (CacheHelper) helperClass.newInstance();
187
188         return helper;
189     }
190
191     /**
192      * Start this Context component.
193      * @exception LifecycleException if a startup error occurs
194      */

195     public void start() throws LifecycleException {
196
197         if (!enabled)
198             return;
199
200         // web container logger
201
_logger = LogDomains.getLogger(LogDomains.PWC_LOGGER);
202         _rb = _logger.getResourceBundle();
203
204         // create the default cache
205
try {
206             defaultCache = createCache(maxEntries, cacheClassName);
207         } catch (Exception JavaDoc e) {
208             _logger.log(Level.WARNING, "cache.manager.excep_createCache", e);
209
210             String JavaDoc msg = _rb.getString("cache.manager.excep_createCache");
211             throw new LifecycleException(msg, e);
212         }
213
214         // initialize the "default" helper
215
defaultHelper = new DefaultCacheHelper();
216         defaultHelper.setCacheManager(this);
217         defaultHelper.init(context, defaultHelperProps);
218
219         // initialize the custom cache-helpers
220
Iterator JavaDoc helperNames = helperDefs.keySet().iterator();
221         while(helperNames.hasNext()) {
222             String JavaDoc name = (String JavaDoc) helperNames.next();
223             HashMap JavaDoc map = (HashMap JavaDoc)helperDefs.get(name);
224
225             try {
226                 String JavaDoc className = (String JavaDoc)map.get("class-name");
227                 CacheHelper helper = loadCacheHelper(className);
228                 helper.init(context, map);
229                 cacheHelpers.put(name, helper);
230
231             } catch (Exception JavaDoc e) {
232                 String JavaDoc msg = _rb.getString("cache.manager.excep_initCacheHelper");
233                 Object JavaDoc[] params = { name };
234                 msg = MessageFormat.format(msg, params);
235
236                 throw new LifecycleException(msg, e);
237             }
238         }
239
240         // cache-mappings are ordered by the associated filter name
241
Iterator JavaDoc filterNames = cacheMappings.keySet().iterator();
242         while(filterNames.hasNext()) {
243             String JavaDoc name = (String JavaDoc) filterNames.next();
244             CacheMapping mapping = (CacheMapping)cacheMappings.get(name);
245
246             String JavaDoc helperNameRef = mapping.getHelperNameRef();
247             CacheHelper helper;
248             if (helperNameRef == null || helperNameRef.equals("default")) {
249                 helper = defaultHelper;
250             } else {
251                 helper = (CacheHelper) cacheHelpers.get(helperNameRef);
252             }
253             cacheHelpersByFilterName.put(name, helper);
254         }
255     }
256
257     /**
258      * get the underlying cache name
259      * @return the cacheClassName
260      */

261     public String JavaDoc getCacheClassName() {
262         return cacheClassName;
263     }
264
265     /**
266      * create the designated cache object
267      * @return the Cache implementation
268      * @throws Exception
269      */

270     public Cache createCache() throws Exception JavaDoc {
271         return createCache(maxEntries, DEFAULT_CACHE_CLASSNAME);
272     }
273
274     /**
275      * create the designated cache object
276      * @return the Cache implementation
277      * @throws Exception
278      */

279     public Cache createCache(int cacacity, String JavaDoc className)
280                     throws Exception JavaDoc {
281
282         // use the context class loader to load class so that any
283
// user-defined classes in WEB-INF can also be loaded.
284
ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader();
285         Class JavaDoc cacheClass = cl.loadClass(className);
286
287         Cache cacheImpl = (Cache)cacheClass.newInstance();
288         cacheImpl.init(maxEntries, cacheProps);
289
290         return cacheImpl;
291     }
292
293     /**
294      * get the application wide default cache expiry timeout
295      * @return timeout in seconds
296      */

297     public int getDefaultTimeout() {
298         return defaultTimeout;
299     }
300
301     /**
302      * get the default application-wide cache
303      * @return cache object
304      */

305     public Cache getDefaultCache() {
306         return defaultCache;
307     }
308
309     /**
310      * add cache mapping
311      * @param name unique name of the mapping
312      * @param mapping CacheMapping
313      */

314     public void addCacheMapping(String JavaDoc name, CacheMapping mapping) {
315         cacheMappings.put(name, mapping);
316     }
317
318     /**
319      * get cacheMapping given its name
320      * @param name name identifying the mapping
321      * @return CacheMapping
322      */

323     public CacheMapping getCacheMapping(String JavaDoc name) {
324         return (CacheMapping)cacheMappings.get(name);
325     }
326
327     /**
328      * get the helper by name
329      * @param name name of the cache-helper
330      * @return CacheHelper implementation
331      */

332     public CacheHelper getCacheHelper(String JavaDoc name) {
333         return (CacheHelper)cacheHelpers.get(name);
334     }
335
336     /**
337      * get the helper by filter name
338      * @param filterName filter name
339      * @return CacheHelper implementation
340      */

341     public CacheHelper getCacheHelperByFilterName(String JavaDoc filterName) {
342         return (CacheHelper)cacheHelpersByFilterName.get(filterName);
343     }
344
345     /**
346      * add CacheManagerListener object
347      * @param listener CacheManagerListener object
348      */

349     public void addCacheManagerListener(CacheManagerListener listener) {
350         synchronized (listeners) {
351             listeners.add(listener);
352         }
353     }
354
355     /**
356      * remove CacheManagerListener object
357      * @param listener CacheManagerListener object
358      */

359     public void removeCacheManagerListener(CacheManagerListener listener) {
360         synchronized (listeners) {
361             listeners.remove(listener);
362         }
363     }
364
365     /**
366      * enable the cache manager (and all the listeners)
367      */

368     public void enable() {
369         for (int i = 0; i < listeners.size(); i++) {
370             CacheManagerListener listener = (CacheManagerListener)
371                                         listeners.get(i);
372             listener.cacheManagerEnabled();
373         }
374     }
375
376     /**
377      * enable the cache manager (and all the listeners)
378      */

379     public void disable() {
380         for (int i = 0; i < listeners.size(); i++) {
381             CacheManagerListener listener = (CacheManagerListener)
382                                     listeners.get(i);
383             listener.cacheManagerDisabled();
384         }
385     }
386
387     /**
388      * Stop this Context component.
389      * destroy all the caches created and flush/clear the cached content
390      * @exception LifecycleException if a shutdown error occurs
391      */

392     public void stop() throws LifecycleException {
393         disable();
394
395         try {
396             defaultHelper.destroy();
397         } catch (Exception JavaDoc e) {
398             // XXX: ignore
399
}
400
401         // destroy the cache-helpers
402
Enumeration JavaDoc helpers = Collections.enumeration(cacheHelpers.values());
403         while(helpers.hasMoreElements()) {
404             CacheHelper cacheHelper = (CacheHelper)helpers.nextElement();
405             try {
406                 cacheHelper.destroy();
407             } catch (Exception JavaDoc e) {
408                 // XXX: ignore
409
}
410         }
411         cacheHelpers.clear();
412         cacheMappings.clear();
413         cacheHelpersByFilterName.clear();
414         listeners.clear();
415     }
416 }
417
Popular Tags