package org.jfox.ejb.invoker.soap;

import java.rmi.RemoteException;

import org.jfox.ejb.Invocation;
import org.jfox.ejb.meta.Protocol;
import org.jfox.ejb.invoker.ContainerRemote;
import org.jfox.ejb.invoker.ContainerServiceSupport;

/**
 * 该类实际上只是做为 SOAPContainerService 的启动器,实际绑定到 jndi
 * 上的是 SOAPContainerServiceBinder
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class SOAPContainerService extends ContainerServiceSupport implements ContainerRemote {
  private String protocol = Protocol.SOAP;

  // web server 的机器名和ip
  private String httpHost = "";
  // web server 的 port
  private int httpPort = 8080;
  // 用来处理 xmlrpc 请求的 proxy servlet,需要在启动 web server 的时候配置
  private String servletName = "xmlrpc/RPC2";
//  private transient XmlRpcHandler client;
  private SOAPContainerServiceBinder soapBinder = null;

  public String getHttpHost() {
    return httpHost;
  }

  public int getHttpPort() {
    return httpPort;
  }

  public String getServletName() {
    return servletName;
  }

  public void setHttpHost(String httpHost) {
    this.httpHost = httpHost;
  }

  public void setHttpPort(int httpPort) {
    this.httpPort = httpPort;
  }

  protected void doStart() throws Exception {
    logger.info("soap url: " + getSoapURL());
    INITIAL_CONTEXT.rebind(INVOKER_JNDI_PREFIX + "/" + protocol.toUpperCase(),soapBinder);
  }

  protected void doStop() throws Exception {
    INITIAL_CONTEXT.unbind(INVOKER_JNDI_PREFIX + "/" + protocol.toUpperCase());
  }

  protected void doInit() throws Exception {
    super.doInit();
    soapBinder = new SOAPContainerServiceBinder(getSoapURL());
  }

  protected void doDestroy() throws Exception {
    soapBinder = null;
  }

  public String getSoapURL(){
    return "http://"+httpHost+":"+httpPort+"/"+servletName;
  }

  /**
   * 这个方法实际不会调用到,因为客户端得到的是 SOAPContainerServiceBinder
   * @param invocation
   * @return
   * @throws RemoteException
   */
  public Object invoke(Invocation invocation) throws RemoteException {
    return soapBinder.invoke(invocation);
/*
    Vector params = new Vector(1);
    params.add(marshelledObject(invocation));
    try {
      // handler 可以为任何字符串
      return client.execute("xmlrpc",params);
    }
    catch(Exception e) {
      throw new RemoteException(e.getMessage(),e);
    }
*/
  }

  public static void main(String[] args) {

  }

}