1 10 11 package org.mule.util; 12 13 import java.lang.reflect.InvocationHandler ; 14 import java.lang.reflect.Method ; 15 import java.lang.reflect.Proxy ; 16 import java.util.ArrayList ; 17 import java.util.Collection ; 18 import java.util.Iterator ; 19 import java.util.List ; 20 21 27 public class Multicaster 29 { 30 31 public static Object create(Class theInterface, Collection objects) 32 { 33 return create(new Class []{theInterface}, objects); 34 } 35 36 public static Object create(Class theInterface, Collection objects, InvokeListener listener) 37 { 38 return create(new Class []{theInterface}, objects, listener); 39 } 40 41 public static Object create(Class [] interfaces, Collection objects) 42 { 43 return create(interfaces, objects, null); 44 } 45 46 public static Object create(Class [] interfaces, Collection objects, InvokeListener listener) 47 { 48 return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), interfaces, 49 new CastingHandler(objects, listener)); 50 } 51 52 private static class CastingHandler implements InvocationHandler 53 { 54 private final Collection objects; 55 private final InvokeListener listener; 56 57 public CastingHandler(Collection objects) 58 { 59 this(objects, null); 60 } 61 62 public CastingHandler(Collection objects, InvokeListener listener) 63 { 64 this.objects = objects; 65 this.listener = listener; 66 } 67 68 public Object invoke(Object proxy, Method method, Object [] args) throws Throwable 69 { 70 List results = new ArrayList (); 71 Object item = null; 72 Object result; 73 74 for (Iterator iterator = objects.iterator(); iterator.hasNext();) 75 { 76 try 77 { 78 item = iterator.next(); 79 result = method.invoke(item, args); 80 if (listener != null) 81 { 82 listener.afterExecute(item, method, args); 83 } 84 if (result != null) 85 { 86 results.add(result); 87 } 88 } 89 catch (Throwable t) 90 { 91 if (listener != null) 92 { 93 t = listener.onException(item, method, args, t); 94 if (t != null) 95 { 96 throw t; 97 } 98 } 99 } 100 } 101 return results; 102 } 103 } 104 105 public static interface InvokeListener 106 { 107 void afterExecute(Object object, Method method, Object [] args); 108 109 Throwable onException(Object object, Method method, Object [] args, Throwable t); 110 } 111 112 } 113 | Popular Tags |