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

import java.util.Iterator;
import javax.ejb.EnterpriseBean;

import org.jfox.ejb.Bucket;
import org.jfox.ejb.EJBObjectMethod;
import org.jfox.ejb.EJBPoolableObject;
import org.jfox.ejb.Invocation;
import org.jfox.ejb.SessionBucket;

/**
 * 从实例池取得 Bean 实例，执行后返回
 * <p/>
 * A5 用于排序
 *
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class A5_InstancePoolHandler extends AbstractHandler {

    public Object invokeBean(Bucket bucket, Invocation invocation, Iterator iter) throws Exception {
        EJBPoolableObject pobj = ((SessionBucket) bucket).retrieveBean(invocation.getObjectId());
        EnterpriseBean bean = pobj.getBeanInstance();
        invocation.setBean(bean);

        /**
         * 拦截 remove 方法调用，因为这个调用将不再把 Bean 返回给 ObjectPool
         */
        if(invocation.getMethod().equals(EJBObjectMethod.Remove)) {
            bucket.remove(bean);
            pobj = null;
            return null;
        }

        try {
            return super.invokeBean(bucket, invocation, iter);
        }
        finally {
            ((SessionBucket) bucket).restoreBean(invocation.getObjectId(), pobj);
        }

    }

    public static void main(String[] args) {

    }
}