/* 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.io.IOException;
import java.io.Serializable;
import java.net.ServerSocket;
import java.rmi.server.RMIServerSocketFactory;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;

import org.jfox.framework.logger.Logger;


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

public class RMISSLServerSocketFactory implements RMIServerSocketFactory, Serializable {
    private String SSLKeyFile = "jfox.keystore";
    private String password = "jfox.org";

    public RMISSLServerSocketFactory(String SSLKeyFile, String password) {
        this.SSLKeyFile = SSLKeyFile;
        this.password = password;
    }

    public ServerSocket createServerSocket(int port) throws IOException {
        try {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(SSLKeyFile), password.toCharArray());
            KeyManagerFactory keyMgr = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyMgr.init(keyStore, password.toCharArray());

//      TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
//      tmf.init(keyStore);

            SSLContext sslCtx = SSLContext.getInstance("TLS");
            sslCtx.init(keyMgr.getKeyManagers(), null, null);
            return sslCtx.getServerSocketFactory().createServerSocket(port);
        }
        catch(Exception e) {
            Logger.getLogger(this.getClass().getName()).error("can not initializing SSLContext", e);
            return null;
        }
    }

    public static void main(String[] args) {

    }
}

