package org.jfox.ejb.invoker.jrmp_ssl;

import java.rmi.Remote;
import java.rmi.server.UnicastRemoteObject;

import org.jfox.ejb.invoker.jrmp.JRMPContainerService;
import org.jfox.ejb.meta.Protocol;

/**
 * @author <a href="mailto:yangyong@ufsoft.com.cn">Young Yang</a>
 */

public class JRMP_SSLContainerService extends JRMPContainerService {
  // invoker stub
  private Remote stub = null;
  private String protocol = Protocol.JRMP_SSL;

  private String SSLKeyFile = "jfox.keystore";
  private String SSLTrustKeyFile = "jfox.truststore";
  private String password = "jfox.org";

  private RMISSLServerSocketFactory serverFactory = null;
  private RMISSLClientSocketFactory clientFactory = null;

  protected void doInit() throws Exception {
    super.doInit();
    clientFactory = new RMISSLClientSocketFactory(SSLTrustKeyFile,password);
    serverFactory = new RMISSLServerSocketFactory(SSLKeyFile,password);
  }

  /**
   * export this invoker and set container's invoker to this stub
   * @throws Exception
   */
  protected void doStart() throws Exception {
    stub = UnicastRemoteObject.exportObject(this,0,clientFactory,serverFactory);
    INITIAL_CONTEXT.rebind(INVOKER_JNDI_PREFIX + "/" + protocol.toUpperCase(),stub);
    // 启动一个线程,用来每隔一段时间 ping 一下,防止 rmi 线程死掉
    Thread pingThread = new Thread(this,getClass().getName());
    pingThread.setPriority(Thread.MIN_PRIORITY);
    pingThread.start();
  }

  protected void doStop() throws Exception {
    INITIAL_CONTEXT.unbind(INVOKER_JNDI_PREFIX + "/" + protocol.toUpperCase());
    UnicastRemoteObject.unexportObject(this,true);
  }

  protected synchronized void doDestroy() throws Exception {
    super.doDestroy();
    serverFactory = null;
    clientFactory = null;
  }

  public void setSSLKeyFile(String SSLKeyFile) {
    this.SSLKeyFile = SSLKeyFile;
  }

  public void setSSLTrustKeyFile(String SSLTrustKeyFile) {
    this.SSLTrustKeyFile = SSLTrustKeyFile;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public String getSSLKeyFile() {
    return SSLKeyFile;
  }

  public String getSSLTrustKeyFile() {
    return SSLTrustKeyFile;
  }

  public static void main(String[] args) {

  }
}