/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2007 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * This class allows to run a command in sub-process.
 * @author Helene Joanin : Initial developer
 * @author Christophe Ney : Fix to handle arguments containing white spaces.
 * @author Nozomi Matsumura : GenIC i18n problem. GenIC invoke javac and javac's output has non asc-ii characters,
 *                            javac's output did not show collectly.
 * @author Guillaume Tulloup : Invoke directly the com.sun.tools.javac.Main.compile() method to work around a limitation on Windows.
 *                             (See bug #100587)
 * @author Helene Joanin : Invoke directly the com.sun.tools.rmic.Main.compile() method to work around a limitation on Windows.
 */

public class Cmd {

    /**
     * Class name of the sun javac compiler
     */
    private static final String COMPILER_CLASS_NAME = "com.sun.tools.javac.Main";
    /**
     * Class name of the sun rmic compiler
     */
    private static final String RMICOMPILER_CLASS_NAME = "sun.rmi.rmic.Main";

    /**
     * Command arguments list (included the command name)
     */
    private Vector mCmd = new Vector();

    /**
     * Command environment variables
     */
    private String[] mEnv = null;

    /**
     * Invoke (or not) the compile method of the corresponding sun compiler class
     */
    private boolean tryToInvoke = false;

    /**
     * The Common Logger.
     */
    private static final Logger logger = Log.getLogger("org.ow2.jonas.cmd");

    /**
     * Construtor method of Cmd class.
     * @param cmd command
     * @param invoke try to invoke directly the method of the java class of the
     *        command
     */
    public Cmd(final String cmd, final boolean invoke) {
        mCmd.addElement(cmd);
        tryToInvoke = invoke;
    }

    /**
     * Construtor method of Cmd class. Equivalent to Cmd(cmd, false).
     * @param cmd command
     */
    public Cmd(final String cmd) {
        this(cmd, false);
    }

    /**
     * Construtor method of Cmd class.
     * @param cmd command
     * @param env environment of the command
     * @param invoke invoke the compile method of the class instead of execute the command
     */
    public Cmd(final String cmd, final String[] env, final boolean invoke) {
        this(cmd, invoke);
        mEnv = env;
    }

    /**
     * Add a new argument to the command.
     * @param arg argument added to the tail of the command argument list
     */
    public void addArgument(final String arg) {
        mCmd.addElement(arg);
    }

    /**
     * Add a new argument to the command.
     * @param args argument added to the tail of the command argument list
     */
    public void addArguments(final List args) {
        for (Iterator it = args.iterator(); it.hasNext();) {
            mCmd.addElement(it.next());
        }
    }

    /**
     * Execute the command. (In case of the exit value of the command is not 0,
     * the output and error streams of the command is traced.)
     * @return false if the command cannot be executed, or if its exit value is
     *         not 0.
     */
    public boolean run() {

        if (tryToInvoke) {
            File toolsJar = new File(System.getProperty("java.home") + File.separator + "lib" + File.separator + "tools.jar");
            if (toolsJar.exists()) {
                ClassLoader classLoader = getClass().getClassLoader();
                try {
                    classLoader = new URLClassLoader(new URL[]{toolsJar.toURL()}, classLoader);
                } catch (MalformedURLException e) {
                    logger.log(BasicLevel.WARN, "The tools.jar file was not found in "+ toolsJar.getParent() + ".");
                }

                if ((((String) mCmd.get(0)).endsWith("javac"))) {
                    // Bug #100587 fixed to work around a limitation on Windows
                    return compile(classLoader);
                }
                if ((((String) mCmd.get(0)).endsWith("rmic"))) {
                    return rmicompile(classLoader);
                }
            }
        }

        RunnableStreamListener out, err;
        Process proc = null;
        boolean val = true;
        try {
            String[] cmd = new String[mCmd.size()];
            mCmd.copyInto(cmd);
            proc = Runtime.getRuntime().exec(cmd, mEnv);
        } catch (IOException e) {
            logger.log(BasicLevel.ERROR, "exception", e);
            return (false);
        }
        out = new RunnableStreamListener(new BufferedReader(new InputStreamReader(proc.getInputStream())), System.out);
        new Thread(out, "stdout listener for " + this.toString()).start();
        err = new RunnableStreamListener(new BufferedReader(new InputStreamReader(proc.getErrorStream())), System.err);
        new Thread(err, "stderr listener for " + this.toString()).start();
        try {
            val = proc.waitFor() == 0;
        } catch (InterruptedException e) {
            logger.log(BasicLevel.ERROR, "exception", e);
            val = false;
        } finally {
            // destroy the process
            if (proc != null) {
                proc.destroy();
            }
        }

        return (val);
    }

    /**
     * invoke the compile method of the compiler javac class
     * @return false in error case
     */
    private boolean compile(final ClassLoader classLoader) {
        // first arg should not be added because it's the name of the command
        String[] args = new String[mCmd.size() - 1];
        for (int i = 0; i < mCmd.size() - 1; i++) {
            args[i] = (String) mCmd.get(i + 1);
        }

        try {
            // Use reflection
            Class c = Class.forName(COMPILER_CLASS_NAME, false, classLoader);
            Object compiler = c.newInstance();
            java.lang.reflect.Method compile = c.getMethod("compile", new Class[] {(new String[] {}).getClass()});
            int result = ((Integer) compile.invoke(compiler, new Object[] {args})).intValue();
            return (result == 0);
        } catch (Exception e) {
            logger.log(BasicLevel.ERROR, "exception", e);
            return false;
        }
    }

    /**
     * invoke the main method of the rmi compiler rmic class
     * @return false in error case
     */
    private boolean rmicompile(final ClassLoader classLoader) {
        // first arg should not be added because it's the name of the command
        String[] args = new String[mCmd.size() - 1];
        for (int i = 0; i < mCmd.size() - 1; i++) {
            args[i] = (String) mCmd.get(i + 1);
        }

        try {
            // Use reflection
            Class c = Class.forName(RMICOMPILER_CLASS_NAME, false, classLoader);

            Constructor cons = c.getConstructor(new Class[] { OutputStream.class, String.class });
            Object rmic = cons.newInstance(new Object[] { System.out, "rmic" });

            Method doRmic = c.getMethod("compile", new Class[] { String[].class });
            Boolean result = (Boolean) doRmic.invoke(rmic, new Object[] { args });

            return result;
        } catch (Exception e) {
            logger.log(BasicLevel.ERROR, "exception", e);
            return false;
        }
    }

    /**
     * @return iterator over the command line
     */
    public Iterator getCommandLine() {
        return mCmd.iterator();
    }

    /**
     * @return the string representation of the object for UI purpose
     */
    @Override
    public String toString() {
        StringBuffer buf = new StringBuffer();
        Enumeration e = mCmd.elements();
        while (e.hasMoreElements()) {
            String arg = (String) e.nextElement();
            if (arg == null) {
                arg = "null";
            }
            for (int i = 0; i < arg.length(); i++) {
                if (Character.isWhitespace(arg.charAt(i))) {
                    arg = "\"" + arg + "\"";
                    break;
                }
            }
            buf.append(arg);
            buf.append(' ');
        }
        return buf.toString().trim();
    }

}

/**
 * To run the command happily, and to swallow the stdout from the process
 */
class RunnableStreamListener implements Runnable {

    BufferedReader in_;

    PrintStream stream_;

    RunnableStreamListener(final BufferedReader in, final PrintStream stream) {
        in_ = in;
        stream_ = stream;
    }

    public void run() {
        String line;
        try {
            while ((line = in_.readLine()) != null) {
                stream_.println(line);
            }
        } catch (IOException e) {
            stream_.println(e.toString());
        }

    }
}

