/* ======================================================================
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.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import java.util.Iterator;

// Imported TraX classes
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.Templates;

// Imported DOM classes
import org.w3c.dom.Node;

import org.apache.log4j.Logger;
import org.bodington.server.BuildingServerException;

/**
 * Provides methods for transforming XML using a specified XSL stylesheet or a
 * Templates object.
 * <p>NB: Use OutputStreams instead of Writers to preserve the required output
 * character encoding</p>
 * @author Antony Corfield; Colin Tatham
 */
public class XMLTransformer
{
    private static Logger log = Logger.getLogger( XMLTransformer.class );
    private static TransformerFactory tFactory;

    static
    {
        tFactory = TransformerFactory.newInstance();

        if ( !(tFactory.getFeature( DOMSource.FEATURE )
                        && tFactory.getFeature( DOMResult.FEATURE )) )
        {
            String message = "DOM node processing not supported - cannot continue!";
            log.error( message );
            System.exit( -1 );
        }
        
        tFactory.setURIResolver(new ClassURIResolver()); // Need this to find files on the classpath.
        
    }
    
    /**
     * Transform a Node using an XSL stylesheet contained in a File.
     * @param sourceNode Node to transform
     * @param file File containing stylesheet
     * @return transformed Node
     * @throws BuildingServerException
     */
    public static Node transform( Node sourceNode, File file )
        throws BuildingServerException
    {
        Transformer transformer = getTransformer( file.getPath() );
        return transform( sourceNode,  transformer );
    }

    /**
     * Transform a Node using an XSL stylesheet contained in a File, with parameters supplied.
     * @param sourceNode Node to transform
     * @param file File containing stylesheet
     * @param paramMap Map of parameter names and values
     * @return transformed Node
     * @throws BuildingServerException
     */
    public static Node transform( Node sourceNode, File file, Map paramMap )
        throws BuildingServerException
    {
        Transformer transformer = getTransformer( file.getPath(), paramMap );
        return transform( sourceNode, transformer );
    }

    /**
     * Transform a Node using an XSL stylesheet specified by the URL.
     * @param sourceNode Node to transform
     * @param resource URL specifying the stylesheet
     * @return transformed Node
     * @throws BuildingServerException
     */
    public static Node transform( Node sourceNode, URL resource )
        throws BuildingServerException
    {
        Transformer transformer = getTransformer( resource.getPath() );
        return transform( sourceNode, transformer );
    }

    /**
     * Transform a Node using an XSL stylesheet specified by the URL, with parameters supplied.
     * @param sourceNode Node to transform
     * @param resource URL specifying the stylesheet
     * @param paramMap Map of parameter names and values
     * @return transformed Node
     * @throws BuildingServerException
     */
    public static Node transform( Node sourceNode, URL resource, Map paramMap )
        throws BuildingServerException
    {
        Transformer transformer = getTransformer( resource.getPath(), paramMap );
        return transform( sourceNode, transformer );
    }

    /**
     * Transform a Node using an XSL located at the given path.
     * @param sourceNode Node to transform
     * @param path path to stylesheet
     * @return transformed Node
     * @throws BuildingServerException
     */
    public static Node transform( Node sourceNode, String path )
    throws BuildingServerException
    {
        Transformer transformer = getTransformer( path );
        return transform( sourceNode, transformer );
    }
    
    /**
     * Transform a Node using an XSL located at the given path, with parameters supplied.
     * @param sourceNode Node to transform
     * @param path path to stylesheet
     * @param paramMap Map of parameter names and values
     * @return transformed Node
     * @throws BuildingServerException
     */
    public static Node transform( Node sourceNode, String path, Map paramMap )
    throws BuildingServerException
    {
        Transformer transformer = getTransformer( path, paramMap );
        return transform( sourceNode, transformer );
    }

