/* ======================================================================
The Bodington System Software License, Version 1.0

Copyright (c) 2001 The University of Leeds.  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 acknowledgement:  "This product includes
software developed by the University of Leeds
(http://www.bodington.org/)."  Alternately, this acknowledgement may
appear in the software itself, if and wherever such third-party
acknowledgements normally appear.

4.  The names "Bodington", "Nathan Bodington", "Bodington System",
"Bodington Open Source Project", and "The University of Leeds" must not be
used to endorse or promote products derived from this software without
prior written permission. For written permission, please contact
d.gardner@leeds.ac.uk.

5.  The name "Bodington" may not appear in the name of products derived
from this software without prior written permission of the University of
Leeds.

THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO,  TITLE,  THE IMPLIED WARRANTIES
OF QUALITY  AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
EVENT SHALL THE UNIVERSITY OF LEEDS 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 was originally created by the University of Leeds and may contain voluntary
contributions from others.  For more information on the Bodington Open Source Project, please
see http://bodington.org/

====================================================================== */

package org.bodington.xml;

import java.net.URL;
import java.io.Writer;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Map;

import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.log4j.Logger;

//import org.apache.xalan.templates.OutputProperties;
import org.apache.xml.serializer.OutputPropertiesFactory;
import org.bodington.server.BuildingServerException;

import org.w3c.dom.Node;

/**
 * Provides methods for serializing XML to a File, OutputStream or Writer.
 * Can also transform the xml prior to serialization using transformOutput methods.
 * <p>NB use OutputStreams instead of Writers to preserve the required output character encoding</p>
 * @author Antony Corfield; Colin Tatham
 */
public class XMLSerializer {

  private static Logger log = Logger.getLogger(XMLSerializer.class);
 
  /*
   * out() methods here call transformation methods in org.bodington.xml.XMLTransformer
   *  in order to do the serialisation (Identity transform).
   */
  
