/* $Id: DefaultParser.java,v 1.1 2004/01/09 16:55:43 burkhard Exp $
 * Created on 12.05.2003 by sell
 *
 */
package de.skyrix.zsp.logic.parser;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

/**
 * 
 * @author sell
 * @version 
 */
public class DefaultParser {

	protected InputStream xmlInput = null;

	public DefaultParser() {
	}

	public DefaultParser(String xmlString) {
		if (xmlString == null)
			throw new IllegalArgumentException("xmlString cannot be NULL.");

		xmlInput = new ByteArrayInputStream(xmlString.getBytes());
	}

	public DefaultParser(InputStream inputStream) {
		if (inputStream == null)
			throw new IllegalArgumentException("inputstream cannot be NULL.");

		xmlInput = inputStream;
	}

	protected void setBuilderFactoryPreferences(DocumentBuilderFactory builder) {
		builder.setIgnoringElementContentWhitespace(true);
		builder.setValidating(false);
		builder.setCoalescing(true);
		builder.setNamespaceAware(true);
	}

	protected Document load() throws SAXException, IOException {
		try {

			//Parserfactory initialisieren
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

			//Parsereinstellungen setzen
			setBuilderFactoryPreferences(dbf);

			DocumentBuilder db = dbf.newDocumentBuilder();

			//Handler zur Fehlerbehandlung
			db.setErrorHandler(new EH());

			//Dokument parsen
			return db.parse(new InputSource(xmlInput));
		}
		catch (ParserConfigurationException x) {
			throw new Error(x.toString());
		}
	}

	protected static class EH implements ErrorHandler {
		public void error(SAXParseException x) throws SAXException {
			throw x;
		}
		public void fatalError(SAXParseException x) throws SAXException {
			throw x;
		}

		public void warning(SAXParseException x) throws SAXException {
			throw x;
		}
	}
}
