Interceptors

Jiapi interceptors are similar to jiapi events and jazzpect.

Interceptor example

Following method interceptor example shows a way to measure execution time of methods being invoked. While jazzpect uses aopalliance interfaces to make the call to underlying Objects, method interceptor uses java.lang.reflect classes to accomplish the same thing.

Given a class samples.Foo as

package samples;

public class Foo {
   public static void main(String[] args) {
      foo1("a string");
      System.out.println("> " + foo2(3));
   }

   public static void foo1(String s) {
      System.out.println("> " + s);
   }

   public static int foo2(int i) {
      return i+1;
   }
}

And samples.interceptor.Sample1 as

package samples.interceptor;

import java.lang.reflect.InvocationHandler;

import net.sf.jiapi.interceptor.InvocationInterceptor;
import net.sf.jiapi.reflect.util.Bootstrapper;
import net.sf.jiapi.reflect.util.InstrumentationContext;
import net.sf.jiapi.reflect.util.InstrumentationDescriptor;
import net.sf.jiapi.reflect.util.InstrumentingClassLoader;

public class Sample1 implements InvocationHandler {
   public static void main(String args[]) throws Exception {
      // Configure:
      InstrumentationContext ctx = new InstrumentationContext();
      InstrumentationDescriptor id = new InstrumentationDescriptor();
      id.addInclusionRule("samples.*");
      InvocationInterceptor ii = new InvocationInterceptor(id, "samples*", new Sample1());
      ctx.addInstrumentationDescriptor(id);

      // Launch samples.Foo
      Bootstrapper.launch("samples.Foo", null, ctx,
            InstrumentingClassLoader.createClassLoader(ctx));
   }

   @Override
   public Object invoke(Object o, java.lang.reflect.Method m, Object[] args)
         throws Exception {

      // Make a call to target method through java.lang.reflect.Method
      long l1 = System.currentTimeMillis(); 
      Object rv = m.invoke(o, args);
      long l2 = System.currentTimeMillis();

      System.out.println("### It took " + (l2 - l1) + " ms to invoke "
            + m.getName());

      return rv;
   }
}

Will print following output to console

> a string
### It took 0 ms to invoke foo1
### It took 0 ms to invoke foo2
> 4