KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > beans > config > Cache


1 /**
2  *
3  * Magnolia and its source-code is licensed under the LGPL.
4  * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
5  * When copying, adapting, or redistributing this document in keeping with the guidelines above,
6  * you are required to provide proper attribution to obinary.
7  * If you reproduce or distribute the document without making any substantive modifications to its content,
8  * please use the following attribution line:
9  *
10  * Copyright 1993-2005 obinary Ltd. (http://www.obinary.com) All rights reserved.
11  *
12  */

13 package info.magnolia.cms.beans.config;
14
15 import info.magnolia.cms.core.CacheHandler;
16 import info.magnolia.cms.core.Content;
17 import info.magnolia.cms.core.NodeData;
18 import info.magnolia.cms.core.Path;
19 import info.magnolia.cms.util.SimpleUrlPattern;
20 import info.magnolia.cms.util.UrlPattern;
21
22 import java.util.HashMap JavaDoc;
23 import java.util.Hashtable JavaDoc;
24 import java.util.Iterator JavaDoc;
25 import java.util.Map JavaDoc;
26
27 import javax.jcr.RepositoryException;
28 import javax.jcr.observation.Event;
29 import javax.jcr.observation.EventIterator;
30 import javax.jcr.observation.EventListener;
31 import javax.jcr.observation.ObservationManager;
32 import javax.servlet.http.HttpServletRequest JavaDoc;
33
34 import org.apache.commons.lang.BooleanUtils;
35 import org.apache.commons.lang.StringUtils;
36 import org.apache.log4j.Logger;
37
38
39 /**
40  * @author Sameer Charles
41  * @version 2.0
42  */

