/*
 * 
 * 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 
 *  interfaces it implements (excluding the universally-implemented
 *  Serializable interface).
 *
 *  @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 LookupByInterfaceTest extends TestRegistrar {

    private ServiceItem[] srvcItems ;
    private ServiceRegistration[] srvcRegs ;
    private ServiceTemplate[][] intfcClassTmpls;
    private ServiceRegistrar proxy;
    private int nClasses = 0;
    private int nInstances = 0;
    private int nInstancesPerClass = 0;
    private int maxNIntfcPerClass = 0;
    private LeaseRenewalManager lrm;

    /** Performs actions necessary to prepare for execution of the 
     *  current QA 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 one of the interfaces, implemented
     *  by the corresponding service, from the set of test interfaces.
     *  @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;
        int indx;
        Class sClass;
        Class iClass[] = new Class[super.INTERFACES.length];

        super.setupQATest(); 
        nClasses = super.getNTestClasses();
        nInstances = super.getNInstances();
        nInstancesPerClass = super.getNInstancesPerClass();
        maxNIntfcPerClass  = super.MAX_N_INTFC_PER_CLASS;

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

	intfcClassTmpls = new ServiceTemplate[nClasses][maxNIntfcPerClass];
	try {
            sClass = Class.forName("java.io.Serializable");
            for (int i=0;i<super.INTERFACES.length;i++) {
              iClass[i] = Class.forName(super.INTERFACES[i]);
	    }
	    for(int i=0; i<nClasses; i++) {
                Class c = Class.forName(TEST_SRVC_CLASSES[i]);
                Class[] intfcClassTypes = c.getInterfaces();
                int nInterfaces = intfcClassTypes.length;
		//for(int a = 0; a<nInterfaces; a++)
		//    System.out.println("Interfaces for "+c+": "+
		//		       intfcClassTypes[a]);
		
                for (j=0;j<nInterfaces;j++) {
                    if(!intfcClassTypes[j].isAssignableFrom(sClass)) {
                        indx = 0;
                        for (k=0;k<super.INTERFACES.length;k++) {
			    if(intfcClassTypes[j].isAssignableFrom(iClass[k])){
                                indx = k;
                                break;
			    }
		        }
                        Class[] classTypeArray = {intfcClassTypes[j]};
			intfcClassTmpls[i][k] = new ServiceTemplate
                                                    (null,classTypeArray,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 QA test.
     *
     *  For each registered service:  
     *     For each interface in the set of test interfaces:  
     *        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 intfcM = null;
        for (int i=0; i<nClasses; i++) {
            for (int j=0; j<super.INTERFACES.length;j++) {
                if (super.INTFC_IMPL_MATRIX[i][j] == 0)  continue;
	            try {
                        intfcM = proxy.lookup(intfcClassTmpls[i][j],
                                              Integer.MAX_VALUE);
	            } catch (RemoteException e) {
                        throw new TestFailedException
                                   ("doQATest: RemoteException from lookup",e);
	            }
                if(intfcM.totalMatches != expectedNMatchesIntfc[i][j]) {
                    throw new TestFailedException("totalMatches ("+
                                   intfcM.totalMatches+") != expectedMatches["+
                               i+"]["+j+"] ("+expectedNMatchesIntfc[i][j]+")");
	        } else {
       	            if (!setsAreEqual(j,intfcM)) {
                        throw new TestFailedException
                                 ("At index "+j+", 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            intfcIndx,
                                 ServiceMatches srvcM)
    {
        int     si;
        int     i,j,k;
        boolean inSet;
        for (i=0; i<srvcM.totalMatches; i++) {
            inSet = false;
            for (j=0; (   (inSet==false)
                        &&(j<srvcM.totalMatches/nInstancesPerClass)); j++) {
                si = nInstancesPerClass*super.INTFC_TO_SI[intfcIndx][j];
                for (k=0; ((inSet==false)&&(k<nInstancesPerClass)); k++) {
                    if ((srvcItems[si+k].service.equals
                                                     (srvcM.items[i].service)))
                    {
                        inSet = true;
                    }
		}
	    }
            if (inSet == false) return false;
        }
        return true; /* success */
    }
    
    public String getDescription() {
        return "LookupByInterfaceTest";
    }
}
