/*
 * 
 * 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.admin2;

import java.rmi.RemoteException;
import java.rmi.activation.ActivationException;
import java.rmi.server.RMIClassLoader;
import java.rmi.activation.ActivationGroupID;
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;

import com.sun.jini.compat.harness.SysConfig;
import com.sun.jini.compat.harness.Config;
import com.sun.jini.compat.harness.BasicServiceAdmin;
import com.sun.jini.compat.harness.BasicLookupAdmin;
import com.sun.jini.compat.harness.TestUtility;

import com.sun.jini.start.SharedGroup;
import com.sun.jini.start.ServiceDescriptor;
import com.sun.jini.start.NonActivatableServiceDescriptor;
import com.sun.jini.start.SharedActivatableServiceDescriptor;
import com.sun.jini.start.SharedActivationGroupDescriptor;
import net.jini.core.lookup.ServiceRegistrar;
import net.jini.core.lookup.ServiceItem;
import net.jini.core.lookup.ServiceTemplate;
import net.jini.core.lookup.ServiceID;
import net.jini.config.Configuration;
import net.jini.config.ConfigurationProvider;
import net.jini.config.ConfigurationException;

/**
 * This class implements the BasicServiceAdmin and BasicLookupAdmin
 * interfaces to automate the testing of any <b>activatable</b> program that can be 
 * started by the ServiceStarter framework.  See the <code>start</code> method
 * documentation for config file properties supported by this Admin.
 */
public class ServiceStarterAdmin implements BasicServiceAdmin, BasicLookupAdmin
{

    protected Config compatConfig;
    protected SysConfig compatSysConfig;
    protected PrintWriter log;

    protected NonActivatableServiceDescriptor.Created nonActivatableCreated;
    protected SharedActivatableServiceDescriptor.Created sharedCreated;
    protected SharedActivatableServiceDescriptor.Created activatableCreated;
    protected ActivationGroupID groupCreated;

    protected Object proxy;

    protected String groupLog;

    /**
     * Default constructor.
     */
    public ServiceStarterAdmin() {
    }

    /**
     * Takes the Config object for this test run so that the implementation
     * can get access to property files and other config information.
     *
     * @param conf the Config object for this test run
     */
    public void setConfig(Config config) {
	compatConfig = config;
	compatSysConfig = config.getSysConfig();
        log = compatConfig.getLog();
        if (log == null) {
            log = new PrintWriter(System.out, true);
        }
    }

    /**
     * Returns the address of the host the program is running on by
     * looking up the property com.sun.jini.compat.defaultAdmin.address.
     * If that property is not specified the default is the host the
     * LDJ Kit harness is running on.
     *
     * @return the address of the program
     */
    public InetAddress getAddress() throws RemoteException {
        String addr = compatSysConfig.getStringConfigVal(
            "com.sun.jini.compat.defaultAdmin.address", null);
        try {
            if(addr == null) {
                return InetAddress.getLocalHost();
            } else {
                return InetAddress.getByName(addr);
            }
        } catch(UnknownHostException uhe) {
            throw new RemoteException(addr + " is an unknown host", uhe);
        }
    }

