/* 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 java.util.HashMap;
import java.util.Map;

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

public class SimpleIndexableObjectPool extends AbstractIndexableObjectPool {

    private Map indexedObjects = null;

    public SimpleIndexableObjectPool(ObjectFactory factory) {
        super(factory);
    }

    public SimpleIndexableObjectPool(String objectFactoryClassName, String poolableClassName) {
        super(objectFactoryClassName, poolableClassName);
    }

    protected void doInit() throws Exception {
        super.doInit();
        indexedObjects = new HashMap();
    }

    protected void doDestroy() throws Exception {
        super.doDestroy();
        indexedObjects = null;
    }

    public void clear() {
        super.clear();
        indexedObjects.clear();
    }

    public PoolableObject retrieveObject(Object key) throws Exception {
        if(indexedObjects.containsKey(key)) {
            return (PoolableObject) indexedObjects.remove(key);
        }
        else {
            return pool.retrieveObject();
        }

    }

    public boolean restoreObject(Object key, PoolableObject obj) {
        if(!factory.validateObject(obj)) {
            logger.warn("PoolableObject " + obj + " is not a valid pool object in this ObjectPool");
            return false;
        }

        if(indexedObjects.containsKey(key)) {
            logger.warn("Key " + key + " already exists, will overwrite!");
        }
        indexedObjects.put(key, obj);
        return true;

    }

    public boolean removeObject(Object key) {
        if(!indexedObjects.containsKey(key)) {
            logger.warn("Key " + key + " is not exists!");
            return false;
        }
        else {
            indexedObjects.remove(key);
            return true;
        }
    }

    public static void main(String[] args) {

    }
}
