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

// java.io
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.io.PrintWriter;

// java.rmi
import java.rmi.RemoteException;
import java.rmi.server.RMIClassLoader;

// java.net
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.net.MalformedURLException;

// java.util
import java.util.List;
import java.util.ArrayList;

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

// net.jini
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.core.discovery.LookupLocator;

/**
 * This class implements the BasicServiceAdmin and BasicLookupAdmin
 * interfaces to automate the testing of any <b>transient or persistent</b>
 * programs.  Some methods document properties that they support.
 */
public class ExecServiceAdmin implements BasicServiceAdmin, BasicLookupAdmin {
    private static String sID = null;
    private Config config = null;
    private Process process;

    /**
     * Basic no-arg constructor.
     */
    public ExecServiceAdmin() {
    }

    /**
     * See comments for <code>BasicAdmin</code>.
     */
    public void setConfig(Config conf) {
	config = conf;
    }

    /**
     * Returns the address of this host.  The program must
     * be running on this host.
     *
     * @return the address of the program
     */
    public InetAddress getAddress() throws RemoteException {
	try {
       	    return InetAddress.getLocalHost();
	} catch(UnknownHostException uhe) {
            throw new RemoteException("Problem getting local host InetAddress",uhe);
	}
    }

    /**
     * Using the <code>Runtime.exe()</code> method, starts the program(s)
     * by running the command given by the property 
     * <code>com.sun.jini.compat.admin2.execServiceAdmin.startCommand</code>.
     *
     * @throws java.rmi.RemoteException if problem starting the program
     */
    public void start() throws RemoteException {
	try {
            String command = config.getSysConfig().getStringConfigVal(
		"com.sun.jini.compat.admin2.execServiceAdmin.startCommand","");
            process = Runtime.getRuntime().exec(command);
            bindOutput(process);
	} catch (Exception e) {
            throw new RemoteException("Problem starting program",e);
	}
	try {
            Thread.sleep(15000);
	} catch (InterruptedException ignore) {}
    }

    /**
     * Stops the program.  This method does not need to wait
     * for the program to stop.	In addition, this method may
     * be called safely even if the start() method threw an exception
     * or was never called.
     *
     * @throws java.rmi.RemoteException problem stopping the program
     */
    public void stop() throws RemoteException {
	if (process != null) {
            process.destroy();
	}
	try {
            Thread.sleep(5000);
	} catch (InterruptedException ignore) {}
    }

    /**
     * Given an array of service proxy objects, this method
     * returns the first one that contains a proxy that
     * implements the interface specified by the property
     * <code>com.sun.jini.compat.admin2.execServiceAdmin.interface</code>.
     * If the specified interface is not implemented by any of
     * the listed services, then <code>null</code> is returned.
     *
     * @param services the array <code>ServiceItem</code> objects
     *        from which to choose
     * @return the <code>ServiceItem</code> for the service being tested,
     * 	      or <code>null</code>
     */
    public ServiceItem pickService(ServiceItem[] services)
	throws RemoteException
    {
        String proxyInterface = config.getSysConfig().getStringConfigVal(
		"com.sun.jini.compat.admin2.execServiceAdmin.interface", null);

     	PrintWriter log = null;
	if (config.getDebugLevel() == Config.ALL) {
            log = config.getLog();
	}
        if (log != null) {
            log.println("Admin: looking for proxy that implements "
		+ proxyInterface);
	}

        for (int i = 0; i < services.length; i++) {
            Class serviceClass = services[i].service.getClass();
            String codebase = RMIClassLoader.getClassAnnotation(serviceClass);
            if (log != null) {
		log.println("Admin: found class "
                    + serviceClass.getName() + " with codebase " + codebase);
            }
            try {
                String codebaseHost = (new URL(codebase)).getHost();
		String codebaseIP = 
		    InetAddress.getByName(codebaseHost).getHostAddress();
                int codebasePort = (new URL(codebase)).getPort();
                String thisIP = getAddress().getHostAddress();
                if (log != null) {
		    log.println("Admin:   codebase host:" + codebaseIP 
                        + "  this host:" + thisIP);
                }
                if (codebaseIP.equals(thisIP) && codebasePort != 8080) {
		    ArrayList interfaces = new ArrayList();
		    getSuperinterfaces(interfaces, serviceClass);
                    for (int j = 0; j < interfaces.size(); j++) {
			Class intf = (Class) interfaces.get(j);
                        if (log != null) {
		            log.println("Admin:   proxy implements:" 
                                + intf.getName());
                        }
                        if (intf.getName().equals(proxyInterface)) {
                            if (log != null) {
		                log.println("Admin: returning class "
                                    + services[i].service.getClass().getName() 
                                    + " with codebase " + codebase);
                            }
                            return services[i];
                        }
                    }
                }
            } catch (MalformedURLException mue) {
                if (log != null) {
		    log.println("Admin: malformed codebase: " + codebase);
		    log.println("Admin: exception: " + mue);
                }
            } catch (UnknownHostException uhe) {
                if (log != null) {
		    log.println("Admin: exception: " + uhe);
                }
            } catch (RemoteException re) {
                if (log != null) {
		    log.println("Admin: exception: " + re);
                }
            }
	}

        if (log != null) {
	    log.println("Admin: service not found; returning null");
        }
        return null;
    }

