/*
 * 
 * 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 the 
 *  super classes it extends (excluding the universally-extended Object class).
 *
 *  @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 LookupBySuperClassTest extends TestRegistrar {

    private ServiceItem[] srvcItems ;
    private ServiceRegistration[] srvcRegs ;
    private ServiceTemplate[][] superClassTmpls;
    private ServiceRegistrar proxy;
    private int nClasses = 0;
    private int nInstances = 0;
    private int nInstancesPerClass = 0;
    private int maxChainLen = 0;
    private int[] chainLen;
    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. For each registered service, retrieves the
     *  "chain" of super classes and creates an array of ServiceTemplates 
     *  in which each element contains one of the retrieved super classes 
     *  (excluding the Object class).
     *  @exception TestException will usually indicate an "unresolved"
     *  condition because at this point the test has not yet begun.
     */
    public void setupQATest() throws TestException {
        int j,k;
        boolean exit_loop;
        int indx;

	super.setupQATest(); 
        nClasses = super.getNTestClasses();
        nInstances = super.getNInstances();
        nInstancesPerClass = super.getNInstancesPerClass();
        maxChainLen  = super.MAX_N_SUPER_CHAIN_LEN;

	srvcItems = super.createServiceItems(TEST_SRVC_CLASSES);
	srvcRegs = super.registerAll();
	proxy = super.getProxy();

	superClassTmpls = new ServiceTemplate[nClasses][maxChainLen];

	try {
            Class sClass[] = new Class[maxChainLen];
            chainLen = new int[nClasses];
	    for(int i=0; i<nClasses; i++) {
                Class c = Class.forName(TEST_SRVC_CLASSES[i]);
                /* build the super class "chain" corresponding to class i */
                sClass[0] = c;
                for (j=1,exit_loop=false;
                      ((exit_loop==false)&&(j<maxChainLen));j++) {
                    sClass[j] = sClass[j-1].getSuperclass();
                    if ( !sClass[j].isAssignableFrom(Object.class) ) {
                        Class[] superClassType = {sClass[j]};
		        superClassTmpls[i][j] = new ServiceTemplate
                                                    (null,superClassType,null);
		    } else {
                        exit_loop = true;
                        chainLen[i] = j;
		    }
	        }
	    }
	} 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 registered service:  
     *     For each super class in the set of super classes:  
     *        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 superM = null;
        for (int i=0; i<nClasses; i++) {
	    /** Loop from j = 1 because the chain starts with the class
             *  itself; and this test is testing only its super classes
             */
            for (int j=1; j<chainLen[i];j++) {
                if (super.expectedNMatchesSuper[i][j] == 0)  continue;
	        try {
                    superM = proxy.lookup(superClassTmpls[i][j],
                                          Integer.MAX_VALUE);
	        } catch (RemoteException e) {
                    throw new TestFailedException
                                   ("doQATest: RemoteException from lookup",e);
	        }
		System.out.println("Matches: "+superM.totalMatches);
                if(superM.totalMatches != expectedNMatchesSuper[i][j]) {
                    throw new TestFailedException("totalMatches ("+
                                   superM.totalMatches+") != expectedMatches["+
                               i+"]["+j+"] ("+expectedNMatchesSuper[i][j]+")");
		} else {
       	            if (!setsAreEqual(i,superM)) {
                        throw new TestFailedException
                                 ("At index "+i+", the services do NOT match");
		    }
		}
            }
	}
    }

    /** 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();
	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     n;
        int     i,j,k;
        n  = classIndx - (classIndx%chainLen[classIndx]);
        s0 = nInstancesPerClass*n;

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