    /**
     * Using the <code>ServiceStarter</code>, starts the program(s)
     * specified in the service starter configuration file specified
     * by the property <code>com.sun.jini.compat.admin2.starterConfig</code>.
     * The following strings are passed to this configuration as overrides:
     * <ul>
     * <li><code>com.sun.jini.compat.admin2.jskHome</code>=
     *     &lt;value of <code>com.sun.jini.compat.admin2.jskHome</code> system property&gt;
     * <li><code>com.sun.jini.compat.admin2.javaHome</code>=
     *     &lt;value of <code>com.sun.jini.compat.admin2.javaHome</code> system property&gt;
     * <li><code>com.sun.jini.compat.admin2.groupLog</code>=
     *     &lt;return value of <code>getGroupLog()</code> method call&gt;
     * <li><code>com.sun.jini.compat.admin2.policyDir</code>=
     *     &lt;value of the <code>com.sun.jini.compat.admin2.policyDir</code>
     *     system property or, if <code>null</code>, the value of 
     *     <code>com.sun.jini.compat.installDir</code> property + "/policy"&gt;
     * <li><code>com.sun.jini.compat.admin2.persistenceDir</code>=
     *     &lt;return value of <code>getPersistenceDir()</code> method call&gt;
     * <li><code>com.sun.jini.compat.admin2.host</code>=
     *     &lt;return value of <code>getAddress().getHostName()</code> method call&gt;
     * </ul>
     * See the example configuration files in the <code>configs</code> sub-directory
     * of the LDJ Kit.  The <code>*-activatable.config</code> files 
     * are used by this Admin to test services in the Jini starter kit.
     */
    public synchronized void start() throws RemoteException {
	String starterConfig = compatSysConfig.getStringConfigVal(
	    "com.sun.jini.compat.admin2.starterConfig", null);
        if (compatConfig.getDebugLevel() == Config.ALL) {
            log.println("Using " + starterConfig 
                + " starter configuration file specified "
                + "by the com.sun.jini.compat.admin2.starterConfig property");
        }

	String jskHome = compatSysConfig.getStringConfigVal(
	    "com.sun.jini.compat.admin2.jskHome", null);
	String javaHome = compatSysConfig.getStringConfigVal(
	    "com.sun.jini.compat.admin2.javaHome", null);
	String installDir = compatSysConfig.getStringConfigVal(
	    "com.sun.jini.compat.installDir", null);
	String policyDir = compatSysConfig.getStringConfigVal(
	    "com.sun.jini.compat.admin2.policyDir", installDir + "/policy");

        try {
            Configuration config = ConfigurationProvider.getInstance(
                new String[] { // config file followed by overrides
                    starterConfig,
                    "com.sun.jini.compat.admin2.jskHome=\"" + jskHome + "\"",
                    "com.sun.jini.compat.admin2.javaHome=\"" + javaHome + "\"",
                    "com.sun.jini.compat.admin2.groupLog=\"" 
                        + getGroupLog() + "\"",
                    "com.sun.jini.compat.admin2.policyDir=\"" + policyDir + "\"",
                    "com.sun.jini.compat.admin2.persistenceDir=\"" 
                        + getPersistenceDir() + "\"",
                    "com.sun.jini.compat.admin2.host=\"" 
                        + getAddress().getHostName() + "\""
                },
                this.getClass().getClassLoader());

            ServiceDescriptor[] descs =  (ServiceDescriptor[])
                config.getEntry("com.sun.jini.start", "serviceDescriptors",
                    ServiceDescriptor[].class, null);

            if (descs == null || descs.length == 0) {
                log.println(starterConfig + " does not contain a "
                    + "com.sun.jini.start.serviceDescriptors entry; "
                    + "aborting");
                System.exit(1);
            }

            // Non-activatable case: only 1 service descriptor must be present
            if (descs.length == 1 &&
                descs[0] instanceof NonActivatableServiceDescriptor) 
            {
                if (compatConfig.getDebugLevel() == Config.ALL) {
                    log.println(descs[0].toString());
                }
                nonActivatableCreated = 
                    (NonActivatableServiceDescriptor.Created) 
                        descs[0].create(config);
                proxy = nonActivatableCreated.proxy;

            // Activatable case: only 3 service descriptors must be present
            } else if (
                descs.length == 3 &&
                descs[0] instanceof SharedActivationGroupDescriptor &&
                descs[1] instanceof SharedActivatableServiceDescriptor &&
                descs[2] instanceof SharedActivatableServiceDescriptor)
            {
                if (compatConfig.getDebugLevel() == Config.ALL) {
                    log.println("SharedActivationGroupDescriptor: " 
                        + descs[0].toString());
                }
                groupCreated = (ActivationGroupID) descs[0].create(config);

                if (compatConfig.getDebugLevel() == Config.ALL) {
                    log.println("SharedActivatableServiceDescriptor:"
                        + descs[1].toString());
                }
                sharedCreated = (SharedActivatableServiceDescriptor.Created)
                    descs[1].create(config);

                if (compatConfig.getDebugLevel() == Config.ALL) {
                    log.println("SharedActivatableServiceDescriptor: "
                        + descs[2].toString());
                }
                activatableCreated = 
                    (SharedActivatableServiceDescriptor.Created)
                        descs[2].create(config);

                proxy = activatableCreated.proxy;

            } else {
                log.println(starterConfig + " contains wrong number "
                        + "or type of ServiceDescriptors; aborting");
                System.exit(1);
            }

        } catch (Exception e) {
            if (compatConfig.getDebugLevel() >= Config.ERROR) {
                log.println("Service creation exception: " + e);
                e.printStackTrace();
            }
        }
    }
    
