/**
 * JOnAS : Java(TM) OpenSource 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
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.generators.genbase.archive;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import javax.xml.parsers.ParserConfigurationException;

import org.ow2.jonas.deployment.common.DeploymentDescException;
import org.ow2.jonas.deployment.ejb.BeanDesc;
import org.ow2.jonas.deployment.ejb.DeploymentDesc;
import org.ow2.jonas.deployment.ejb.lib.EjbDeploymentDescManager;
import org.ow2.jonas.deployment.ws.WSDeploymentDesc;
import org.ow2.jonas.deployment.ws.lib.WSDeploymentDescManager;
import org.ow2.jonas.generators.genbase.GenBaseException;
import org.ow2.jonas.generators.genbase.utils.XMLUtils;
import org.ow2.jonas.lib.loader.EjbJarClassLoader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;




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

/**
 * EjbJar represents an EjbJar J2EE Archive.
 *
 * @author Guillaume Sauthier
 */
public class EjbJar extends J2EEArchive implements WsEndpoint {

    /** Application containing the ejbjar */
    private Application app;

    /** WebServices deployment descriptor */
    private WSDeploymentDesc wsDD = null;

    /** EjbJar deployment descriptor */
    private DeploymentDesc ejbDD = null;

    /** inner EJBs List */
    private List ejbs;

    /** descriptors list */
    private Map<String, Document> descriptors;

    /** jonas-ejb-jar document */
    private Document jEjbJar;

    /** jonas-webservices document */
    private Document jWebservices = null;

    /**
     * Create a new EjbJar not contained in Application
     *
     * @param archive
     *            the archive file
     *
     * @throws GenBaseException
     *             When init fails
     */
    public EjbJar(Archive archive) throws GenBaseException {
        super(archive);
        if (getLogger().isLoggable(BasicLevel.DEBUG)) {
            getLogger().log(BasicLevel.DEBUG, "Wrapping '" + archive.getName() + "' in EjbJar");
        }
        init();
    }

    /**
     * Create a new EjbJar contained in Application
     *
     * @param archive
     *            the archive file
     * @param app
     *            container application
     *
     * @throws GenBaseException
     *             When init fails
     */
    public EjbJar(Archive archive, Application app) throws GenBaseException {
        super(archive);
        setApplication(app);
        if (getLogger().isLoggable(BasicLevel.DEBUG)) {
            getLogger().log(BasicLevel.DEBUG, "Wrapping '" + archive.getName() + "' in EjbJar");
        }
        init();
    }

    /**
     * Initialize the EjbJar module.
     *
     * @throws GenBaseException
     *             When ejb classlaoder cannot be created or when Descriptor
     *             cannot be loaded.
     */
    private void init() throws GenBaseException {
        loadDescriptors();
    }


    /**
     * Initialize the Archive.
     * @throws GenBaseException When initialization fails.
     */
    public void initialize() throws GenBaseException {

        try {
            if (app == null) {
                // simple ejb case
                setModuleClassloader(new EjbJarClassLoader(new URL[] {getArchive()
                        .getRootFile().toURL()}, Thread.currentThread()
                        .getContextClassLoader()));
            } else {
                // embedded ejb case
                setModuleClassloader(app.getEJBClassLoader());
            }
        } catch (IOException ioe) {
            String err = getI18n().getMessage("EjbJar.init.loader", getArchive()
                    .getRootFile());
            throw new GenBaseException(err, ioe);
        }

        try {
            ejbDD = EjbDeploymentDescManager.getDeploymentDesc(getRootFile()
                    .getAbsolutePath(), getModuleClassloader());
        } catch (DeploymentDescException dde) {
            throw new GenBaseException(dde);
        }

        try {
            wsDD = WSDeploymentDescManager.getDeploymentDesc(getRootFile()
                    .getAbsolutePath(), getModuleClassloader());
        } catch (DeploymentDescException dde) {
            throw new GenBaseException(dde);
        }

        // create inner EJBs
        ejbs = new Vector();

        BeanDesc[] bd = ejbDD.getBeanDesc();

        for (int i = 0; i < bd.length; i++) {
            Element jElement = null;
            if (jEjbJar != null) {
                jElement = XMLUtils.getBeanElement(jEjbJar.getDocumentElement(), bd[i].getEjbName());
            }
            ejbs.add(new Ejb(bd[i], jElement));
        }

    }


