/*
 * 
 * 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 java.io.IOException;

import java.rmi.MarshalledObject;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RemoteException;

import com.sun.jini.compat.harness.TestUtility;
import com.sun.jini.compat.harness.Status;
import com.sun.jini.compat.harness.DefaultTest;
import com.sun.jini.compat.harness.BasicServiceAdmin;
import com.sun.jini.compat.harness.BasicAdmin;
import com.sun.jini.compat.harness.Config;
import com.sun.jini.compat.harness.RegistrationListener;

import com.sun.jini.lookup.entry.LookupAttributes;

import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceItem;
import net.jini.core.event.EventRegistration;
import net.jini.core.lease.UnknownLeaseException;

/**
 * Tests whether a service registers with multiple lookup services 
 * properly, including registering the same information (ServiceID 
 * and attributes) with all of the lookup services.
 */
public class MultipleRegistrationTest extends DefaultTest {
    
    private BasicServiceAdmin admin;
    private ServiceRegistrar[] lookups;
    private EventRegistration[] er;
    private RegistrationListener[] rl;

    /**
     * Starts up three lookup services, all of which are at least in 
     * the public group (some are in multiple groups), and then starts 
     * up the service being tested. The test then registers with all 
     * three of the lookup services to be notified when the service of
     * interest registers. If the test is not notified within twelve 
     * times the failureTime by all three lookup services, it queries 
     * the lookup services. Finally, if the service is in all three 
     * lookup services, the test compares the ServiceID and the attributes
     * that are registered with the three lookup services to make sure 
     * they are the same.  If the service isn't registered in all 
     * three of the lookup services, or the registration information 
     * is different between the three lookup services, the service fails.
     *
     * @param args Command line arguments passed through
     * @return The status of this run (failed or passed
     *         and a comment)
     */
    public Status run(String[] args){
	String[][] groups = {{""},
			    {"tck-random-group-1", ""},
			    {"tck-random-group-1", "tck-random-group-2", ""}};
	lookups = new ServiceRegistrar[groups.length];

	Config conf = getConfig();
	admin = (BasicServiceAdmin) conf.getAdmin();

	try {
	    for (int i = 0; i < lookups.length; i++) {
		TestUtility.log(Config.ALL,"Test: starting lookup " + i);
	        lookups[i] = TestUtility.startLookup(groups[i], 
		    conf.getQuietTime(),
		    "MultipleRegistrationTest_RegistrarLog" + i, conf);
	    }
	} catch (Exception e) {
            TestUtility.log(Config.ERROR,"Test: caught exception",e);
            return Status.failed(Status.ENV,"Problem starting lookup services");
        }

	try {
	    TestUtility.log(Config.ALL,"Test: starting program");
	    admin.start();
	} catch (RemoteException re) {
            TestUtility.log(Config.ERROR,"Test: caught exception",re);
            return Status.failed(Status.ENV,"Problem starting program");
        }
	    
	ServiceItem[] theService = null;
	try {
	    long timeout = 12 * conf.getFailureTime();
	    TestUtility.log(Config.ALL,"Test: waiting up to " + (timeout * 3)
		+ " milliseconds for program to register in all lookups");
	    theService = waitForAllRegistrations(lookups,timeout);
	} catch (Exception e) {
            TestUtility.log(Config.ERROR,"Test: caught exception",e);
            return Status.failed(Status.ENV,"Problem while waiting for "
                + "program to register with all lookups");
        }
	    
	if (theService == null) {
	    return Status.failed(Status.TEST, "Service not found "
		+ "in all lookups");
	}
	    
	TestUtility.log(Config.ALL,"Test: checking that the registrations "
	    + "are consistent");
	if (!registrationsAreConsistent(theService)) {
	    return Status.failed(Status.TEST, "Service registered "
		+ "inconsistently in lookups");
	}
	    
	return Status.passed("OK");
    }

    public void tearDown() {
        super.tearDown();

	for (int i = 0; i < lookups.length; i++) {
	    if (er != null && er[i] != null) {
		try {
		    er[i].getLease().cancel();
		} catch (UnknownLeaseException ignore) {
		} catch (RemoteException ignore) {}
	    }
	    if (rl != null && rl[i] != null) {
		try {
		    UnicastRemoteObject.unexportObject(rl[i],true);
		} catch (RemoteException ignore) {}
	    }
            if (lookups != null && lookups[i] != null) {
                try {
		    TestUtility.log(Config.ALL,"Test: stopping lookup " + i);
                    TestUtility.stopLookup(lookups[i], getConfig());
                } catch (RemoteException ignore) {}
            }
	}
        try {
            if (admin != null) {
		TestUtility.log(Config.ALL,"Test: stopping program");
                admin.stop();
            }
        } catch (RemoteException ignore) {}
    }

