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.
17 package org.wamblee.cache;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.Serializable;
23 import net.sf.ehcache.Cache;
24 import net.sf.ehcache.CacheException;
25 import net.sf.ehcache.CacheManager;
26 import net.sf.ehcache.Element;
28 import org.apache.log4j.Logger;
29 import org.wamblee.io.InputResource;
32 * Cache implemented on top of EhCache.
34 public class EhCache<KeyType extends Serializable, ValueType extends Serializable>
35 implements org.wamblee.cache.Cache<KeyType, ValueType> {
37 private static final Logger LOGGER = Logger.getLogger(EhCache.class);
42 private CacheManager _manager;
50 * Constructs a cache based on EHCache.
53 * Resource containing the configuration file for EHCache.
55 * Name of the cache to use. If a cache with this name does not
56 * exist, one is created based on default settings.
58 * @throws CacheException
60 public EhCache(InputResource aResource, String aCacheName)
61 throws IOException, CacheException {
62 InputStream is = aResource.getInputStream();
64 _manager = CacheManager.create(is);
65 _cache = _manager.getCache(aCacheName);
67 LOGGER.warn("Creating cache '" + aCacheName
68 + "' because it is not configured");
69 _manager.addCache(aCacheName);
70 _cache = _manager.getCache(aCacheName);
72 assert _cache != null;
82 * @see org.wamblee.cache.Cache#put(KeyType, ValueType)
84 public void put(KeyType aKey, ValueType aValue) {
85 _cache.put(new Element(aKey, aValue));
91 * @see org.wamblee.cache.Cache#get(KeyType)
93 public ValueType get(KeyType aKey) {
95 Element element = _cache.get(aKey);
96 if (element == null) {
99 return (ValueType) element.getValue();
100 } catch (CacheException e) {
101 throw new RuntimeException("Cache problem key = '" + aKey + "'", e);
108 * @see org.wamblee.cache.Cache#remove(KeyType)
110 public void remove(KeyType aKey) {
117 * @see org.wamblee.cache.Cache#clear()
119 public void clear() {