/* 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.Socket;
import java.rmi.server.RMIClientSocketFactory;
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import org.jfox.framework.logger.Logger;

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

public class RMISSLClientSocketFactory implements RMIClientSocketFactory, Serializable {

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


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

    public synchronized Socket createSocket(String host, int port) throws IOException {
        try {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(SSLTrustKeyFile), 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(null, tmf.getTrustManagers(), null);
            return sslCtx.getSocketFactory().createSocket(host, port);
        }
        catch(Exception e) {
            Logger.getLogger(this.getClass().getName()).error("can not initializing SSLContext", e);
            return null;
        }
    }

    public static void main(String[] args) {

    }
}

