/*
 * $Id: main.java,v 1.4 2000/02/17 04:13:17 mode Exp $
 *
 * Copyright (c) 1998 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use,
 * modify and redistribute this software in source and binary code form,
 * provided that i) this copyright notice and license appear on all copies of
 * the software; and ii) Licensee does not utilize the software in a manner
 * which is disparaging to Sun.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY
 * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE
 * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
 * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS
 * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
 * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER
 * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF
 * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * This software is not designed or intended for use in on-line control of
 * aircraft, air traffic, aircraft navigation or aircraft communications; or in
 * the design, construction, operation or maintenance of any nuclear
 * facility. Licensee represents and warrants that it will not use or
 * redistribute the Software for such purposes.
 */

import java.io.*;

import org.w3c.dom.*;
import org.xml.sax.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;


public class main implements DocumentHandler
{
    //
    // Simple demonstration of using SAX event-driven APIs directly.
    //
    // This shows the most significant SAX callback APIs:
    //
    //	- The Parser class can represent an XML parser.
    //
    //	- This DocumentHandler just prints its input in more or
    //	  less the form in which the source document held it.
    //	  Almost any SAX based application will implement this.
    //
    //	- There is also an ErrorHandler implementation, which will
    //	  treat validation errors as fatal.  SAX normally ignores
    //	  such errors, even when used with a validating parser.
    //
    //
    public static void main (String argv [])
    throws IOException
    {

	if (argv.length != 1) {
	    System.err.println ("Usage: cmd filename");
	    System.exit (1);
	}

	try {

	    String uri = "file:" + new File (argv [0]).getAbsolutePath ();

	    //
	    // turn it into an in-memory object.
	    //

	    Parser		parser;

	    SAXParserFactory spf = SAXParserFactory.newInstance ();

	    String validation = System.getProperty (
    				"javax.xml.parsers.validation", "false");
	    if (validation.equalsIgnoreCase("true"))
	        spf.setValidating (true);

	    SAXParser sp = spf.newSAXParser ();
	    parser = sp.getParser ();

	    parser.setDocumentHandler (new main ());
	    parser.setErrorHandler (new MyErrorHandler ());
	    parser.parse (uri);

	} catch (SAXParseException err) {
	    System.out.println ("** Parsing error" 
		+ ", line " + err.getLineNumber ()
		+ ", uri " + err.getSystemId ());
	    System.out.println("   " + err.getMessage ());
	    
	} catch (SAXException e) {
	    Exception	x = e;
	    if (e.getException () != null)
		x = e.getException ();
	    x.printStackTrace ();

	} catch (Throwable t) {
	    t.printStackTrace ();
	}

	System.exit (0);
    }

    static class MyErrorHandler extends HandlerBase
    {
	// treat validation errors as fatal
	public void error (SAXParseException e)
	throws SAXParseException
	{
	    throw e;
	}

	// dump warnings too
	public void warning (SAXParseException err)
	throws SAXParseException
	{
	    System.out.println ("** Warning" 
		+ ", line " + err.getLineNumber ()
		+ ", uri " + err.getSystemId ());
	    System.out.println("   " + err.getMessage ());
	}
    }


    private Writer	out;


    // here are all the SAX DocumentHandler methods

    public void setDocumentLocator (Locator l)
    {
	// we'd record this if we needed to resolve relative URIs
	// in content or attributes, or wanted to give diagnostics.
    }

    public void startDocument ()
    throws SAXException
    {
	try {
	    out = new OutputStreamWriter (System.out, "UTF8");
	    emit ("<?xml version='1.0' encoding='UTF-8'?>\n");
	} catch (IOException e) {
	    throw new SAXException ("I/O error", e);
	}
    }

    public void endDocument ()
    throws SAXException
    {
	try {
	    out.write ('\n');
	    out.flush ();
	    out = null;
	} catch (IOException e) {
	    throw new SAXException ("I/O error", e);
	}
    }

    public void startElement (String tag, AttributeList attrs)
    throws SAXException
    {
	emit ("<");
	emit (tag);
	if (attrs != null) {
	    for (int i = 0; i < attrs.getLength (); i++) {
		emit (" ");
		emit (attrs.getName (i));
		emit ("\"");
		// XXX this doesn't quote '&', '<', and '"' in the
		// way it should ... needs to scan the value and
		// emit '&amp;', '&lt;', and '&quot;' respectively
		emit (attrs.getValue (i));
		emit ("\"");
	    }
	}
	emit (">");
    }

    public void endElement (String name)
    throws SAXException
    {
	emit ("</");
	emit (name);
	emit (">");
    }

    public void characters (char buf [], int offset, int len)
    throws SAXException
    {
	// NOTE:  this doesn't escape '&' and '<', but it should
	// do so else the output isn't well formed XML.  to do this
	// right, scan the buffer and write '&amp;' and '&lt' as
	// appropriate.

	try {
	    out.write (buf, offset, len);
	} catch (IOException e) {
	    throw new SAXException ("I/O error", e);
	}
    }

    public void ignorableWhitespace (char buf [], int offset, int len)
    throws SAXException
    {
	// this whitespace ignorable ... so we ignore it!

	// this callback won't be used consistently by all parsers,
	// unless they read the whole DTD.  Validating parsers will
	// use it, and currently most SAX nonvalidating ones will
	// also; but nonvalidating parsers might hardly use it,
	// depending on the DTD structure.
    }

    public void processingInstruction (String target, String data)
    throws SAXException
    {
	emit ("<?");
	emit (target);
	emit (" ");
	emit (data);
	emit ("?>");
    }

    // helpers ... wrap I/O exceptions in SAX exceptions, to
    // suit handler signature requirements
    private void emit (String s)
    throws SAXException
    {
	try {
	    out.write (s);
	    out.flush ();
	} catch (IOException e) {
	    throw new SAXException ("I/O error", e);
	}
    }
}
