001: package samples.tracing;
002:
003: import net.sf.cglib.proxy.MethodProxy;
004: import net.sf.cglib.proxy.MethodInterceptor;
005: import net.sf.cglib.proxy.Enhancer;
006:
007: /**
008: * This class is taken from the regular cglib samples.
009: */
010: public class Trace implements MethodInterceptor {
011:
012: public static class Target {
013: static int s_count = 0;
014:
015: private int m_count;
016:
017: public Target() {
018: m_count = s_count++;
019: }
020:
021: public void step1() {
022: step2(new Target());
023: }
024:
025: public void step2(Target arg) {
026: step3();
027: }
028:
029: public void step3() {
030: }
031:
032: public String toString() {
033: return "I am Target " + m_count;
034: }
035: }
036:
037: int ident = 1;
038: static Trace callback = new Trace();
039:
040: public static Object newInstance(Class clazz) {
041: try {
042: Enhancer e = new Enhancer();
043: e.setSuperclass(clazz);
044: e.setCallback(callback);
045: return e.create();
046: } catch (Throwable e) {
047: e.printStackTrace();
048: throw new Error(e.getMessage());
049: }
050:
051: }
052:
053: public static void main(String[] args) {
054: Target target = (Target) newInstance(Target.class);
055: target.step1();
056: }
057:
058: public Object intercept(Object obj,
059: java.lang.reflect.Method method, Object[] args,
060: MethodProxy proxy) throws Throwable {
061: printIdent(ident);
062: System.out.println(method);
063: for (int i = 0; i < args.length; i++) {
064: printIdent(ident);
065: System.out.print("arg" + (i + 1) + ": ");
066: if (obj == args[i]) {
067: System.out.println("this");
068: } else {
069: System.out.println(args[i]);
070: }
071: }
072: ident++;
073:
074: Object retValFromSuper = null;
075: try {
076: retValFromSuper = proxy.invokeSuper(obj, args);
077: ident--;
078: } catch (Throwable t) {
079: ident--;
080: printIdent(ident);
081: System.out.println("throw " + t);
082: System.out.println();
083: throw t.fillInStackTrace();
084: }
085:
086: printIdent(ident);
087: System.out.print("return ");
088: if (obj == retValFromSuper) {
089: System.out.println("this");
090: } else {
091: System.out.println(retValFromSuper);
092: }
093:
094: if (ident == 1) {
095: System.out.println();
096: }
097:
098: return retValFromSuper;
099: }
100:
101: void printIdent(int ident) {
102: while (--ident > 0) {
103: System.out.print(".......");
104: }
105: System.out.print(" ");
106: }
107:
108: private Trace() {
109: }
110: }
|