/* 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.connector.jrmp_ssl;

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

import org.jfox.ejb.connector.ConnectorHelper;
import org.jfox.ejb.connector.jrmp.JRMPContainerService;
import org.jfox.ejb.meta.Protocol;
import org.jfox.framework.extra.Managable;
import org.jfox.framework.extra.ManagementInfo;

/**
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class JRMP_SSLContainerService extends JRMPContainerService implements Managable {
    // invoker stub
    private Remote stub = null;
    private Protocol 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(ConnectorHelper.getJNDIName(protocol), 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(ConnectorHelper.getJNDIName(protocol));
        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 ManagementInfo getManagementInfo() {
        return ManagementInfo.exposePublic(JRMP_SSLContainerService.class);
    }

    public static void main(String[] args) {

    }
}