User: slaboure
  Date: 01/11/09 14:54:28

  Added:       src/main/org/jboss/ejb/plugins HAPersistentManager.java
                        StatefulHASessionPersistenceManager.java
                        StatefulHASessionSynchronisationInterceptor.java
  Log:
  Clustering for SFSB
  
  Revision  Changes    Path
  1.1                  jbossmx/src/main/org/jboss/ejb/plugins/HAPersistentManager.java
  
  Index: HAPersistentManager.java
  ===================================================================
  /*
   * JBoss, the OpenSource J2EE webOS
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  
  package org.jboss.ejb.plugins;
  
  import org.jboss.ejb.StatefulSessionEnterpriseContext;
  
  /**
   *  Tag interface to differentiate standard PersistentManager with HA one.
   *
   *  @see StatefulHASessionPersistenceManager
   *  @author <a href="mailto:[EMAIL PROTECTED]";>Sacha Labourey</a>
   *  @version $Revision: 1.1 $
   *
   *   <p><b>Revisions:</b>
   */
  
  public interface HAPersistentManager {
  
     public void synchroSession (StatefulSessionEnterpriseContext ctx) throws 
java.rmi.RemoteException;
     
  }
  
  
  
  
  1.1                  
jbossmx/src/main/org/jboss/ejb/plugins/StatefulHASessionPersistenceManager.java
  
  Index: StatefulHASessionPersistenceManager.java
  ===================================================================
  /*
   * JBoss, the OpenSource J2EE webOS
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  
  package org.jboss.ejb.plugins;
  
  import java.lang.reflect.Method;
  import java.lang.reflect.Field;
  import java.lang.reflect.Modifier;
  import java.lang.reflect.InvocationTargetException;
  import java.rmi.RemoteException;
  import java.rmi.NoSuchObjectException;
  import java.rmi.ServerException;
  import java.util.Collection;
  import java.util.ArrayList;
  import java.util.Iterator;
  import java.io.ByteArrayInputStream;
  import java.io.ByteArrayOutputStream;
  import java.io.ObjectInputStream;
  import java.io.ObjectOutputStream;
  import java.io.IOException;
  
  import javax.ejb.EJBObject;
  import javax.ejb.Handle;
  import javax.ejb.SessionBean;
  import javax.ejb.SessionContext;
  import javax.ejb.CreateException;
  import javax.ejb.DuplicateKeyException;
  import javax.ejb.FinderException;
  import javax.ejb.RemoveException;
  import javax.ejb.EJBException;
  import javax.naming.Context;
  import javax.naming.InitialContext;
  
  import org.jboss.ejb.Container;
  import org.jboss.ejb.StatefulSessionContainer;
  import org.jboss.ejb.StatefulSessionPersistenceManager;
  import org.jboss.ejb.StatefulSessionEnterpriseContext;
  import org.jboss.metadata.ClusterConfigMetaData;
  import org.jboss.logging.Logger;
  
  import org.jboss.ha.hasessionstate.interfaces.HASessionState;
  import org.jboss.ha.hasessionstate.interfaces.PackagedSession;
  import org.jboss.ha.framework.interfaces.HAPartition;
  
  /**
   *  This persistence manager work with an underlying HASessionState to get
   *  clustered state.
   *
   *  @see HASessionState, HASessionStateImpl
   *  @author <a href="mailto:[EMAIL PROTECTED]";>Sacha Labourey</a>
   *  @version $Revision: 1.1 $
   *
   *   <p><b>Revisions:</b>
   */
  
  public class StatefulHASessionPersistenceManager
  implements org.jboss.ejb.StatefulSessionPersistenceManager,
  HASessionState.HASessionStateListener,
  HAPersistentManager
  {
     
     /** Creates new StatefulHASessionPersistenceManager */
     public StatefulHASessionPersistenceManager ()
     {
     }
     
     // Constants -----------------------------------------------------
     
     // Attributes ----------------------------------------------------
     private static Logger log = Logger.create 
(StatefulSessionFilePersistenceManager.class);
     private StatefulSessionContainer con;
     
     private Method ejbActivate;
     private Method ejbPassivate;
     private Method ejbRemove;
     
     private ArrayList fields;
     
     private HASessionState sessionState = null;
     
     private String localNodeName = null;
     private String appName = null;
     
     // Static --------------------------------------------------------
     private static long id = System.currentTimeMillis ();
     private static String DEFAULT_HASESSIONSTATE_JNDI_NAME = 
"/HASessionState/Default";
     
     // Constructors --------------------------------------------------
     
     // Public --------------------------------------------------------
     public void setContainer (Container c)
     {
        con = (StatefulSessionContainer)c;
     }
     
     public void init ()
     throws Exception
     {
        
        // Find methods
        ejbActivate = SessionBean.class.getMethod ("ejbActivate", new Class[0]);
        ejbPassivate = SessionBean.class.getMethod ("ejbPassivate", new Class[0]);
        ejbRemove = SessionBean.class.getMethod ("ejbRemove", new Class[0]);
        
        // Initialize the dataStore
        String ejbName = con.getBeanMetaData ().getEjbName ();
        
        // Find HASessionState that we will use
        //
        String sessionStateName = 
org.jboss.metadata.ClusterConfigMetaData.DEFAULT_SESSION_STATE_NAME;;
        ClusterConfigMetaData config = con.getBeanMetaData ().getClusterConfigMetaData 
();
        if (config != null)
           sessionStateName = config.getHaSessionStateName ();
        Context ctx = new InitialContext ();
        this.sessionState = (HASessionState)ctx.lookup (sessionStateName);
        this.localNodeName = this.sessionState.getNodeName ();
        
        // Get fields of class
        Class beanClass = con.getBeanClass ();
        fields = new ArrayList ();
        while (!beanClass.equals (Object.class))
        {
           Field[] f = beanClass.getDeclaredFields ();
           
           // Skip transient fields
           for (int i = 0; i < f.length; i++)
              if (!Modifier.isTransient (f[i].getModifiers ()))
              {
                 fields.add (f[i]);
              }
           
           beanClass = beanClass.getSuperclass ();
        }
        
        this.appName = this.con.getBeanMetaData ().getJndiName ();
     }
     
     public void start () throws Exception
     {
     }
     
     public void stop ()
     {
     }
     
     public void destroy ()
     {
     }
     
     public void createSession (Method m, Object[] args, 
StatefulSessionEnterpriseContext ctx) throws Exception
     {
        // Set id
        ctx.setId (nextId ());
        
        // Get methods
        try
        {
           Method createMethod = con.getBeanClass ().getMethod ("ejbCreate", 
m.getParameterTypes ());
           
           // Call ejbCreate
           createMethod.invoke (ctx.getInstance (), args);
           
           this.sessionState.createSession (this.appName, ctx.getId ());
           
        } catch (IllegalAccessException e)
        {
           // Clear id
           ctx.setId (null);
           
           // Throw this as a bean exception...(?)
           throw new EJBException (e);
        } catch (InvocationTargetException ite)
        {
           // Clear id
           ctx.setId (null);
           
           Throwable e = ite.getTargetException ();
           if (e instanceof EJBException)
           {
              // Rethrow exception
              throw (EJBException)e;
           }
           else if (e instanceof RuntimeException)
           {
              // Wrap runtime exceptions
              throw new EJBException ((Exception)e);
           }
           else if (e instanceof Exception)
           {
              // Remote, Create, or custom app. exception
              throw (Exception)e;
           }
           else
           {
              throw (Error)e;
           }
        }
        
        // Insert in cache
        ((StatefulSessionContainer)con).getInstanceCache ().insert (ctx);
        
        // Create EJBObject
        if (con.getContainerInvoker () != null)
           ctx.setEJBObject (con.getContainerInvoker ().getStatefulSessionEJBObject 
(ctx.getId ()));
        // Create EJBLocalObject
        if (con.getLocalHomeClass () != null)
           ctx.setEJBLocalObject (con.getLocalContainerInvoker 
().getStatefulSessionEJBLocalObject (ctx.getId ()));
     }
     
     public void activateSession (StatefulSessionEnterpriseContext ctx) throws 
RemoteException
     {
        try
        {
           ObjectInputStream in;
           
           // Load state
           PackagedSession state = this.sessionState.getStateWithOwnership 
(this.appName, ctx.getId ());
           in = new SessionObjectInputStream (ctx, new ByteArrayInputStream 
(state.getState ()));;
           
           ctx.setInstance ( in.readObject () );
           
           in.close ();
           
           removePassivated (ctx.getId ());
           
           // Call bean
           ejbActivate.invoke (ctx.getInstance (), new Object[0]);
           
        } catch (ClassNotFoundException e)
        {
           throw new ServerException ("Could not activate", e);
        } catch (IOException e)
        {
           throw new ServerException ("Could not activate", e);
        } catch (IllegalAccessException e)
        {
           // Throw this as a bean exception...(?)
           throw new EJBException (e);
        } catch (InvocationTargetException ite)
        {
           Throwable e = ite.getTargetException ();
           if (e instanceof EJBException)
           {
              // Rethrow exception
              throw (EJBException)e;
           }
           else if (e instanceof RuntimeException)
           {
              // Wrap runtime exceptions
              throw new EJBException ((Exception)e);
           }
           else if (e instanceof RemoteException)
           {
              // Remote, Create, or custom app. exception
              throw (RemoteException)e;
           }
           else
           {
              throw (Error)e;
           }
        }
     }
     
     public void passivateSession (StatefulSessionEnterpriseContext ctx)
     throws RemoteException
     {
        // do nothing
     }
     
     public void synchroSession (StatefulSessionEnterpriseContext ctx) throws 
RemoteException
     {
        try
        {
           // Call bean
           ejbPassivate.invoke (ctx.getInstance (), new Object[0]);
           
           // Store state
           ByteArrayOutputStream baos = new ByteArrayOutputStream ();
           ObjectOutputStream out = new SessionObjectOutputStream (baos);
           
           out.writeObject (ctx.getInstance ());
           
           out.close ();
           
           this.sessionState.setState (this.appName, ctx.getId (), baos.toByteArray 
());
           
           ejbActivate.invoke (ctx.getInstance (), new Object[0]); //needed?
           
           
        } catch (IOException e)
        {
           throw new ServerException ("Could not passivate", e);
        }catch (IllegalAccessException e)
        {
           // Throw this as a bean exception...(?)
           throw new EJBException (e);
        } catch (InvocationTargetException ite)
        {
           Throwable e = ite.getTargetException ();
           if (e instanceof EJBException)
           {
              // Rethrow exception
              throw (EJBException)e;
           }
           else if (e instanceof RuntimeException)
           {
              // Wrap runtime exceptions
              throw new EJBException ((Exception)e);
           }
           else if (e instanceof RemoteException)
           {
              // Remote, Create, or custom app. exception
              throw (RemoteException)e;
           }
           else
           {
              throw (Error)e;
           }
        }
     }
     
     
     public void removeSession (StatefulSessionEnterpriseContext ctx) throws 
RemoteException, RemoveException
     {
        // Call bean
        try
        {
           ejbRemove.invoke (ctx.getInstance (), new Object[0]);
           
        } catch (IllegalAccessException e)
        {
           // Throw this as a bean exception...(?)
           throw new EJBException (e);
        } catch (InvocationTargetException ite)
        {
           Throwable e = ite.getTargetException ();
           if (e instanceof EJBException)
           {
              // Rethrow exception
              throw (EJBException)e;
           }
           else if (e instanceof RuntimeException)
           {
              // Wrap runtime exceptions
              throw new EJBException ((Exception)e);
           }
           else if (e instanceof RemoveException)
           {
              throw (RemoveException)e;
           }
           else if (e instanceof RemoteException)
           {
              throw (RemoteException)e;
           }
           else
           {
              throw (Error)e;
           }
        }
     }
     
     public void removePassivated (Object key)
     {
        this.sessionState.removeSession (this.appName, key);
     }
     
     // Protected -----------------------------------------------------
     protected String nextId ()
     {
        return this.localNodeName + ":" + id++;
     }
     
     // HASessionState.HASessionStateListener methods -----------------
     //
     public void sessionExternallyModified (PackagedSession session)
     {
        // this callback warns us that a session (i.e. a bean) has been externally 
modified
        // this means that we need to tell to our InstanceCache that this bean is no 
more under its control
        // and that it should not keep a cached version of it => CACHE MISS
        //
        this.con.getInstanceCache ().remove (session.getKey ());
     }
     
     public void newSessionStateTopology (HAPartition haSubPartition)
     {
     }
     
  }
  
  
  
  1.1                  
