/* 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.lang.reflect.Method;
import java.util.Iterator;
import javax.ejb.Handle;

import org.jfox.ejb.Bucket;
import org.jfox.ejb.EJBHomeMethod;
import org.jfox.ejb.EJBObjectId;
import org.jfox.ejb.EJBObjectMethod;
import org.jfox.ejb.Invocation;

/**
 * 执行在 EJBObject 和 EJBHome 中定义的方法
 *
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class B5_EJBOperationHandler extends AbstractHandler {

    public Object invokeHome(Bucket bucket, Invocation invocation, Iterator iter) throws Exception {
//    System.out.println(this.getClass().getName() + " " + invocation.getMethod().getName());
        Method method = invocation.getMethod();
        if(method.equals(EJBHomeMethod.GetEJBMetaData)) {
            return bucket.getEJBMetaData();
        }
        else if(method.equals(EJBHomeMethod.GetHomeHandle)) {
            // 这个方法因为已经在 JRMPContainerInvoker 客户端执行，所以从不会调用
            return bucket.getHomeHandle();
        }
        else if(method.equals(EJBHomeMethod.RemoveByHandle)) {
            bucket.remove((Handle) (invocation.getArgs()[0]));
            return null;
            // 对于 StatelessSessionBean，这个方法不执行任何操作
        }
        else if(method.equals(EJBHomeMethod.RemoveByPrimaryKey)) {
            bucket.remove(invocation.getArgs()[0]);
            return null;
        }
        return super.invokeHome(bucket, invocation, iter);
    }

    public Object invokeBean(Bucket bucket, Invocation invocation, Iterator iter) throws Exception {
        Method method = invocation.getMethod();
        if(method.equals(EJBObjectMethod.GetEJBHome)) {
            return bucket.getEJBHome();
        }
        else if(method.equals(EJBObjectMethod.GetHandle)) {
            return bucket.getHandle(invocation.getBean());
        }
        else if(method.equals(EJBObjectMethod.GetPrimaryKey)) {
            return bucket.getPrimaryKey(invocation.getBean());
        }
        else if(method.equals(EJBObjectMethod.IsIdentical)) {
            // InvocationHandler 已经将 Args 转换成了要比较的 EJBObject 的　ObjectId
            return new Boolean(bucket.isIdentical(invocation.getObjectId(), (EJBObjectId) invocation.getArgs()[0]));
        }
        return super.invokeBean(bucket, invocation, iter);
    }

    public static void main(String[] args) {

    }
}