/*
 * Approved for Public Release; Distribution Unlimited. Case Number 14-4275
 * Copyright 2014 The MITRE Corporation.  All rights reserved.
 */
package org.mitre.deluge;

import java.io.PrintStream;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

/**
 * A custom content handler for the SAX events.<p>
 * It basically attempts to be an identity transformation.<p>
 * Special thanks to Michael Kay for the original example of this code.<p>
 * @author James Garriss
 */
public class DelugeContentHandler implements ContentHandler
{
    private PrintStream printStream;
    
    /**
     * Default constructor.<p>
     * @param printStream The printstream used to write out the result of processing the SAX events.
     */
    public DelugeContentHandler(PrintStream printStream)
    {
        this.printStream = printStream;
    }
    
    // The start of an element (opening tag)
    @Override
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException
    {
        // Assumes elements should be represented as elements.  :-)
        printStream.print("<" + localName);
        // Blindly spit out the namespace every time
        if (!namespaceURI.isEmpty())
        {
            printStream.print(" xmlns=\"" + namespaceURI + "\"");
        }
        // Add any attributes
        for (int i=0; i<atts.getLength(); i++)
        {
            printStream.print(" " + atts.getLocalName(i) + "=\"" + atts.getValue(i) + "\"");
        }
        printStream.print(">");
    }

    // The end of an element (closing tag)
    @Override
    public void endElement(String namespaceURI, String localName, String qName) throws SAXException
    {
        printStream.print("</" + localName + ">");
    }

    // This is real data, the value of the elements
    @Override
    public void characters(char ch[], int start, int length)
            throws SAXException
    {
        String s = new String(ch);
        printStream.print(s);
    }

    // Add any PI's
    @Override
    public void processingInstruction(String target, String data) throws SAXException
    {
        printStream.println("<?" + target + " " + data + "?>");
    }
    
    // Don't care about these events for now, so ignore them.
    @Override
    public void setDocumentLocator(Locator locator) {}

    @Override
    public void startDocument() throws SAXException {}

    @Override
    public void endDocument() throws SAXException {}

    @Override
    public void startPrefixMapping(String prefix, String uri) throws SAXException {}

    @Override
    public void endPrefixMapping(String prefix) throws SAXException {}

    @Override
    public void ignorableWhitespace(char ch[], int start, int length) throws SAXException {}

    @Override
    public void skippedEntity(String name) throws SAXException {}
}
