1 package com.tirsen.nanning.samples; 2 3 import java.lang.reflect.Method ; 4 import java.util.Arrays ; 5 import java.util.HashMap ; 6 import java.util.List ; 7 import java.util.Map ; 8 9 import com.tirsen.nanning.*; 10 import com.tirsen.nanning.attribute.Attributes; 11 import org.apache.commons.logging.Log; 12 import org.apache.commons.logging.LogFactory; 13 14 public class CacheInterceptor implements MethodInterceptor, FilterMethodsInterceptor { 15 private static final Log logger = LogFactory.getLog(CacheInterceptor.class); 16 17 20 private Map cache = new HashMap (); 21 22 public boolean interceptsMethod(Method method) { 23 return Attributes.hasAttribute(method, "cache"); 24 } 25 26 public Object invoke(Invocation invocation) throws Throwable { 27 Method method = invocation.getMethod(); 28 Map methodCache = getMethodCache(method); 29 List args = Arrays.asList(invocation.getArgs()); Object cachedResult = methodCache.get(args); 31 if (cachedResult == null) { 32 if (logger.isDebugEnabled()) { 33 logger.debug("caching call for method " + method + " with args " + args); 34 } 35 cachedResult = invocation.invokeNext(); 36 methodCache.put(args, cachedResult); 37 } 38 return cachedResult; 39 } 40 41 private Map getMethodCache(Method method) { 42 Map methodCache = (Map ) cache.get(method); 43 if (methodCache == null) { 44 methodCache = new HashMap (); 45 cache.put(method, methodCache); 46 } 47 return methodCache; 48 } 49 50 public void clearCache() { 51 cache.clear(); 52 } 53 } 54 | Popular Tags |