hi,

attached is a modified version of file
<jakarta-taglist>/xsl/src/org/apache/taglibs/xsl/ApplyTag.java
This uses the recent API of xalan (version 2), where the old one
uses/requires xalan1compat.jar. It furthermore fixes a bug of the old
version which does not set the current directory to the context-root of
the calling webapp - this causes relative 'xsl:include' tags to fail.
Additionally this version provides instance caching for
xsl-transformer-objects. This gains 20%-30% speed for my jsp-pages here!

I would like you to try out this one. The jar is attached too for
convinience.

Stefan
-- 

 < W E B M A C H E R > 
EDV+INTERNETSERVICE GMBH

POST: August Bebel Str. 69
      04275 Leipzig

FON:  +49 341 30 34 832
FAX:  +49 341 30 34 840
WEB:  www.webmacher.de
/*
 * $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 [EMAIL PROTECTED]
 *
 * 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 java.util.HashMap;
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 javax.xml.transform.*;
import javax.xml.transform.stream.*;

/**
 * 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 {
	// ------------------------------------------------------------- Cache Instances
	static TransformerFactory tFactory = null;
	static HashMap transformerHash;

	static
	{
		transformerHash=new HashMap();
	}

    // ------------------------------------------------------------- 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 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 {

		//System.err.println("<!-- ***** ApplyTag.doStartTag() ***** -->");

	// 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 __old__doEndTag() throws JspException {

		//System.err.println("<!-- ***** ApplyTag.doEndTag() ***** -->");

		String realPath=pageContext.getServletContext().getRealPath("/");
		//if(realPath.endsWith("/")) {
		//	try {
		//		realPath=realPath.substring(0, realPath.length()-1);
		//	}
		//	catch(IndexOutOfBoundsException ioobe) { }
		//}
		System.setProperty("user.dir",realPath);
		//System.err.println("<!-- ***** application root : ["+ realPath +"] ***** -->");

		// 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();
			processor.process(data, style, result);
		}
		catch (SAXException e) {
			throw new JspException(e.toString());
		}
		return (EVAL_PAGE);
    }


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

		//System.err.println("<!-- ***** ApplyTag.doEndTag() ***** -->");

		String realPath=pageContext.getServletContext().getRealPath("/");
		//if(realPath.endsWith("/")) {
		//	try {
		//		realPath=realPath.substring(0, realPath.length()-1);
		//	}
		//	catch(IndexOutOfBoundsException ioobe) { }
		//}
		System.setProperty("user.dir",realPath);
		//System.err.println("<!-- ***** application root : ["+ realPath +"] ***** -->");

		// 1. Instantiate a TransformerFactory, if not done already
		if(tFactory==null) {
			//System.err.println("<!--  new transformerFactory -->");
			tFactory = TransformerFactory.newInstance();
		}

		// 2. Use the TransformerFactory to process the stylesheet Source and
		//    generate a Transformer.
		Long key=getKey(nameXsl, propertyXsl, xsl);
		Transformer transformer=(Transformer)transformerHash.get(key);
		if(transformer==null) {
			try {
				transformer = tFactory.newTransformer(getStreamSource(nameXsl, propertyXsl, xsl));
				transformerHash.put(key,(Object)transformer);
			}
			catch(TransformerConfigurationException tce) {
				tce.printStackTrace(System.err);
				//throw new JspException("TransformerConfigurationException");
				return(SKIP_PAGE);
			}
		}
		//else {
		//	System.err.println("<!-- *****   cached transformer okay -->");
		//}
																			  
		// 3. Use the Transformer to transform an XML Source and send the
		//    output to a Result object.
		StreamSource data = null;
		if (body != null)
			data = new StreamSource(new StringReader(body));
		else
			data = getStreamSource(nameXml, propertyXml, xml);

		try {
			transformer.transform(data,new StreamResult(pageContext.getOut()));
		}
		catch(TransformerException te) {
			te.printStackTrace(System.err);
			throw new JspException("TransformerException");
		}
		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() + "'");

    }

    /**
     * Construct and return an StreamSource 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 StreamSource getStreamSource(String name, String property,String resource)
	throws JspException {

		//System.err.println("<!-- ***** ApplyTag.getStreamSource("+name+","+property+","+resource+") -->");

		// 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 + "'");
			//System.err.println("<!-- *****   okay via resource -->");
			return new StreamSource(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());
			}
		}
		
		//System.err.println("<!-- *****   okay else -->");
		
		// Create an StreamSource for the specified source object
		if (source instanceof StreamSource)
			return ((StreamSource) source);
		else if (source instanceof String)
			return (new StreamSource(new StringReader((String) source)));
		//	else if (source instanceof InputSource)
		//	    return (new StreamSource((InputSource) source));
		else if (source instanceof InputStream)
			return (new StreamSource((InputStream) source));
		//	else if (source instanceof Node)
		//	    return (new StreamSource((Node) source));
		else if (source instanceof Reader)
			return (new StreamSource((Reader) source));
		else
			throw new JspException("Invalid input source type '" +
								   source.getClass().getName() + "'");
		
    }

	private Long getKey(String name, String property,String resource) {
		if(resource!=null) {
			return(new Long(resource.hashCode()));
		}
		else if((name!=null) && (property!=null)) {
			return(new Long((name+property).hashCode()));
		}
		return(new Long(0));
	}
}

xsl.jar

Reply via email to