jbossmx/src/main/org/jboss/ejb/plugins/StatefulHASessionSynchronisationInterceptor.java
  
  Index: StatefulHASessionSynchronisationInterceptor.java
  ===================================================================
  /*
   * JBoss, the OpenSource J2EE webOS
   *
   * Distributable under LGPL license.
   * See terms of license at gnu.org.
   */
  package org.jboss.ejb.plugins;
  
  import java.lang.reflect.Method;
  import java.rmi.RemoteException;
  import java.util.Map;
  
  import javax.transaction.Transaction;
  import javax.transaction.RollbackException;
  import javax.transaction.Status;
  import javax.transaction.Synchronization;
  
  import javax.ejb.EJBException;
  import javax.ejb.EJBObject;
  
  import org.apache.log4j.Category;
  
  import org.jboss.ejb.BeanLock;
  import org.jboss.ejb.BeanLockManager;
  import org.jboss.ejb.Container;
  import org.jboss.ejb.InstanceCache;
  import org.jboss.ejb.InstancePool;
  import org.jboss.ejb.StatefulSessionContainer;
  import org.jboss.ejb.StatefulSessionEnterpriseContext;
  import org.jboss.ejb.EnterpriseContext;
  import org.jboss.ejb.MethodInvocation;
  import org.jboss.metadata.SessionMetaData;
  
  /**
   *  This interceptor synchronizes a HA SFSB instance with its underlying persistent 
manager.
   *
   *  @see
   *  @author <a href="mailto:[EMAIL PROTECTED]";>Sacha Labourey</a>
   *  @version $Revision: 1.1 $
   *
   *   <p><b>Revisions:</b>
   */
  
  public class StatefulHASessionSynchronisationInterceptor extends AbstractInterceptor
  {
     
     protected StatefulSessionContainer container;
     
     // Constructors -------------------------------------------------
     
     // Public -------------------------------------------------------
     
     public Object invokeHome (MethodInvocation mi)
     throws Exception
     {
        EnterpriseContext ctx = mi.getEnterpriseContext ();
        
        try
        {
           // Invoke through interceptors
           return getNext ().invokeHome (mi);
        } finally
        {
           if ( (ctx != null) && (ctx.getId () != null) )
              // Still a valid instance and instance not removed
              //
           {
              // Everything went ok (at least no J2EE problem) and the instance will 
most probably be called
              // many more times. Consequently, we need to synchronize the state of 
our bean instance with
              // our persistant store (which will forward this to its HASessionState 
implementation) for clustering
              // behaviour. This is only necessary for "create" calls (which is the 
case because ctx.getId() != null)
              //
              try
              {
                 ((HAPersistentManager)container.getPersistenceManager 
()).synchroSession ((StatefulSessionEnterpriseContext)ctx);
              }
              catch (RemoteException re)
              {
                 re.printStackTrace ();
              }
           }
        }
     }
     
     public Object invoke (MethodInvocation mi)
     throws Exception
     {
        Object id = mi.getId ();
        EnterpriseContext ctx = mi.getEnterpriseContext ();
        
        try
        {
           // Invoke through interceptors
           return getNext ().invoke (mi);
        } catch (RemoteException e)
        {
           ctx = null;
           throw e;
        } catch (RuntimeException e)
        {
           ctx = null;
           throw e;
        } catch (Error e)
        {
           ctx = null;
           throw e;
        } finally
        {
           if ( (ctx != null) && (ctx.getId () != null) )
              // Still a valid instance and instance not removed
              //
           {
              // Everything went ok (at least no J2EE problem) and the instance will 
most probably be called
              // many more times. Consequently, we need to synchronize the state of 
our bean instance with
              // our persistant store (which will forward this to its HASessionState 
implementation) for clustering
              // behaviour.
              //
              try
              {
                 ((HAPersistentManager)container.getPersistenceManager 
()).synchroSession ((StatefulSessionEnterpriseContext)ctx);
              }
              catch (RemoteException re)
              {
                 re.printStackTrace ();
              }
           }
        }
     }
     
     /**
      * This callback is set by the container so that the plugin may access it
      *
      * @param con    The container using this plugin.
      */
     public void setContainer (Container container)
     {
        this.container = (StatefulSessionContainer)container;
     }
     
     public  Container getContainer ()
     {
        return container;
     }
     
  }
  
  
  
  

_______________________________________________
Jboss-development mailing list
[EMAIL PROTECTED]
https://lists.sourceforge.net/lists/listinfo/jboss-development

Reply via email to