/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2006 Bull S.A.S.
 * 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: WebServicesXmlFinder.java 16329 2009-01-28 13:38:07Z sauthieg $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.generators.wsgen.finder;

import org.ow2.jonas.generators.genbase.archive.J2EEArchive;
import org.ow2.jonas.lib.util.Log;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.objectweb.util.monolog.api.Logger;
import org.objectweb.util.monolog.api.BasicLevel;

import javax.xml.parsers.SAXParser;
import java.util.Iterator;
import java.util.List;
import java.io.InputStream;
import java.io.IOException;


/**
 * <code>WebServicesXmlFinder</code> finds out if there is any
 * <code>webservices.xml</code> within the given {@link J2EEArchive}.
 *
 * @author Guillaume Sauthier
 */
public class WebServicesXmlFinder extends DefaultHandler implements J2EEWebServicesFinder {

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

    /**
     * WebApp's webservices.xml.
     */
    private static final String WEBINF_WEBSERVICES_XML = "WEB-INF/webservices.xml";

    /**
     * EjbJar's webservices.xml.
     */
    private static final String METAINF_WEBSERVICES_XML = "META-INF/webservices.xml";

    /**
     * JAX-RPC value for the version attribute of the webservices.xml
     */
    private static final String JAXRPC_VERSION = "1.1";

    /**
     * Archive to browse.
     */
    private J2EEArchive archive = null;

    /**
     * Tell if the archive is a jaxrpc archive or not.
     */
    private boolean jaxrpc = false;

    /**
     * Constructs a <code>WebServicesXmlFinder</code> that will
     * explore the given {@link J2EEArchive}.
     * @param archive archive to explore.
     */
    public WebServicesXmlFinder(J2EEArchive archive) {
        this.archive = archive;
    }

    /**
     * @see org.ow2.jonas.generators.wsgen.finder.J2EEWebServicesFinder#find()
     */
    public boolean find() {
        return jaxrpc;
    }

    /**
     * Explore the archive and find a webservices.xml. If found, parse the
     * file and observe the 'version' attribute.
     * @param parser SAX Parser
     */
    public void init(SAXParser parser) {
        List files = archive.getContainedFiles();
        for (Iterator i = files.iterator(); i.hasNext();) {
            String filename = (String) i.next();

            // If there is a webservices.xml file, check if it's a JAX-RPC file
            if (WEBINF_WEBSERVICES_XML.equals(filename)) {
                parseWebservicesDescriptor(parser, filename);
            }
            if (METAINF_WEBSERVICES_XML.equals(filename)) {
                parseWebservicesDescriptor(parser, filename);
            }
        }
    }

    /**
     * Parse the descriptor.
     * @param parser SAX Parser
     * @param filename webservices.xml filename
     */
    private void parseWebservicesDescriptor(SAXParser parser, String filename) {
        InputStream is = null;
        try {
            is = archive.getArchive().getInputStream(filename);
            parser.parse(is, this);
        } catch (IOException e) {
            logger.log(BasicLevel.DEBUG, "Cannot open " + filename + " in archive " + archive.getArchive().getName());
        } catch (SAXException e) {
            logger.log(BasicLevel.DEBUG, "Cannot parse " + filename + " in archive " + archive.getArchive().getName());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    logger.log(BasicLevel.DEBUG, "Ignored");
                }
            }
        }
    }

    /**
     * Receive notification of the start of an element.
     * <p/>
     * <p>By default, do nothing.  Application writers may override this
     * method in a subclass to take specific actions at the start of
     * each element (such as allocating a new tree node or writing
     * output to a file).</p>
     *
     * @param uri        The Namespace URI, or the empty string if the
     *                   element has no Namespace URI or if Namespace
     *                   processing is not being performed.
     * @param localName  The local name (without prefix), or the
     *                   empty string if Namespace processing is not being
     *                   performed.
     * @param qName      The qualified name (with prefix), or the
     *                   empty string if qualified names are not available.
     * @param attributes The attributes attached to the element.  If
     *                   there are no attributes, it shall be an empty
     *                   Attributes object.
     * @throws org.xml.sax.SAXException Any SAX exception, possibly
     *                                  wrapping another exception.
     * @see org.xml.sax.ContentHandler#startElement
     */
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        // the 'version' attribute is located on the 'webservices' element
        if ("webservices".equals(localName)) {

            // Check value of the 'version' attribute
            String value = attributes.getValue("version");
            if (JAXRPC_VERSION.equals(value)) {
                jaxrpc = true;
            }
        }
    }
}
