package org.jfox.ejb.invoker.soap;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Vector;

import org.apache.xmlrpc.XmlRpcHandler;
import org.jfox.ejb.Invocation;
import org.jfox.ejb.ObjectId;
import org.jfox.ejb.invoker.ContainerRemote;
import org.jfox.ejb.invoker.ContainerInvokerHelper;
import org.jfox.ejb.invoker.local.LOCALContainerService;

/**
 * 通过 JRMP 转发给 JRMPContainerService 来执行
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class JRMPXmlRpcHandler implements XmlRpcHandler {
  private ContainerRemote stub = ContainerInvokerHelper.lookupContainerInvoker("JRMP");
  private ContainerRemote local = LOCALContainerService.getInstance();
  public JRMPXmlRpcHandler() {
  }

  public Object execute(String string, Vector vector) throws Exception {
    Invocation invocation = (Invocation)unmarshelledObject((byte[])vector.get(0));
    ObjectId objectId = invocation.getObjectId();
    if(objectId.getIdentity().equals(ObjectId.CONTAINER_IDENTITY)) {
//      System.out.println("@@@@@@@ soap with local protocol");
      return marshelledObject((Serializable)local.invoke(invocation));
    }
    else {
      return marshelledObject((Serializable)stub.invoke(invocation));
    }
  }

  public static Object unmarshelledObject(byte[] bytes){
    try {
      ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes));
      Object obj = in.readObject();
      in.close();
      return obj;
    }
    catch(Exception e){
      e.printStackTrace();
      return bytes;
    }
  }

  public static byte[] marshelledObject(Serializable obj) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
      ObjectOutputStream oos = new ObjectOutputStream(out);
      oos.writeObject(obj);
      oos.flush();
    }
    catch(IOException e){
      e.printStackTrace();
    }
    return out.toByteArray();
  }
  public static void main(String[] args) {

  }
}