package javakurs.musterloesung.uebung02.aufgabe2;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * {@link DomPrinter} is an auxiliary class containing a static method printXML
 * that prints a DOM to an String. The main method reads an XML file (filename
 * in arg1) into DOM and prints as String to stdout.
 *
 * @author Ulrich Schaefer, DFKI
 * @author Joerg Steffen, DFKI
 * @version $Id: DomPrinter.java,v 1.1 2010/11/11 16:51:26 steffen Exp $
 */
public final class DomPrinter {

  /**
   * This would create a new instance of {@link DomPrinter}. Not to be used.
   */
  private DomPrinter() {

    // private constructor to enforce noninstantiability
  }


  /**
   * This prints a DOM document node to an XML string using a transformer.
   *
   * @param doc
   *          an XML document} to print
   * @return the XML string
   * @throws TransformerException
   *           if there is an error when applying the transformation
   */
  public static String printXML(Document doc)
      throws TransformerException {

    // use a transformer for output
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();

    DOMSource source = new DOMSource(doc);
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    transformer.transform(source, result);
    return sw.toString();
  }


  /**
   * This reads an XML file (filename in args[0]) into a DOM document
   * and prints it to stdout.
   *
   * @param args
   *          an array containing the command line arguments, the first one
   *          containing the XML file to open
   */
  public static void main(String[] args) {

    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      factory.setValidating(true);
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document document = builder.parse(new File(args[0]));
      System.out.println(printXML(document));
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    }
  }
}
