/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.jfox.ejb;

import org.jfox.pool.AbstractObjectPool;
import org.jfox.pool.ObjectFactory;
import org.jfox.pool.ObjectPool;
import org.jfox.pool.PoolableObject;
import org.jfox.pool.SimpleObjectPool;
import org.jfox.system.AbstractComponent;

/**
 * 用来存储 StatelessSessionBean 的对象池，该池的后端使用一个 SimpleObjectPool
 *
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class StatelessSessionObjectPool extends AbstractComponent implements ObjectPool {
    private AbstractObjectPool pool = null;
    private ObjectFactory factory = null;


    public StatelessSessionObjectPool(ObjectFactory factory) {
        if(factory == null) throw new NullPointerException("factory is null.");
        this.factory = factory;
    }

    public synchronized PoolableObject createObject() throws Exception {
        return retrieveObject();
    }

    public synchronized PoolableObject retrieveObject() throws Exception {
        // not need call ejbCreate, bucket will call it after get instance from the pool
        return pool.retrieveObject();
    }

    /**
     * 如果数目过多，则返回给 pool，但是先得调用 ejbRemove，释放资源
     *
     * @param obj
     * @return
     */
    public boolean restoreObject(PoolableObject obj) {
        try {
            return pool.restoreObject(obj);
        }
        catch(Exception e) {
            logger.warn("restoreObject " + obj + " failed, exception is: " + e);
            return false;
        }
    }

    /**
     * 如果池中对象小于 max, 存到池中，池满，则调用 ejbRemove，并返回上级池
     *
     * @param obj
     * @return
     */
    public boolean removeObject(PoolableObject obj) {
        try {
            return pool.restoreObject(obj);
        }
        catch(Exception e) {
            logger.warn("removeObject " + obj + " failed, exception is: " + e);
            return false;
        }
    }

    public void clear() {
        pool.clear();
    }

    public ObjectFactory getObjectFactory() {
        return factory;
    }

    public String getObjectClass() {
        return factory.getObjectClass().getName();
    }

    public int getWorking() {
        return pool.getWorking();
    }

    public int getRest() {
        return pool.getRest();
    }

    protected void doInit() throws Exception {
        pool = new SimpleObjectPool(factory, 0, 10);
        pool.init();
    }

    protected void doDestroy() throws Exception {
        pool.destroy();
    }

    public int getInitNum() {
        return pool.getInitNum();
    }

    public int getMaxRest() {
        return pool.getMaxRest();
    }

    public static void main(String[] args) {

    }
}