001 /* 002 * Copyright 2010 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 package com.hs.mail.util; 017 018 import java.util.List; 019 020 import net.sf.ehcache.Ehcache; 021 import net.sf.ehcache.Element; 022 023 public class EhCacheWrapper<K, V> implements CacheWrapper<K, V> { 024 025 private Ehcache cache; 026 027 public EhCacheWrapper(Ehcache cache) { 028 this.cache = cache; 029 } 030 031 @SuppressWarnings("unchecked") 032 public V get(K key) { 033 Element element = getCache().get(key); 034 if (element != null) { 035 return (V) element.getObjectValue(); 036 } 037 return null; 038 } 039 040 public void put(K key, V value) { 041 getCache().put(new Element(key, value)); 042 } 043 044 public boolean remove(K key) { 045 return getCache().remove(key); 046 } 047 048 public Ehcache getCache() { 049 return cache; 050 } 051 052 public int remove(List<K> keys) { 053 int evicted = 0; 054 if (keys != null) { 055 for (K key : keys) { 056 if (remove(key)) { 057 evicted++; 058 } 059 } 060 } 061 return evicted; 062 } 063 064 public static void flush(EhCacheWrapper<?, ?> wrapper) { 065 if (wrapper != null) { 066 wrapper.getCache().flush(); 067 } 068 } 069 070 }