    /**
     * Transform a Node using an existing template.
     * An XSL stylesheet can be precompiled into a reusable Templates object.
     * @param sourceNode Node to transform
     * @param template precompiled template
     * @return transformed Node
     * @throws BuildingServerException
     */
    public static Node transform( Node sourceNode, Templates template )
        throws BuildingServerException
    {
        Transformer transformer = getTransformer( template );
        return transform( sourceNode, transformer );
    }

    /**
     * Transform a Node using an existing template, with parameters supplied.
     * An XSL stylesheet can be precompiled into a reusable Templates object.
     * @param sourceNode Node to transform
     * @param template precompiled template
     * @param paramMap Map of parameter names and values
     * @return transformed Node
     * @throws BuildingServerException
     */
    public static Node transform( Node sourceNode, Templates template, Map paramMap )
        throws BuildingServerException
    {
        Transformer transformer = getTransformer( template, paramMap );
        return transform( sourceNode, transformer );
    }

   
    
    /**
     * Creates a new Transformer.
     * Used for serialisation without any stylesheet for transformation.
     * @return a Transformer
     * @throws BuildingServerException
     */
    static Transformer getTransformer()
        throws BuildingServerException
    {
        try
        {
            Transformer transformer = tFactory.newTransformer();
            transformer.setErrorListener( new ErrorListener() );
            return transformer;
        }
        catch ( Exception e )
        {
            String message = "Error in creating Transformer";
            log.error( message, e );
            throw new BuildingServerException( e.getMessage(), message );
        }
    }
  
    /**
     * Creates a new Transformer for use with a specific XSL stylesheet.
     * @param path path specifying stylesheet location
     * @return a Transformer
     * @throws BuildingServerException
     */
    static Transformer getTransformer( String path )
        throws BuildingServerException
    {
        try
        {
            Transformer transformer = tFactory.newTransformer( new StreamSource( path ) );
            transformer.setErrorListener( new ErrorListener() );
            return transformer;
        }
        catch ( Exception e )
        {
            String message = "Error in creating Transformer";
            log.error( message, e );
            throw new BuildingServerException( e.getMessage(), message );
        }
    }
    
    /**
     * Creates a new Transformer for use with a specific XSL stylesheet and parameters supplied.
     * @param path path specifying stylesheet location
     * @param paramMap Map of parameter names and values
     * @return a Transformer
     * @throws BuildingServerException
     */
    static Transformer getTransformer( String path, Map paramMap )
        throws BuildingServerException
    {
        Transformer transformer = getTransformer( path );
        setTransformerParams( transformer, paramMap );
        
        return transformer;
    }
    
    /**
     * Creates a new Transformer for use with a specific XSL stylesheet.
     * @param inStream InputStream containing stylesheet
     * @return a Transformer
     * @throws BuildingServerException
     */
    static Transformer getTransformer( InputStream inStream )
        throws BuildingServerException
    {
        try
        {
            Transformer transformer = tFactory.newTransformer( new StreamSource( inStream ) );
            transformer.setErrorListener( new ErrorListener() );
            return transformer;
        }
        catch ( Exception e )
        {
            String message = "Error in creating Transformer";
            log.error( message, e );
            throw new BuildingServerException( e.getMessage(), message );
        }
    }
    
    /**
     * Creates a new Transformer for use with a specific XSL stylesheet and parameters supplied.
     * @param inStream InputStream containing stylesheet
     * @param paramMap Map of parameter names and values
     * @return a Transformer
     * @throws BuildingServerException
     */
    static Transformer getTransformer( InputStream inStream, Map paramMap )
        throws BuildingServerException
    {
        Transformer transformer = getTransformer( inStream );
        setTransformerParams( transformer, paramMap );
        
        return transformer;
    }
    
    /**
     * Creates a new Transformer configured from existing Templates object.
     * @param template template to use in Transformer configuration
     * @return a Transformer
     * @throws BuildingServerException
     */
    static Transformer getTransformer( Templates template )
        throws BuildingServerException
    {// Create Transformer object from thread safe templates object
        try
        {
            Transformer transformer = template.newTransformer();
            transformer.setErrorListener( new ErrorListener() );
            return transformer;
        }
        catch ( Exception e )
        {
            String message = "Error in creating Transformer";
            log.error( message, e );
            throw new BuildingServerException( e.getMessage(), message );
        }
    }

