/* JFox, the OpenSource J2EE Application Server
 *
 * Copyright (C) 2002 huihoo.com
 * Distributable under GNU LGPL license
 * See the GNU Lesser General Public License for more details.
 */

package org.huihoo.jfox.pool;

import java.util.HashMap;
import java.util.Map;

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

public class SimpleIndexedObjectPool extends AbstractIndexedObjectPool {

  private Map indexedObjects = null;

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

  public SimpleIndexedObjectPool(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) {

  }
}