/*
 * $Header: /home/cvspublic/jakarta-slide/testsuite/testsuite/junit/src/org/apache/slide/testsuite/testtools/tprocessor/XMLOutput.java,v 1.12 2004/07/28 09:31:54 ib Exp $
 * $Revision: 1.12 $
 * $Date: 2004/07/28 09:31:54 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Slide", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * [Additional notices, if required by prior licensing conditions]
 *
 */

package org.apache.slide.testsuite.testtools.tprocessor;

//java
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Hashtable;
import java.util.Stack;
import org.jdom.*;
import org.jdom.output.XMLOutputter;


/**
 * Helper class to output XML fragments
 *
 * @version $Revision: 1.12 $
 */
public class XMLOutput {


    private OutputElements elements = null;
    private PrintStream xmlResult   = null;

    public XMLOutput(PrintStream out) {
        xmlResult = out;
    }

    public void writeException(Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace( new PrintWriter(sw, true) ); //autoFlush=true
        String s = sw.toString();
        writeElement("exception", s );
    }

    public void writeElement(String elementName, long value) {
        writeElement(elementName, new Long(value).toString());
    }

    public void writeElementStart(String elementName, String attrName, String attrValue) {
        Element element = new Element(elementName);
        element.getAttributes().add(getAttribute(attrName, attrValue));
        elements.push(element);
    }
    public void writeRootElementStart(String elementName) {
        elements = new OutputElements(new Element(elementName));
    }

    public void writeRootElementEnd(String elementName) {
        elements.delete();
    }

    public void writeElementStart(String elementName) {
        elements.push(new Element(elementName));
    }

    public void writeElementEnd(String elementName) {
        elements.pop();
    }


    public void writeElement(String elementName, String value) {
        elements.addElement((Element)new Element(elementName).addContent(value));
    }



    public void writeElement(String elementName, String attrName, String attrValue, String value) {
        Element element = (Element)new Element(elementName).addContent(value);
        element.getAttributes().add(getAttribute(attrName, attrValue));
        elements.addElement(element);
    }


    public void flush() {
        try {
            synchronized (xmlResult) {
                xmlResult.println();
                xmlResult.write(elements.getElementString().getBytes("UTF-8"));
                xmlResult.println();
                xmlResult.println();
            }
        } catch (java.io.IOException e) {e.printStackTrace();}

        elements.delete();
    }






    private Attribute getAttribute(String attrName, String attrValue) {
        return new Attribute(attrName, attrValue);
    }





    /**************************************************************/
    /* Inner class describe the Ouput element                     */
    /**************************************************************/
    private class OutputElement extends Stack {

        public OutputElement(Element rootElement) {
            push(rootElement);
        }

    }


    /****************************************************************/
    /* Inner class describe the Ouput elements seperated by threads */
    /****************************************************************/
    private class OutputElements {

        private Hashtable openElements = null;
        private Element   rootElement  = null;

        public OutputElements(Element root) {
            this.openElements = new Hashtable();
            this.rootElement = root;
        }

        public String getElementString() {
            return getElementString(getRootElement());
        }


        public void push(Element e) {
            if (getElement() == null) {
                openElements.put(Thread.currentThread().getName(), new OutputElement(e));
                synchronized (getRootElement()) {
                    getRootElement().getChildren().add(e);
                }
            } else {
                getElement().getChildren().add(e);
                ((OutputElement)openElements.get(Thread.currentThread().getName())).push(e);
            }
        }


        public void pop() {
            OutputElement open = ((OutputElement)openElements.get(Thread.currentThread().getName()));
            open.pop();
            if (open.isEmpty()) {
                openElements.remove(Thread.currentThread().getName());
            }
        }


        public void addElement(Element e) {
            if (getElement() == null) {
                getRootElement().getChildren().add(e);
            } else {
                getElement().getChildren().add(e);
            }
        }


        public Element getElement() {
            Element result = null;
            OutputElement outElement = (OutputElement)openElements.get(Thread.currentThread().getName());
            if (outElement == null) {
                result = null;
            } else {
                result = (Element)outElement.peek();
            }
            return result;
        }

        public Element getRootElement() {
            return rootElement;
        }


        public void delete() {
            openElements = null;
        }

        private String getElementString (Element e) {
            XMLOutputter out = new XMLOutputter(org.jdom.output.Format.getPrettyFormat());
            String result = null;

            if (e == null) return "null";

            try {
                result = out.outputString (e);
            }
            catch (Exception ex) {ex.printStackTrace();}

            return result;
        }


    }



}









