/* 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.pool;

import org.jfox.system.AbstractComponent;

/**
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public abstract class AbstractIndexableObjectPool extends AbstractComponent implements IndexableObjectPool {
    /**
     * 这个池用来实际的生成和缓存池对象
     */
    protected AbstractObjectPool pool = null;

    protected ObjectFactory factory = null;

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

    public AbstractIndexableObjectPool(String objectFactoryClassName, String poolableClassName) {
//    super(objectFactoryClassName);
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {
            Class factoryClass = loader.loadClass(objectFactoryClassName);
            factory = (ObjectFactory) factoryClass.getConstructor(new Class[]{java.lang.String.class}).newInstance(new String[]{poolableClassName});
        }
        catch(ClassNotFoundException e) {
            logger.fatal("Class " + objectFactoryClassName + " not found!" + e);
        }
        catch(NoSuchMethodException e) {
            logger.fatal("No such constructor" + e);
        }
        catch(Exception e) {
            logger.fatal("ObjectFactory " + objectFactoryClassName + " instantiator error" + e);
        }
    }

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

    public ObjectFactory getObjectFactory() {
        return factory;
    }

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

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

    protected void doInit() throws Exception {
        pool = new SimpleObjectPool(factory);
    }

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