/*
 * 
 * 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 com.sun.jini.compat.test.lookup.TestUtils;
import com.sun.jini.compat.test.lookup.TestImpl;
import com.sun.jini.compat.test.lookup.TestRegistrar;
import com.sun.jini.compat.test.lookup.TestException;
import com.sun.jini.compat.test.lookup.TestFailedException;
import com.sun.jini.compat.test.lookup.TestUnresolvedException;
import com.sun.jini.compat.harness.Config;

import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceEvent;
import net.jini.core.lookup.ServiceItem;
import net.jini.core.lookup.ServiceRegistration;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.core.event.EventRegistration;
import net.jini.core.event.RemoteEvent;
import net.jini.core.event.RemoteEventListener;
import net.jini.core.lease.UnknownLeaseException;
import java.rmi.Remote;
import java.rmi.NoSuchObjectException;
import java.rmi.RemoteException;
import java.rmi.StubNotFoundException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Vector;

/** This class is used to test that all event notifications cease to be
 *  delivered after all event leases have expired.
 *
 *  @see com.sun.jini.compat.test.lookup.Test
 *  @see com.sun.jini.compat.test.lookup.TestImpl
 *  @see com.sun.jini.compat.test.lookup.TestRegistrar
 *  @see com.sun.jini.compat.test.lookup.TestUtils
 */
public class EventLeaseExpirationTest extends TestRegistrar {

    /** Class which handles all events sent by the lookup service */
    public class Listener implements RemoteEventListener {
        Object proxy;
        public Listener() throws RemoteException {
            proxy = UnicastRemoteObject.exportObject((Remote)this);
        }
        /** Method called remotely by lookup to handle the generated event. */
        public void notify(RemoteEvent ev) {
            ServiceEvent srvcEvnt = (ServiceEvent)ev;
            evntVec.addElement(srvcEvnt);
        }
        public Object getProxy() {
            return proxy;
        }
    }

    /** The event handler for the services registered by this class */
    private static Listener listener;

    protected Vector evntVec = new Vector();

    private long realLeaseDuration;
    private ServiceItem[] srvcItems ;
    private ServiceRegistration[] srvcRegs ;
    private ServiceTemplate template;
    private ServiceRegistrar proxy;

    /** Performs actions necessary to prepare for execution of the 
     *  current  test.
     *
     *  Creates a single event handler to handle all events generated
     *  by any of the registered service items. Creates the lookup
     *  service. Loads and instantiates all service classes. Registers 
     *  each service class instance with the maximum service lease duration. 
     *  Retrieves the proxy to the lookup Registrar. Creates a single
     *  ServiceTemplate using ServiceID of registered services.
     *  Register an event notification request based on the contents of that
     *  template, a transition mask including all three transitions, and
     *  a lease duration that is less than the duration of the service
     *  leases.
     *  @exception TestException will usually indicate an "unresolved"
     *  condition because at this point the test has not yet begun.
     */
    public void setupQATest() throws TestException {
	try {
	    listener = new Listener();
	} catch (RemoteException e) {
            throw new TestUnresolvedException
                     ("setupQATest: RemoteException from listener creation",e);
	}
	super.setupQATest();
	Config conf = getConfig();
        srvcItems = super.createServiceItems(TEST_SRVC_CLASSES);
	srvcRegs = super.registerAll();
	proxy = super.getProxy();
	template = new ServiceTemplate(srvcRegs[0].getServiceID(),null,null);
	try {
	    EventRegistration evntReg = proxy.notify(template,
		ServiceRegistrar.TRANSITION_NOMATCH_MATCH |
		    ServiceRegistrar.TRANSITION_MATCH_NOMATCH |
		    ServiceRegistrar.TRANSITION_MATCH_MATCH,
		(RemoteEventListener) listener.getProxy(), 
                null, 
                conf.getFailureTime());
	    long leaseExpiration = evntReg.getLease().getExpiration();
	    long leaseStartTime = TestUtils.getCurTime();
	    realLeaseDuration = leaseExpiration - leaseStartTime;
	} catch (RemoteException e) {
            throw new TestUnresolvedException
                                ("setupQATest: RemoteException from notify",e);
	}
    }

    /** wait for the event lease to expire and then verify that NO events
     *  have arrived
     */
    /** Executes the current  test.
     *
     *  Computes the amount of time to wait to guarantee that all event
     *  leases have expired. Waits that amount of time. Cancels each
     *  service lease (to generate an event for each cancellation). Waits
     *  an appropriate amount of time to allow any events that may be
     *  generated to be sent and collected. Verifies that no events were
     *  sent by the Lookup service. 
     *  @exception TestException usually indicates test failure
     */

    /*  The time-line diagram below shows the steps of this test:
     *
     *           |-----------------------------------------------------------|
     *           :         :         ^      :  
     * |-------------------|         :      :  
     * 0                 5 secs      :      : 
     *                     :         :      :
     *                     :         :      :
     *                  Expires    Cancel   :
     *                             Service  :
     *                             Lease    Analyze
     */
    public void doQATest() throws TestException {
        ServiceEvent evnt = null;
        /* wait for the event lease to expire */
	try {
            Thread.sleep(realLeaseDuration);
	} catch (InterruptedException e) {
        }

	/* throw out previous, spurious received events */
	evntVec = new Vector();

        /* cancel each service lease so as to generate events */
	for(int i=0; i<srvcRegs.length; i++) {
	    try {
                srvcRegs[i].getLease().cancel();
	    } catch (UnknownLeaseException e) {
                throw new TestFailedException
                       ("doQATest: UnknownLeaseException from cancel (index = "
                         +i+")",e);
	    } catch (RemoteException e) {
                throw new TestFailedException
                             ("doQATest: RemoteException from cancel (index = "
                               +i+")",e);
            }
	}
        /* give the Listener a chance to collect all events */
	try {
            Thread.sleep(getConfig().getQuietTime());
	} catch (InterruptedException e) {
        }

        /* Verify that no events have arrived. If no events have arrived
         * the event vector should be empty. If not, declare failure
         */
        if (evntVec.size() != 0) {
            throw new TestFailedException("doQATest: evntVec.size() != 0");
	}
    }

    /** Performs cleanup actions necessary to achieve a graceful exit of 
     *  the current  test.
     *
     *  Unexports the listener and then performs any remaining standard
     *  cleanup duties.
     *  @exception TestException will usually indicate an "unresolved"
     *  condition because at this point the test has completed.
     */
    public void cleanupQATest() throws TestException  {
	try {
	    UnicastRemoteObject.unexportObject((Remote)listener, true);
	} catch (NoSuchObjectException e) {
        }
	super.cleanupQATest();
    }
    
    public String getDescription() {
	return "EventLeaseExpirationTest";
    }   
}
