
/**
 * RegistrarObserver.java
 *
 *
 * Created: Fri Oct 22 15:32:13 1999
 *
 * @author Jan Newmarch
 * @version 1.1
 *    uses Jini 1.1 LeaseRenewalManager
 */

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; // Jini 1.0
import net.jini.lease.LeaseRenewalManager;        // Jini 1.1
import net.jini.core.lookup.ServiceMatches;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import net.jini.core.entry.Entry;
import net.jini.core.event.UnknownEventException;

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

    protected final int transitions = ServiceRegistrar.TRANSITION_MATCH_NOMATCH |
                                  ServiceRegistrar.TRANSITION_NOMATCH_MATCH |
                                  ServiceRegistrar.TRANSITION_MATCH_MATCH;

    public RegistrarObserver() throws RemoteException {
    }

    public RegistrarObserver(ServiceRegistrar registrar) throws RemoteException {
	this.registrar = registrar;
	ServiceTemplate templ = new ServiceTemplate(null, null, null);
	EventRegistration reg = null;
	try {
	    // eventCatcher = new MyEventListener();
	    reg = registrar.notify(templ,
			     transitions,
			     this,
			     null,
			     Lease.ANY);
	    System.out.println("notifed id " + reg.getID());
	} catch(RemoteException e) {
	    e.printStackTrace();
	}
	leaseManager.renewUntil(reg.getLease(), Lease.FOREVER, null);
    }

    public void notify(RemoteEvent evt)
	throws RemoteException, UnknownEventException {
	try {
	    ServiceEvent sevt = (ServiceEvent) evt;
	    int transition = sevt.getTransition();
	    System.out.println("transition " + transition);
	    switch (transition) {
	    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 is " + service.toString());
	    }
	} catch(Exception e) {
	    e.printStackTrace();
	}

    }
    
} // RegistrarObserver
