/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-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
 *
 * Initial developer(s): Florent BENOIT & Ludovic BERT
 * --------------------------------------------------------------------------
 * $Id: EarDeploymentDescManager.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.deployment.ear.lib;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLConnection;

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.common.digester.JDigester;
import org.ow2.jonas.deployment.common.lib.AbsDeploymentDescManager;
import org.ow2.jonas.deployment.ear.EarDTDs;
import org.ow2.jonas.deployment.ear.EarDeploymentDesc;
import org.ow2.jonas.deployment.ear.EarDeploymentDescException;
import org.ow2.jonas.deployment.ear.EarSchemas;
import org.ow2.jonas.deployment.ear.JonasEarSchemas;
import org.ow2.jonas.deployment.ear.rules.ApplicationRuleSet;
import org.ow2.jonas.deployment.ear.rules.JonasApplicationRuleSet;
import org.ow2.jonas.deployment.ear.xml.Application;
import org.ow2.jonas.deployment.ear.xml.JonasApplication;
import org.ow2.jonas.deployment.ear.xml.Module;
import org.ow2.jonas.deployment.ear.xml.Web;
import org.ow2.jonas.lib.util.Log;
import org.ow2.util.archive.api.ArchiveException;
import org.ow2.util.archive.api.IArchive;
import org.ow2.util.ee.deploy.api.deployable.CARDeployable;
import org.ow2.util.ee.deploy.api.deployable.EARDeployable;
import org.ow2.util.ee.deploy.api.deployable.EJBDeployable;
import org.ow2.util.ee.deploy.api.deployable.RARDeployable;
import org.ow2.util.ee.deploy.api.deployable.WARDeployable;

/**
 * This class extends the AbsDeploymentDescriptor class of JOnAS It provides a
 * description of the specific EAR desployment descriptor.
 * @author Florent Benoit
 * @author Ludovic Bert
 * @author Helene Joanin
 */
public final class EarDeploymentDescManager extends AbsDeploymentDescManager {

    /**
     * Path of the application.xml deploymnet descriptor file.
     */
    public static final String APPLICATION_FILE_NAME = "META-INF/application.xml";

    /**
     * Path of the jonas-application.xml deploymnet descriptor file.
     */
    public static final String JONAS_APPLICATION_FILE_NAME = "META-INF/jonas-application.xml";

    /**
     * Digester used to parse application.xml.
     */
    private static JDigester earDigester = null;

    /**
     * Digester used to parse jonas-application.xml.
     */
    private static JDigester jonasEarDigester = null;

    /**
     * Rules to parse the application.xml.
     */
    private static ApplicationRuleSet appRuleSet = new ApplicationRuleSet();

    /**
     * Rules to parse the jonas-application.xml.
     */
    private static JonasApplicationRuleSet jonasApplicationRuleSet = new JonasApplicationRuleSet();

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

    /**
     * Flag for parser validation.
     */
    private static boolean parsingWithValidation = true;

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

