/*
 * 
 * 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 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 java.rmi.RemoteException;

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

/** This class is used to test that every service item registered with
 *  the Lookup service can be successfully looked up using only its class type.
 *
 *  @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 LookupByClassTest extends TestRegistrar {

    private ServiceItem[] srvcItems ;
    private ServiceRegistration[] srvcRegs ;
    private ServiceTemplate[] exactClassTmpls;
    private ServiceRegistrar proxy;
    private int nClasses = 0;
    private int nInstances = 0;
    private int nInstancesPerClass = 0;

    private LeaseRenewalManager lrm;

    /** Performs actions necessary to prepare for execution of the 
     *  current  test.
     *
     *  Creates the lookup service. Loads and instantiates all service 
     *  classes; then registers each service class instance with the maximum
     *  service lease duration. Creates an array of ServiceTemplates in 
     *  which each element contains the class type of one of the registered
     *  services.
     *  @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();
        nClasses = super.getNTestClasses();
        nInstances = super.getNInstances();
        nInstancesPerClass = super.getNInstancesPerClass();
	srvcItems = super.createServiceItems(TEST_SRVC_CLASSES);
	srvcRegs = super.registerAll();
	proxy = super.getProxy();
	exactClassTmpls = new ServiceTemplate[nClasses];
	for(int i=0; i<nClasses; i++) {
	    try {
                Class c = Class.forName(TEST_SRVC_CLASSES[i]);
                Class[] exactClassType = {c};
	        exactClassTmpls[i] = new ServiceTemplate(null,
                                                         exactClassType,null);
	    } catch (ClassNotFoundException e) {
                throw new TestUnresolvedException
                                     ("setupQATest: ClassNotFoundException",e);
	    }
	}
	lrm = new LeaseRenewalManager();
        for(int i=0; i<srvcRegs.length; i++) {
            lrm.renewUntil(srvcRegs[i].getLease(),
                         Long.MAX_VALUE, null);
        }
    }

    /** Executes the current  test.
     *
     *  For each service registered:  
     *      Performs a match lookup using the corresponding template 
     *      created during setup and then tests that the number of matches
     *      found equals the number of matches expected; and that the set
     *      of objects returned equals the expected set of corresponding
     *      service items.
     *  @exception TestException usually indicates test failure
     */
    public void doQATest() throws TestException {
        ServiceMatches exactM = null;
        for (int i=0; i<nClasses; i++) {
	    try {
                exactM =
		    proxy.lookup(exactClassTmpls[i],Integer.MAX_VALUE);
	    } catch (RemoteException e) {
                throw new TestFailedException
                                   ("doQATest: RemoteException from lookup",e);
	    }
            if (exactM.totalMatches != expectedNMatchesExact[i]) {
                throw new TestFailedException
                                        ("totalMatches ("+exactM.totalMatches+
                                          ") != expectedMatches["+
                                         i+"] ("+expectedNMatchesExact[i]+")");
	    } else {
	        if (!setsAreEqual(i,exactM)) {
                    throw new TestFailedException
                                 ("At index "+i+", the services do NOT match");
		}
	    }
	}

    }

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

    /** Tests for equality between the returned set of services and the 
     *  expected set of services
     */
    private boolean setsAreEqual(int           classIndx,
                                 ServiceMatches srvcM)
    {
        int     s0,si;
        int     i,j,k;
        s0 = nInstancesPerClass*classIndx;

        iLoop:
            for (i=0; i<srvcM.totalMatches; i++) {
                si = s0;
                for (j=0;(j<srvcM.totalMatches/nInstancesPerClass); j++) {
                    si = si+(nInstancesPerClass*j);
                    for (k=0; k<nInstancesPerClass; k++) {
                        if ((srvcItems[si+k].service.equals
                                                     (srvcM.items[i].service)))
                        {
                           continue iLoop;
	                }
		    }
	        }
                return false;
            }
        return true; /* success */
    }

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