/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2004 Bull S.A.
 * 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.generators.genclientstub.wrapper;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.ow2.jonas.lib.bootstrap.LoaderManager;


/**
 * ClientGenStub wrapper Used to launch ClientGenStub in DeployFile of JSR 88
 * @author Florent Benoit
 */
public class ClientGenStubWrapper {

    /**
     * ClientGenStub fully qualified classname
     */
    private static final String GENSTUB_CLASSNAME = "org.ow2.jonas.generators.genclientstub.ClientStubGen";

    /**
     * Number of arguments of execute method
     */
    private static final int ARGS_NUMBER = 3;

    /**
     * Method execute of ClientGenStub
     */
    private static Method executeMethod = null;

    /**
     *  The archive was changed or not ?
     */
    private static Method isInputModifiedMethod = null;

    /**
     * ClientGenStub class
     */
    private Object clientGenStub = null;

    /**
     * Empty constructor.
     */
    public ClientGenStubWrapper() {
    };

    /**
     * Wrapper around ClientstubGen.execute(String[]) method
     * @param fileName name of the file
     * @return name of the modified/built file
     * @throws Exception If ClientstubGen fails or if Reflection errors occurs
     */
    public String callClientGenStubExecute(final String fileName) throws Exception {
        LoaderManager lm = LoaderManager.getInstance();
        ClassLoader old = null;

        try {
            ClassLoader ext = lm.getExternalLoader();
            old = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(ext);
            if (executeMethod == null) {
                Class clazz = ext.loadClass(GENSTUB_CLASSNAME);
                executeMethod = clazz.getDeclaredMethod("execute", new Class[] {String[].class});
            }

            if (clientGenStub == null) {
                Class clazz = ext.loadClass(GENSTUB_CLASSNAME);
                clientGenStub = clazz.newInstance();
            }

            String[] args = new String[ARGS_NUMBER];
            args[0] = "-d";
            args[1] = System.getProperty("java.io.tmpdir");
            args[2] = fileName;

            return (String) executeMethod.invoke(clientGenStub, new Object[] {args});
        } catch (InvocationTargetException e) {
            if (e.getTargetException() instanceof Error) {
                throw (Error) e.getTargetException();
            } else {
                throw new Exception("Exception when executing ClientstubGen.execute(String[])", e.getTargetException());
            }
        } catch (Exception e) {
            throw new Exception("Problems when invoking method ClientstubGen.execute(String[])", e);
        } finally {
            if (old != null) {
                Thread.currentThread().setContextClassLoader(old);
            }
        }
    }

    /**
     * Wrapper around ClientGenStubGen.isModified() method
     * @return true/false
     * @throws Exception If ClientStub fails or if Reflection errors occurs
     */
    public boolean callClientGenStubIsInputModifed() throws Exception {
        LoaderManager lm = LoaderManager.getInstance();
        ClassLoader old = null;

        try {
            ClassLoader ext = lm.getExternalLoader();
            old = Thread.currentThread().getContextClassLoader();
            Thread.currentThread().setContextClassLoader(ext);

            if (isInputModifiedMethod == null) {
                Class clazz = ext.loadClass(GENSTUB_CLASSNAME);
                isInputModifiedMethod = clazz.getDeclaredMethod("isInputModified", new Class[] {});
            }

            if (clientGenStub == null) {
                Class clazz = ext.loadClass(GENSTUB_CLASSNAME);
                clientGenStub = clazz.newInstance();
            }

            return ((Boolean) isInputModifiedMethod.invoke(clientGenStub, (Object[]) null)).booleanValue();
        } catch (InvocationTargetException e) {
            if (e.getTargetException() instanceof Error) {
                throw (Error) e.getTargetException();
            } else {
                throw new Exception("Exception when executing clientGenStub.isInputModified()", e.getTargetException());
            }
        } catch (Exception e) {
            throw new Exception("Problems when invoking method clientGenStub.isInputModified()", e);
        } finally {
            if (old != null) {
                Thread.currentThread().setContextClassLoader(old);
            }
        }
    }
}

