/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.ha.httpsession.beanimpl.ejb;


import java.rmi.RemoteException;

import javax.ejb.EJBException;

import org.jboss.ha.httpsession.interfaces.SerializableHttpSession;
import org.jboss.invocation.MarshalledValue;
import org.jboss.metadata.WebMetaData;
import org.jboss.logging.Logger;

/**
 * Core implementation of methods for the bean.
 *
 * @see org.jboss.ha.httpsession.beanimpl.interfaces.ClusteredHTTPSession
 * @see org.jboss.ha.httpsession.beanimpl.ejb.ClusteredHTTPSessionBeanAbstract
 *
 * @author  <a href="mailto:sacha.labourey@cogito-info.ch">Sacha Labourey</a>.
 * @version $Revision: 1.2.4.7 $
 */
public abstract class ClusteredHTTPSessionBeanImpl extends ClusteredHTTPSessionBeanAbstract
{
   private static Logger log = Logger.getLogger(ClusteredHTTPSessionBeanImpl.class);

   // Constants -----------------------------------------------------

   // Attributes ----------------------------------------------------
   protected SerializableHttpSession tmpSession = null;
   protected boolean isModified = false;

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

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

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

   // ClusteredHTTPSessionBeanAbstract overrides ---------------------------------------------------

   public void ejbStore () throws EJBException, RemoteException
   {
      if (tmpSession != null)
      {
         // the tmpSession has been assigned. Furthermore, if ejbStore is called
         // it means that isModified==true => we need to rebuild a serialized representation
         //
         serializeSession();

         this.tmpSession.sessionHasBeenStored ();
      }

      isModified = false;
   }

   public void ejbLoad () throws EJBException, RemoteException
   {
      // the tmp value is no more valid: a new serialized representation is just loaded.
      // it will be transformed only if explicitly asked.
      //
      tmpSession = null;
      isModified = false;
   }

   public SerializableHttpSession getSession ()
   {
      if (tmpSession == null)
      {
         // this is the first access to the object representation.
         // we use a lazy scheme => we unserialize now
         unserializeSession ();
      }
      if( trace )
      {
         String id = this.getSessionId();
         log.trace("getSession("+id+"), session.hashCode="+
            System.identityHashCode(tmpSession));
      }
      return this.tmpSession;
   }

   public void setSession (SerializableHttpSession session)
   {
      if (tmpSession == null)
         isModified = true;
      else
         isModified = session.areAttributesModified (tmpSession);

      // in any case, we update the "time" attributes
      //
      this.setCreationTime (session.getContentCreationTime ());
      this.setLastAccessedTime (session.getContentLastAccessTime ());

      // in any cases, we assign the new session: this is because the session
      // may have internal data that is not used for the isModified comparison
      // (such as last access time). Consequently, if we use a load-balancer with
      // sticky sessions, the values will be kept in cache correctly whereas if we
      // don't have sticky session, these values will only be clustered-saved if
      // an attributed is modified!
      //
      this.tmpSession = session;
      if( trace )
      {
         String id = this.getSessionId();
         log.trace("setSession("+id+"), session.hashCode="+
            System.identityHashCode(tmpSession));
      }
   }

    // Optimisation: called by the CMP engine
    //
    public boolean isModified () { return this.isModified; }

   public boolean useAsyncReplication ()
   {
      if (this.tmpSession != null)
         return tmpSession.getReplicationTypeForSession() == WebMetaData.REPLICATION_TYPE_ASYNC;
      else
         return true; // happens when a session is removed without unserializing it (lazy- (un-) serialization)
   }

   // Package protected ---------------------------------------------

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

   protected void serializeSession() throws EJBException
   {
      try
      {
         String id = null;
         if( trace )
         {
            id = this.getSessionId();
            log.trace("serializeSession("+id+")");
         }
         MarshalledValue mv = new MarshalledValue (this.tmpSession);
         this.setSerializedSession (mv);
         if( trace )
            log.trace("serializeSession("+id+"), wrote bytes: "+mv.size());
      }
      catch (Exception e)
      {
         throw new EJBException ("serializeSession failed", e);
      }
   }

   protected void unserializeSession() throws EJBException
   {
      try
      {
         String id = null;
         if( trace )
         {
            id = this.getSessionId();
            log.trace("unserializeSession("+id+")");
         }
         MarshalledValue mo = (MarshalledValue)this.getSerializedSession ();
         if( trace )
            log.trace("unserializeSession("+id+"), read bytes: "+mo.size());
         if (mo != null)
            this.tmpSession = (SerializableHttpSession)(mo.get ());
      }
      catch (Exception e)
      {
         throw new EJBException ("unserializeSession failed", e);
      }
   }

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

   // Inner classes -------------------------------------------------

}