43 public final class Cache {
44
45     private static final String JavaDoc CONFIG_PATH = "server/cache/level1"; //$NON-NLS-1$
46

47     private static final String JavaDoc CACHE_MAPPING_NODE = "URI"; //$NON-NLS-1$
48

49     private static final String JavaDoc COMPRESSION_LIST_NODE = "compression"; //$NON-NLS-1$
50

51     private static final String JavaDoc ALLOW_LIST = "allow"; //$NON-NLS-1$
52

53     private static final String JavaDoc DENY_LIST = "deny"; //$NON-NLS-1$
54

55     private static final String JavaDoc ACTIVE = "active"; //$NON-NLS-1$
56

57     private static final String JavaDoc DOMAIN = "domain"; //$NON-NLS-1$
58

59     /**
60      * Logger.
61      */

62     private static Logger log = Logger.getLogger(Cache.class);
63
64     private static Map JavaDoc cachedCacheableURIMapping = new HashMap JavaDoc();
65
66     /**
67      * Compression wont work for these pre compressed formats.
68      */

69     private static final Map JavaDoc COMPRESSION_LIST = new Hashtable JavaDoc();
70
71     private static boolean active;
72
73     private static String JavaDoc domain;
74
75     /**
76      * Utility class, don't instantiate.
77      */

78     private Cache() {
79         // unused
80
}
81
82     protected static void init() {
83         load();
84         registerEventListener();
85     }
86
87     public static void load() {
88         cachedCacheableURIMapping.clear();
89         COMPRESSION_LIST.clear();
90
91         log.info("Config : loading cache mapping"); //$NON-NLS-1$
92
try {
93             Content startPage = ContentRepository.getHierarchyManager(ContentRepository.CONFIG).getContent(CONFIG_PATH);
94             active = startPage.getNodeData(ACTIVE).getBoolean();
95             if (active) {
96                 domain = startPage.getNodeData(DOMAIN).getString();
97                 Content contentNode = startPage.getContent(CACHE_MAPPING_NODE + "/" + ALLOW_LIST); //$NON-NLS-1$
98
cacheCacheableURIMappings(contentNode, true);
99                 contentNode = startPage.getContent(CACHE_MAPPING_NODE + "/" + DENY_LIST); //$NON-NLS-1$
100
cacheCacheableURIMappings(contentNode, false);
101                 Content compressionListNode = startPage.getContent(COMPRESSION_LIST_NODE);
102                 updateCompressionList(compressionListNode);
103                 // @todo sort ascending so there wont be too much work on comparing
104
}
105             log.info("Config: cache mapping loaded"); //$NON-NLS-1$
106
}
107         catch (RepositoryException re) {
108             log.error("Config: Failed to load cache mapping or no mapping defined - " + re.getMessage(), re); //$NON-NLS-1$
109
}
110     }
111
112     public static void reload() {
113         log.info("Config : reloading cache mapping"); //$NON-NLS-1$
114

115         // @todo this should probably not be here, but it's important to remove cached entries when the configuration is
116
// reloaded
117
info.magnolia.cms.beans.runtime.Cache.clearCachedURIList();
118         CacheHandler.flushCache();
119
120         load();
121     }
122
123     /**
124      * Register an event listener: reload cache configuration when something changes.
125      */

126     private static void registerEventListener() {
127
128         log.info("Registering event listener for cache"); //$NON-NLS-1$
129

130         try {
131             ObservationManager observationManager = ContentRepository
132                 .getHierarchyManager(ContentRepository.CONFIG)
133                 .getWorkspace()
134                 .getObservationManager();
135
136             observationManager.addEventListener(new EventListener() {
137
138                 public void onEvent(EventIterator iterator) {
139                     // reload everything
140
reload();
141                 }
142             }, Event.NODE_ADDED
143                 | Event.NODE_REMOVED
144                 | Event.PROPERTY_ADDED
145                 | Event.PROPERTY_CHANGED
146                 | Event.PROPERTY_REMOVED, "/" + CONFIG_PATH, true, null, null, false); //$NON-NLS-1$
147
}
148         catch (RepositoryException e) {
149             log.error("Unable to add event listeners for cache", e); //$NON-NLS-1$
150
}
151     }
152
153     /**
154      * @param nodeList to be added in cache
155      */

156     private static void cacheCacheableURIMappings(Content nodeList, boolean allow) {
157         if (nodeList == null) {
158             return;
159         }
160         Iterator JavaDoc it = nodeList.getChildren().iterator();
161         while (it.hasNext()) {
162             Content container = (Content) it.next();
163             NodeData uri = container.getNodeData(CACHE_MAPPING_NODE);
164             UrlPattern p = new SimpleUrlPattern(uri.getString());
165             cachedCacheableURIMapping.put(p, BooleanUtils.toBooleanObject(allow));
166         }
167         try {
168             CacheHandler.validatePath(CacheHandler.CACHE_DIRECTORY);
169         }
170         catch (Exception JavaDoc e) {
171             log.error("Failed to validate cache directory location: " + e.getMessage(), e); //$NON-NLS-1$
172
}
173     }
174
175     private static void updateCompressionList(Content list) {
176         if (list == null) {
177             return;
178         }
179         Iterator JavaDoc it = list.getChildren().iterator();
180         while (it.hasNext()) {
181             Content node = (Content) it.next();
182             COMPRESSION_LIST.put(node.getNodeData("extension").getString(), node.getNodeData("type").getString()); //$NON-NLS-1$ //$NON-NLS-2$
183
}
184     }
185
186     public static boolean applyCompression(String JavaDoc key) {
187         return COMPRESSION_LIST.containsKey(key.trim().toLowerCase());
188     }
189
190     /**
191      * If cache enabled?.
192      * @return <code>true</code> if cache is enabled
193      * @deprecated use Cache.isActive()
194      * @see Cache#isActive()
195      */

196     public static boolean isCacheable() {
197         return active;
198     }
199
200     /**
201      * If cache enabled?.
202      * @return <code>true</code> if cache is enabled
203      */

204     public static boolean isActive() {
205         return active;
206     }
207
208     public static String JavaDoc getDomain() {
209         return domain;
210     }
211
212     /**
213      * @return true if the requested URI can be added to cache
214      */

215     public static boolean isCacheable(HttpServletRequest JavaDoc request) {
216
217         // is cache enabled?
218
if (!isActive()) {
219             return false;
220         }
221
222         // || Server.isAdmin()
223

224         // don't cache POSTs or requests with parameters
225
if ("POST".equals(request.getMethod()) || request.getParameterMap().size() > 0) { //$NON-NLS-1$
226
return false;
227         }
228
229         // first check for MIMEMappings, extension must exist otherwise its a fake request
230
if (StringUtils.isEmpty(MIMEMapping.getMIMEType(Path.getExtension(request)))) {
231             return false;
232         }
233
234         Iterator JavaDoc listEnum = cachedCacheableURIMapping.keySet().iterator();
235
236         String JavaDoc uri = Path.getURI(request);
237         boolean isAllowed = false;
238         int lastMatchedPatternlength = 0;
239
240         while (listEnum.hasNext()) {
241             UrlPattern p = (UrlPattern) listEnum.next();
242             if (p.match(uri)) {
243                 int patternLength = p.getLength();
244                 if (lastMatchedPatternlength < patternLength) {
245                     lastMatchedPatternlength = patternLength;
246                     isAllowed = ((Boolean JavaDoc) cachedCacheableURIMapping.get(p)).booleanValue();
247                 }
248             }
249         }
250         return isAllowed;
251     }
252
253 }
254
Popular Tags