/*
 * $Id: ApplyTag.java,v 1.1 2000/07/03 19:30:00 craigmcc Exp $
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  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 acknowlegement:  
 *       "This product includes software developed by the 
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written 
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION 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 consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * [Additional notices, if required by prior licensing conditions]
 *
 */ 

package org.apache.taglibs.xsl;


import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Method;
import javax.servlet.ServletContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import org.apache.xalan.xslt.XSLTInputSource;
import org.apache.xalan.xslt.XSLTProcessor;
import org.apache.xalan.xslt.XSLTProcessorFactory;
import org.apache.xalan.xslt.XSLTResultTarget;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.util.Collection;
import java.util.Iterator;

/**
 * Apply an XSL stylesheet to an XML data source, rendering the output
 * to the writer of our JSP page.  This tag uses the Xalan XSLT processor,
 * available at <code>http://xml.apache.org</code>.
 *
 * @author Craig R. McClanahan
 * @version $Revision: 1.1 $ $Date: 2000/07/03 19:30:00 $
 */

public class ApplyTag extends BodyTagSupport {


    // ------------------------------------------------------------- Properties


    /**
     * The body content of this tag, if we are using it as the data source.
     */
    private String body = null;


    /**
     * The name of the XML data bean.
     */
    private String nameXml = null;

    public String getNameXml() {
	return (this.nameXml);
    }

    public void setNameXml(String nameXml) {
	this.nameXml = nameXml;
    }


    /**
     * The name of the XSL stylesheet bean.
     */
    private String nameXsl = null;

    public String getNameXsl() {
	return (this.nameXsl);
    }

    public void setNameXsl(String nameXsl) {
	this.nameXsl = nameXsl;
    }


    /**
     * The property of the XML data bean.
     */
    private String propertyXml = null;

    public String getPropertyXml() {
	return (this.propertyXml);
    }

    public void setPropertyXml(String propertyXml) {
	this.propertyXml = propertyXml;
    }


    /**
     * The property of the XSL stylesheet bean.
     */
    private String propertyXsl = null;

    public String getPropertyXsl() {
	return (this.propertyXsl);
    }

    public void setPropertyXsl(String propertyXsl) {
	this.propertyXsl = propertyXsl;
    }
    /**
     * The Iterator of XSL-styesheet's parameters ArrayList.
     */
    private Iterator iterator = null;

    public void setParams(Collection parameters) {
      if(parameters.size() > 0)
         iterator = parameters.iterator();
    }

    /**
     * The XML data resource.
     */
    private String xml = null;

    public String getXml() {
	return (this.xml);
    }

    public void setXml(String xml) {
	this.xml = xml;
    }


    /**
     * The XSL stylesheet resource.
     */
    private String xsl = null;

    public String getXsl() {
	return (this.xsl);
    }

    public void setXsl(String xsl) {
	this.xsl = xsl;
    }


    // --------------------------------------------------------- Public Methods


    /**
     * Validate the attributes that were specified for consistency.
     * Evaluate the body content of this tag if we will be using it as the
     * XML data source; otherwise skip it.
     *
     * @exception JspException if a JSP error occurs
     */
    public int doStartTag() throws JspException {

	// Validate the data source attributes
	if (nameXml != null) {
	    if (xml != null)
		throw new JspException
		    ("Cannot specify both 'nameXml' and 'xml'");
	} else if (propertyXml != null) {
	    throw new JspException
		("Cannot specify 'propertyXml' without 'nameXml'");
	}

	// Validate the stylesheet source attributes
	if (nameXsl != null) {
	    if (xsl != null)
		throw new JspException
		    ("Cannot specify both 'nameXsl' and 'xsl'");
	} else if (propertyXsl != null) {
	    throw new JspException
		("Cannot specify 'propertyXsl' without 'nameXsl'");
	}
	if ((nameXsl == null) && (xsl == null)) {
	    throw new JspException
		("Must specify either 'nameXsl' or 'xsl'");
	}

	// Evaluate the tag body only if we need it
	if ((nameXml == null) && (xml == null))
	    return (EVAL_BODY_TAG);
	else
	    return (SKIP_BODY);

    }


