/*
 * 
 * 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.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 net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceItem;

/**
 * Tests whether a service registers with a lookup service that 
 * belongs to multiple groups, including the public group.
 */
public class MultipleGroupTest extends DefaultTest {
    
    /**
     * Starts up the service and waits quietTime
     * so that (hopefully) there are no further multicast 
     * requests, and then starts up a lookup service that belongs to 
     * three groups. The lookup service belongs to the public
     * group and two groups whose names are ten randomly generated 
     * characters. The test then registers with the 
     * lookup service to be notified if the service of interest registers. 
     * If notification does not happen within six times the
     * failureTime, the test queries the lookup service to make sure 
     * the event wasn't lost or delayed and that the service really 
     * did register. If the service did not register, the service fails. 
     * The service and the lookup service are stopped. If the service
     * didn't fail, the process of starting a lookup service and waiting 
     * for a notification repeats two more times with the public group 
     * being the second, and then the third, group in the lookup 
     * service's group list.
     *
     * @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 nonpub1 = TestUtility.randomString(10);
	String nonpub2 = TestUtility.randomString(10);

	try {
	    String[] groups1 = {"", nonpub1, nonpub2};
	    if (!registers(groups1)) {
		return Status.failed(Status.TEST, "Service did not register "
		    + "with the lookup which is in the following groups: "
		    + groupsString(groups1));
	    }
	    
	    String[] groups2 = {nonpub1, "", nonpub2};
	    if (!registers(groups2)) {
		return Status.failed(Status.TEST, "Service did not register "
		    + "with the lookup which is in the following groups: "
		    + groupsString(groups2));
	    }

	    String[] groups3 = {nonpub1, nonpub2, ""};
	    if (!registers(groups3)) {
		return Status.failed(Status.TEST, "Service did not register "
		    + "with the lookup which is in the following groups: "
		    + groupsString(groups3));
	    }
	} catch (Exception e) {
            TestUtility.log(Config.ERROR,"Test: exception caught",e);
	    return Status.failed(Status.ENV, "Problem while waiting for "
		+ "program to register with lookup");
	}

	return Status.passed("OK");
    }   

    private boolean registers(String[] groups) throws Exception {
	ServiceRegistrar lookup = null;
	Config conf = getConfig();
	BasicServiceAdmin admin = (BasicServiceAdmin) conf.getAdmin();

	try {
            try {
                TestUtility.log(Config.ALL,"Test: starting program");
                admin.start();
            } catch (RemoteException re) {
                TestUtility.log(Config.ERROR,"Test: caught exception",re);
                return false;
            }

	    /* Try to wait through all the multicast requests so that
	     * the registration is more likely to be from announcements */
	    try {
		TestUtility.log(Config.ALL,"Test: waiting " 
		    + conf.getQuietTime() + " milliseconds for (hopefully) "
		    + "all multicast requests");
                Thread.sleep(conf.getQuietTime());
            } catch (InterruptedException ie) {
		TestUtility.log(Config.ERROR,"Test: caught exception",ie);
		return false;
	    }
	    	   
	    String logSuffix = TestUtility.randomString(4);
	    TestUtility.log(Config.ALL,"Test: starting lookup which is in "
		+ "the following groups: " + groupsString(groups));
	    lookup = TestUtility.startLookup(groups, conf.getQuietTime(), 
			"MultipleGroupTest_RegistrarLog" + logSuffix, conf);
	    
	    long timeout = 6 * conf.getFailureTime();
            TestUtility.log(Config.ALL,"Test: waiting up to " + timeout 
                + " milliseconds for program to register in lookup");
	    ServiceItem serviceItem = TestUtility.waitForRegistration(lookup,
			timeout, conf);
	
	    return (serviceItem != null);
	} finally {
            try {
                if (lookup != null) {
		    TestUtility.log(Config.ALL,"Test: stopping lookup");
                    TestUtility.stopLookup(lookup, conf);
                }
            } catch (RemoteException ignore) {}
            try {
                if (admin != null) {
		    TestUtility.log(Config.ALL,"Test: stopping program");
                    admin.stop();
                }
            } catch (RemoteException ignore) {}
	}
    }

    private String groupsString(String[] groups) {
	StringBuffer buf = new StringBuffer("");
	for (int i = 0; i < groups.length; i++) {
	    if (groups[i].equals(""))
		buf.append("<public> ");
	    else
		buf.append(groups[i] + " ");
	}
	return buf.toString();
    }

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

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

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