/*

 * Asynchronous Engine .

 * 

 * Copyright (C) 2004 Claude Hussenet

 * Contact : chussenet@yahoo.com

 * 

 * Distributable under LGPL license.

 * See terms of license at gnu.org.

 */

package org.jboss.aspects.asynchronous.aspects.jboss;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.aop.joinpoint.MethodInvocation;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author <a href="mailto:chussenet@yahoo.com">{Claude Hussenet Independent Consultant}</a>.
 * @version <tt>$Revision: 1.2.4.3 $</tt>
 */

public class TraceThreadAspect
{

   static private final Log log = LogFactory.getLog(TraceThreadAspect.class);

   static private SimpleDateFormat formatter =

   new SimpleDateFormat("hh:mm:ss:SSS aaa z");

   public TraceThreadAspect() {}

   public Object trace(MethodInvocation methodInvocation) throws Throwable
   {

      String className = null;

      if (methodInvocation.getTargetObject() != null)

         className = methodInvocation.getTargetObject().getClass().getName();

      else

         className = methodInvocation.getMethod().getDeclaringClass().getName();

      StringBuffer txt =

      new StringBuffer(Thread.currentThread().toString())

      .append(" ")

      .append(methodInvocation.getMethod().getReturnType().getName())

      .append(" ")

      .append(className)

      .append(".")

      .append(methodInvocation.getMethod().getName())

      .append("(");

      Class[] parameterTypes =

      methodInvocation.getActualMethod().getParameterTypes();

      for (int i = 0; i < parameterTypes.length; i++)
      {

         txt.append(parameterTypes[i].getName());

         if (i + 1 < parameterTypes.length)

            txt.append(",");

      }

      txt.append(")");

      log.info(new StringBuffer("TRACE ENTER: ").append(getCurrentDate()).append(" ").append(txt));

      Object rsp = methodInvocation.invokeNext();

      log.info(new StringBuffer("TRACE EXIT: ").append(getCurrentDate()).append(" ").append(txt));

      return rsp;

   }

   static public String getCurrentDate()
   {

      return formatter.format(new Date(System.currentTimeMillis()));

   }

}