    /**
     * Save the body content that has been processed, but do not iterate.
     *
     * @exception JspException if a JSP error has occurred
     */
    public int doAfterBody() throws JspException {

	if (bodyContent == null)
	    body = "";
	else
	    body = bodyContent.getString().trim();
	return (SKIP_BODY);

    }


    /**
     * Finish up by performing the transformation and rendering the output.
     *
     * @exception JspException if a JSP exception occurs
     */
    public int doEndTag() throws JspException {

	// Prepare an input source for the data
	XSLTInputSource data = null;
	if (body != null)
	    data = new XSLTInputSource(new StringReader(body));
	else
	    data = getInputSource(nameXml, propertyXml, xml);

	// Prepare an input source for the stylesheet
	XSLTInputSource style =
	    getInputSource(nameXsl, propertyXsl, xsl);

	// Prepare an output source for the results
	XSLTResultTarget result =
	    new XSLTResultTarget(pageContext.getOut());

	// Create an XSLT processor and use it to perform the transformation
	XSLTProcessor processor = null;
	try {
	    processor = XSLTProcessorFactory.getProcessor();
            // Set a parameter value that the stylesheet can obtain.
            if(iterator != null) {
               while(iterator.hasNext()) {
                     String[] param = (String[]) iterator.next();
                     // param[0]=parameter's name, param[1]=value type, param[2]=value
                     // Set a param named in "param[0]", that the stylesheet can obtain.
                     processor.setStylesheetParam(param[0], processor.createXString(param[2]));
               } // While
            } // If
	    processor.process(data, style, result);
	} catch (SAXException e) {
	    throw new JspException(e.toString());
	}
	return (EVAL_PAGE);

    }


    /**
     * Release any allocated resources.
     */
    public void release() {

	this.body = null;

    }


    // -------------------------------------------------------- Private Methods


    /**
     * Construct and return an XSLTInputSource based on the specified
     * parameters.
     *
     * @param name Name of a bean containing the input source (or has a
     *  property that returns the input source)
     * @param property Name of a property of the specified bean that
     *  returns the input source
     * @param resource Context-relative path to an application resource
     *  that provides the input source
     *
     * @exception JspException if a JSP error occurs
     */
    private XSLTInputSource getInputSource(String name, String property,
					   String resource)
	throws JspException {


	// If the resource is specified, use that for the input source
	if (resource != null) {
	    ServletContext context = pageContext.getServletContext();
	    if (context == null)
		throw new JspException("Cannot find servlet context");
	    InputStream stream =
		context.getResourceAsStream(resource);
	    if (stream == null)
		throw new JspException("Missing resource '" + resource + "'");
	    return new XSLTInputSource(stream);
	}

	// Locate the source object
	Object source = null;
	Object bean = pageContext.findAttribute(name);
	if (bean == null)
	    throw new JspException("Missing bean '" + name + "'");
	if (property == null)
	    source = bean;
	else {
	    try {
		char first = Character.toUpperCase(property.charAt(0));
		String methodName = "get" + first + property.substring(1);
		Class paramTypes[] = new Class[0];
		Method method =
		    bean.getClass().getMethod(methodName, paramTypes);
		source = method.invoke(bean, new Object[0]);
	    } catch (Exception e) {
		throw new JspException(e.toString());
	    }
	}


	// Create an XSLTInputSource for the specified source object
	if (source instanceof XSLTInputSource)
	    return ((XSLTInputSource) source);
	else if (source instanceof String)
	    return (new XSLTInputSource(new StringReader((String) source)));
	else if (source instanceof InputSource)
	    return (new XSLTInputSource((InputSource) source));
	else if (source instanceof InputStream)
	    return (new XSLTInputSource((InputStream) source));
	else if (source instanceof Node)
	    return (new XSLTInputSource((Node) source));
	else if (source instanceof Reader)
	    return (new XSLTInputSource((Reader) source));
	else
	    throw new JspException("Invalid input source type '" +
				   source.getClass().getName() + "'");

    }


}