    public String[] getCategories() {
	return (new String[] { BasicServiceAdmin.CATEGORY });
    }

    public Class[] getRequiredAdmins() {
	return (new Class[] { BasicAdmin.class,
			      BasicServiceAdmin.class });
    }

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

    private boolean registrationsAreConsistent(ServiceItem[] si) {
	TestUtility.log(Config.ALL,"Test: checking ServiceIDs are identical");
	if (!si[0].serviceID.equals(si[1].serviceID))
	    return false;
	if (!si[1].serviceID.equals(si[2].serviceID))
	    return false;
	
	try {
	    TestUtility.log(Config.ALL,"Test: checking service objects are "
		+ "identical");
	    MarshalledObject mo0 = new MarshalledObject(si[0].service);
	    MarshalledObject mo1 = new MarshalledObject(si[1].service);
	    MarshalledObject mo2 = new MarshalledObject(si[2].service);
	    
	    if (!mo0.equals(mo1))
		return false;
	    if (!mo0.equals(mo2))
		return false;
	} catch (IOException ioe) {
	    return false;
	}

	TestUtility.log(Config.ALL,"Test: checking number of attributes "
	    + "are identical");
	int len0 = -1;
	int len1 = -1;
	int len2 = -1;
	if (si[0].attributeSets != null)
	    len0 = si[0].attributeSets.length;
	if (si[1].attributeSets != null)
	    len1 = si[1].attributeSets.length;
	if (si[2].attributeSets != null)
	    len2 = si[2].attributeSets.length;
	if (len0 != len1 || len0 != len2 || len0 == -1)
	    return false;

	TestUtility.log(Config.ALL,"Test: checking attributes are identical");
	try {
            return (LookupAttributes.equal(
                        si[0].attributeSets,si[1].attributeSets)
                && LookupAttributes.equal(
                        si[0].attributeSets,si[2].attributeSets));
        } catch (NullPointerException npe) {
	    TestUtility.log(Config.ERROR,"Test: received NullPointerException "
		+ "while comparing attributes; most likely found a null "
		+ "ServiceItem.attributeSets array entry which indicates "
		+ "that an entry cannot be deserialized");
            return false;
        }
    }

    /**
     * This method registers a listener with the 
     * ServiceRegistrars provided and then waits for notification.  
     * If they don't all notify then the ServiceRegistrars are polled to
     * see if the event was lost but the service still registered.
     * The method returns the ServiceItems from ServiceRegistrars
     * provided.
     *
     * @param lookups an array of the lookup services
     * @param timeOut the amount of milliseconds to wait for the
     *                service to register 
     * @return the ServiceItems from all ServiceRegistrars provided;
     *         null if the service did not register with all of them
     */
    public ServiceItem[] waitForAllRegistrations(ServiceRegistrar[] lookups,
	long timeOut) throws RemoteException, InterruptedException
    {
	BasicServiceAdmin bsa = (BasicServiceAdmin) getConfig().getAdmin();
	rl = new RegistrationListener[lookups.length];
	er = new EventRegistration[lookups.length];
	ServiceItem[] theService = new ServiceItem[lookups.length];

	for (int i = 0; i < lookups.length; i++) {
	    rl[i] = new RegistrationListener(this, bsa);
	}
	
	synchronized (this) {
	    for (int i = 0; i < lookups.length; i++) {
		er[i] = lookups[i].notify(bsa.getTemplate(),
		    ServiceRegistrar.TRANSITION_NOMATCH_MATCH, rl[i], null, 
		    timeOut * 3);
	    }
	    for (int i = 0; i < lookups.length; i++) {
	        TestUtility.log(Config.ALL,"Test: waiting up to " + timeOut 
		    + " milliseconds for program to register in lookup " + i);
	        wait(timeOut);
	    }
	}
	
	int count = 0;
	for (int i = 0; i < lookups.length; i++) {
	    if (rl[i].getNotified()) {
		count++;
		theService[i] = rl[i].getServiceItem();
	    } else {
		ServiceItem temp = TestUtility.getService(lookups[i],
							  getConfig());
		if (temp != null) {
		    count++;
		    theService[i] = temp;
		}
	    }
	}

	TestUtility.log(Config.ALL,"Test: program registered with "
	    + count + " of " + lookups.length + " lookups");	
	if (count != lookups.length)
	    return null;
	
	return theService;
    }
}
