/* ======================================================================
   Parts Copyright 2006 University of Leeds, Oxford University, University of the Highlands and Islands.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

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

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 );
     }
 }
}
