/**
 * 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: WebManagerWrapper.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.deployment.web.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.web.WebContainerDeploymentDesc;
import org.ow2.jonas.deployment.web.WebContainerDeploymentDescException;
import org.ow2.jonas.lib.bootstrap.LoaderManager;
import org.ow2.jonas.lib.util.Log;

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

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

    /**
     * WebDeploymentDescManager classname
     */
    private static final String WEBMANAGER_CLASSNAME = "org.ow2.jonas.deployment.web.lib.WebDeploymentDescManager";

    /**
     * Private Empty constructor for utility class
     */
    private WebManagerWrapper() { }

    /**
     * Wrap the WebDeploymentDescManager.getInstance().getDeploymentDesc() call.
     *
     * @param url WebApp URL
     * @param moduleCL WebApp module ClassLoader
     * @param earCL Application ClassLoader
     *
     * @return the WebContainerDeploymentDesc of the given WebApp
     *
     * @throws WebContainerDeploymentDescException When WebContainerDeploymentDesc cannot be instanciated
     */
    public static WebContainerDeploymentDesc getDeploymentDesc(final URL url, final ClassLoader moduleCL, final ClassLoader earCL)
            throws WebContainerDeploymentDescException {
        LoaderManager lm = LoaderManager.getInstance();
        WebContainerDeploymentDesc webDD = null;

        try {
            ClassLoader ext = lm.getExternalLoader();
            Class manager = ext.loadClass(WEBMANAGER_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});
            webDD = (WebContainerDeploymentDesc) m.invoke(instance, new Object[] {url, moduleCL, earCL});
        } catch (InvocationTargetException ite) {
            Throwable t = ite.getTargetException();
            if (WebContainerDeploymentDescException.class.isInstance(t)) {
                throw (WebContainerDeploymentDescException) ite.getTargetException();
            } else {
                throw new WebContainerDeploymentDescException("WebDeploymentDescManager.getDeploymentDesc fails", t);
            }
        } catch (Exception e) {
            // TODO add i18n here
            throw new WebContainerDeploymentDescException("Problems when using reflection on WebDeploymentDescManager", e);
        }

        return webDD;
    }

    /**
     * Wrap the WebDeploymentDescManager.getInstance().setAltDD() call.
     *
     * @param earClassLoader Application ClassLoader
     * @param warUrls Array of WebApp URLs
     * @param warsAltDDs Array of Alternatives WebApp Descriptor URL
     */
    public static void setAltDD(final URLClassLoader earClassLoader, final URL[] warUrls, final URL[] warsAltDDs) {
        LoaderManager lm = LoaderManager.getInstance();

        try {
            ClassLoader ext = lm.getExternalLoader();
            Class manager = ext.loadClass(WEBMANAGER_CLASSNAME);
            Method m = manager.getDeclaredMethod("getInstance", new Class[] {});
            Object instance = m.invoke(null, new Object[] {});
            m = manager.getDeclaredMethod("setAltDD", new Class[] {ClassLoader.class, URL[].class, URL[].class});
            m.invoke(instance, new Object[] {earClassLoader, warUrls, warsAltDDs});
        } catch (Exception e) {
            // Should never occurs
            logger.log(BasicLevel.ERROR, e);
        }
    }

    /**
     * Wrap the WebDeploymentDescManager.setParsingWithValidation() call.
     *
     * @param b true/false
     */
    public static void setParsingWithValidation(final boolean b) {
        LoaderManager lm = LoaderManager.getInstance();

        try {
            ClassLoader ext = lm.getExternalLoader();
            Class manager = ext.loadClass(WEBMANAGER_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 the WebDeploymentDescManager.getInstance().removeCache() call.
     *
     * @param classLoader WebApp ClassLoader
     */
    public static void removeCache(final ClassLoader classLoader) {
        LoaderManager lm = LoaderManager.getInstance();

        try {
            ClassLoader ext = lm.getExternalLoader();
            Class manager = ext.loadClass(WEBMANAGER_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);
        }
    }

    /**
     * Wrap the WebDeploymentDescManager.getDeploymentDesc() call.
     *
     * @param warName war filename
     * @param cl WebApp ClassLoader
     *
     * @return the WebContainerDeploymentDesc of the given WebApp
     *
     * @throws WebContainerDeploymentDescException When WebContainerDeploymentDesc cannot be instanciated
     */
    public static WebContainerDeploymentDesc getDeploymentDesc(final String warName, final ClassLoader cl)
            throws WebContainerDeploymentDescException {
        LoaderManager lm = LoaderManager.getInstance();
        WebContainerDeploymentDesc desc = null;

        try {
            ClassLoader ext = lm.getExternalLoader();
            Class manager = ext.loadClass(WEBMANAGER_CLASSNAME);
            Method m = manager.getDeclaredMethod("getDeploymentDesc", new Class[] {String.class, ClassLoader.class});
            desc = (WebContainerDeploymentDesc) m.invoke(null, new Object[] {warName, cl});
        } catch (InvocationTargetException ite) {
            Throwable t = ite.getTargetException();
            if (WebContainerDeploymentDescException.class.isInstance(t)) {
                throw (WebContainerDeploymentDescException) ite.getTargetException();
            } else {
                throw new WebContainerDeploymentDescException("WebDeploymentDescManager.getDeploymentDesc fails", t);
            }
        } catch (Exception e) {
            // TODO add i18n here
            throw new WebContainerDeploymentDescException("Problems when using reflection on WebDeploymentDescManager", e);
        }

        return desc;
    }

}