package javakurs.musterloesung.uebung03.aufgabe2;

import java.io.File;
import java.util.Map;

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 javax.xml.transform.stream.StreamSource;

import org.w3c.dom.Document;

/**
 * {@link DomConverter} provides a method to convert a DOM document using an
 * XSL file.
 *
 * @author Joerg Steffen, DFKI
 * @version $Id: DomConverter.java,v 1.1 2010/11/18 23:06:11 steffen Exp $
 */
public final class DomConverter {

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

    // private constructor to enforce noninstantiability
  }


  /**
   * This transforms the given DOM document using the given XSL file. The result
   * is stored in the file with the given name.
   *
   * @param doc
   *          the document to transform
   * @param xslFileName
   *          the name of the XSL file
   * @param parameters
   *          the transformation parameters; {@code null} if no parameters are
   *          used
   * @param outputFileName
   *          the name of the result file
   * @throws TransformerException
   *           if there is an error when applying the transformation
   */
  public static void convert(Document doc, String xslFileName,
      Map<String, Object> parameters, String outputFileName)
      throws TransformerException {

    // read stylesheet
    StreamSource stylesheet = new StreamSource(xslFileName);
    // create transformer factory
    TransformerFactory tFactory = TransformerFactory.newInstance();
    // create transformer
    Transformer transformer = tFactory.newTransformer(stylesheet);
    // set parameters
    if (null != parameters) {
      for (Map.Entry<String, Object> oneParam : parameters.entrySet()) {
        transformer.setParameter(oneParam.getKey(), oneParam.getValue());
      }
    }
    // prepare input and output
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File(outputFileName));
    // transform
    transformer.transform(source, result);
  }
}
