// Copyright 2008-2012 severally by the contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package net.sf.practicalxml.util;

import java.io.IOException;

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

import net.sf.practicalxml.XmlException;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.XMLFilterImpl;


/**
 *  An implementation of {@link org.xml.sax.XMLReader} based on  {@link
 *  XMLFilterImpl}, which implements the <code>parse()</code> methods
 *  (default behavior of <code>XMLFilterImpl</code> is to delegate to a
 *  parent <code>XMLReader</code>, and throw <code>NullPointerException</code>
 *  if there is no parent).
 *  <p>
 *  Since this class extends <code>XMLFilterImpl</code>, it exposes all
 *  public handler methods, and can be used to write a filtered source
 *  for an XML transform.
 *
 *  @since 1.1.1
 */
public class SimpleXMLReader
extends XMLFilterImpl
{
    private SAXParser _parser;

    /**
     *  Creates a new instance, using the default configuration of {@link
     *  SAXParserFactory}. The checked exceptions thrown by the factory are
     *  caught and rethrown as <code>XmlException</code>.
     */
    public SimpleXMLReader()
    {
        try
        {
            _parser = SAXParserFactory.newInstance().newSAXParser();
        }
        catch (Exception ee)
        {
            throw new XmlException(ee);
        }
    }


    /**
     *  Creates a new instance, wrapping a pre-existing parser.
     */
    public SimpleXMLReader(SAXParser parser)
    {
        _parser = parser;
    }


    @Override
    public void parse(InputSource input)
    throws SAXException, IOException
    {
        _parser.parse(input, new XMLFilterImplBridge(this));
    }


    @Override
    public void parse(String systemId)
    throws SAXException, IOException
    {
        _parser.parse(systemId, new XMLFilterImplBridge(this));
    }
}