    /**
     * Stops the program.
     *
     * If the program is activatable and implements 
     * <code>net.jini.admin.Administrable</code> and
     * <code>com.sun.jini.admin.DestroyAdmin</code>
     * then this method will make certain the program is 
     * unregistered with the activation system before returning. 
     */
    public synchronized void stop() throws RemoteException {
        int returnCode = ServiceDestroyer.DESTROY_SUCCESS;
	try {

            // stop non-activatable service (if non-null)
	    if (nonActivatableCreated != null) {
                returnCode = ServiceDestroyer.destroy(
                    nonActivatableCreated.proxy);
                nonActivatableCreated = null;
                if (returnCode != ServiceDestroyer.DESTROY_SUCCESS) {
                    if (compatConfig.getDebugLevel() >= Config.ERROR) {
	                log.println("Warning: program may not have shutdown "
                        + "cleanly; destroy code is: " + returnCode);
                    }
                }
            }

            // stop activatable service (if non-null)
	    if (activatableCreated != null) {
                returnCode = ServiceDestroyer.destroy(activatableCreated,30);
                activatableCreated = null;
            }

            // stop shared group (if non-null)
	    if (sharedCreated != null) {
                ((SharedGroup)sharedCreated.proxy).destroyVM();
                sharedCreated = null;
                if (compatConfig.getDebugLevel() == Config.ALL) {
	            log.println("Destroyed activation group VM");
                }
            }
	} catch (ActivationException ae) {
            if (compatConfig.getDebugLevel() >= Config.ERROR) {
	        log.println("Warning: program may not have shutdown cleanly");
	        ae.printStackTrace(log);
            }
	}

        // delete group log if present
        if (groupLog != null) {
            File groupLogFile = new File(groupLog);
            File[] contents = groupLogFile.listFiles();
            if (contents != null) {
                for (int i = 0; i< contents.length; i++) {
                    contents[i].delete();
                }
            }
            groupLogFile.delete();
        }
    }

    /**
     * Given a list of objects which are ServiceItems this method
     * determines if any of them are the program we are testing.  It
     * does this by comparing the <code>service</code> field of each
     * <code>ServiceItem</code> to the program's proxy returned from
     * the ServiceStarter framework when the program was started.
     *
     * @param services the array of ServiceItems that need to be picked from
     *
     * @return the ServiceItem for the program being tested or null if
     *         none of the ServiceItems represent the program being tested
     */
    public synchronized ServiceItem pickService(ServiceItem[] services)
	throws RemoteException
    {
	for (int i = 0; i < services.length; i++) {
	    if (services[i].service.equals(proxy)) {
		return services[i];
	    }
	}
	return null;
    }

    /**
     * Returns a fully wild-carded template.
     *
     * @return the template
     */ 
    public ServiceTemplate getTemplate() throws RemoteException {
	return new ServiceTemplate(null, null, null);
    }

    /**
     * Returns the proxy for the lookup service being tested.
     *
     * @return lookup service proxy
     */
    public ServiceRegistrar getServiceRegistrar() throws RemoteException {
        return (ServiceRegistrar) proxy;
    }

    /**
     * Returns a randomized directory name within the
     * <code>com.sun.jini.compat.scratchDir</code> that can be used
     * as the group log directory.  The returned directory name
     * is saved so that this Admin can remove it later.
     */
    public String getGroupLog() {
        String scratchDir = compatSysConfig.getStringConfigVal(
            "com.sun.jini.compat.scratchDir", null);
        groupLog = scratchDir + "/" + TestUtility.randomString(8);
        return groupLog;
    }

    /**
     * Returns a randomized directory name within the
     * <code>com.sun.jini.compat.scratchDir</code> that can be used
     * as the program's persistence directory.
     */
    public String getPersistenceDir() {
        String scratchDir = compatSysConfig.getStringConfigVal(
            "com.sun.jini.compat.scratchDir", null);
        return scratchDir + "/" + TestUtility.randomString(8);
    }
}