    /**
     * Get an instance of an EAR deployment descriptor by parsing the
     * application.xml deployment descriptor.
     * @param earDeployable the deployable to analyze.
     * @param classLoaderForCls the classloader for the classes.
     * @return an EAR deployment descriptor by parsing the application.xml
     *         deployment descriptor.
     * @throws EarDeploymentDescException if the deployment descriptor is
     *         corrupted.
     */
    public static EarDeploymentDesc getDeploymentDesc(final EARDeployable earDeployable, final ClassLoader classLoaderForCls)
            throws EarDeploymentDescException {

        // Input Stream
        Reader appReader = null;
        Reader jonasApplicationReader = null;

        Application application = null;
        JonasApplication jonasApplication = null;

        String xmlContent = "";
        String jonasXmlContent = "";

        // Get Archive
        IArchive archive = earDeployable.getArchive();

        // Get the stream
        URL applicationXMLURL;
        try {
            applicationXMLURL = archive.getResource(APPLICATION_FILE_NAME);
        } catch (ArchiveException e) {
            throw new EarDeploymentDescException("Cannot get entry '" + APPLICATION_FILE_NAME + "' from the archive '"
                    + archive + "'.", e);
        }
        if (applicationXMLURL != null) {
            URLConnection urlConnection = null;
            try {
                urlConnection = applicationXMLURL.openConnection();
            } catch (IOException e) {
                throw new EarDeploymentDescException("Unable to open connection on URL '" + applicationXMLURL + "'.", e);
            }
            urlConnection.setDefaultUseCaches(false);
            try {
                xmlContent = xmlContent(urlConnection.getInputStream());
                // Read again the input stream
                appReader = new StringReader(xmlContent);
            } catch (IOException e) {
                throw new EarDeploymentDescException("Unable to get Stream on URL '" + applicationXMLURL + "'.", e);
            }

        }

        URL jonasApplicationXMLURL;
        try {
            jonasApplicationXMLURL = archive.getResource(JONAS_APPLICATION_FILE_NAME);
        } catch (ArchiveException e) {
            throw new EarDeploymentDescException("Cannot get entry '" + JONAS_APPLICATION_FILE_NAME
                    + "' from the archive '" + archive + "'.", e);
        }
        if (jonasApplicationXMLURL != null) {
            URLConnection urlConnection = null;
            try {
                urlConnection = jonasApplicationXMLURL.openConnection();
            } catch (IOException e) {
                throw new EarDeploymentDescException("Unable to open connection on URL '" + applicationXMLURL + "'.", e);
            }
            urlConnection.setDefaultUseCaches(false);
            try {
                jonasXmlContent = xmlContent(urlConnection.getInputStream());
                // Read again the input stream
                jonasApplicationReader = new StringReader(jonasXmlContent);
            } catch (IOException e) {
                throw new EarDeploymentDescException("Unable to get Stream on URL '" + applicationXMLURL + "'.", e);
            }
        }

        if (appReader != null) {
            application = loadApplication(appReader, APPLICATION_FILE_NAME);
            try {
                appReader.close();
            } catch (IOException e) {
                // Can't close the file
                logger.log(BasicLevel.WARN, "Cannot close InputStream for META-INF/application.xml in '" + earDeployable
                        + "'");
            }
        } else {
            application = new Application();

            // Get URL of the deployable
            URL earDeployableURL = null;
            try {
                earDeployableURL = earDeployable.getArchive().getURL();
            } catch (ArchiveException e) {
                throw new EarDeploymentDescException("Cannot get URL for the deployable for the archive '" + archive
                        + "'", e);
            }

            // Perform update
            if (earDeployable != null) {

                // For clients
                for (CARDeployable carDeployable : earDeployable.getCARDeployables()) {
                    Module m = new Module();
                    try {
                        m.setJava(carDeployable.getArchive().getURL().toExternalForm().substring(
                                earDeployableURL.toExternalForm().length()));
                    } catch (ArchiveException e) {
                        throw new EarDeploymentDescException("Cannot get URL for the deployable for the deployable '"
                                + carDeployable + "'", e);
                    }
                    application.addModule(m);
                }

                // For Web
                for (WARDeployable warDeployable : earDeployable.getWARDeployables()) {
                    Web web = new Web();
                    web.setContextRoot(warDeployable.getContextRoot());
                    try {
                        web.setWebUri(warDeployable.getArchive().getURL().toExternalForm().substring(
                                earDeployableURL.toExternalForm().length()));
                    } catch (ArchiveException e) {
                        throw new EarDeploymentDescException("Cannot get URL for the deployable for the deployable '"
                                + warDeployable + "'", e);
                    }
                    Module m = new Module();
                    m.setWeb(web);
                    application.addModule(m);
                }

                // For EJBs
                for (EJBDeployable ejbDeployable : earDeployable.getEJBDeployables()) {
                    Module m = new Module();
                    try {
                        m.setEjb(ejbDeployable.getArchive().getURL().toExternalForm().substring(
                                earDeployableURL.toExternalForm().length()));
                    } catch (ArchiveException e) {
                        throw new EarDeploymentDescException("Cannot get URL for the deployable for the deployable '"
                                + ejbDeployable + "'", e);
                    }
                    application.addModule(m);
                }

                // For Connectors
                for (RARDeployable rarDeployable : earDeployable.getRARDeployables()) {
                    Module m = new Module();
                    try {
                        m.setEjb(rarDeployable.getArchive().getURL().toExternalForm().substring(
                                earDeployableURL.toExternalForm().length()));
                    } catch (ArchiveException e) {
                        throw new EarDeploymentDescException("Cannot get URL for the deployable for the deployable '"
                                + rarDeployable + "'", e);
                    }
                    application.addModule(m);
                }
            }

        }

        // load jonas-application deployment descriptor data
        // (META-INF/jonas-application.xml)
        if (jonasApplicationReader != null) {
            jonasApplication = loadJonasApplication(jonasApplicationReader,
                    JONAS_APPLICATION_FILE_NAME);
            try {
                jonasApplicationReader.close();
            } catch (IOException e) {
                // We can't close the file
                logger.log(BasicLevel.WARN, "Cannot close InputStream for '" + earDeployable + "'");
            }
        } else {
            jonasApplication = new JonasApplication();
        }

        // instantiate deployment descriptor
        EarDeploymentDesc earDD = new EarDeploymentDesc(classLoaderForCls, application, jonasApplication);
        earDD.setXmlContent(xmlContent);
        earDD.setJonasXmlContent(jonasXmlContent);
        return earDD;
    }

