1 8 package org.picocontainer.defaults; 9 10 import org.picocontainer.ComponentAdapter; 11 import org.picocontainer.Parameter; 12 import org.picocontainer.PicoContainer; 13 import org.picocontainer.PicoIntrospectionException; 14 15 import java.lang.reflect.InvocationTargetException ; 16 import java.lang.reflect.Method ; 17 import java.util.ArrayList ; 18 import java.util.Collections ; 19 import java.util.Iterator ; 20 import java.util.List ; 21 import java.io.Serializable ; 22 23 24 30 public class LifecycleVisitor extends AbstractPicoVisitor implements Serializable { 31 32 private transient Method method; 33 private Class type; 34 private boolean visitInInstantiationOrder; 35 private List componentInstances; 36 private ComponentMonitor componentMonitor; 37 38 public LifecycleVisitor(Method method, Class ofType, boolean visitInInstantiationOrder, ComponentMonitor componentMonitor) { 39 this.method = method; 40 this.type = ofType; 41 this.visitInInstantiationOrder = visitInInstantiationOrder; 42 this.componentMonitor = componentMonitor; 43 this.componentInstances = new ArrayList (); 44 } 45 46 public LifecycleVisitor(Method method, Class ofType, boolean visiInInstantiationOrder) { 47 this(method, ofType, visiInInstantiationOrder, NullComponentMonitor.getInstance()); 48 } 49 50 public Object traverse(Object node) { 51 componentInstances.clear(); 52 try { 53 super.traverse(node); 54 if (!visitInInstantiationOrder) { 55 Collections.reverse(componentInstances); 56 } 57 for (Iterator iterator = componentInstances.iterator(); iterator.hasNext();) { 58 Object o = iterator.next(); 59 try { 60 componentMonitor.invoking(method, o); 61 long startTime = System.currentTimeMillis(); 62 method.invoke(o, null); 63 componentMonitor.invoked(method, o, System.currentTimeMillis() - startTime); 64 } catch (IllegalArgumentException e) { 65 componentMonitor.invocationFailed(method, o, e); 66 throw new PicoIntrospectionException("Can't call " + method.getName() + " on " + o, e); 67 } catch (IllegalAccessException e) { 68 componentMonitor.invocationFailed(method, o, e); 69 throw new PicoIntrospectionException("Can't call " + method.getName() + " on " + o, e); 70 } catch (InvocationTargetException e) { 71 componentMonitor.invocationFailed(method, o, e); 72 throw new PicoIntrospectionException("Failed when calling " + method.getName() + " on " + o, e.getTargetException()); 73 } 74 } 75 } finally { 76 componentInstances.clear(); 77 } 78 return Void.TYPE; 79 } 80 81 public void visitContainer(PicoContainer pico) { 82 checkTraversal(); 83 componentInstances.addAll(pico.getComponentInstancesOfType(type)); 84 } 85 86 public void visitComponentAdapter(ComponentAdapter componentAdapter) { 87 checkTraversal(); 88 } 89 90 public void visitParameter(Parameter parameter) { 91 checkTraversal(); 92 } 93 94 } 95 | Popular Tags |