    /**
     * Creates a new Transformer configured from existing Templates object and parameters supplied.
     * @param template  template to use in Transformer configuration
     * @param paramMap Map of parameter names and values
     * @return a Transformer
     * @throws BuildingServerException
     */
    static Transformer getTransformer( Templates template, Map paramMap )
        throws BuildingServerException
    {
        Transformer transformer = getTransformer( template );
        setTransformerParams( transformer, paramMap );
        
        return transformer;
    }
    
    /**
     * Set the specified parameters in this transformer. 
     * @param transformer existing Transformer to configure
     * @param paramMap Map of parameter names and values
     */
    private static void setTransformerParams( Transformer transformer, Map paramMap )
    {
        //TODO: check for null paraMap, and param values?
        Iterator keys = paramMap.keySet().iterator();
        while ( keys.hasNext() )
        {
            String param = (String)keys.next();
            String value = (String)paramMap.get( param );
            transformer.setParameter( param, value );
        }
    }
    
    /**
     * Transform the Node supplied, using a preconfigured Transformer.
     * @param sourceNode  Node to transform
     * @param transformer preconfigured Transformer
     * @return transformed Node
     * @throws BuildingServerException
     */
    private static Node transform( Node sourceNode, Transformer transformer )
        throws BuildingServerException
    {
        try
        {
            // Define a DOMSource object.
            DOMSource domSource = new DOMSource( sourceNode );
            // Create an empty DOMResult for the Result.
            DOMResult domResult = new DOMResult( sourceNode.cloneNode( false ) );
            // Perform the transformation, placing the output in the DOMResult.
            transformer.transform( domSource, domResult );
            return domResult.getNode().getFirstChild();
        }
        catch ( Exception e )
        {
            String message = "Cannot transform XML node.";
            log.error( message, e );
            throw new BuildingServerException( e.getMessage(), message );
        }
    }
    

 /**
  * Create a reusable template from an XSL stylesheet contained in a File.
  * @param file File containing stylesheet
  * @return a reusable Templates object
  * @throws BuildingServerException
  */
 public static Templates createTemplate( File file )
     throws BuildingServerException
 {
     return createTemplate( new StreamSource( file ) );
 }

 /**
  * Create a reusable template from an XSL stylesheet specified by a URL.
  * @param resource URL specifying stylesheet location
  * @return a reusable Templates object
  * @throws BuildingServerException
  */
 public static Templates createTemplate( URL resource )
     throws BuildingServerException
 {
     return createTemplate( new StreamSource( resource.getPath() ) );
 }
 
 /**
  * Create a reusable template from an XSL stylesheet at the given path.
  * @param path location of stylesheet
  * @return a reusable Templates object
  * @throws BuildingServerException
  */
 public static Templates createTemplate( String path )
     throws BuildingServerException
 {
     return createTemplate( new StreamSource( path ) );
 }

 /**
  * Create a reusable template from an XSL stylesheet as an InputStream.
  * @param stream stylesheet as an InputStream
  * @return a reusable Templates object
  * @throws BuildingServerException
  */
 public static Templates createTemplate( InputStream stream )
     throws BuildingServerException
 {
     return createTemplate( new StreamSource( stream ) );
 }

 /**
  * Create a reusable template from an XSL stylesheet source.
  * @param source stylesheet source
  * @return a reusable Templates object
  * @throws BuildingServerException
  */
 private static Templates createTemplate( StreamSource source )
     throws BuildingServerException
 {
     try
     {// Create a templates object, which is the processed, thread-safe
         // representation of the stylesheet - NB. namespace?
         return tFactory.newTemplates( source );
     }
     catch ( Exception e )
     {
         String message = "Cannot create template from stylesheet";
         log.error( message, e );
         throw new BuildingServerException( e.getMessage(), message );
     }
 }
}