/*
 * 
 * Copyright 2005 Sun Microsystems, Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * 	http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package com.sun.jini.compat.test;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

import net.jini.core.event.EventRegistration;
import net.jini.core.event.RemoteEventListener;
import net.jini.core.event.RemoteEvent;
import net.jini.core.lease.UnknownLeaseException;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.core.lookup.ServiceItem;
import net.jini.core.lookup.ServiceEvent;

import com.sun.jini.compat.harness.TestUtility;
import com.sun.jini.compat.harness.Status;
import com.sun.jini.compat.harness.Config;
import com.sun.jini.compat.harness.DefaultTest;
import com.sun.jini.compat.harness.BasicServiceAdmin;
import com.sun.jini.compat.harness.BasicAdmin;

/**
 * Tests whether a service maintains its lookup service registration
 * lease.
 */
public class LeaseTest extends DefaultTest {
    
    BasicServiceAdmin admin;
    ServiceRegistrar lookup;
    ServiceItem serviceItem;

    /**
     * Starts up a lookup service with a maximum lease time that is 
     * set to the failureTime, and then starts up the service. The 
     * test registers with the lookup service to be notified if the 
     * service of interest registers, and waits for the service to
     * register. If necessary, a query is performed as is done in the 
     * other registration tests. Once the service has been confirmed 
     * as registered with the lookup service, the test asks the lookup 
     * service to notify it when the service of interest cancels its
     * lease with the lookup service. The test then waits for three 
     * times the provided lease duration (to avoid problems with 
     * registration ceasing at the exact same time as the test stops 
     * waiting and to get past network transmit times). If the test was not
     * notified in that period it then queries the lookup service for 
     * the service. If the test was notified of the service ceasing to 
     * be registered, or if the service is gone when the lookup service 
     * is queried, the service fails.
     *
     * @param args Command line arguments passed through
     * @return The status of this run (failed or passed
     *         and a comment)
     */
    public Status run(String[] args) {
        int failureTime = getConfig().getFailureTime();

	try {
	    TestUtility.log(Config.ALL,"Test: starting lookup in public group");
	    lookup = TestUtility.startLookup(new String[] {""}, failureTime,
		"LeaseTest_RegistrarLog", getConfig());
	} catch (Exception e) {
            TestUtility.log(Config.ERROR,"Test: caught exception",e);
            return Status.failed(Status.ENV,"Problem starting lookup service");
        }

	try {
	    admin = (BasicServiceAdmin) getConfig().getAdmin();
	    TestUtility.log(Config.ALL,"Test: starting program");
	    admin.start();
	} catch (RemoteException re) {
            TestUtility.log(Config.ERROR,"Test: caught exception",re);
            return Status.failed(Status.ENV,"Problem starting program");
        }

	try {
            TestUtility.log(Config.ALL,"Test: waiting up to " + (4*failureTime)
                + " milliseconds for program to register in lookup");
	    serviceItem = TestUtility.waitForRegistration(lookup,
		4 * failureTime, getConfig());
	} catch (Exception e) {
            TestUtility.log(Config.ERROR,"Test: caught exception",e);
            return Status.failed(Status.ENV,"Problem while waiting for "
		+ "program to register with lookup");
        }

	if (serviceItem == null) {
	    return Status.failed(Status.TEST, "Service did not register");
        }
	    
	try {
	    boolean unregistered = waitForUnregistration(3 * failureTime);
	    if (unregistered) {
		return Status.failed(Status.TEST, "Service did not properly "
                    + "maintain its lease in the lookup service");
	    }    
	} catch (Exception e) {
            TestUtility.log(Config.ERROR,"Test: caught exception",e);
            return Status.failed(Status.ENV,"Problem while waiting for "
		+ "program to unregister with lookup");
        }

	return Status.passed("OK");
    }
    
    public void tearDown() {
	super.tearDown();
	
	try {
	    if (lookup != null) {
		TestUtility.log(Config.ALL,"Test: stopping lookup");
		TestUtility.stopLookup(lookup, getConfig());
	    }
	} catch (RemoteException ignore) {}
	try {
	    if (admin != null) {
		TestUtility.log(Config.ALL,"Test: stopping program");
		admin.stop();
	    }
	} catch (RemoteException ignore) {}
    }

    public String[] getCategories() {
	return (new String[] { BasicServiceAdmin.CATEGORY });
    }

    public Class[] getRequiredAdmins() {
	return (new Class[] { BasicAdmin.class, BasicServiceAdmin.class });
    }

    public String getDescription() {
	return "LeaseTest";
    }

    private boolean waitForUnregistration(long timeout) 
	throws RemoteException, InterruptedException 
    {
       	RegistrationListener rl = new RegistrationListener();
	EventRegistration er = null;
	synchronized (rl) {
	    er = lookup.notify(
		new ServiceTemplate(serviceItem.serviceID, null, null),
		ServiceRegistrar.TRANSITION_MATCH_NOMATCH |
		ServiceRegistrar.TRANSITION_NOMATCH_MATCH,
		rl, null, timeout * 2);

	    TestUtility.log(Config.ALL,"Test: waiting up to " + timeout
		+ " milliseconds for program to be unregistered");
	    rl.wait(timeout);
	}

	try {
	    if (er != null) {
		er.getLease().cancel();
	    }
	} catch (UnknownLeaseException ignore) {
	} catch (RemoteException ignore) {}
	try {
	    UnicastRemoteObject.unexportObject(rl,true);
	} catch (RemoteException ignore) {}
	
	return (rl.isNotified() || 
	       TestUtility.getService(lookup, getConfig()) == null);
    }

    private class RegistrationListener extends UnicastRemoteObject
	implements RemoteEventListener 
    {
	private boolean notified = false;
	public RegistrationListener() throws RemoteException {
            super();
        }
	public boolean isNotified() {
	    return notified;
	}
	public void notify(RemoteEvent re) {
	    String type = "MATCH_NOMATCH";
	    if (((ServiceEvent)re).getTransition() == 
		ServiceRegistrar.TRANSITION_NOMATCH_MATCH) 
	    {
	        type = "NOMATCH_MATCH";
	    }
	    TestUtility.log(Config.ALL,"Test: received " + type + " event");
	    if (!notified) {
	        synchronized(this) {
		    notified = true;
                    this.notify();
		}
            }
	}
    }

}
