1 25 26 package org.snipsnap.interceptor; 27 28 import org.snipsnap.interceptor.custom.*; 29 import org.snipsnap.snip.BlogImpl; 30 import org.snipsnap.snip.SnipImpl; 31 import org.snipsnap.snip.SnipSpaceImpl; 32 33 import java.lang.reflect.InvocationHandler ; 34 import java.lang.reflect.Method ; 35 import java.lang.reflect.Proxy ; 36 import java.util.ArrayList ; 37 import java.util.List ; 38 39 public class Aspects implements InvocationHandler { 40 private Object target = null; 41 private List interceptors; 42 43 46 static ThreadLocal currentThis = new ThreadLocal (); 47 48 public static boolean hasTarget(Object proxy) { 49 return ((Aspects) Proxy.getInvocationHandler(proxy)).hasTarget(); 50 } 51 52 private boolean hasTarget() { 53 return null != target; 54 } 55 56 public static Object getThis() { 57 return currentThis.get(); 58 } 59 60 public static Object newInstance(Object target) { 61 return newInstance(target, target.getClass().getInterfaces()); 62 } 63 64 public static Object newInstance(Object target, Class interfaceTarget) { 65 return newInstance(target, new Class []{interfaceTarget}); 66 } 67 68 public static Object newInstance(Object target, Class [] interfaceTargets) { 69 Class targetClass = target.getClass(); 70 Class interfaces[] = interfaceTargets; 71 Aspects aspects = new Aspects(target); 72 if (target.getClass().equals(SnipImpl.class)) { 73 aspects.addInterceptor(new ACLInterceptor()); 74 } else if (target.getClass().equals(SnipSpaceImpl.class)) { 75 aspects.addInterceptor(new MissingInterceptor()); 76 aspects.addInterceptor(new SnipSpaceACLInterceptor()); 77 aspects.addInterceptor(new StoreInterceptor()); 78 } else if (target.getClass().equals(BlogImpl.class)) { 79 aspects.addInterceptor(new BlogACLInterceptor()); 80 } 81 return Proxy.newProxyInstance(targetClass.getClassLoader(), 82 interfaces, aspects); 83 } 84 85 public Aspects(Object target) { 86 this.target = target; 87 interceptors = new ArrayList (); 88 } 89 90 public void addInterceptor(Interceptor interceptor) { 91 interceptors.add(interceptor); 92 } 93 94 public Object invoke(Object proxy, Method method, Object [] args) throws Throwable { 95 Object invocationResult = null; 97 Object previousThis = currentThis.get(); 98 currentThis.set(proxy); 99 Invocation i = new Invocation(target, method, args, interceptors); 100 try { 101 invocationResult = i.next(); 102 } catch (Throwable throwable) { 103 throwable.printStackTrace(); 104 } finally { 105 currentThis.set(previousThis); 106 } 107 108 return invocationResult; 109 } 110 } 111 | Popular Tags |