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

import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.jboss.aop.util.PayloadKey;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;

/**
 * An interceptor that tests dumps any logging into the
 * invocation response
 *
 * @author  <a href="mailto:adrian@jboss">Adrian Brock</a>.
 * @version $Revision: 1.2.2.4 $
 */
public class InvocationLogClientInterceptor
   implements org.jboss.aop.advice.Interceptor, Serializable
{
   // Constants -----------------------------------------------------

   private static final long serialVersionUID = 9191894622629072033L;

   // Attributes ----------------------------------------------------

   // Static --------------------------------------------------------

   // Constructors --------------------------------------------------

   // Public --------------------------------------------------------

   // Interceptor Implementation ------------------------------------

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

   /**
    * @todo remove the hardwiring of the meta data (needs next invocation metadata)
    */
   public Object invoke(org.jboss.aop.joinpoint.Invocation invocation)
      throws Throwable
   {
      // TODO: This should be set by the caller when required
      invocation.getMetaData().addMetaData(ThreadLocalAppender.LOG, ThreadLocalAppender.LOG, "Log", PayloadKey.AS_IS);

      // Perform the invocation and dump any attached log
      Object response = invocation.invokeNext();
      if (response != null)
         dumpLog(invocation);
      return response;
   }

   public void dumpLog(org.jboss.aop.joinpoint.Invocation invocation)
   {
      Logger root = Logger.getRootLogger();
      ArrayList list = (ArrayList) invocation.getResponseAttachment(ThreadLocalAppender.LOG);
      for (Iterator i = list.iterator(); i.hasNext();)
          root.callAppenders((LoggingEvent) i.next());
   }

   // Y Overrides ---------------------------------------------------

   // Protected -----------------------------------------------------

   // Private -------------------------------------------------------

   // Inner Classes -------------------------------------------------
}
