View Javadoc

    1   package groovy.lang;
    2
    3   import java.io.IOException;
    4   import java.io.PrintWriter;
    5   import java.io.Writer;
    6
    7   public class TracingInterceptor implements Interceptor {
    8
    9       protected Writer writer = new PrintWriter(System.out);
    10      private int indent = 0;
    11
    12      public Writer getWriter() {
    13          return writer;
    14      }
    15
    16      public void setWriter(Writer writer) {
    17          this.writer = writer;
    18      }
    19
    20      public Object beforeInvoke(Object object, String methodName, Object[] arguments) {
    21          write(object, methodName, arguments, "before");
    22          indent++ ;
    23          return null;
    24      }
    25
    26      public Object afterInvoke(Object object, String methodName, Object[] arguments, Object result) {
    27          indent--;
    28          write(object, methodName, arguments, "after ");
    29          return result;
    30      }
    31
    32      public boolean doInvoke() {
    33          return true;
    34      }
    35      private String indent(){
    36          StringBuffer result = new StringBuffer();
    37          for (int i=0; i<indent;i++){
    38              result.append("  ");
    39          }
    40          return result.toString();
    41      }
    42
    43      protected void write(Object object, String methodName, Object[] arguments, final String origin) {
    44          try {
    45              writer.write(indent());
    46              writer.write(origin);
    47              writer.write(" ");
    48              Class theClass = object instanceof Class ? (Class) object: object.getClass();
    49              writeInfo(theClass, methodName, arguments);
    50              writer.write("\n");
    51              writer.flush();
    52          } catch (IOException e) {
    53              e.printStackTrace();
    54          }
    55      }
    56
    57      protected void writeInfo(final Class aClass, String methodName, Object[] arguments) throws IOException {
    58          writer.write(aClass.getName());
    59          writer.write(".");
    60          writer.write(methodName);
    61          writer.write("(");
    62          for (int i = 0; i < arguments.length; i++) {
    63              if (i > 0) writer.write(", ");
    64              Object argument = arguments[i];
    65              writer.write(argument.getClass().getName());
    66          }
    67          writer.write(")");
    68      }
    69  }