/* $Id: SaxParser.java,v 1.12 2005/08/31 21:47:47 m31 Exp $
 *
 * This file is part of the project "Hilbert II" - http://www.qedeq.org
 *
 * Copyright 2000-2005,  Michael Meyling <mime@qedeq.org>.
 *
 * "Hilbert II" is free software; you can redistribute
 * it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 */
package org.qedeq.kernel.xml.parser;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.qedeq.kernel.log.Trace;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;


/**
 * Parser for XML files. This class uses features specific for Xerces.
 *
 * @version $Revision: 1.12 $
 * @author Michael Meyling
 */
public final class SaxParser {

    /** Namespaces feature id (http://xml.org/sax/features/namespaces). */
    private static final String NAMESPACES_FEATURE_ID = "http://xml.org/sax/features/namespaces";

    /** Validation feature id (http://xml.org/sax/features/validation). */
    private static final String VALIDATION_FEATURE_ID = "http://xml.org/sax/features/validation";

    /** Schema validation feature id (http://apache.org/xml/features/validation/schema). */
    private static final String SCHEMA_VALIDATION_FEATURE_ID
        = "http://apache.org/xml/features/validation/schema";

    /** Schema full checking feature id
     * (http://apache.org/xml/features/validation/schema-full-checking). */
    protected static final String SCHEMA_FULL_CHECKING_FEATURE_ID
        = "http://apache.org/xml/features/validation/schema-full-checking";

    /** Handler which deals with the XML contents. */
    private SaxDefaultHandler handler;

    /** SAX parser. */
    private XMLReader reader;

    /** Default handler for validation purpose only. */
    private final DefaultHandler deflt;

    /** Saved errors of parsing. */
    private ExceptionList exceptionList;

    /**
     * Constructor.
     *
     * @param   handler   Default handler for this application.
     * @throws  ParserConfigurationException    Severe parser configuration problem.
     * @throws  SAXException
     */
    public SaxParser(final SaxDefaultHandler handler) throws ParserConfigurationException,
            SAXException {
        super();

        this.handler = handler;
        this.deflt = new DefaultHandler();

        final String factoryImpl = System.getProperty("javax.xml.parsers.SAXParserFactory");
        if (factoryImpl == null) {
            System.setProperty("javax.xml.parsers.SAXParserFactory",
                "org.apache.xerces.jaxp.SAXParserFactoryImpl");
        }
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(true);

        factory.setFeature(NAMESPACES_FEATURE_ID, true);
        factory.setFeature(VALIDATION_FEATURE_ID, true);
        try {
            factory.setFeature(SCHEMA_VALIDATION_FEATURE_ID, true);
        } catch (SAXNotRecognizedException e) {
            Trace.trace(this, "constructor", e);
            // ignore
        }
        try {
            factory.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, true);
        } catch (SAXNotRecognizedException e) {
            Trace.trace(this, "constructor", e);
            // ignore
        }

        final SAXParser parser = factory.newSAXParser();
        if (!parser.isNamespaceAware()) {
            throw new ParserConfigurationException(
                "Current XML parser doesn't support namespaces.");
        }
        if (!parser.isValidating()) {
            throw new ParserConfigurationException(
                "Current XML parser doesn't support schema validation.");
        }

        reader = parser.getXMLReader();
        reader.setEntityResolver(new SaxEntityResolver());

        // set parser features
        reader.setFeature(NAMESPACES_FEATURE_ID, true);
        reader.setFeature(VALIDATION_FEATURE_ID, true);
        try {
            reader.setFeature(SCHEMA_VALIDATION_FEATURE_ID, true);
        } catch (SAXNotRecognizedException e) {
            Trace.trace(this, "constructor", e);
            // ignore
        }
        try {
            reader.setFeature(SCHEMA_FULL_CHECKING_FEATURE_ID, true);
        } catch (SAXNotRecognizedException e) {
            Trace.trace(this, "constructor", e);
            // ignore
        }
    }

    /**
     * Parse input source.
     *
     * @param   file   Parse data from this source.
     * @param   validateOnly    validate with {@link #deflt} or parse with {@link #handler}.
     * @throws  SAXException    Syntactical or semantical problem occurred.
     * @throws  IOException     Technical problem occurred.
     */
    private void parse(final File file, final boolean validateOnly)
            throws SAXException, IOException {
        final InputSource input = new InputSource(new FileInputStream(file));
        exceptionList = new ExceptionList();
        try {
            reader.setErrorHandler(new SaxErrorHandler(file, exceptionList));
            if (validateOnly) {
                reader.setContentHandler(deflt);
                reader.parse(input);
            } else {
                handler.setExceptionList(exceptionList);
                reader.setContentHandler(handler);
                reader.parse(input);
            }
        } catch (SAXException e) {
            Trace.trace(this, "parse", e);
            if (exceptionList.size() == 0) { // should not occur, exception must be already here
                exceptionList.add(e);
            }
        }
        if (exceptionList.size() > 0) {
            throw new SAXException(exceptionList.toString());
        }
    }

    /**
     * Parses XML file.
     *
     * @param   fileName File name.
     * @throws  SAXException    Syntactical or semantical problem occurred.
     * @throws  IOException     Technical problem occurred.
     */
    public final void parse(final String fileName) throws SAXException,
            IOException {
        final File file = new File(fileName);
        parse(file.getAbsoluteFile());
    }

    /**
     * Parses the XML file.
     *
     * @param   file    File to parse.
     * @throws  SAXException    Syntactical or semantical problem occurred.
     * @throws  IOException     Technical problem occurred.
     */
    public final void parse(final File file) throws SAXException,
            IOException {
        parse(file.getAbsoluteFile(), true);
        parse(file.getAbsoluteFile(), false);
    }

    /**
     * Get errors that occurred during last parsing.
     *
     * @return  List with collected Exceptions.
     */
    public ExceptionList getExceptionList() {
        return exceptionList;
    }

}
