/*
 * JBoss, the OpenSource WebOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.web.tomcat.tc5.session;

import org.apache.catalina.Manager;
import org.apache.catalina.Context;
import org.apache.catalina.Session;

import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Map;

import org.apache.catalina.util.StringManager;
import org.apache.catalina.util.Enumerator;
import org.apache.catalina.session.StandardSession;
import org.jboss.logging.Logger;

import javax.servlet.http.*;

/**
 * Abstract base class for session clustering based on StandardSession. Different session
 * replication strategy can be implemented such as session- or attribute-based ones.
 *
 * @author Ben Wang
 * @version $Revision: 1.1.2.9 $
 */
abstract class ClusteredSession
   extends StandardSession
{
   private static final long serialVersionUID = -758573655613558722L;
   protected static Logger log = Logger.getLogger(ClusteredSession.class);

   // ----------------------------------------------------- Instance Variables
   /**
    * Descriptive information describing this Session implementation.
    */
   protected static final String info = "ClusteredSession/1.0";

   protected int invalidationPolicy;

   /**
    * The string manager for this package.
    */
   protected static StringManager sm =
      StringManager.getManager("org.jboss.web.tomcat.session");

   public ClusteredSession(AbstractJBossManager manager)
   {
      super(manager);
      invalidationPolicy = ((AbstractJBossManager) this.manager).getInvalidateSessionPolicy();
   }

   /**
    * This is called after loading a session to initialize the transient values.
    *
    * @param manager
    */
   public abstract void initAfterLoad(AbstractJBossManager manager);

   /**
    * Set the Manager within which this Session is valid.
    *
    * @param manager The new Manager
    */
   public void setManager(Manager manager)
   {

      super.setManager(manager);

      this.manager = manager;
   }

   /**
    * Propogate session to the internal store.
    */
   public abstract void processSessionRepl();

   /**
    * Remove myself from the internal store.
    */
   public abstract void removeMyself();

   /**
    * Remove myself from the <t>local</t> internal store.
    */
   public abstract void removeMyselfLocal();

   //
   // ------------------------------------------------- Session Public Methods

   public Object getAttribute(String name)
   {

      if (!isValid())
         throw new IllegalStateException
            (sm.getString("standardSession.getAttribute.ise"));

      return getAttributeInternal(name);
   }

   public Enumeration getAttributeNames()
   {
      if (!isValid())
         throw new IllegalStateException
            (sm.getString("standardSession.getAttributeNames.ise"));

      return (new Enumerator(getAttributesInternal().keySet(), true));
   }

   public void setAttribute(String name, Object value)
   {
      // Name cannot be null
      if (name == null)
         throw new IllegalArgumentException
            (sm.getString("standardSession.setAttribute.namenull"));

      // Null value is the same as removeAttribute()
      if (value == null)
      {
         removeAttribute(name);
         return;
      }

      // Validate our current state
      if (!isValid())
         throw new IllegalStateException
            (sm.getString("standardSession.setAttribute.ise"));
      if ((manager != null) && manager.getDistributable() &&
         !(value instanceof Serializable))
         throw new IllegalArgumentException
            (sm.getString("standardSession.setAttribute.iae"));

      // Construct an event with the new value
      HttpSessionBindingEvent event = null;

      // Call the valueBound() method if necessary
      if (value instanceof HttpSessionBindingListener)
      {
         event = new HttpSessionBindingEvent(getSession(), name, value);
         try
         {
            ((HttpSessionBindingListener) value).valueBound(event);
         }
         catch (Throwable t)
         {
            log(sm.getString("standardSession.bindingEvent"), t);
         }
      }

      // Replace or add this attribute
      Object unbound = setInternalAttribute(name, value);

      // Call the valueUnbound() method if necessary
      if ((unbound != null) &&
         (unbound instanceof HttpSessionBindingListener))
      {
         try
         {
            ((HttpSessionBindingListener) unbound).valueUnbound
               (new HttpSessionBindingEvent(getSession(), name));
         }
         catch (Throwable t)
         {
            log(sm.getString("standardSession.bindingEvent"), t);
         }
      }

      // Notify interested application event listeners
      Context context = (Context) manager.getContainer();
      Object listeners[] = context.getApplicationEventListeners();
      if (listeners == null)
         return;
      for (int i = 0; i < listeners.length; i++)
      {
         if (!(listeners[i] instanceof HttpSessionAttributeListener))
            continue;
         HttpSessionAttributeListener listener =
            (HttpSessionAttributeListener) listeners[i];
         try
         {
            if (unbound != null)
            {
               fireContainerEvent(context,
                  "beforeSessionAttributeReplaced",
                  listener);
               if (event == null)
               {
                  event = new HttpSessionBindingEvent
                     (getSession(), name, unbound);
               }
               listener.attributeReplaced(event);
               fireContainerEvent(context,
                  "afterSessionAttributeReplaced",
                  listener);
            }
            else
            {
               fireContainerEvent(context,
                  "beforeSessionAttributeAdded",
                  listener);
               if (event == null)
               {
                  event = new HttpSessionBindingEvent
                     (getSession(), name, value);
               }
               listener.attributeAdded(event);
               fireContainerEvent(context,
                  "afterSessionAttributeAdded",
                  listener);
            }
         }
         catch (Throwable t)
         {
            try
            {
               if (unbound != null)
               {
                  fireContainerEvent(context,
                     "afterSessionAttributeReplaced",
                     listener);
               }
               else
               {
                  fireContainerEvent(context,
                     "afterSessionAttributeAdded",
                     listener);
               }
            }
            catch (Exception e)
            {
               ;
            }
            log(sm.getString("standardSession.attributeEvent"), t);
         }
      }

   }


   /**
    * Override here to reverse the order of manager session removal and
    * attribute removal.
    *
    * @param notify
    */
   public void expire(boolean notify)
   {
      if (log.isDebugEnabled())
      {
         log.debug("The session has expired with id: " + id);
      }
      // Mark this session as "being expired" if needed
      if (expiring)
         return;

      synchronized (this)
      {

         if (manager == null)
            return;

         expiring = true;

         // Notify interested application event listeners
         // FIXME - Assumes we call listeners in reverse order
         Context context = (Context) manager.getContainer();
         Object listeners[] = context.getApplicationLifecycleListeners();
         if (notify && (listeners != null))
         {
            HttpSessionEvent event =
               new HttpSessionEvent(getSession());
            for (int i = 0; i < listeners.length; i++)
            {
               int j = (listeners.length - 1) - i;
               if (!(listeners[j] instanceof HttpSessionListener))
                  continue;
               HttpSessionListener listener =
                  (HttpSessionListener) listeners[j];
               try
               {
                  fireContainerEvent(context,
                     "beforeSessionDestroyed",
                     listener);
                  listener.sessionDestroyed(event);
                  fireContainerEvent(context,
                     "afterSessionDestroyed",
                     listener);
               }
               catch (Throwable t)
               {
                  try
                  {
                     fireContainerEvent(context,
                        "afterSessionDestroyed",
                        listener);
                  }
                  catch (Exception e)
                  {
                     ;
                  }
                  log(sm.getString("standardSession.sessionEvent"), t);
               }
            }
         }
         accessCount = 0;
         setValid(false);

         // Notify interested session event listeners
         if (notify)
         {
            fireSessionEvent(Session.SESSION_DESTROYED_EVENT, null);
         }

         // We have completed expire of this session
         expiring = false;

         // Remove this session from our manager's active sessions
         if (manager != null)
            ((AbstractJBossManager) manager).removeLocal(this);
      }

   }

   public void passivate()
   {
      // TODO. We don't do this now.
   }

   public void activate()
   {
      // TODO. We don't do this now.
   }

   // ------------------------------------------------ Internal protected method override

   /**
    * Method inherited from Tomcat. Return zero-length based string if not found.
    */
   protected String[] keys()
   {
      return ((String[]) getAttributesInternal().keySet().toArray(EMPTY_ARRAY));
   }

   protected void removeAttributeInternal(String name, boolean notify)
   {

      // Remove this attribute from our collection
      Object value = removeJBossInternalAttribute(name);

      // Do we need to do valueUnbound() and attributeRemoved() notification?
      if (!notify || (value == null))
      {
         return;
      }

      // Call the valueUnbound() method if necessary
      HttpSessionBindingEvent event = null;
      if (value instanceof HttpSessionBindingListener)
      {
         event = new HttpSessionBindingEvent(getSession(), name, value);
         ((HttpSessionBindingListener) value).valueUnbound(event);
      }

      // Notify interested application event listeners
      Context context = (Context) manager.getContainer();
      Object listeners[] = context.getApplicationEventListeners();
      if (listeners == null)
         return;
      for (int i = 0; i < listeners.length; i++)
      {
         if (!(listeners[i] instanceof HttpSessionAttributeListener))
            continue;
         HttpSessionAttributeListener listener =
            (HttpSessionAttributeListener) listeners[i];
         try
         {
            fireContainerEvent(context,
               "beforeSessionAttributeRemoved",
               listener);
            if (event == null)
            {
               event = new HttpSessionBindingEvent
                  (getSession(), name, value);
            }
            listener.attributeRemoved(event);
            fireContainerEvent(context,
               "afterSessionAttributeRemoved",
               listener);
         }
         catch (Throwable t)
         {
            try
            {
               fireContainerEvent(context,
                  "afterSessionAttributeRemoved",
                  listener);
            }
            catch (Exception e)
            {
               ;
            }
            log(sm.getString("standardSession.attributeEvent"), t);
         }
      }

   }

   protected Object getAttributeInternal(String name)
   {
      return getJBossInternalAttribute(name);
   }

   protected Map getAttributesInternal()
   {
      return getJBossInternalAttributes();
   }

   protected Object setInternalAttribute(String name, Object value)
   {
      return setJBossInternalAttribute(name, value);
   }

   // ------------------------------------------------ JBoss internal abstract method
   protected abstract Object getJBossInternalAttribute(String name);

   protected abstract Object removeJBossInternalAttribute(String name);

   protected abstract Map getJBossInternalAttributes();

   protected abstract Object setJBossInternalAttribute(String name, Object value);

   // ------------------------------------------------ Session Package Methods
   protected void writeObject(java.io.ObjectOutputStream out)
      throws IOException
   {
      synchronized (attributes)
      {
         out.defaultWriteObject();
      }
   }

   protected void readObject(java.io.ObjectInputStream in)
      throws IOException, ClassNotFoundException
   {
      in.defaultReadObject();
   }

}
