KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > components > store > impl > JCSDefaultStore


1 /*
2  * Copyright 2004,2004 The Apache Software Foundation.
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 package org.apache.cocoon.components.store.impl;
17
18 import java.io.File JavaDoc;
19 import java.io.IOException JavaDoc;
20 import java.io.Serializable JavaDoc;
21 import java.util.Arrays JavaDoc;
22 import java.util.Enumeration JavaDoc;
23 import java.util.Properties JavaDoc;
24
25 import org.apache.avalon.framework.activity.Disposable;
26 import org.apache.avalon.framework.activity.Initializable;
27 import org.apache.avalon.framework.context.Context;
28 import org.apache.avalon.framework.context.ContextException;
29 import org.apache.avalon.framework.context.Contextualizable;
30 import org.apache.avalon.framework.logger.AbstractLogEnabled;
31 import org.apache.avalon.framework.parameters.ParameterException;
32 import org.apache.avalon.framework.parameters.Parameterizable;
33 import org.apache.avalon.framework.parameters.Parameters;
34 import org.apache.avalon.framework.service.ServiceException;
35 import org.apache.avalon.framework.service.ServiceManager;
36 import org.apache.avalon.framework.service.Serviceable;
37 import org.apache.avalon.framework.thread.ThreadSafe;
38 import org.apache.cocoon.Constants;
39 import org.apache.cocoon.util.IOUtils;
40 import org.apache.commons.collections.iterators.IteratorEnumeration;
41 import org.apache.excalibur.store.Store;
42 import org.apache.excalibur.store.StoreJanitor;
43 import org.apache.jcs.access.GroupCacheAccess;
44 import org.apache.jcs.access.exception.CacheException;
45 import org.apache.jcs.engine.control.CompositeCache;
46 import org.apache.jcs.engine.control.CompositeCacheManager;
47 import org.apache.jcs.engine.memory.MemoryCache;
48
49
50 /**
51  * This is the default store implementation based on JCS
52  * http://jakarta.apache.org/turbine/jcs/BasicJCSConfiguration.html
53  *
54  * @version CVS $Id: JCSDefaultStore.java 36466 2004-08-16 10:08:39Z cziegeler $
55  */

