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

import org.jboss.aop.InstanceAdvisor;
import org.jboss.aop.util.PayloadKey;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.2.8.4 $
 */
public class AsynchProxyMixin implements AsynchProvider, Externalizable
{
   private static final long serialVersionUID = -6895953696792282031L;

   public static final String CURRENT_FUTURE = "CURRENT_FUTURE";
   private transient ThreadLocal currentFuture;

   private InstanceAdvisor advisor;

   public void setAdvisor(InstanceAdvisor advisor)
   {
      this.advisor = advisor;
   }


   public void setFuture(Future future)
   {
      try
      {
         Future oldFuture = getFuture();
         if (oldFuture != null) oldFuture.release();
      }
      catch (Exception e)
      {
         // eat it.
      }
      currentFuture.set(future);
   }

   public Future getFuture()
   {
      Future future = (Future) currentFuture.get();
      currentFuture.set(null);
      return future;
   }

   public void writeExternal(ObjectOutput out) throws IOException
   {
      out.writeObject(advisor);
   }

   public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
   {
      advisor = (InstanceAdvisor) in.readObject();
      currentFuture = new ThreadLocal();
      advisor.getMetaData().addMetaData(CURRENT_FUTURE, CURRENT_FUTURE, currentFuture, PayloadKey.TRANSIENT);
   }
}
