
package server;

/**
 *  Server implementation for the Compute interface
 * @author Tinsae Ghilay
 * 
 * mimics an authentication service for some client to access a secure resource 
 * (mocked as a door that opens or remains closed based on authentication result)
 * verification is done randomly for demo purposes
 */

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Random;

// needs the compute and task interfaces from compute package
// define constructor for each
// and provide an implementation for each remote method in the remote interfaces
import compute.Compute;

/**
 * The implementation of the Compute interface for the compute engine.
 * it has to declare the remote class to be implemented (in this case Compute
 * (implements it)
 */
public class Server implements Compute {

    public Server() {
        super();
    }

    @Override
    public boolean authenticate() throws RemoteException {
        return new Random().nextBoolean();
    }

    // entry
    public static void main(String[] args) {

        // the code provided on the tutorial was deprecated.
        // so google led me to
        // [this](https://docs.oracle.com/javase/8/docs/technotes/guides/rmi/hello/hello-world.html#create)
        try {
            // create remote object that provides service (server).
            Compute server = new Server();

            // and export remote object to java RMI runtime
            // so it may receive remote incoming calls
            Compute stub = (Compute) UnicastRemoteObject.exportObject(server, 0);
            // the register the remote object with java RMI registry
            // the registry is a name service that allows clients get a reference of remote
            // objects
            // once a remote object is registered, callers can look up the object by name
            // and obtain its remote object reference
            Registry registry = LocateRegistry.createRegistry(1099);
            registry.rebind(Compute.SERVICE_NAME, stub);
            System.out.println("Server bound");
        } catch (Exception e) {
            System.err.println("Server exception: " + e.getMessage());
        }
    }
}