  public static void out(Node node, boolean omitXMLDeclaration, String filePath) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer();
      transformer.setOutputProperties( getModifiedProperties( omitXMLDeclaration) );
      serialise(node, transformer, filePath);
    }
  
  public static void out(Node node, boolean omitXMLDeclaration, OutputStream stream) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer();
      transformer.setOutputProperties( getModifiedProperties( omitXMLDeclaration) );
      serialise(node, transformer, stream);
  }

  public static void out(Node node, boolean omitXMLDeclaration, Writer writer) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer();
      transformer.setOutputProperties( getModifiedProperties( omitXMLDeclaration) );
      serialise(node, transformer, writer);
  }


  public static void out(Node node, String method, String filePath) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer();
      transformer.setOutputProperties( getDefaultProperties(method) );
      serialise(node, transformer, filePath);
    }
  
  public static void out(Node node, String method, OutputStream stream) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer();
      transformer.setOutputProperties( getDefaultProperties(method) );
      serialise(node, transformer, stream);
  }

  public static void out(Node node, String method, Writer writer) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer();
      transformer.setOutputProperties( getDefaultProperties(method) );
      serialise(node, transformer, writer);
  }

  /*
   * transformOutput() methods here call transformation methods in org.bodington.xml.XMLTransformer
   *  in order to do combined transformation and serialisation.
   */

  public static void transformOutput(Node sourceNode, URL stylesheet, String filePath) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer( stylesheet.getPath() );
      serialise(sourceNode, transformer, filePath );
    }
  
  public static void transformOutput(Node sourceNode, URL stylesheet, Map parameters, String filePath) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer( stylesheet.getPath(), parameters );
      serialise(sourceNode, transformer, filePath );
    }
  
  public static void transformOutput(Node sourceNode, URL stylesheet, OutputStream stream) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer( stylesheet.getPath() );
      serialise(sourceNode, transformer, stream);
  }
  
  public static void transformOutput(Node sourceNode, URL stylesheet, Map parameters, OutputStream stream) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer( stylesheet.getPath(), parameters );
      serialise(sourceNode, transformer, stream);
    }
  
  public static void transformOutput(Node sourceNode, URL stylesheet, Writer writer) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer( stylesheet.getPath() );
      serialise(sourceNode, transformer, writer);
  }

  public static void transformOutput(Node sourceNode, URL stylesheet, Map parameters, Writer writer) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer(stylesheet.getPath(), parameters);
      serialise(sourceNode, transformer, writer);
  }  
  
  public static void transformOutput(Node sourceNode, InputStream stylesheet, String filePath) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer( stylesheet );
      serialise(sourceNode, transformer, filePath);
  }

  public static void transformOutput(Node sourceNode, InputStream stylesheet, Map parameters, String filePath) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer( stylesheet, parameters );
      serialise(sourceNode, transformer, filePath);
  }
  
  public static void transformOutput(Node sourceNode, InputStream stylesheet, OutputStream stream) throws BuildingServerException {

    Transformer transformer = XMLTransformer.getTransformer( stylesheet );
    serialise(sourceNode, transformer, stream);
  }
  
  public static void transformOutput(Node sourceNode, InputStream stylesheet, Map parameters, OutputStream stream) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer( stylesheet, parameters );
      serialise(sourceNode, transformer, stream);
  }

  public static void transformOutput(Node sourceNode, InputStream stylesheet, Writer writer) throws BuildingServerException {

    Transformer transformer = XMLTransformer.getTransformer( stylesheet );
    serialise(sourceNode, transformer, writer);
  }
  
  public static void transformOutput(Node sourceNode, InputStream stylesheet, Map parameters, Writer writer) throws BuildingServerException {

      Transformer transformer = XMLTransformer.getTransformer( stylesheet, parameters );
      serialise(sourceNode, transformer, writer);
  }

  
  
  private static Properties getDefaultProperties(String method) throws BuildingServerException {

    method = method.toLowerCase();

    if (method.equals("xml") || method.equals("html") || method.equals("xhtml") || method.equals("text"))
      return OutputPropertiesFactory.getDefaultMethodProperties(method);
    else
    {
      log.error("Method supplied must be \"xml\", \"html\", \"xhtml\", or \"text\"");
      return OutputPropertiesFactory.getDefaultMethodProperties( "xml" );
    }
  }

  private static Properties getModifiedProperties( boolean omitXMLDeclaration ) throws BuildingServerException {

    Properties properties = getDefaultProperties( "xml" );
    if (omitXMLDeclaration)
      properties.setProperty("omit-xml-declaration", "yes");
    return properties;
  }
 
  private static void serialise(Node sourceNode, Transformer transformer, String filePath ) throws BuildingServerException {

      OutputStream stream = getFileOutputStream(filePath);
      serialise( sourceNode, transformer, new StreamResult(stream)  );
    }

  private static void serialise(Node sourceNode, Transformer transformer, OutputStream stream ) throws BuildingServerException {

      serialise( sourceNode, transformer, new StreamResult(stream) );
    }
  
  private static void serialise(Node sourceNode, Transformer transformer, Writer writer ) throws BuildingServerException {

      serialise( sourceNode, transformer, new StreamResult(writer) );
    }
  
  private static void serialise(Node sourceNode, Transformer transformer, Result result) throws BuildingServerException {

      try {
        DOMSource domSource = new DOMSource(sourceNode);
        transformer.transform(domSource, result);
      } catch (Exception e) {
        String message = "Cannot serialise XML node.";
        log.error(message, e);
        throw new BuildingServerException(e.getMessage(), message);
      } 
    }

  private static FileOutputStream getFileOutputStream(String filePath) throws BuildingServerException {

    try {
      return new FileOutputStream(filePath);
    }
    catch (IOException e) {
      String message = "Error in serializing output: (I/O error with path: " + filePath + ")";
      log.error(message);
      throw new BuildingServerException(e.getMessage(), message);
    }
  }
}