    /**
     * Load the application.xml file.
     * @param reader the Reader of the XML file.
     * @param fileName the name of the file (application.xml).
     * @throws EarDeploymentDescException if the deployment descriptor is
     *         corrupted.
     * @return an application object.
     */
    public static Application loadApplication(final Reader reader, final String fileName) throws EarDeploymentDescException {

        Application app = new Application();
        // Create if earDigester is null
        if (earDigester == null) {
            try {
                // Create and initialize the digester
                earDigester = new JDigester(appRuleSet, getParsingWithValidation(), true, new EarDTDs(),
                        new EarSchemas());
            } catch (DeploymentDescException e) {
                throw new EarDeploymentDescException(e);
            }
        }

        try {
            earDigester.parse(reader, fileName, app);
        } catch (DeploymentDescException e) {
            throw new EarDeploymentDescException(e);
        } finally {
            earDigester.push(null);
        }

        return app;
    }

    /**
     * Load the jonas-application.xml file.
     * @param reader the stream of the XML file.
     * @param fileName the name of the file (jonas-application.xml).
     * @return a structure containing the result of the jonas-application.xml
     *         parsing.
     * @throws EarDeploymentDescException if the deployment descriptor is
     *         corrupted.
     */
    public static JonasApplication loadJonasApplication(final Reader reader, final String fileName)
            throws EarDeploymentDescException {

        JonasApplication ja = new JonasApplication();

        // Create if null
        if (jonasEarDigester == null) {
            try {
                jonasEarDigester = new JDigester(jonasApplicationRuleSet, getParsingWithValidation(), true, null,
                        new JonasEarSchemas());
            } catch (DeploymentDescException e) {
                throw new EarDeploymentDescException(e);
            }
        }

        try {
            jonasEarDigester.parse(reader, fileName, ja);

        } catch (DeploymentDescException e) {
            throw new EarDeploymentDescException(e);
        } finally {
            jonasEarDigester.push(null);
        }
        return ja;
    }

    /**
     * Controls whether the parser is reporting all validity errors.
     * @return if true, all external entities will be read.
     */
    public static boolean getParsingWithValidation() {
        return parsingWithValidation;
    }

    /**
     * Controls whether the parser is reporting all validity errors.
     * @param validation if true, all external entities will be read.
     */
    public static void setParsingWithValidation(final boolean validation) {
        EarDeploymentDescManager.parsingWithValidation = validation;
    }
}
