/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.cache.aop;

//import org.jboss.aop.InvocationResponse;

import org.jboss.aop.advice.Interceptor;
import org.jboss.aop.joinpoint.Invocation;
import org.jboss.aop.joinpoint.MethodInvocation;

import java.lang.reflect.Method;

/**
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.5 $
 */
public class MetricsInterceptor implements org.jboss.aop.advice.Interceptor
{

   public MetricsInterceptor()
   {
      System.out.println("### MetricsInterceptor was created ####");
   }

   public String getName()
   {
      return "MetricsInterceptor";
   }

   public Object invoke(org.jboss.aop.joinpoint.Invocation invocation) throws Throwable
   {
      if (invocation == null) {
         System.err.println("\n-- MetricsInterceptor: invocation is null !");
         return null;
      }

      try {

         System.out.println("*** MetricsInterceptor: inv=" + invocation);
         org.jboss.aop.joinpoint.MethodInvocation methodInvocation = (org.jboss.aop.joinpoint.MethodInvocation) invocation;
         Object[] args = methodInvocation.getArguments();
         Method meth = methodInvocation.getMethod();
         String method_name = meth != null ? meth.getName() : null;

         System.out.println("\n\n-- [MetricsInterceptor]: type=" + invocation.getClass().getName());
         if (method_name != null)
            System.out.println("-- [MetricsInterceptor]: method_name("
                  + printArgs(args)
                  + ")");
      } catch (Throwable t) {
         System.err.println("\n-- [MetricsInterceptor]: error " + t);
         throw t;
      }

      return invocation.invokeNext();
   }

   String printArgs(Object[] args)
   {
      StringBuffer sb = new StringBuffer();
      if (args != null) {
         for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            sb.append(arg).append(" ");
         }
      }
      return sb.toString();
   }

}