/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 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: EjbManagerWrapper.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.deployment.ejb.wrapper;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;
import org.ow2.jonas.deployment.common.DeploymentDescException;
import org.ow2.jonas.deployment.ejb.DeploymentDesc;
import org.ow2.jonas.lib.bootstrap.LoaderManager;
import org.ow2.jonas.lib.util.Log;



/**
 * Wrap the EjbDeploymentDescManager to solve ClassLoader problems linked to Digester.
 *
 * @author Guillaume Sauthier
 */
public class EjbManagerWrapper {

    /**
     * EjbDeploymentDescManager fully qualified classname
     */
    private static final String EJB_MANAGER_CLASSNAME = "org.ow2.jonas.deployment.ejb.lib.EjbDeploymentDescManager";

    /**
     * logger
     */
    private static Logger logger = Log.getLogger(Log.JONAS_EJB_PREFIX);

    /**
     * Private empty constructor for utility class
     */
    private EjbManagerWrapper() { }

    /**
     * Wrap EjbDeploymentDescManager.getInstance().getDeploymentDesc()
     *
     * @param url EjbJar URL
     * @param moduleCL EjbJar ClassLoader
     * @param earCL Application ClassLoader
     *
     * @return the EjbJar DeploymentDesc of the given EjbJar
     *
     * @throws DeploymentDescException When DeploymentDesc cannot be instanciated
     */
    public static DeploymentDesc getDeploymentDesc(final URL url, final ClassLoader moduleCL, final ClassLoader earCL)
    throws DeploymentDescException {
        LoaderManager lm = LoaderManager.getInstance();
        DeploymentDesc dd = null;

        try {
            ClassLoader ext = lm.getExternalLoader();
            Class manager = ext.loadClass(EJB_MANAGER_CLASSNAME);
            Method m = manager.getDeclaredMethod("getInstance", new Class[] {});
            Object instance = m.invoke(null, new Object[] {});
            m = manager.getDeclaredMethod("getDeploymentDesc", new Class[] {URL.class, ClassLoader.class, ClassLoader.class});
            dd = (DeploymentDesc) m.invoke(instance, new Object[] {url, moduleCL, earCL});
        } catch (InvocationTargetException ite) {
            Throwable t = ite.getTargetException();
            if (DeploymentDescException.class.isInstance(t)) {
                throw (DeploymentDescException) ite.getTargetException();
            } else {
                throw new DeploymentDescException("EjbDeploymentDescManager.getDeploymentDesc fails", t);
            }
        } catch (Exception e) {
            // TODO add i18n here
            throw new DeploymentDescException("Problems when using reflection on EjbDeploymentDescManager", e);
        }

        return dd;
    }

    /**
     * Wrap EjbDeploymentDescManager.getInstance().setAvailableEjbJarsAndAltDDs()
     *
     * @param earClassLoader Application ClassLoader
     * @param jarUrls Array of EjbJar URLs
     * @param ejbsAltDDs Array of alternatives EjbJar Descriptor URLs
     */
    public static void setAvailableEjbJarsAndAltDDs(final URLClassLoader earClassLoader, final URL[] jarUrls, final URL[] ejbsAltDDs) {
        LoaderManager lm = LoaderManager.getInstance();
        try {
            ClassLoader ext = lm.getExternalLoader();
            Class manager = ext.loadClass(EJB_MANAGER_CLASSNAME);
            Method m = manager.getDeclaredMethod("getInstance", new Class[] {});
            Object instance = m.invoke(null, new Object[] {});
            m = manager.getDeclaredMethod("setAvailableEjbJarsAndAltDDs", new Class[] {ClassLoader.class, URL[].class, URL[].class});
            m.invoke(instance, new Object[] {earClassLoader, jarUrls, ejbsAltDDs});
        } catch (Exception e) {
            // Should never occurs
            logger.log(BasicLevel.ERROR, e);
        }
    }

    /**
     * Wrap EjbDeploymentDescManager.setParsingWithValidation()
     *
     * @param b true/false
     */
    public static void setParsingWithValidation(final boolean b) {
        LoaderManager lm = LoaderManager.getInstance();
        try {
            ClassLoader ext = lm.getExternalLoader();
            Class manager = ext.loadClass(EJB_MANAGER_CLASSNAME);
            Method m = manager.getDeclaredMethod("setParsingWithValidation", new Class[] {boolean.class});
            m.invoke(null, new Object[] {new Boolean(b)});
        } catch (Exception e) {
            // Should never occurs
            logger.log(BasicLevel.ERROR, e);
        }
    }

    /**
     * Wrap EjbDeploymentDescManager.getInstance().removeCache()
     *
     * @param classLoader EjbJar Classloader
     */
    public static void removeCache(final ClassLoader classLoader) {
        LoaderManager lm = LoaderManager.getInstance();
        try {
            ClassLoader ext = lm.getExternalLoader();
            Class manager = ext.loadClass(EJB_MANAGER_CLASSNAME);
            Method m = manager.getDeclaredMethod("getInstance", new Class[] {});
            Object instance = m.invoke(null, new Object[] {});
            m = manager.getDeclaredMethod("removeCache", new Class[] {ClassLoader.class});
            m.invoke(instance, new Object[] {classLoader});
        } catch (Exception e) {
            // Should never occurs
            logger.log(BasicLevel.ERROR, e);
        }
    }

}
