package org.dancres.jini;

import java.io.IOException;

import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;

import net.jini.core.discovery.LookupLocator;

import net.jini.discovery.Constants;

import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceMatches;

import net.jini.space.JavaSpace;

/**
   This is an example of a simple Unicast lookup.  In certain situations, this
   means of lookup is useful but, obviously, we need to know the address
   (or hostname) and port number for the lookup service in advance.  Thus
   we largely lose the late-binding advantages of JINI.
*/
public class LookupWithLocator {
    public static void main(String args[]) {
        if (args.length != 1) {
            System.err.println("You must specify a hostname");
        }

        /*
          Gotta do this to enable remote class downloading
         */
        System.setSecurityManager(new RMISecurityManager());

        String myHost = args[0];

        /*
           We'll use the default port - note that ServiceRegistrars can be
           configured to use other ports via their .config files or
           configuration overrides supplied at startup.
         */
        int myPort = Constants.discoveryPort;

        /**
           You could also pass in a URL of the form:
           jini://host/  or jini://host:port/
         */
        LookupLocator myLocator = new LookupLocator(myHost, myPort);

        try {
            ServiceRegistrar myRegistrar = myLocator.getRegistrar();

            if (myRegistrar != null) {
                System.out.println("Found registrar:");

                DiscoveryUtil.dumpRegistrar(myRegistrar);
                ServiceMatches myMatches = 
                    DiscoveryUtil.findServicesOfType(JavaSpace.class,
                                                     myRegistrar);

                DiscoveryUtil.dump(myMatches);
            }

        } catch (RemoteException aRE) {
            System.err.println("Couldn't talk to ServiceRegistrar");
            aRE.printStackTrace(System.err);
        } catch (IOException anIOE) {
            System.err.println("Whoops couldn't talk to ServiceRegistrar");
            anIOE.printStackTrace(System.err);
        } catch (ClassNotFoundException aCNFE) {
            System.err.println("Whoops, couldn't download proxy for ServiceRegistrar");
            aCNFE.printStackTrace(System.err);
        }
    }
}
