package org.jcon.test.rmi;

import java.rmi.Naming;
import java.rmi.RMISecurityManager;

/**
 * The client entry point and marker class, similar to
 * DataClient but through RMI.
 * <p>
 * Note we implement Runnable, which is on all clients.
 *
 * @author Jack Harich
 */
public class EntryPoint implements Runnable {

//---------- Private Fields ------------------------------
private static String   hostName = "rmi://sheba/";

//---------- Initialization ------------------------------
// Use this to skip Bootstrap
public static void main(String args[]) {
    if (args.length > 0) hostName = args[0];
    new EntryPoint().lookupRemoteDatastore();
}
//---------- Runnable Implementation ---------------------
/**
 * Since this class originated on the server, classes it
 * references will be loaded from the server via the RMI
 * classloader, if the classes are not on the client.
 * For example this is how ItemSystemMgr is loaded.
 */
public void run() {
    print(".run() - Entered");
    lookupRemoteDatastore();
}
//---------- Private Methods -----------------------------
// Set datastore. Could be on demand.
private boolean lookupRemoteDatastore() {

// Note the remote object was bound with boundName
String boundName = "DatastoreRemote";
String remoteName = hostName + boundName;

    try {
        // All RMI clients should always install a SecurityManager
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }
        // Here we use RMI to get a remote object
        // Note we must use the interface, not the class
        print(" - Looking up '" + remoteName + "', please wait...");
        DatastoreRemote datastore = (DatastoreRemote)
            Naming.lookup(remoteName);
        print("   RMI Naming lookup complete");
        datastore.start();

        // Test ability to get class from server, 2 ways
        TestWorker worker = new TestWorker();
        worker.printYourself();

        TestWorker worker2 = datastore.getTestWorker();
        worker2.printYourself();

        return true;

    } catch(Exception ex) {
        print("lookup failure");
        ex.printStackTrace();
        return false;
    }
}
//--- Std
private static void print(String text) {
    System.out.println("EntryPoint" + text);
}

} // End class
