1 package org.sapia.gumby.tags.script; 2 3 import java.lang.reflect.InvocationHandler ; 4 import java.lang.reflect.Method ; 5 import java.lang.reflect.Proxy ; 6 import java.util.ArrayList ; 7 import java.util.HashMap ; 8 import java.util.List ; 9 import java.util.Map ; 10 11 import org.sapia.gumby.RenderContext; 12 import org.sapia.gumby.factory.ContextAware; 13 import org.sapia.util.xml.confix.ConfigurationException; 14 import org.sapia.util.xml.confix.ObjectCreationCallback; 15 16 31 public class ProxyTag implements ContextAware, ObjectCreationCallback { 32 33 private RenderContext _context; 34 private List _implements = new ArrayList (); 35 private List _methods = new ArrayList (); 36 37 public void addImplements(String intfName) { 38 Class intf = _context.getSettings().resolveClass(intfName); 39 if(intf == null) { 40 throw new IllegalArgumentException ("Interface not found: " + intfName); 41 } 42 _implements.add(intf); 43 } 44 45 public MethodTag createMethod() { 46 MethodTag m = new MethodTag(); 47 _methods.add(m); 48 return m; 49 } 50 51 54 public Object onCreate() throws ConfigurationException { 55 Map methods = new HashMap (); 56 MethodTag m; 57 for(int i = 0; i < _methods.size(); i++) { 58 m = (MethodTag) _methods.get(i); 59 methods.put(m.getName(), m); 60 } 61 62 Class [] impl = (Class []) _implements.toArray(new Class [_implements.size()]); 63 return Proxy.newProxyInstance(Thread.currentThread() 64 .getContextClassLoader(), impl, new ProxyHandler(_context, methods)); 65 } 66 67 70 public void handleContext(RenderContext context) { 71 _context = context; 72 } 73 74 public static class ProxyHandler implements InvocationHandler { 75 76 private RenderContext _context; 77 private Map _methodTags; 78 79 ProxyHandler(RenderContext context, Map methodTags) { 80 _context = context; 81 _methodTags = methodTags; 82 } 83 84 88 public Object invoke(Object proxy, Method method, Object [] args) 89 throws Throwable { 90 MethodTag m = (MethodTag) _methodTags.get(method.getName()); 91 if(m != null) { 92 return m.execute(_context, args); 93 } else { 94 return method.invoke(this, args); 95 } 96 } 97 } 98 99 } 100 | Popular Tags |