    /**
     * Load Deployment Descriptor of an EjbJar.
     *
     * @throws GenBaseException
     *             When parsing fails
     */
    private void loadDescriptors() throws GenBaseException {
        InputStream jonasEJBXMLIS = null;
        InputStream isJws = null;
        try {

            jonasEJBXMLIS = getJonasEjbJarInputStream();
            if (jonasEJBXMLIS != null) {
                jEjbJar = XMLUtils.newDocument(jonasEJBXMLIS, "META-INF/jonas-ejb-jar.xml", isDTDsAllowed());
            }

            isJws = getJonasWebservicesInputStream();
            if (isJws != null) {
                jWebservices = XMLUtils.newDocument(isJws,
                    "META-INF/jonas-webservices.xml", isDTDsAllowed());
            }

        } catch (SAXException saxe) {
            String err = getI18n().getMessage("EjbJar.loadDescriptors.parseError");
            throw new GenBaseException(err, saxe);
        } catch (ParserConfigurationException pce) {
            String err = getI18n().getMessage("EjbJar.loadDescriptors.prepare");
            throw new GenBaseException(err, pce);
        } catch (IOException ioe) {
            String err = getI18n().getMessage("EjbJar.loadDescriptors.parseError");
            throw new GenBaseException(err, ioe);
        }

        descriptors = new Hashtable<String, Document>();
        if (jEjbJar != null) {
            descriptors.put("META-INF/jonas-ejb-jar.xml", jEjbJar);
        }
    }

    /**
     * Returns the List of Ejb contained in this EjbJar.
     *
     * @return the List of Ejb contained in this EjbJar.
     */
    public List getEjbs() {
        return ejbs;
    }

    /**
     * Returns the list of webservice-description elements contained by a
     * module.
     *
     * @return the list of webservice-description elements contained by a
     *         module.
     */
    public List getServiceDescs() {
        if (wsDD != null) {
            return wsDD.getServiceDescs();
        } else {
            return new Vector();
        }
    }

    /**
     * Add *.class from directory in the archive.
     *
     * @param classes
     *            directory containing classes files.
     */
    public void addClasses(File classes) {
        addDirectory(classes);
    }

    /**
     * @return Returns the desired war filename (jonas-webservices/war)
     */
    public String getWarName() {
       if (wsDD != null) {
           return wsDD.getWarFile();
       } else {
           return null;
       }
    }

    /**
     * @return Returns the desired context-root (jonas-webservices/context-root)
     */
    public String getContextRoot() {
        // compute context root name from ejbjar name
        String archiveName = this.getArchive().getName();
        String root = null;
        if (archiveName.toLowerCase().endsWith(".jar")) {
            root = archiveName.toLowerCase().substring(0, archiveName.length() - ".jar".length());
        } else {
            root = archiveName;
        }
        if (wsDD != null) {
            String croot = wsDD.getContextRoot();
            if (croot != null) {
                root = croot;
            }
        }
        if (getLogger().isLoggable(BasicLevel.DEBUG)) {
            getLogger().log(BasicLevel.DEBUG, "Computed context root : " + root);
        }
        return root;
    }

    /**
     * Set the container application of this EjbJar
     *
     * @param app
     *            container application
     */
    public void setApplication(Application app) {
        this.app = app;
    }

    /**
     * Return the container application of this EjbJar
     *
     * @return the container application of this EjbJar
     */
    public Application getApplication() {
        return app;
    }

    /**
     * Returns a Map of name to Document for each modified Descriptor of the
     * archive.
     *
     * @return a Map of name to Document
     */
    public Map getDescriptors() {
        return descriptors;
    }

    /**
     * Returns true if filename must be omitted in the archive.
     *
     * @param name
     *            filename to be tested
     *
     * @return true if filename must be omitted.
     */
    public boolean omit(String name) {
        return (name.equals("META-INF/jonas-ejb-jar.xml")
                || name.equals("META-INF\\jonas-ejb-jar.xml"));
    }

    /**
     * Returns the Document of the jonas-ejb-jar.xml file.
     *
     * @return the Document of the jonas-ejb-jar.xml file.
     */
    public Document getJonasEjbJarDoc() {
        return jEjbJar;
    }

    /**
     * Return the Document of the the jonas-webservices.xml
     *
     * @return the Document of the jonas-webservices.xml file
     */
    public Document getJonasWebservicesDoc() {
        return jWebservices;
    }

    /**
     * Returns the InputStream of the jonas-ejb-jar.xml file.
     *
     * @return the InputStream of the jonas-ejb-jar.xml file.
     *
     * @throws IOException if stream is invalid
     */
    public InputStream getJonasEjbJarInputStream() throws IOException {
        InputStream is = null;

        if (isPacked()) {
            is = getInputStream("META-INF/jonas-ejb-jar.xml");
        } else {
            is = getInputStream("META-INF" + File.separator
                    + "jonas-ejb-jar.xml");
        }

        // may be null (optional entry)
        return is;
    }

    /**
     * Returns the InputStream of the jonas-webservices.xml file.
     *
     * @return the InputStream of the jonas-webservices.xml file.
     * @throws IOException When InputStream of jonas-webservices.xml cannot be returned
     */
    public InputStream getJonasWebservicesInputStream() throws IOException {
        InputStream is = null;

        if (isPacked()) {
            is = getInputStream("META-INF/jonas-webservices.xml");
        } else {
            is = getInputStream("META-INF" + File.separator
                       + "jonas-webservices.xml");
        }
        return is;
    }





}
