1 8 package examples.caching; 9 10 import java.util.HashMap ; 11 import java.util.Map ; 12 13 import org.codehaus.aspectwerkz.joinpoint.JoinPoint; 14 import org.codehaus.aspectwerkz.joinpoint.MethodSignature; 15 import org.codehaus.aspectwerkz.joinpoint.MethodRtti; 16 import org.codehaus.aspectwerkz.joinpoint.Rtti; 17 import org.codehaus.aspectwerkz.AspectContext; 18 import org.codehaus.aspectwerkz.AspectContext; 19 import org.codehaus.aspectwerkz.AspectContext; 20 21 25 public class CachingAspect { 26 27 30 private final AspectContext m_info; 31 32 35 private final Map m_cache = new HashMap (); 36 37 43 public CachingAspect(final AspectContext info) { 44 m_info = info; 45 } 46 47 51 public void invocationCounter(final JoinPoint joinPoint) throws Throwable { 52 MethodSignature signature = (MethodSignature) joinPoint.getSignature(); 53 CacheStatistics.addMethodInvocation(signature.getName(), signature.getParameterTypes()); 54 } 55 56 59 public Object cache(final JoinPoint joinPoint) throws Throwable { 60 MethodRtti mrtti = (MethodRtti) joinPoint.getRtti(); 61 final Long hash = new Long (calculateHash(mrtti)); 62 final Object cachedResult = m_cache.get(hash); 63 if (cachedResult != null) { 64 System.out.println("using cache"); 65 CacheStatistics.addCacheInvocation(mrtti.getName(), mrtti.getParameterTypes()); 66 System.out.println("parameter: timeout = " + m_info.getParameter("timeout")); 67 return cachedResult; 68 } 69 final Object result = joinPoint.proceed(); 70 m_cache.put(hash, result); 71 return result; 72 } 73 74 76 private long calculateHash(final MethodRtti rtti) { 77 int result = 17; 78 result = 37 * result + rtti.getName().hashCode(); 79 Object [] parameters = rtti.getParameterValues(); 80 for (int i = 0, j = parameters.length; i < j; i++) { 81 result = 37 * result + parameters[i].hashCode(); 82 } 83 return result; 84 } 85 } | Popular Tags |