// A simple Client to exercise the HelloWorldService

package corejini.chapter5;

import net.jini.discovery.DiscoveryListener;
import net.jini.discovery.DiscoveryEvent;
import net.jini.discovery.LookupDiscovery;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceTemplate;
import java.util.Vector;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;

public class HelloWorldClient implements Runnable {
    protected ServiceTemplate template;
    protected LookupDiscovery disco;
    
    // An inner class to implement DiscoveryListener
    class Listener implements DiscoveryListener {
        public void discovered(DiscoveryEvent ev) {
            ServiceRegistrar[] newregs = ev.getRegistrars();
            for (int i=0 ; i<newregs.length ; i++) {
                lookForService(newregs[i]);
            }
        }
        public void discarded(DiscoveryEvent ev) {
        }
    }
    
    public HelloWorldClient() throws IOException {
        Class[] types = { HelloWorldServiceInterface.class };
        
        template = new ServiceTemplate(null, types, null);
        
        // Set a security manager
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }
        
        // Only search the public group
        disco = new LookupDiscovery(new String[] { "" });
        
        // Install a listener
        disco.addDiscoveryListener(new Listener());
    }
    
    // Once we've found a new lookup service, search
    // for proxies that implement 
    // HelloWorldServiceInterface
    protected Object lookForService(ServiceRegistrar lusvc) {
        Object o = null;
        
        try {
            o = lusvc.lookup(template);
        } catch (RemoteException ex) {
            System.err.println("Error doing lookup: " + ex.getMessage());
            return null;
        }
        
        if (o == null) {
            System.err.println("No matching service.");
            return null;
        }
        
        System.out.println("Got a matching service.");
        System.out.println("It's message is: " +
                           ((HelloWorldServiceInterface) o).getMessage());
        return o;
    }
    
    // This thread does nothing--it simply keeps the
    // VM from exiting while we do discovery.
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000000);
            } catch (InterruptedException ex) {
            }
        }
    }
    
    // Create a HelloWorldClient and start its thread
    public static void main(String args[]) {
        try {
            HelloWorldClient hwc = new HelloWorldClient();
            new Thread(hwc).start();
        } catch (IOException ex) {
            System.out.println("Couldn't create client: " +
                               ex.getMessage());
        }
    }
}
