/*
 * $Id: Validator.java,v 1.1.1.1 2002/09/30 15:08:51 smartine Exp $
 * Copyright (C) 1999-2000 David Brownell
 * 
 * This program 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.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package xml.aelfred2;

import java.io.IOException;
import java.util.Locale;

import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.ext.*;

import xml.pipeline.*;


// $Id: Validator.java,v 1.1.1.1 2002/09/30 15:08:51 smartine Exp $

/**
 * This SAX2 parser layers a validation component over the standards-enhanced
 * SAX2 version of &AElig;lfred.  While it can't evaluate every XML validity
 * constraint, it does support all the validity constraints that seem to be
 * of any substantial utility outside the strict SGML-compatible world.
 *
 * <p> See the documentation for the SAXDriver class for information
 * about the SAX2 features and properties supported; the only difference
 * between these two classes is that this one supports validation (which
 * feature value is currently immutable, though that could easily change).
 *
 * <p> Note that due to its internal construction, you can't change any
 * handlers except the ErrorHandler and the EntityResolver until parse()
 * returns.  This diverges from SAX, which specifies later binding for
 * handlers.  Early binding involves less runtime overhead, which is an
 * issue for composite objects such as this.  Rather than relying on the
 * parser to perform late binding to your own handlers, do it yourself.
 *
 * @see SAXDriver
 * @see xml.pipeline.ValidationConsumer
 *
 * @author David Brownell
 * @version $Date: 2002/09/30 15:08:51 $
 */
public final class Validator implements XMLReader
{
    private SAXDriver		aelfred2 = new SAXDriver ();
    private ValidationConsumer	val = new ValidationConsumer ();
    private EventFilter		filter = new EventFilter ();
    private boolean		active;


    /** Constructs a SAX Parser.  */
    public Validator ()
    {
	val.setErrorHandler (aelfred2.getErrorHandler ());
    }

    /**
     * Constructs a SAX Parser, optionally treating validity errors
     * as if they were fatal errors.
     */
    public Validator (boolean invalidIsFatal)
    {
	if (invalidIsFatal)
	    setErrorHandler (new DefaultHandler () {
		public void error (SAXParseException e)
		throws SAXException
		    { fatalError (e); }
		});
	else
	    val.setErrorHandler (aelfred2.getErrorHandler ());
    }

    /**
     * <b>SAX2</b>: Returns the object used to report the logical
     * content of an XML document.
     */
    public ContentHandler getContentHandler ()
    {
	return filter.getContentHandler ();
    }

    /**
     * <b>SAX2</b>: Assigns the object used to report the logical
     * content of an XML document.
     */
    public void setContentHandler (ContentHandler handler)
    {
	if (active)
	    throw new IllegalStateException ("already parsing");
	filter.setContentHandler (handler);
    }

    /**
     * <b>SAX2</b>: Returns the object used to process declarations related
     * to notations and unparsed entities.
     */
    public DTDHandler getDTDHandler ()
    {
	return filter.getDTDHandler ();
    }

    /** <b>SAX1</b> Assigns DTD handler */
    public void setDTDHandler (DTDHandler handler)
    {
	if (active)
	    throw new IllegalStateException ("already parsing");
	filter.setDTDHandler (handler);
    }

    /**
     * <b>SAX2</b>: Returns the object used when resolving external
     * entities during parsing (both general and parameter entities).
     */
    public EntityResolver getEntityResolver ()
    {
	return aelfred2.getEntityResolver ();
    }

    /** <b>SAX1</b> Assigns parser's entity resolver */
    public void setEntityResolver (EntityResolver handler)
    {
	if (active)
	    throw new IllegalStateException ("already parsing");
	aelfred2.setEntityResolver (handler);
    }

    /**
     * <b>SAX2</b>: Returns the object used to receive callbacks for XML
     * errors of all levels (fatal, nonfatal, warning); this is never null;
     */
    public ErrorHandler getErrorHandler ()
	{ return aelfred2.getErrorHandler (); }

    /** <b>SAX1</b> Assigns error handler */
    public void setErrorHandler (ErrorHandler handler)
    {
	if (active)
	    throw new IllegalStateException ("already parsing");
	aelfred2.setErrorHandler (handler);
	val.setErrorHandler (handler);
    }

    /**
     * <b>SAX2</b>:  Assigns the specified property.
     */
    public void setProperty (String propertyId, Object value)
    throws SAXNotRecognizedException, SAXNotSupportedException
    {
	if (active)
	    throw new IllegalStateException ("already parsing");
	if (getProperty (propertyId) != value)
	    filter.setProperty (propertyId, value);
    }

    /**
     * <b>SAX2</b>:  Returns the specified property.
     */
    public Object getProperty (String propertyId)
    throws SAXNotRecognizedException
    {
	if ((filter.HANDLER_URI + "declaration-handler").equals (propertyId)
		|| (filter.HANDLER_URI + "lexical-handler").equals (propertyId))
	    return filter.getProperty (propertyId);
	throw new SAXNotRecognizedException (propertyId);
    }

    /**
     * <b>SAX2</b>:  Sets the state of features supported in this parser.
     */
    public void setFeature (String featureId, boolean state)
    throws SAXNotRecognizedException, SAXNotSupportedException
    {
	if (active)
	    throw new IllegalStateException ("already parsing");

	boolean value = getFeature (featureId);

	if (state == value)
	    return ;

	if ((SAXDriver.FEATURE + "validation").equals (featureId))
	    throw new SAXNotSupportedException ("disable validation");

	aelfred2.setFeature (featureId, state);
    }

    /**
     * <b>SAX2</b>: Tells whether this parser supports the specified feature.
     * At this time, this directly parallels the underlying SAXDriver,
     * except that validation is always supported.
     *
     * @see SAXDriver
     */
    public boolean getFeature (String featureId)
    throws SAXNotRecognizedException
    {
	if ((SAXDriver.FEATURE + "validation").equals (featureId))
	    return true;

	return aelfred2.getFeature (featureId);
    }

    /**
     * <b>SAX1</b>: Sets the locale used for diagnostics; currently,
     * only locales using the English language are supported.
     * @param locale The locale for which diagnostics will be generated
     */
    public void setLocale (Locale locale)
    throws SAXException
    {
	if (active)
	    throw new IllegalStateException ("already parsing");
	aelfred2.setLocale (locale);
	// XXX should set validator's locale also ...
    }

    /**
     * <b>SAX1</b>: Preferred API to parse an XML document, using a
     * system identifier (URI).
     */
    public void parse (String systemId)
    throws SAXException, IOException
    {
	parse (new InputSource (systemId));
    }

    /**
     * <b>SAX1</b>: Auxiliary API to parse an XML document, used mostly
     * when no URI is available.
     *
     * @param source The XML input source.
     *
     * @exception SAXException The handlers may throw any SAXException,
     *	and the parser normally throws SAXParseException objects.
     * @exception IOException IOExceptions are normally through through
     *	the parser if there are problems reading the source document.
     */
    public void parse (InputSource source)
    throws SAXException, IOException
    {
	synchronized (aelfred2) {
	    if (active)
		throw new IllegalStateException ("already parsing");
	    active = true;
	}

	try {
	    EventProducer	producer;
	    EventConsumer	consumer;

	    // NOTE:  can't change handlers mid-stream ... late binding
	    // hurts speed.

	    producer = new EventProducer ((XMLReader) aelfred2, source);
	    consumer = filter;

	    // if not validating, no tee needed ...
	    consumer = new TeeConsumer (val, consumer);

	    producer.produce (consumer);
	} finally {
	    active = false;
	}
    }
}
