1 4 package com.tc.util; 5 6 import org.apache.commons.lang.exception.ExceptionUtils; 7 8 import java.io.IOException ; 9 import java.io.Writer ; 10 import java.lang.reflect.InvocationHandler ; 11 import java.lang.reflect.InvocationTargetException ; 12 import java.lang.reflect.Method ; 13 import java.lang.reflect.Proxy ; 14 import java.util.ArrayList ; 15 import java.util.List ; 16 17 26 public class LoggingInvocationHandler implements InvocationHandler { 27 28 private final Object delegate; 29 private final Writer dest; 30 private final Class [] furtherProxies; 31 32 public LoggingInvocationHandler(Object delegate, Writer dest, Class [] furtherProxies) { 33 Assert.assertNotNull(delegate); 34 Assert.assertNotNull(dest); 35 Assert.assertNoNullElements(furtherProxies); 36 this.delegate = delegate; 37 this.dest = dest; 38 this.furtherProxies = furtherProxies; 39 } 40 41 public Object invoke(Object arg0, Method arg1, Object [] arg2) throws Throwable { 42 Thread theThread = Thread.currentThread(); 43 StringBuffer message = new StringBuffer (); 44 45 message.append("[" + theThread.getName() + "]: " + delegate + "." + arg1 + "(" + describeArguments(arg2) + ")"); 46 try { 47 Object result = arg1.invoke(delegate, arg2); 48 message.append(" ==> " + result); 49 process(message.toString()); 50 return reproxify(result); 51 } catch (InvocationTargetException ite) { 52 message.append(" => THROWABLE: "); 53 message.append(ExceptionUtils.getStackTrace(ite.getCause())); 54 message.append("."); 55 process(message.toString()); 56 throw ite.getCause(); 57 } 58 } 59 60 private Object reproxify(Object out) { 61 if (out == null) return out; 62 if (Proxy.isProxyClass(out.getClass())) return out; 63 64 List implementedClasses = new ArrayList (); 65 66 for (int i = 0; i < furtherProxies.length; ++i) { 67 if (furtherProxies[i].isInstance(out)) { 68 implementedClasses.add(furtherProxies[i]); 69 } 70 } 71 72 if (implementedClasses.size() > 0) { 73 return Proxy.newProxyInstance(getClass().getClassLoader(), (Class []) implementedClasses 74 .toArray(new Class [implementedClasses.size()]), new LoggingInvocationHandler(out, this.dest, 75 this.furtherProxies)); 76 } else { 77 return out; 78 } 79 } 80 81 private String describeArguments(Object [] arguments) { 82 if (arguments == null) return ""; 83 84 StringBuffer out = new StringBuffer (); 85 86 for (int i = 0; i < arguments.length; ++i) { 87 if (i > 0) out.append(", "); 88 out.append(arguments[i]); 89 } 90 91 return out.toString(); 92 } 93 94 private void process(String message) { 95 try { 96 dest.write("\n\n" + message + "\n"); 97 dest.flush(); 98 } catch (IOException ioe) { 99 throw Assert.failure("Got an IOException when writing.", ioe); 100 } 101 } 102 103 } 104 | Popular Tags |