/* 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.jfox.ejb.plugin;

import java.util.Iterator;
import java.lang.reflect.Method;

import javax.ejb.Handle;

import org.jfox.ejb.Invocation;
import org.jfox.ejb.Bulk;
import org.jfox.ejb.EJBHomeMethod;
import org.jfox.ejb.EJBObjectMethod;
import org.jfox.ejb.ObjectId;

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

public class B5_EJBOperationInvoker extends AbstractInvoker{

  public Object invokeHome(Bulk bulk, 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 bulk.getEJBMetaData();
    }
    else if(method.equals(EJBHomeMethod.GetHomeHandle)){
      // 这个方法因为已经在 JRMPContainerInvoker 客户端执行,所以从不会调用
      return bulk.getHomeHandle();
    }
    else if(method.equals(EJBHomeMethod.RemoveByHandle)){
      bulk.remove((Handle)(invocation.getArgs()[0]));
      return null;
      // 对于 StatelessSessionBean,这个方法不执行任何操作
    }
    else if(method.equals(EJBHomeMethod.RemoveByPrimaryKey)){
      bulk.remove(invocation.getArgs()[0]);
      return null;
    }
    return super.invokeHome(bulk, invocation, iter);
  }

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

  public static void main(String[] args) {

  }
}