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

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.ServiceTemplate;
import net.jini.core.lease.*;
import java.rmi.RemoteException;

/** This class is used to test that service 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 MultipleServiceLeaseRenewalTest 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 Lease[] srvcLeases ;
    private ServiceTemplate[] srvcIDTmpls;
    private ServiceRegistrar proxy;
    private int nInstances = 0;
    private long leaseStartTime;

    /** Performs actions necessary to prepare for execution of the 
     *  current  test.
     *
     *  Creates the lookup service. Loads and instantiates all service 
     *  classes. Retrieves the proxy to the lookup Registrar. Establishes 
     *  an approximate service lease start time for each service item by 
     *  retrieving the current system time. Registers each service class 
     *  instance with a specified lease duration. Creates an array of 
     *  Leases in which each element contains the service lease of one 
     *  of the registered services. Creates an array of ServiceTemplate objects 
     *  in which each element contains the service ID of one of the 
     *  registered service items.
     *  @exception TestException will usually indicate an "unresolved"
     *  condition because at this point the test has not yet begun.
     */
    public void setupQATest() throws TestException {
        int i;
	super.setupQATest();

	Config conf = getConfig();
	requestedLeaseDuration = 4*conf.getFailureTime();

        nInstances = super.getNInstances();
	srvcItems = super.createServiceItems(TEST_SRVC_CLASSES);
	proxy = super.getProxy();
	srvcIDTmpls = new ServiceTemplate[nInstances];
	leaseStartTime = TestUtils.getCurTime();
 	srvcRegs = registerAll(requestedLeaseDuration);
	
	long minExp = leaseStartTime+requestedLeaseDuration;
 
        srvcLeases = new Lease[srvcRegs.length];
	for(i=0; i<srvcLeases.length; i++) {
	    srvcLeases[i] = srvcRegs[i].getLease();
	}
	// The minimum lease duration granted
	leaseDuration = findMinLeaseDuration(srvcLeases);
	leaseWaitTime = leaseDuration*3/4;
	halfDurationTime = leaseDuration/2;

	for(i=0; i<srvcIDTmpls.length; i++) {
	    srvcIDTmpls[i] = new ServiceTemplate(srvcRegs[i].getServiceID(),
                                                 null,null);
	}
    }

    /** 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 service leases; requesting the new lease duration.
     *     Waits for one-half of the current lease duration time.
     *     Performs a simple lookup of each registered service item.
     *     Verifies that the set of service items returned by the lookup 
     *     operation equals the expected set of service items.
     *  @exception TestException usually indicates test failure
     */

    /*  The time-line diagram below shows the steps of this test:
     *
     *                                                     Renewal
     *                                                     R4 |---------------|
     *                                         Renewal        :        ^      .
     *                                         R3 |---------------|    :      .
     *                             Renewal        :       ^       .    :      .
     *                             R2 |---------------|   :       .    :      .
     *                 Renewal        :       ^       .   :       .    :      .
     *                 R1 |---------------|   :       .   :       .    :      .
     *     Renewal        :       ^       .   :       .   :       .    :      .
     *     R0 |---------------|   :       .   :       .   :       .    :      .
     *        :       ^       .   :       .   :       .   :       .    :      .
  |---------------|   :       .   :       .   :       .   :       .    :      .
  0      0.5      1   :      1.75 :      2.5  :     3.25  :       4    :    4.75
     *                :           :           :           :            :
     *                :           :           :           :            :
     *               L0          L1          L2          L3           L4
     */
    public void doQATest() throws TestException {
	for(int i =0; i<loopCount; i++) {
	    TestUtils.computeDurAndWait(leaseStartTime, leaseWaitTime);
	    leaseStartTime = TestUtils.getCurTime();
	    TestUtils.doRenewLease(srvcLeases, leaseDuration);
	    leaseDuration = findMinLeaseDuration(srvcLeases);
	    leaseWaitTime = leaseDuration*3/4;
	    halfDurationTime = leaseDuration/2;
	    TestUtils.computeDurAndWait(leaseStartTime, halfDurationTime);
	    TestUtils.doLookup(srvcItems, srvcIDTmpls, proxy ); 
	}
    }

    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;
    }

    /** Performs cleanup actions necessary to achieve a graceful exit of 
     *  the current  test.
     *  @exception TestException will usually indicate an "unresolved"
     *  condition because at this point the test has completed.
     */
    public void cleanupQATest() throws TestException {
	super.cleanupQATest();
    }
    
    public String getDescription() {
	return "MultipleServiceLeaseRenewalTest";
    }   
}
