/*
 * Written by Dawid Kurzyniec and released to the public domain, as explained
 * at http://creativecommons.org/licenses/publicdomain
 */

package edu.emory.mathcs.util.xml;

import org.xml.sax.*;
import java.io.*;
import java.util.*;

/**
 * SAX error handler that displays information of all encountered errors
 * and warnings on the specified output, System.err by default.
 *
 * @author Dawid Kurzyniec
 * @version 1.0
 */
public class ConsoleErrorHandler implements ErrorHandler {
    final String source;
    final PrintStream err;

    /**
     * Creates new console error handler.
     *
     * @param source the label for parsed source file, used for error reporting.
     */
    public ConsoleErrorHandler(String source) {
        this(source, System.err);
    }

    /**
     * Creates new console error handler that writes to the specified output.
     *
     * @param source the label for parsed source file, used for error reporting.
     * @param err the output to write to.
     */
    public ConsoleErrorHandler(String source, PrintStream err) {
        this.source = source;
        this.err = err;
    }
    public void warning(SAXParseException ex) {
        err.print("XML Parser warning: " + createMsgString(source, ex));
    }
    public void error(SAXParseException ex) {
        err.print("XML Parser error: " + createMsgString(source, ex));
    }
    public void fatalError(SAXParseException ex) {
        err.print("XML Parser fatal error: " + createMsgString(source, ex));
    }

    private static String createMsgString(String source, SAXParseException ex) {
        StringBuffer buf = new StringBuffer();
        int line = ex.getLineNumber();
        int column = ex.getColumnNumber();
        buf.append(ex.toString()).append('\n');
        buf.append("In ").append(source).append(':').append(line);
        if (column > 0) buf.append(',').append(column);
        buf.append('\n');
        return buf.toString();
    }
};
