2 * Copyright 2005 the original author or authors.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.wamblee.cache;
18 import net.sf.ehcache.Cache;
19 import net.sf.ehcache.CacheException;
20 import net.sf.ehcache.CacheManager;
21 import net.sf.ehcache.Element;
23 import org.apache.log4j.Logger;
25 import org.wamblee.io.InputResource;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.Serializable;
33 * Cache implemented on top of EhCache.
35 * @author Erik Brakkee
37 * @param <KeyType> DOCUMENT ME!
38 * @param <ValueType> DOCUMENT ME!
40 public class EhCache<KeyType extends Serializable, ValueType extends Serializable>
41 implements org.wamblee.cache.Cache<KeyType, ValueType> {
45 private static final Logger LOGGER = Logger.getLogger(EhCache.class);
50 private CacheManager manager;
58 * Constructs a cache based on EHCache.
61 * Resource containing the configuration file for EHCache.
63 * Name of the cache to use. If a cache with this name does not
64 * exist, one is created based on default settings.
66 * @throws CacheException
68 public EhCache(InputResource aResource, String aCacheName)
69 throws IOException, CacheException {
70 InputStream is = aResource.getInputStream();
73 manager = new CacheManager(is);
74 cache = manager.getCache(aCacheName);
77 LOGGER.warn("Creating cache '" + aCacheName
78 + "' because it is not configured");
79 manager.addCache(aCacheName);
80 cache = manager.getCache(aCacheName);
91 * @see org.wamblee.cache.Cache#put(KeyType, ValueType)
96 * @param aKey DOCUMENT ME!
97 * @param aValue DOCUMENT ME!
99 public void put(KeyType aKey, ValueType aValue) {
100 cache.put(new Element(aKey, aValue));
106 * @see org.wamblee.cache.Cache#get(KeyType)
111 * @param aKey DOCUMENT ME!
113 * @return DOCUMENT ME!
115 public ValueType get(KeyType aKey) {
117 Element element = cache.get(aKey);
119 if (element == null) {
123 return (ValueType) element.getValue();
124 } catch (CacheException e) {
125 throw new RuntimeException("Cache problem key = '" + aKey + "'", e);
132 * @see org.wamblee.cache.Cache#remove(KeyType)
137 * @param aKey DOCUMENT ME!
139 public void remove(KeyType aKey) {
146 * @see org.wamblee.cache.Cache#clear()
151 public void clear() {