package eu.osci.helper;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
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.w3c.dom.Node;


/**
 * Helper class for XML creation and handling.<br>
 * Copyright © 2010 Freie Hansestadt Bremen.<br>
 * Created by bremen online services Entwicklungs- und Betriebsgesellschaft mbH & Co. KG. <br>
 * This library (Starter Kit) can be used by anybody according to the Bremer Lizenz für freie
 * Softwarebibliotheken. The license terms can be viewed at www.osci.de or can be ordered at the
 * OSCI-Leitstelle (Die Senatorin für Finanzen, Freie Hansestadt Bremen, Postfach 10 15 40, 28015 Bremen).
 * 
 * @author A. Bastian, R. Lindemann
 */
public class XMLGeneralHelper
{

  /**
   * Returns an OutputStream including the serialised DOM node.
   * 
   * @param element The node that will be serialised.
   * @throws TransformerException
   */
  public static ByteArrayOutputStream dumpDomNode(Node element) throws TransformerException
  {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    dumpDomNode(element, out);
    return out;
  }

  /**
   * Writes the DOM node to the given OutputStream.
   * 
   * @param node The node that will be serialised.
   * @param out The OutputStream to write into.
   * @throws TransformerException
   */
  public static void dumpDomNode(Node node, OutputStream out) throws TransformerException
  {
    DOMSource domSource = new DOMSource(node);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer xform = null;
    xform = tf.newTransformer();
    xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    StreamResult tmpStreamResult = new StreamResult(out);
    xform.transform(domSource, tmpStreamResult);
  }

  /**
   * Creates a new DOM document.
   * 
   * @throws ParserConfigurationException
   */
  public static Document createDOMDocument() throws ParserConfigurationException
  {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = dbf.newDocumentBuilder();
    return builder.newDocument();
  }
}