56 public class JCSDefaultStore
57     extends AbstractLogEnabled
58     implements Store,
59                Contextualizable,
60                Parameterizable,
61                Initializable,
62                Disposable,
63                ThreadSafe,
64                Serviceable {
65
66     /** The JCS configuration properties */
67     protected Properties JavaDoc properties;
68     
69     /** The JCS region name */
70     protected String JavaDoc region;
71     
72     /** JCS Cache manager */
73     private CompositeCacheManager cacheManager;
74     
75     /** The Java Cache System object */
76     private JCSCacheAccess jcs;
77
78     /** The location of the JCS default properties file */
79     private static final String JavaDoc DEFAULT_PROPERTIES = "org/apache/cocoon/components/store/default.ccf";
80
81     /** The context containing the work and the cache directory */
82     private Context context;
83
84     /** Service Manager */
85     private ServiceManager manager;
86     
87     /** Store janitor */
88     private StoreJanitor janitor;
89     
90     /* (non-Javadoc)
91      * @see org.apache.avalon.framework.context.Contextualizable#contextualize(org.apache.avalon.framework.context.Context)
92      */

93     public void contextualize(Context aContext) throws ContextException {
94         this.context = aContext;
95     }
96     
97     /* (non-Javadoc)
98      * @see org.apache.avalon.framework.service.Serviceable#service(org.apache.avalon.framework.service.ServiceManager)
99      */

100     public void service(ServiceManager aManager) throws ServiceException {
101         this.manager = aManager;
102         this.janitor = (StoreJanitor)this.manager.lookup(StoreJanitor.ROLE);
103     }
104     
105     /* (non-Javadoc)
106      * @see org.apache.avalon.framework.parameters.Parameterizable#parameterize(org.apache.avalon.framework.parameters.Parameters)
107      */

108     public void parameterize(Parameters parameters)
109     throws ParameterException {
110         // TODO describe options
111
this.region = parameters.getParameter("region-name","main");
112         
113         Properties JavaDoc defaults = new Properties JavaDoc();
114         try {
115             String JavaDoc defaultsFile = this.getDefaultPropertiesFile();
116             if (defaultsFile != null) {
117                 defaults.load(Thread.currentThread().getContextClassLoader().
118                     getResourceAsStream(defaultsFile));
119             }
120         } catch (IOException JavaDoc e) {
121             throw new ParameterException("Failure loading cache defaults",e);
122         }
123         
124         this.properties = new Properties JavaDoc(defaults);
125         String JavaDoc[] names = parameters.getNames();
126         for (int i = 0; i < names.length; i++) {
127             if (names[i].startsWith("jcs.")) {
128                 this.properties.put(names[i], parameters.getParameter(names[i]));
129             }
130         }
131         
132         int maxobjects = parameters.getParameterAsInteger("maxobjects", -1);
133         if (maxobjects != -1) {
134             String JavaDoc key = "jcs.region." + region + ".cacheattributes.MaxObjects";
135             this.properties.setProperty(key, String.valueOf(maxobjects));
136         }
137
138         // get the directory to use
139
try {
140             final File JavaDoc workDir = (File JavaDoc) context.get(Constants.CONTEXT_WORK_DIR);
141             if (parameters.getParameterAsBoolean("use-cache-directory", false)) {
142                 final File JavaDoc cacheDir = (File JavaDoc) context.get(Constants.CONTEXT_CACHE_DIR);
143                 if (getLogger().isDebugEnabled()) {
144                     getLogger().debug("Using cache directory: " + cacheDir);
145                 }
146                 setDirectory(cacheDir);
147             } else if (parameters.getParameterAsBoolean("use-work-directory", false)) {
148                 if (getLogger().isDebugEnabled()) {
149                     getLogger().debug("Using work directory: " + workDir);
150                 }
151                 setDirectory(workDir);
152             } else if (parameters.getParameter("directory", null) != null) {
153                 String JavaDoc dir = parameters.getParameter("directory");
154                 dir = IOUtils.getContextFilePath(workDir.getPath(), dir);
155                 if (getLogger().isDebugEnabled()) {
156                     getLogger().debug("Using directory: " + dir);
157                 }
158                 setDirectory(new File JavaDoc(dir));
159             } else {
160                 if (getLogger().isDebugEnabled()) {
161                     getLogger().debug("Using default directory: " + workDir);
162                 }
163                 setDirectory(workDir);
164             }
165         } catch (ContextException ce) {
166             throw new ParameterException("Unable to get directory information from context.", ce);
167         } catch (IOException JavaDoc e) {
168             throw new ParameterException("Unable to set directory", e);
169         }
170         
171     }
172     
173     /* (non-Javadoc)
174      * @see org.apache.avalon.framework.activity.Initializable#initialize()
175      */

176     public void initialize() throws Exception JavaDoc {
177         this.cacheManager = CompositeCacheManager.getUnconfiguredInstance();
178         this.cacheManager.configure(this.properties);
179         this.jcs = new JCSCacheAccess(cacheManager.getCache(region));
180         this.janitor.register(this);
181     }
182     
183     /* (non-Javadoc)
184      * @see org.apache.avalon.framework.activity.Disposable#dispose()
185      */

186     public void dispose() {
187         if( this.janitor != null ) {
188             this.janitor.unregister( this );
189         }
190         if ( this.jcs != null ) {
191             this.jcs.dispose();
192             this.jcs = null;
193         }
194         if ( this.cacheManager != null ) {
195             this.cacheManager.release();
196             this.cacheManager = null;
197         }
198         this.properties = null;
199         if ( this.manager != null ) {
200             this.manager.release( this.janitor );
201             this.janitor = null;
202             this.manager = null;
203         }
204     }
205     
206     protected String JavaDoc getDefaultPropertiesFile() {
207         return DEFAULT_PROPERTIES;
208     }
209     
210     /**
211      * Sets the disk cache location.
212      */

213     private void setDirectory(final File JavaDoc directory)
214     throws IOException JavaDoc {
215
216         /* Does directory exist? */
217         if (!directory.exists()) {
218             /* Create it anew */
219             if (!directory.mkdirs()) {
220                 throw new IOException JavaDoc(
221                 "Error creating store directory '" + directory.getAbsolutePath() + "'. ");
222             }
223         }
224
225         /* Is given file actually a directory? */
226         if (!directory.isDirectory()) {
227             throw new IOException JavaDoc("'" + directory.getAbsolutePath() + "' is not a directory");
228         }
229
230         /* Is directory readable and writable? */
231         if (!(directory.canRead() && directory.canWrite())) {
232             throw new IOException JavaDoc(
233                 "Directory '" + directory.getAbsolutePath() + "' is not readable/writable"
234             );
235         }
236         
237         this.properties.setProperty("jcs.auxiliary.DC.attributes.DiskPath",
238                                     directory.getAbsolutePath());
239     }
240
241     // ---------------------------------------------------- Store implementation
242

243     /* (non-Javadoc)
244      * @see org.apache.excalibur.store.Store#get(java.lang.Object)
245      */

246     public Object JavaDoc get(Object JavaDoc key) {
247         Object JavaDoc value = this.jcs.get(key);
248         if (getLogger().isDebugEnabled()) {
249             if (value != null) {
250                 getLogger().debug("Found key: " + key);
251             } else {
252                 getLogger().debug("NOT Found key: " + key);
253             }
254         }
255         
256         return value;
257     }
258     
259     /* (non-Javadoc)
260      * @see org.apache.excalibur.store.Store#store(java.lang.Object, java.lang.Object)
261      */

262     public void store(Object JavaDoc key, Object JavaDoc value)
263     throws IOException JavaDoc {
264         
265         if (getLogger().isDebugEnabled()) {
266             getLogger().debug("Store object " + value + " with key "+ key);
267         }
268         
269         try {
270             this.jcs.put(key, value);
271         } catch (CacheException ce) {
272             getLogger().error("Failure storing object ", ce);
273         }
274     }
275     
276     /* (non-Javadoc)
277      * @see org.apache.excalibur.store.Store#free()
278      */

279     public void free() {
280         // TODO Find a better way
281
MemoryCache memoryCache = this.cacheManager.getCache(region).getMemoryCache();
282         Object JavaDoc[] keys = memoryCache.getKeyArray();
283         if ( keys != null && keys.length > 0 ) {
284             final Object JavaDoc key = keys[0];
285             try {
286                 memoryCache.remove((Serializable JavaDoc)key);
287             } catch (Exception JavaDoc ignore) {
288             }
289         }
290     }
291     
292     /* (non-Javadoc)
293      * @see org.apache.excalibur.store.Store#clear()
294      */

295     public void clear() {
296         if (getLogger().isDebugEnabled()) {
297             getLogger().debug("Clearing the store");
298         }
299         
300         try {
301             this.jcs.remove();
302         } catch (CacheException ce) {
303             getLogger().error("Failure clearing store", ce);
304         }
305     }
306     
307     /* (non-Javadoc)
308      * @see org.apache.excalibur.store.Store#remove(java.lang.Object)
309      */

310     public void remove(Object JavaDoc key) {
311         if (getLogger().isDebugEnabled()) {
312             getLogger().debug("Removing item " + key);
313         }
314         
315         try {
316            this.jcs.remove(key);
317         } catch (CacheException ce) {
318             getLogger().error("Failure removing object", ce);
319         }
320     }
321     
322     /* (non-Javadoc)
323      * @see org.apache.excalibur.store.Store#containsKey(java.lang.Object)
324      */

325     public boolean containsKey(Object JavaDoc key) {
326         return this.jcs.get(key) != null;
327     }
328     
329     
330     /* (non-Javadoc)
331      * @see org.apache.excalibur.store.Store#keys()
332      */

333     public Enumeration JavaDoc keys() {
334         // TODO Find a better way
335
final MemoryCache memoryCache = this.cacheManager.getCache(region).getMemoryCache();
336         final Object JavaDoc[] keys = memoryCache.getKeyArray();
337         return new IteratorEnumeration(Arrays.asList(keys).iterator());
338         //return new IteratorEnumeration(this.jcs.getGroupKeys("").iterator());
339
}
340     
341     /* (non-Javadoc)
342      * @see org.apache.excalibur.store.Store#size()
343      */

344     public int size() {
345         // TODO Find a better way
346
MemoryCache memoryCache = this.cacheManager.getCache(region).getMemoryCache();
347         return memoryCache.getSize();
348         //return this.jcs.getSize();
349
}
350     
351
352     private static class JCSCacheAccess extends GroupCacheAccess {
353         private JCSCacheAccess(CompositeCache cacheControl) {
354             super(cacheControl);
355         }
356         
357         /*private int getSize() {
358             return super.cacheControl.getSize();
359         }*/

360         
361         public void dispose() {
362             super.dispose();
363         }
364     }
365     
366 }
367
Popular Tags