    /**
     * Return a blank <code>ServiceTemplate</code>.
     *
     * @return the template
     */
    public ServiceTemplate getTemplate() throws RemoteException {
        return new ServiceTemplate(null, null, null);
    }

    /**
     * Returns the ServiceRegistrar from an already started Lookup.
     * If there are any problems getting the ServiceRegistrar it
     * throws a RemoteException.  It uses a property called:
     * <code>com.sun.jini.compat.admin2.execServiceAdmin.lookupPort</code>.
     * Using that port and the address of the lookup provided by
     * the <code>getAddress</code> method it generates a
     * <code>LookupLocator</code> to get the
     * <code>ServiceRegistrar</code> for the lookup service being
     * tested.
     *
     * @return the <code>ServiceRegistrar</code> for the lookup being
     *		tested.
     */
    public ServiceRegistrar getServiceRegistrar()
	throws RemoteException
    {
	PrintWriter log = null;
	if (config.getDebugLevel() == Config.ALL) {
	    log = config.getLog();
	}
	SysConfig sys = config.getSysConfig();
	int port = sys.getIntConfigVal(
            "com.sun.jini.compat.admin2.execServiceAdmin.lookupPort",-1);
	String lookupURLString = "jini://"+getAddress();
	if(port != -1) {
            lookupURLString = lookupURLString + ":" + port;
        }
	lookupURLString = lookupURLString + "/";

	try {
            if (log != null) {
                log.println("Admin: attempting to discover "
                    + "lookup service at locator " + lookupURLString);
            }
            LookupLocator lLoc = new LookupLocator(lookupURLString);
            return lLoc.getRegistrar();
	} catch( Exception e) {
            throw new RemoteException("Admin: could not get "
		+ "the ServiceRegistrar",e);
	}
    }

    /**
     * Fills the given list with the superinterfaces implemented by
     * the given class eliminating duplicates.
     *
     * @param	list the list to fill with interfaces
     * @param	class the class to get the superinterfaces of
     * @throws	NullPointerException if the specified class or list is null
     **/
    private static void getSuperinterfaces(List list, Class cl) {
	Class superclass = cl.getSuperclass();
	if (superclass != null) {
	    getSuperinterfaces(list, superclass);
	}
	Class[] interfaces = cl.getInterfaces();
	for (int i = 0; i < interfaces.length; i++) {
	    getSuperinterfaces(list, interfaces[i]);
	}
	if (cl.isInterface()) {
	    list.add(cl);
	}
    }


    /*
     * Attach stdout and stderr to the subprocess.
     */
    private void bindOutput(Process proc) throws IOException {
	(new Thread(new Dumper(proc.getInputStream(), System.out))).start();
	(new Thread(new Dumper(proc.getErrorStream(), System.err))).start();
    }

    /**
     * Utility class to forward bytes from one stream to another.
     */
    private class Dumper implements Runnable {
	private final InputStream in;
	private final OutputStream out;

	/**
	 * Create a new <code>Dumper</code>
	 * @param in The stream to take bytes from
	 * @param out The stream to dump the bytes to
	 */
	Dumper(InputStream in, OutputStream out) {
            this.in = in;
            this.out = out;
	}

	/**
	 * Read a bunch of bytes from the associated
	 * <code>InputStream</code> and write them to the associated
	 * <code>OutputStream<code>, repeat until the read returns
	 * EOF, or until there is an <code>IOException</code>
         */
	public void run() {
            byte[] buf = new byte[4096];
            try {
            while (true) {
		final int bytesRead = in.read(buf);
		if (bytesRead > 0) {
                   out.write(buf, 0, bytesRead);
		} else if (bytesRead < 0) {
                    break;
		}
            }
            } catch (IOException e) {
		e.printStackTrace();
            } finally {
		try {
                    in.close();
		} catch (IOException ignore) {
		}
            }
	}
    } // end of Dumper class

}
