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

import com.sun.jini.compat.lease.LeaseRenewalManager;

import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceItem;
import net.jini.core.lookup.ServiceRegistration;
import net.jini.core.lookup.ServiceMatches;
import net.jini.core.lookup.ServiceEvent;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.core.event.*;
import net.jini.core.lease.*;
import java.rmi.Remote;
import java.rmi.MarshalledObject;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;
import java.rmi.NoSuchObjectException;
import java.io.IOException;

/** This class is used to test that event lease renewal works as expected for
 *  N (currently N = 5) successive lease renewal attempts.
 *
 *  @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 MultipleEventLeaseRenewalTest extends TestRegistrar {
    /** the expected number of matches when testing lookup by ID */
    private static int EXPECTED_N_MATCHES = 1;
    private final static int DEFAULT_LOOP_COUNT = 5;
    private static int  loopCount= DEFAULT_LOOP_COUNT; 
    private long requestedLeaseDuration;  
    private long leaseDuration;
    private long leaseWaitTime;
    private long halfDurationTime;
    private ServiceItem[] srvcItems ;
    private ServiceRegistration[] srvcRegs ;
    private ServiceTemplate[] srvcIDTmpls;
    private ServiceRegistrar proxy;
    private int nInstances = 0;
    private LeaseRenewalManager lrm;

    private long leaseStartTime;

    private ServiceEvent[] notificationEvnt;
    private int numEvnt = 0;
    private Lease[] evntLeases ;
    private EventRegistration[] evntRegs;
    
    /** Class which handles all events sent by the lookup service */
    private class Listener implements RemoteEventListener {
        Object proxy;
	Listener() throws RemoteException {
	    proxy = UnicastRemoteObject.exportObject((Remote)this);
	}
        /** Method called remotely by lookup to handle the generated event. */
	public void notify(RemoteEvent theEvent)
	    throws UnknownEventException, RemoteException 
	{
	    notificationEvnt[numEvnt++] = (ServiceEvent) theEvent;
	}
        public Object getProxy() {
            return proxy;
        }
    }

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

    /** 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 an array of 
     *  ServiceTemplate objects in which each element contains the service ID
     *  of one of the registered service items. Associates with each service
     *  item, the corresponding service ID returned by the registration 
     *  process; to enable reuse of the service IDs during the re-registration 
     *  of the services. Establishes an approximate event lease start time 
     *  for each event lease by retrieving the current system time. For
     *  each registered service, registers an event notification request,
     *  with a specified lease duration, based on the contents of the 
     *  corresponding template created previously and the appropriate 
     *  transition mask. Creates an array of Leases in which each element 
     *  contains one of the event leases created during the event 
     *  notification registration process.
     *  @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();
	requestedLeaseDuration = 8*conf.getFailureTime();

        nInstances = super.getNInstances();
	srvcItems = super.createServiceItems(TEST_SRVC_CLASSES);
	srvcRegs = registerAll();
	proxy = super.getProxy();
	srvcIDTmpls = new ServiceTemplate[nInstances];
	for(int i=0; i<srvcIDTmpls.length; i++) {
	    srvcIDTmpls[i] = new ServiceTemplate(srvcRegs[i].getServiceID(),
                                                 null,null);
	}
	reuseServiceID();
	evntRegs = new EventRegistration[nInstances];
	evntLeases = new Lease[nInstances];
	notificationEvnt = new ServiceEvent[nInstances];
	leaseStartTime = TestUtils.getCurTime();
	registerAllEvents();

	lrm = new LeaseRenewalManager();
	for(int i=0; i<srvcRegs.length; i++) {
	    lrm.renewUntil(srvcRegs[i].getLease(),
			 Long.MAX_VALUE, null);
	}
	leaseDuration = findMinLeaseDuration(evntLeases);
	leaseWaitTime = leaseDuration*3/4;
	halfDurationTime = leaseDuration/2;
    }

    /** Executes the current  test.
     *
     *  Repeats the following steps N times:
     *     Waits for three-fourths of the current lease duration time.
     *     Sets the new (approximate) lease start time to the current time.
     *     Renews all event leases; requesting the new lease duration.
     *     Verifies that the lease duration returned is the duration requested.
     *     Waits for one-half of the current lease duration time.
     *     If the loop index is even, cancels each service lease (to generate 
     *     an event).
     *     If the loop index is odd, re-registers each instance of each service
     *     class that was previously registered (also to generate an event).
     *     Waits for a specified amount of time to allow time for any events
     *     to be generated, sent and collected.
     *     Performs a simple lookup of each registered service item.
     *     Verifies that the set of events sent by the lookup service is
     *     the set of events expected. 
     *     Verifies that each event corresponds to the expected service ID 
     *     and that the transition is the expected transition (MATCH_NOMATCH
     *     if the service lease was cancelled, NOMATCH_MATCH if the service
     *     was re-registered).
     *  @exception TestException usually indicates test failure
     */

    /*  The time-line diagram below shows the steps of this test:
     *
     *                                                     Renewal
     *                                                    NR4 |---------------|
     *                                        Renewal         :       ^  ^    .
     *                                        NR3 |---------------|   :  :    .
     *                            Renewal         :      ^  ^     .   :  :    .
     *                            NR2 |---------------|  :  :     .   :  :    .
     *                Renewal         :     ^  ^      .  :  :     .   :  :    .
     *                NR1 |---------------| :  :      .  :  :     .   :  :    .
     *    Renewal         :      ^  ^     . :  :      .  :  :     .   :  :    .
     *    NR0 |---------------|  :  :     . :  :      .  :  :     .   :  :    .
     *        :      ^  ^     .  :  :     . :  :      .  :  :     .   :  :    .
  |---------------|  :  :     .  :  :     . :  :      .  :  :     .   :  :    .
  0      0.5      1  :  :   1.75 :  :   2.5 :  :    3.25 :  :     4   :  :  4.75
     *               :  :        :  :       :  :         :  :         :  :
     *               :  :        :  :       :  :         :  :         :  :
     *               :  A0       :  A1      :  A2        :  A3        :  A4
     *               :           :          :            :            :
     *               :           :          :            :            :
     *              P0          P1         P2           P3           P4
     */
    public void doQATest() throws TestException {
	for(int i =0; i<loopCount; i++) {
	    numEvnt = 0;
	    TestUtils.computeDurAndWait(leaseStartTime, leaseWaitTime);
	    leaseStartTime = TestUtils.getCurTime();
	    TestUtils.doRenewLease(evntLeases,
				   requestedLeaseDuration);
	    leaseDuration = findMinLeaseDuration(evntLeases);
	    leaseWaitTime = leaseDuration*3/4;
	    halfDurationTime = leaseDuration/2;
	 
	    TestUtils.computeDurAndWait(leaseStartTime, halfDurationTime);
	    int transition;
	    if( TestUtils.isEven(i) ) {
		cancelAllLeases(srvcRegs);
		transition = ServiceRegistrar.TRANSITION_MATCH_NOMATCH;
	    } else {
		srvcRegs = registerAll();
		for(int j=0; j<srvcRegs.length; j++) {
		    lrm.renewUntil(srvcRegs[j].getLease(),
				 Long.MAX_VALUE, null);
		}
	      	transition = ServiceRegistrar.TRANSITION_NOMATCH_MATCH;
	    }
	    try {
		Thread.sleep(leaseDuration/8);
	    } catch (InterruptedException e) {
	    }
	    verifyNotification(transition);
	}
    }

    /** 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();
	
	lrm.clear();
    }
    
    private long findMinLeaseDuration(Lease[] ls) {
	long minExp = Long.MAX_VALUE;
	for(int i=0; i<ls.length; i++) {
	    long tempExp = ls[i].getExpiration();
	    if(tempExp < minExp)
		minExp = tempExp;
	}
       
	long startTime = TestUtils.getCurTime();
	return minExp-startTime;
    }
    
    /* For each registered service, registers an event notification request,
     * with a specified lease duration, based on the contents of the 
     * corresponding template created during setup and corresponding to
     * the appropriate transition mask. Populates the array of Leases so
     * that each element contains one of the event leases returned by the 
     * event notification registration process.
     */
    private void registerAllEvents() throws TestException {
        for(int i=0; i<evntRegs.length; i++) {
	    try {
		evntRegs[i] = proxy.notify(srvcIDTmpls[i],
		    ServiceRegistrar.TRANSITION_NOMATCH_MATCH  |
		        ServiceRegistrar.TRANSITION_MATCH_NOMATCH |
		        ServiceRegistrar.TRANSITION_MATCH_MATCH,
		    (RemoteEventListener) listener.getProxy(),
		    null,
		    requestedLeaseDuration);
		evntLeases[i] = evntRegs[i].getLease();
	    } catch (RemoteException e) {
                throw new TestUnresolvedException
                    ("registerAllEvents: RemoteException from notify (index = "
                      +i+")",e);
	    } catch (IOException e) {
                throw new TestUnresolvedException
     ("registerAllEvents: IOException from MarshalledObject creation (index = "
                                                                     +i+")",e);
	    }
	}
    }

    /* Cancels the service lease of each registered service item. */
    private void cancelAllLeases(ServiceRegistration[] regs)
                                                         throws TestException
    {
        for(int i=0; i<regs.length; i++) {
	    try {
		lrm.cancel(regs[i].getLease());
	    } catch (UnknownLeaseException e) {
                throw new TestUnresolvedException
                           ("cancelAllLeases: lease["+i+"] -- unknown lease",e);
	    } catch (RemoteException e) {
                throw new TestUnresolvedException
                    ("cancelAllLeases: RemoteException while cancelling lease["
                     +i+"]",e);
	    }
	}
    }

    /* Associates with each registered service item, the corresponding 
     * service ID returned by the registration process; so as to enable 
     * reuse of the service IDs during the re-registration process.
     */
    private void reuseServiceID() {
        for(int i=0; i< srvcItems.length; i++) {
	    srvcItems[i].serviceID = srvcRegs[i].getServiceID();
	}
    }
  
    /* Verifies that the number of events received equals the number of
     * events expected. For each registered service item, verifies that
     * service's ID equals the service ID associated with the corresponding
     * event; and that the transition associated with the event equals
     * the expected transition.
     */
    private void verifyNotification(int transition) throws TestException {
	if(srvcItems.length != numEvnt )
            throw new TestFailedException("# of Events Received ("+
                                             numEvnt+
                                             ") != # of Events Expected ("+
                                             srvcItems.length+")");

	for(int i=0; i <srvcItems.length; i++) {
	    if(!verifyServiceItemTransition(srvcItems[i],transition)) {
                throw new TestFailedException
                                         ("transition mismatch (index "+i+")");
	    }
	}	
    }

    /* For each event associated with the given service item, verifies that
     * verifies that service's ID equals the service ID associated with the 
     * event; and that the transition associated with the event equals
     * the expected transition.
     */
    private boolean verifyServiceItemTransition(ServiceItem serviceItem,
                                                int transition)
    {
	for(int i=0; i<numEvnt; i++ ) {
	    if(    (notificationEvnt[i].getServiceID().equals
                                                       (serviceItem.serviceID))
                && (notificationEvnt[i].getTransition() == transition) )
            {
		return true;
	    }
	}
	//System.out.println("verifyServiceItemTransition failed");
	return false;
    }
    
    public String getDescription() {
	return "MultipleEventLeaseRenewalTest";
    }  
}



