package org.objectweb.jonas.jtests.beans.relation.tier;

import javax.ejb.CreateException;


/**
 * Sequence Block Session Bean
 */
public class SequenceSessionBean implements javax.ejb.SessionBean {

   private class Entry {
      SequenceLocal sequence;
      int last;
   }

   private java.util.Hashtable _entries = new java.util.Hashtable();
   private int _blockSize;
   private int _retryCount;
   private SequenceLocalHome _sequenceHome;
   private javax.naming.Context namingContext;

   public int getNextSequenceNumber(String name) {
      try {
         Entry entry = (Entry) _entries.get(name);

         if (entry == null) {
            // add an entry to the sequence table
            entry = new Entry();
            try {
               entry.sequence = _sequenceHome.findByPrimaryKey(name);
            } catch (javax.ejb.FinderException e) {
               // if we couldn't find it, then create it...
               entry.sequence = _sequenceHome.create(name);
            }
            _entries.put(name, entry);
         }
         if (entry.last % _blockSize == 0) {
            for (int retry = 0; true; retry++) {
               try {
                  entry.last = entry.sequence.getValueAfterIncrementingBy(_blockSize);
                  break;
               } catch (javax.ejb.TransactionRolledbackLocalException e) {
                  if (retry < _retryCount) {
                     // we hit a concurrency exception, so try again...
                     continue;
                  } else {
                     // we tried too many times, so fail...
                     throw new javax.ejb.EJBException(e);
                  }
               }
            }
         }
         return entry.last++;
      } catch (javax.ejb.CreateException e) {
         throw new javax.ejb.EJBException(e);
      }
   }

   public void setSessionContext( javax.ejb.SessionContext sessionContext) {
      try {
         namingContext = new javax.naming.InitialContext();
         _blockSize = ((Integer) namingContext.lookup("java:comp/env/blockSize")).intValue();
         _retryCount = ((Integer) namingContext.lookup("java:comp/env/retryCount")).intValue();

         _sequenceHome = SequenceUtil.getLocalHome();
      } catch(javax.naming.NamingException e) {
         throw new javax.ejb.EJBException(e);
      }
   }
   
   	public void ejbCreate() throws CreateException {
	}

   public void ejbActivate() 
   {
   }

   public void ejbPassivate() 
   {
   }

   public void unsetSessionContext() 
   {
   		namingContext = null;
   }

   public void ejbRemove() 
   {
   }
   
}
