
/**
 * RegistrarObserver.java
 *
 *
 * Created: Fri Oct 22 15:32:13 1999
 *
 * @author Jan Newmarch
 * @version 1.0
 */

package observer;

import net.jini.core.event.RemoteEventListener;
import net.jini.core.event.RemoteEvent;
import net.jini.core.lookup.ServiceEvent;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lease.Lease;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.core.lookup.ServiceID;
import net.jini.core.event.EventRegistration;
import com.sun.jini.lease.LeaseRenewalManager;
import net.jini.core.lookup.ServiceMatches;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class RegistrarObserver extends UnicastRemoteObject implements RemoteEventListener {
    
    protected static LeaseRenewalManager leaseManager = new LeaseRenewalManager();
    protected ServiceRegistrar registrar;

    public RegistrarObserver(ServiceRegistrar registrar) throws RemoteException {
	this.registrar = registrar;
	ServiceTemplate templ = new ServiceTemplate(null, null /*new Class[] {Object.class}*/, null);
	EventRegistration reg = null;
	try {
	    reg = registrar.notify(templ,
			     (ServiceRegistrar.TRANSITION_MATCH_MATCH |
			      ServiceRegistrar.TRANSITION_MATCH_NOMATCH |
			      ServiceRegistrar.TRANSITION_NOMATCH_MATCH),
			     this,
			     null,
			     Lease.FOREVER);
	    System.out.println("notifed id " + reg.getID());
	} catch(RemoteException e) {
	    e.printStackTrace();
	}
	leaseManager.renewUntil(reg.getLease(), Lease.FOREVER, null);
    }

    public void notify(RemoteEvent evt) {

	    ServiceTemplate templ = new ServiceTemplate(null, new Class[] {Object.class}, null);
	    ServiceMatches matches = null;
	    try {
		matches = registrar.lookup(templ, 10);
	    } catch(RemoteException e) {
		System.out.println("lookup failed");
	    }
System.out.println("here7");          
	    for (int m = 0; m < matches.items.length; m++) {
		System.out.println("Reg after event knows about " +
				   matches.items[m].service.toString() +
				   " with id " + matches.items[m].serviceID);
	    }

	ServiceEvent sevt = (ServiceEvent) evt;
	ServiceID id = sevt.getServiceID();
	 System.out.println("service id " + id);
 
	switch (sevt.getTransition()) {
	case ServiceRegistrar.TRANSITION_NOMATCH_MATCH:
	    System.out.println("nomatch -> match");
	    break;
	case ServiceRegistrar.TRANSITION_MATCH_MATCH:
	    System.out.println("match -> match");
	    break;
	case ServiceRegistrar.TRANSITION_MATCH_NOMATCH:
	    System.out.println("match -> nomatch");
	    break;
	}
	System.out.println(sevt.toString());
	if (sevt.getServiceItem() == null) {
	    System.out.println("now null");
	} else {
	    Object service = sevt.getServiceItem().service;
	    System.out.println(service.toString());
	}
    }
    
} // RegistrarObserver
