/*
 * 
 * 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 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 any service item registered with the Lookup
 *  service can no longer be successfully looked up after the service
 *  item's lease has 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 ServiceLeaseExpirationTest 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 leaseDuration;
    private long leaseWaitTime;
    private long lookupWaitTime;
    private ServiceItem[] srvcItems ;
    private ServiceRegistration[] srvcRegs ;
    private ServiceTemplate[] srvcIDTmpls;
    private ServiceRegistrar proxy;
    private int nInstances = 0;
    private long leaseStartTime;
    private long maxLeaseDuration;

    /** Performs actions necessary to prepare for execution of the 
     *  current  test.
     *
     *  Creates the lookup service. Loads and instantiates all service 
     *  classes. Registers each service class instance with a specified 
     *  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. Establishes 
     *  an approximate service lease start time for each service item by 
     *  retrieving the current system time.
     *  @exception TestException will usually indicate an "unresolved"
     *  condition because at this point the test has not yet begun.
     */
    public void setupQATest() throws TestException {
	super.setupQATest();
	Config conf = getConfig();
	leaseDuration = conf.getFailureTime();
	leaseWaitTime = leaseDuration*3/4;
	lookupWaitTime = leaseDuration/2;

        nInstances = super.getNInstances();

	srvcItems = super.createServiceItems(TEST_SRVC_CLASSES);
	srvcRegs = super.registerAll(leaseDuration);
	proxy = super.getProxy();
	
	long maxExp = 0;
	for(int i = 0; i < srvcRegs.length; i++) {
	    Lease l = srvcRegs[i].getLease();
	    long tempExp = l.getExpiration();
	    if(tempExp > maxExp)
		maxExp = tempExp;
	}
	
	srvcIDTmpls = new ServiceTemplate[nInstances];
	for(int i=0; i<srvcIDTmpls.length; i++) {
	    srvcIDTmpls[i] = new ServiceTemplate(srvcRegs[i].getServiceID(),
                                                 null,null);
	}
	leaseStartTime = TestUtils.getCurTime();
	maxLeaseDuration = maxExp - leaseStartTime;
    }

    /** Executes the current  test.
     *
     *  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.
     *  Waits a specified amount of time so as to guarantee that each
     *  service lease expires.
     *  Performs both a simple and a match lookup of each registered service
     *  item.
     *  For each lookup performed, verifies that a null service, as well as
     *  zero matches, are returned.
     *  @exception TestException usually indicates test failure
     */

    /*  The time-line diagram below shows the steps of this test:
     *
     *           |-------------------------------------------------------|
     *           :         :         ^         
     * |-------------------|         :         
     * 0    ^   0.5        1         :        
     *      :              :         :
     *      :              :         :
     *   Lookup          Lease    Lookup
     *                  Expires
     */
    public void doQATest() throws TestException {
	TestUtils.doLookup(srvcItems, srvcIDTmpls, proxy );
	TestUtils.computeDurAndWait(leaseStartTime, maxLeaseDuration);
        doLookupNoMatch();
    }
 
    /** 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();
    }

    /* Perform both a simple and a match lookup using the ServiceTemplate
     * created during setup. Verifies that every simple lookup returns
     * a null object; and every match lookup returns zero matches.
     */
    private void doLookupNoMatch() throws TestException {
        Object serviceObj = null;
        ServiceMatches matches = null;
        for (int i=0; i<srvcIDTmpls.length; i++) {
	    try {
	        if(proxy.lookup(srvcIDTmpls[i]) != null) {
                    throw new TestFailedException
                               ("doLookupNoMatch: srvcIDTmpls["+i+"] != null");
	        }
	    } catch (RemoteException e) {
                throw new TestFailedException
                     ("doLookupNoMatch: RemoteException from single lookup",e);
	    }
	    try {
                matches = proxy.lookup(srvcIDTmpls[i],Integer.MAX_VALUE);
	    } catch (RemoteException e) {
                throw new TestFailedException
                   ("doLookupNoMatch: RemoteException from multiple lookup",e);
	    }
            if ( matches.totalMatches != 0) {
                throw new TestFailedException
                                        ("doLookupNoMatch: totalMatches != 0");
	    }
	}
    }

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