package org.objectweb.jonas.jtests.beans.ejbql;

public class SequenceSessionSL 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;

    public int getNextNumberInSequence(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.getNextKeyAfterIncrementingBy(_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);
			}
		    }
		}
	    }
	    int ret = entry.last+1;
	    return entry.last++;
	} catch (javax.ejb.CreateException e) {
	    throw new javax.ejb.EJBException(e);
	}
    }
    public void setSessionContext( javax.ejb.SessionContext sessionContext) {
	try {
	    javax.naming.Context namingContext = new javax.naming.InitialContext();
	    _blockSize = ((Integer) namingContext.lookup("java:comp/env/blockSize")).intValue();
	    _retryCount = ((Integer) namingContext.lookup("java:comp/env/retryCount")).intValue();
      
	    _sequenceHome = (SequenceLocalHome) namingContext.lookup("java:comp/env/ejb/SequenceLocalHome");
	} catch(javax.naming.NamingException e) {
	    throw new javax.ejb.EJBException(e);
	}
    }
    public void ejbActivate() {}
    public void ejbCreate() {}
    public void ejbPassivate() {}
    public void ejbRemove() {}

   
}
