bodewig 2003/02/06 06:19:50
Modified: docs/manual/CoreTasks Tag: ANT_15_BRANCH style.html
src/main/org/apache/tools/ant/taskdefs Tag: ANT_15_BRANCH
XSLTProcess.java
src/main/org/apache/tools/ant/taskdefs/optional Tag:
ANT_15_BRANCH TraXLiaison.java
Log:
Merge fixes for bugs 13859 and 16809 from HEAD
Revision Changes Path
No revision
No revision
1.18.2.7 +34 -26 jakarta-ant/docs/manual/CoreTasks/style.html
Index: style.html
===================================================================
RCS file: /home/cvs/jakarta-ant/docs/manual/CoreTasks/style.html,v
retrieving revision 1.18.2.6
retrieving revision 1.18.2.7
diff -u -r1.18.2.6 -r1.18.2.7
--- style.html 29 Jun 2002 15:36:14 -0000 1.18.2.6
+++ style.html 6 Feb 2003 14:19:50 -0000 1.18.2.7
@@ -23,13 +23,13 @@
want to use default exclusions or not. See the section on <a
href="../dirtasks.html#directorybasedtasks">directory based tasks</a>, on
how the
inclusion/exclusion of files works, and how to write patterns.</p>
-<p>This task forms an implicit <a
href="../CoreTypes/fileset.html">FileSet</a> and supports all
- attributes of <code><fileset></code> (<code>dir</code> becomes
<code>basedir</code>)
- as well as the nested <code><include></code>,
<code><exclude></code>
+<p>This task forms an implicit <a
href="../CoreTypes/fileset.html">FileSet</a> and supports all
+ attributes of <code><fileset></code> (<code>dir</code> becomes
<code>basedir</code>)
+ as well as the nested <code><include></code>,
<code><exclude></code>
and <code><patternset></code> elements.</p>
-<p>This task supports the use of a nested <param> element which is
used to pass values
+<p>This task supports the use of a nested <param> element which is
used to pass values
to an <xsl:param> declaration.</p>
-<p>This task supports the use of a nested <a
href="../CoreTypes/xmlcatalog.html">xmlcatalog</a>
+<p>This task supports the use of a nested <a
href="../CoreTypes/xmlcatalog.html">xmlcatalog</a>
element which is used to perform Entity and URI resolution</p>
<p><i><style> and <xslt> refer to the same Ant task and can be
used interchangeably.</i></p>
<p>If you want to use Xalan-J 1 or XSL:P, you also need Ant's
optional.jar</p>
@@ -54,7 +54,7 @@
</tr>
<tr>
<td valign="top">extension</td>
- <td valign="top">desired file extension to be used for the targets. If
not
+ <td valign="top">desired file extension to be used for the targets. If
not
specified, the default is ".html".</td>
<td align="center" valign="top">No</td>
</tr>
@@ -68,7 +68,7 @@
<td align="center" valign="top">Yes</td>
</tr>
<tr>
- <td valign="top">classpath</td>
+ <td valign="top">classpath</td>
<td valign="top">the classpath to use when looking up the XSLT
processor.</td>
<td align="center" valign="top">No</td>
@@ -104,25 +104,25 @@
</tr>
<tr>
<td valign="top">includes</td>
- <td valign="top">comma- or space-separated list of patterns of files
that must be included.
+ <td valign="top">comma- or space-separated list of patterns of files
that must be included.
All files are included when omitted.</td>
<td valign="top" align="center">No</td>
</tr>
<tr>
<td valign="top">includesfile</td>
- <td valign="top">the name of a file. Each line of this file is taken to
be
+ <td valign="top">the name of a file. Each line of this file is taken to
be
an include pattern</td>
<td valign="top" align="center">No</td>
</tr>
<tr>
<td valign="top">excludes</td>
- <td valign="top">comma- or space-separated list of patterns of files
that must be excluded.
+ <td valign="top">comma- or space-separated list of patterns of files
that must be excluded.
No files (except default excludes) are excluded when omitted.</td>
<td valign="top" align="center">No</td>
</tr>
<tr>
<td valign="top">excludesfile</td>
- <td valign="top">the name of a file. Each line of this file is taken to
be
+ <td valign="top">the name of a file. Each line of this file is taken to
be
an exclude pattern</td>
<td valign="top" align="center">No</td>
</tr>
@@ -134,13 +134,13 @@
</tr>
<tr>
<td valign="top">in</td>
- <td valign="top">specifies a single XML document to be styled. Should be
used
+ <td valign="top">specifies a single XML document to be styled. Should be
used
with the out attribute.</td>
<td valign="top" align="center">No</td>
</tr>
<tr>
<td valign="top">out</td>
- <td valign="top">specifies the output name for the styled result from
the
+ <td valign="top">specifies the output name for the styled result from the
in attribute.</td>
<td valign="top" align="center">No</td>
</tr>
@@ -151,34 +151,42 @@
directories. Default is <code>true</code></td>
<td valign="top" align="center">No</td>
</tr>
+ <tr>
+ <td valign="top">reloadstylesheet</td>
+ <td valign="top">Control whether the stylesheet transformer is created
+ anew for every transform opertaion. If you set this to true, performance
may
+ suffer, but you may work around a bug in certain Xalan-J versions.
+ Default is <code>false</code>. <em>Since Ant 1.5.2</em>.</td>
+ <td valign="top" align="center">No</td>
+ </tr>
</table>
<h3>Parameters specified as nested elements</h3>
<h4>classpath</h4>
<p>The classpath to load the processor from can be specified via a
-nested <code><classpath></code>, as well - that is, a
+nested <code><classpath></code>, as well - that is, a
<a href="../using.html#path">path</a>-like structure.</p>
<h4>xmlcatalog</h4>
-<p>The <a href="../CoreTypes/xmlcatalog.html">xmlcatalog</a>
+<p>The <a href="../CoreTypes/xmlcatalog.html">xmlcatalog</a>
element is used to perform Entity and URI resolution.</p>
<h4>param</h4>
<p>Param is used to pass a parameter to the XSL stylesheet.</p>
<h4>Parameters</h4>
<table width="60%" border="1" cellpadding="2" cellspacing="0">
- <tr>
+ <tr>
<td valign="top"><b>Attribute</b></td>
<td valign="top"><b>Description</b></td>
<td align="center" valign="top"><b>Required</b></td>
</tr>
- <tr>
+ <tr>
<td valign="top">name</td>
<td valign="top">Name of the XSL parameter</td>
<td align="center" valign="top">Yes</td>
</tr>
- <tr>
+ <tr>
<td valign="top">expression</td>
- <td valign="top">XSL expression to be placed into the param. To pass a
text
+ <td valign="top">XSL expression to be placed into the param. To pass a
text
value into the style sheet it needs to be escaped using single
quotes.</td>
<td align="center" valign="top">Yes</td>
</tr>
@@ -190,17 +198,17 @@
XSLT specifications</a>.
<h4>Parameters</h4>
<table width="60%" border="1" cellpadding="2" cellspacing="0">
- <tr>
+ <tr>
<td valign="top"><b>Attribute</b></td>
<td valign="top"><b>Description</b></td>
<td align="center" valign="top"><b>Required</b></td>
</tr>
- <tr>
+ <tr>
<td valign="top">name</td>
<td valign="top">Name of the property</td>
<td align="center" valign="top">Yes</td>
</tr>
- <tr>
+ <tr>
<td valign="top">value</td>
<td valign="top">value of the property.</td>
<td align="center" valign="top">Yes</td>
@@ -221,7 +229,7 @@
<xslt basedir="doc" destdir="build/doc"
extension=".html" style="style/apache.xsl">
<xmlcatalog>
- <dtd
+ <dtd
publicId="-//ArielPartners//DTD XML Article V1.0//EN"
location="com/arielpartners/knowledgebase/dtd/article.dtd"/>
</xmlcatalog>
@@ -236,20 +244,20 @@
element <xsl:param name="date"/>, the variable
<code>$date</code> will subsequently have the value 07-01-2000.
</p>
-
+
<h4>Using output properties</h4>
<pre><xslt in="doc.xml" out="build/doc/output.xml"
style="style/apache.xsl">
<outputproperty name="method" value="xml";/>
<outputproperty name="standalone" value="yes"/>
<outputproperty name="encoding"
value="iso8859_1"/>
- <outputproperty name="indent" value="yes"/>
+ <outputproperty name="indent" value="yes"/>
</xslt></pre>
</blockquote>
<hr>
-<p align="center">Copyright © 2000-2002 Apache Software Foundation. All
rights
+<p align="center">Copyright © 2000-2003 Apache Software Foundation. All
rights
Reserved.</p>
</body>
No revision
No revision
1.43.2.7 +114 -95
jakarta-ant/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java
Index: XSLTProcess.java
===================================================================
RCS file:
/home/cvs/jakarta-ant/src/main/org/apache/tools/ant/taskdefs/XSLTProcess.java,v
retrieving revision 1.43.2.6
retrieving revision 1.43.2.7
diff -u -r1.43.2.6 -r1.43.2.7
--- XSLTProcess.java 29 Jun 2002 15:31:07 -0000 1.43.2.6
+++ XSLTProcess.java 6 Feb 2003 14:19:50 -0000 1.43.2.7
@@ -1,7 +1,7 @@
/*
* The Apache Software License, Version 1.1
*
- * Copyright (c) 2000-2002 The Apache Software Foundation. All rights
+ * Copyright (c) 2000-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -79,6 +79,7 @@
* @author <a href="mailto:[EMAIL PROTECTED]">Sam Ruby</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Russell Gold</a>
* @author <a href="mailto:[EMAIL PROTECTED]">Stefan Bodewig</a>
+ * @author <a href="mailto:[EMAIL PROTECTED]">Stephane Bailliez</a>
*
* @since Ant 1.1
*
@@ -88,63 +89,63 @@
public class XSLTProcess extends MatchingTask implements XSLTLogger {
/** destination directory */
private File destDir = null;
-
+
/** where to find the source XML file, default is the project's basedir
*/
private File baseDir = null;
-
+
/** XSL stylesheet */
private String xslFile = null;
-
+
/** extension of the files produced by XSL processing */
private String targetExtension = ".html";
/** additional parameters to be passed to the stylesheets */
private Vector params = new Vector();
-
+
/** Input XML document to be used */
private File inFile = null;
-
+
/** Output file */
private File outFile = null;
-
+
/** The name of the XSL processor to use */
private String processor;
-
+
/** Classpath to use when trying to load the XSL processor */
private Path classpath = null;
/** The Liason implementation to use to communicate with the XSL
* processor */
private XSLTLiaison liaison;
-
- /** Flag which indicates if the stylesheet has been loaded into
+
+ /** Flag which indicates if the stylesheet has been loaded into
* the processor */
private boolean stylesheetLoaded = false;
-
+
/** force output of target files even if they already exist */
private boolean force = false;
-
+
/** Utilities used for file operations */
private FileUtils fileUtils;
-
- /** XSL output method to be used */
+
+ /** XSL output properties to be used */
private Vector outputProperties = new Vector();
-
+
/** for resolving entities such as dtds */
private XMLCatalog xmlCatalog = new XMLCatalog();
-
- /** Name of the TRAX Liason class */
+
+ /** Name of the TRAX Liaison class */
private static final String TRAX_LIAISON_CLASS =
"org.apache.tools.ant.taskdefs.optional.TraXLiaison";
- /** Name of the now-deprecated XSLP Liason class */
+ /** Name of the now-deprecated XSLP Liaison class */
private static final String XSLP_LIAISON_CLASS =
"org.apache.tools.ant.taskdefs.optional.XslpLiaison";
- /** Name of the Xalan liason class */
+ /** Name of the Xalan liaison class */
private static final String XALAN_LIAISON_CLASS =
"org.apache.tools.ant.taskdefs.optional.XalanLiaison";
-
+
/**
* Whether to style all files in the included directories as well.
*
@@ -153,23 +154,41 @@
private boolean performDirectoryScan = true;
/**
+ * whether to reuse Transformer if transforming multiple files.
+ * @since 1.5.2
+ */
+ private boolean reuseLoadedStylesheet = true;
+
+ /**
* Creates a new XSLTProcess Task.
*/
public XSLTProcess() {
fileUtils = FileUtils.newFileUtils();
} //-- XSLTProcess
-
+
/**
* Whether to style all files in the included directories as well;
* optional, default is true.
- *
+ *
* @param b true if files in included directories are processed.
* @since Ant 1.5
*/
public void setScanIncludedDirectories(boolean b) {
performDirectoryScan = b;
}
-
+
+ /**
+ * Controls whether the stylesheet is reloaded for every transform
+ *
+ * <p>Setting this to true may get around a bug in certain
+ * Xalan-J versions, default is false.</p>
+ *
+ * @since Ant 1.5.2
+ */
+ public void setReloadStylesheet(boolean b) {
+ reuseLoadedStylesheet = !b;
+ }
+
/**
* Executes the task.
*
@@ -182,26 +201,26 @@
DirectoryScanner scanner;
String[] list;
String[] dirs;
-
+
if (xslFile == null) {
- throw new BuildException("no stylesheet specified", location);
+ throw new BuildException("no stylesheet specified",
getLocation());
}
-
+
try {
if (baseDir == null) {
- baseDir = project.resolveFile(".");
+ baseDir = getProject().resolveFile(".");
}
-
+
liaison = getLiaison();
-
+
// check if liaison wants to log errors using us as logger
if (liaison instanceof XSLTLoggerAware) {
((XSLTLoggerAware) liaison).setLogger(this);
}
-
+
log("Using " + liaison.getClass().toString(),
Project.MSG_VERBOSE);
-
- File stylesheet = project.resolveFile(xslFile);
+
+ File stylesheet = getProject().resolveFile(xslFile);
if (!stylesheet.exists()) {
stylesheet = fileUtils.resolveFile(baseDir, xslFile);
/*
@@ -209,23 +228,23 @@
* the wrong version has been used.
*/
if (stylesheet.exists()) {
- log("DEPRECATED - the style attribute should be relative
"
+ log("DEPRECATED - the style attribute should be relative
"
+ "to the project\'s");
log(" basedir, not the tasks\'s basedir.");
}
}
-
+
// if we have an in file and out then process them
if (inFile != null && outFile != null) {
process(inFile, outFile, stylesheet);
return;
}
-
+
/*
* if we get here, in and out have not been specified, we are
* in batch processing mode.
*/
-
+
//-- make sure Source directory exists...
if (destDir == null) {
String msg = "destdir attributes must be set!";
@@ -233,7 +252,7 @@
}
scanner = getDirectoryScanner(baseDir);
log("Transforming into " + destDir, Project.MSG_INFO);
-
+
// Process all the files marked for styling
list = scanner.getIncludedFiles();
for (int i = 0; i < list.length; ++i) {
@@ -255,7 +274,7 @@
baseDir = savedBaseDir;
}
}
-
+
/**
* Set whether to check dependencies, or always generate;
* optional, default is false.
@@ -265,9 +284,9 @@
public void setForce(boolean force) {
this.force = force;
}
-
+
/**
- * Set the base directory;
+ * Set the base directory;
* optional, default is the project's basedir.
*
* @param dir the base directory
@@ -275,10 +294,10 @@
public void setBasedir(File dir) {
baseDir = dir;
}
-
+
/**
* Set the destination directory into which the XSL result
- * files should be copied to;
+ * files should be copied to;
* required, unless <tt>in</tt> and <tt>out</tt> are
* specified.
* @param dir the name of the destination directory
@@ -286,26 +305,26 @@
public void setDestdir(File dir) {
destDir = dir;
}
-
+
/**
* Set the desired file extension to be used for the target;
- * optional, default is html.
+ * optional, default is html.
* @param name the extension to use
**/
public void setExtension(String name) {
targetExtension = name;
}
-
+
/**
* Name of the stylesheet to use - given either relative
* to the project's basedir or as an absolute path; required.
- *
+ *
* @param xslFile the stylesheet to use
*/
public void setStyle(String xslFile) {
this.xslFile = xslFile;
}
-
+
/**
* Set the optional classpath to the XSL processor
*
@@ -314,7 +333,7 @@
public void setClasspath(Path classpath) {
createClasspath().append(classpath);
}
-
+
/**
* Set the optional classpath to the XSL processor
*
@@ -322,41 +341,41 @@
*/
public Path createClasspath() {
if (classpath == null) {
- classpath = new Path(project);
+ classpath = new Path(getProject());
}
return classpath.createPath();
}
-
+
/**
* Set the reference to an optional classpath to the XSL processor
*
- * @param r the id of the Ant path instance to act as the classpath
+ * @param r the id of the Ant path instance to act as the classpath
* for loading the XSL processor
*/
public void setClasspathRef(Reference r) {
createClasspath().setRefid(r);
}
-
+
/**
* Set the name of the XSL processor to use; optional, default trax.
* Other values are "xalan" for Xalan1 and "xslp" for XSL:P, though the
- * later is strongly deprecated.
+ * later is strongly deprecated.
*
* @param processor the name of the XSL processor
*/
public void setProcessor(String processor) {
this.processor = processor;
}
-
+
/**
* Add the catalog to our internal catalog
- *
+ *
* @param xmlCatalog the XMLCatalog instance to use to look up DTDs
*/
public void addConfiguredXMLCatalog(XMLCatalog xmlCatalog) {
this.xmlCatalog.addConfiguredXMLCatalog(xmlCatalog);
}
-
+
/**
* Load processor here instead of in setProcessor - this will be
* called from within execute, so we have access to the latest
@@ -381,7 +400,7 @@
liaison = (XSLTLiaison) loadClass(proc).newInstance();
}
}
-
+
/**
* Load named class either via the system classloader or a given
* custom classloader.
@@ -394,15 +413,15 @@
if (classpath == null) {
return Class.forName(classname);
} else {
- AntClassLoader al = new AntClassLoader(project, classpath);
+ AntClassLoader al = new AntClassLoader(getProject(), classpath);
Class c = al.loadClass(classname);
AntClassLoader.initializeClass(c);
return c;
}
}
-
+
/**
- * Specifies the output name for the styled result from the
+ * Specifies the output name for the styled result from the
* <tt>in</tt> attribute; required if <tt>in</tt> is set
*
* @param outFile the output File instance.
@@ -410,9 +429,9 @@
public void setOut(File outFile){
this.outFile = outFile;
}
-
+
/**
- * specifies a single XML document to be styled. Should be used
+ * specifies a single XML document to be styled. Should be used
* with the <tt>out</tt> attribute; ; required if <tt>out</tt> is set
*
* @param inFile the input file
@@ -420,7 +439,7 @@
public void setIn(File inFile){
this.inFile = inFile;
}
-
+
/**
* Processes the given input XML file and stores the result
* in the given resultFile.
@@ -434,11 +453,11 @@
private void process(File baseDir, String xmlFile, File destDir,
File stylesheet)
throws BuildException {
-
+
String fileExt = targetExtension;
File outFile = null;
File inFile = null;
-
+
try {
long styleSheetLastModified = stylesheet.lastModified();
inFile = new File(baseDir, xmlFile);
@@ -448,10 +467,10 @@
Project.MSG_VERBOSE);
return;
}
-
+
int dotPos = xmlFile.lastIndexOf('.');
if (dotPos > 0) {
- outFile = new File(destDir,
+ outFile = new File(destDir,
xmlFile.substring(0, xmlFile.lastIndexOf('.')) +
fileExt);
} else {
outFile = new File(destDir, xmlFile + fileExt);
@@ -461,7 +480,7 @@
styleSheetLastModified > outFile.lastModified()) {
ensureDirectoryFor(outFile);
log("Processing " + inFile + " to " + outFile);
-
+
configureLiaison(stylesheet);
liaison.transform(inFile, outFile);
}
@@ -472,12 +491,12 @@
if (outFile != null) {
outFile.delete();
}
-
+
throw new BuildException(ex);
}
-
+
} //-- processXML
-
+
/**
* Process the input file to the output file with the given stylesheet.
*
@@ -486,7 +505,7 @@
* @param stylesheet the stylesheet to use.
* @exception BuildException if the processing fails.
*/
- private void process(File inFile, File outFile, File stylesheet)
+ private void process(File inFile, File outFile, File stylesheet)
throws BuildException {
try {
long styleSheetLastModified = stylesheet.lastModified();
@@ -500,7 +519,7 @@
inFile.lastModified() > outFile.lastModified() ||
styleSheetLastModified > outFile.lastModified()) {
ensureDirectoryFor(outFile);
- log("Processing " + inFile + " to " + outFile,
+ log("Processing " + inFile + " to " + outFile,
Project.MSG_INFO);
configureLiaison(stylesheet);
liaison.transform(inFile, outFile);
@@ -513,14 +532,14 @@
throw new BuildException(ex);
}
}
-
+
/**
- * Ensure the directory exists for a given file
+ * Ensure the directory exists for a given file
*
* @param targetFile the file for which the directories are required.
* @exception BuildException if the directories cannot be created.
*/
- private void ensureDirectoryFor(File targetFile)
+ private void ensureDirectoryFor(File targetFile)
throws BuildException {
File directory = fileUtils.getParentFile(targetFile);
if (!directory.exists()) {
@@ -530,7 +549,7 @@
}
}
}
-
+
/**
* Get the Liason implementation to use in processing.
*
@@ -566,7 +585,7 @@
}
return liaison;
}
-
+
/**
* Create an instance of an XSL parameter for configuration by Ant.
*
@@ -577,36 +596,36 @@
params.addElement(p);
return p;
}
-
+
/**
* The Param inner class used to store XSL parameters
*/
- public class Param {
+ public static class Param {
/** The parameter name */
private String name = null;
-
+
/** The parameter's XSL expression */
private String expression = null;
-
- /**
+
+ /**
* Set the parameter name.
- *
+ *
* @param name the name of the parameter.
*/
public void setName(String name){
this.name = name;
}
-
- /**
+
+ /**
* The XSL expression for the parameter value
*
- * @param expression the XSL expression representing the
+ * @param expression the XSL expression representing the
* parameter's value.
*/
public void setExpression(String expression){
this.expression = expression;
}
-
+
/**
* Get the parameter name
*
@@ -619,7 +638,7 @@
}
return name;
}
-
+
/**
* Get the parameter expression
*
@@ -697,7 +716,7 @@
*/
public void init() throws BuildException {
super.init();
- xmlCatalog.setProject(project);
+ xmlCatalog.setProject(getProject());
}
/**
@@ -707,11 +726,11 @@
* @exception BuildException if the stylesheet cannot be loaded.
*/
protected void configureLiaison(File stylesheet) throws BuildException {
- if (stylesheetLoaded) {
+ if (stylesheetLoaded && reuseLoadedStylesheet) {
return;
}
stylesheetLoaded = true;
-
+
try {
log("Loading stylesheet " + stylesheet, Project.MSG_INFO);
liaison.setStylesheet(stylesheet);
@@ -729,8 +748,8 @@
}
/**
- * Specific configuration for the TRaX liaison... support for
- * all other has been dropped so this liaison will soon look
+ * Specific configuration for the TRaX liaison. Support for
+ * all others has been dropped so this liaison will soon look
* like the exact copy of JAXP interface..
* @param liaison the TRaXLiaison to configure.
*/
No revision
No revision
1.17.2.5 +191 -71
jakarta-ant/src/main/org/apache/tools/ant/taskdefs/optional/TraXLiaison.java
Index: TraXLiaison.java
===================================================================
RCS file:
/home/cvs/jakarta-ant/src/main/org/apache/tools/ant/taskdefs/optional/TraXLiaison.java,v
retrieving revision 1.17.2.4
retrieving revision 1.17.2.5
diff -u -r1.17.2.4 -r1.17.2.5
--- TraXLiaison.java 31 Oct 2002 14:21:51 -0000 1.17.2.4
+++ TraXLiaison.java 6 Feb 2003 14:19:50 -0000 1.17.2.5
@@ -1,7 +1,7 @@
/*
* The Apache Software License, Version 1.1
*
- * Copyright (c) 2001-2002 The Apache Software Foundation. All rights
+ * Copyright (c) 2001-2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -54,10 +54,15 @@
package org.apache.tools.ant.taskdefs.optional;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Vector;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.util.JAXPUtils;
@@ -80,6 +85,8 @@
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.Source;
+import javax.xml.transform.SourceLocator;
+import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.URIResolver;
import javax.xml.transform.sax.SAXSource;
@@ -97,13 +104,19 @@
/** The trax TransformerFactory */
private TransformerFactory tfactory = null;
- /** stylesheet stream, close it asap */
- private FileInputStream xslStream = null;
+ /** stylesheet to use for transformation */
+ private File stylesheet;
- /** Stylesheet template */
+ /** The In memory version of the stylesheet */
private Templates templates = null;
- /** transformer */
+ /**
+ * The modification time of the stylesheet from which the templates
+ * are read
+ */
+ private long templatesModTime;
+
+ /** transformer to use for processing files */
private Transformer transformer = null;
private XSLTLogger logger;
@@ -114,9 +127,13 @@
/** possible resolver for URIs */
private URIResolver uriResolver;
+ /** transformer output properties */
+ private Vector outputProperties = new Vector();
+
+ /** stylesheet parameters */
+ private Vector params = new Vector();
+
public TraXLiaison() throws Exception {
- tfactory = TransformerFactory.newInstance();
- tfactory.setErrorListener(this);
}
@@ -126,12 +143,11 @@
* this method.
* @param name the output property name.
* @param value the output property value.
+ * @since Ant 1.5
*/
public void setOutputProperty(String name, String value){
- if (transformer == null){
- throw new IllegalStateException("stylesheet must be set prior to
setting the output properties");
- }
- transformer.setOutputProperty(name, value);
+ final String[] pair = new String[]{name, value};
+ outputProperties.addElement(pair);
}
//------------------- IMPORTANT
@@ -147,108 +163,101 @@
// in xsl and xml...
public void setStylesheet(File stylesheet) throws Exception {
- xslStream = new FileInputStream(stylesheet);
- StreamSource src = new StreamSource(xslStream);
- src.setSystemId(JAXPUtils.getSystemId(stylesheet));
- templates = tfactory.newTemplates(src);
- transformer = templates.newTransformer();
- transformer.setErrorListener(this);
+ if (this.stylesheet != null) {
+ // resetting the stylesheet - reset transformer
+ transformer = null;
+
+ // do we need to reset templates as well
+ if (!this.stylesheet.equals(stylesheet)
+ || (stylesheet.lastModified() != templatesModTime)) {
+ templates = null;
+ }
+ }
+ this.stylesheet = stylesheet;
}
public void transform(File infile, File outfile) throws Exception {
- FileInputStream fis = null;
- FileOutputStream fos = null;
+ if (transformer == null) {
+ createTransformer();
+ }
+
+ InputStream fis = null;
+ OutputStream fos = null;
try {
- fis = new FileInputStream(infile);
- fos = new FileOutputStream(outfile);
- // FIXME: need to use a SAXSource as the source for the transform
- // so we can plug in our own entity resolver
- Source src = null;
- if (entityResolver != null) {
- if (tfactory.getFeature(SAXSource.FEATURE)) {
- SAXParserFactory spFactory =
SAXParserFactory.newInstance();
- spFactory.setNamespaceAware(true);
- XMLReader reader =
spFactory.newSAXParser().getXMLReader();
- reader.setEntityResolver(entityResolver);
- src = new SAXSource(reader, new InputSource(fis));
- } else {
- throw new IllegalStateException("xcatalog specified, but
" +
- "parser doesn't support SAX");
- }
- } else {
- src = new StreamSource(fis);
- }
- src.setSystemId(JAXPUtils.getSystemId(infile));
+ fis = new BufferedInputStream(new FileInputStream(infile));
+ fos = new BufferedOutputStream(new FileOutputStream(outfile));
StreamResult res = new StreamResult(fos);
// not sure what could be the need of this...
res.setSystemId(JAXPUtils.getSystemId(outfile));
-
- if (uriResolver != null)
- transformer.setURIResolver(uriResolver);
-
+ Source src = getSource(fis, infile);
transformer.transform(src, res);
} finally {
// make sure to close all handles, otherwise the garbage
// collector will close them...whenever possible and
// Windows may complain about not being able to delete files.
try {
- if (xslStream != null){
- xslStream.close();
- }
- } catch (IOException ignored){}
- try {
- if (fis != null){
+ if (fis != null) {
fis.close();
}
- } catch (IOException ignored){}
+ } catch (IOException ignored) {
+ // ignore
+ }
try {
- if (fos != null){
+ if (fos != null) {
fos.close();
}
- } catch (IOException ignored){}
+ } catch (IOException ignored) {
+ // ignore
+ }
}
}
public void addParam(String name, String value){
- transformer.setParameter(name, value);
+ final String[] pair = new String[]{name, value};
+ params.addElement(pair);
}
public void setLogger(XSLTLogger l) {
logger = l;
}
-
- public void error(TransformerException e) {
+
+ public void error(TransformerException e) {
logError(e, "Error");
}
-
- public void fatalError(TransformerException e) {
+
+ public void fatalError(TransformerException e) {
logError(e, "Fatal Error");
throw new BuildException("Fatal error during transformation", e);
}
-
- public void warning(TransformerException e) {
+
+ public void warning(TransformerException e) {
logError(e, "Warning");
}
-
+
private void logError(TransformerException e, String type) {
if (logger == null) {
return;
}
-
+
StringBuffer msg = new StringBuffer();
- if (e.getLocator() != null) {
- String systemId = e.getLocator().getSystemId();
- if (systemId != null) {
- msg.append(systemId);
+ SourceLocator locator = e.getLocator();
+ if (locator != null) {
+ String systemid = locator.getSystemId();
+ if (systemid != null) {
+ String url = systemid;
+ if (url.startsWith("file:///")) {
+ url = url.substring(8);
+ }
+ msg.append(url);
} else {
msg.append("Unknown file");
}
- int line = e.getLocator().getLineNumber();
- if (line != 0) {
- msg.append(':').append(line);
- int col = e.getLocator().getColumnNumber();
- if (col != 0) {
- msg.append(':').append(col);
+ int line = locator.getLineNumber();
+ if (line != -1) {
+ msg.append(":" + line);
+ int column = locator.getColumnNumber();
+ if (column != -1) {
+ msg.append(":" + column);
}
}
}
@@ -273,6 +282,117 @@
uriResolver = aResolver;
}
+ /**
+ * Get the source instance from the stream and id of the file.
+ * @param is the stream containing the stylesheet data.
+ * @param infile the file that will be used for the systemid.
+ * @return the configured source instance matching the stylesheet.
+ * @throws Exception if there is a problem creating the source.
+ */
+ private Source getSource(InputStream is, File infile) throws Exception {
+ // todo: is this comment still relevant ??
+ // FIXME: need to use a SAXSource as the source for the transform
+ // so we can plug in our own entity resolver
+ Source src = null;
+ if (entityResolver != null) {
+ if (getFactory().getFeature(SAXSource.FEATURE)) {
+ SAXParserFactory spFactory = SAXParserFactory.newInstance();
+ spFactory.setNamespaceAware(true);
+ XMLReader reader = spFactory.newSAXParser().getXMLReader();
+ reader.setEntityResolver(entityResolver);
+ src = new SAXSource(reader, new InputSource(is));
+ } else {
+ throw new IllegalStateException("xcatalog specified, but " +
+ "parser doesn't support SAX");
+ }
+ } else {
+ src = new StreamSource(is);
+ }
+ src.setSystemId(JAXPUtils.getSystemId(infile));
+ return src;
+ }
+
+ /**
+ * Read in templates from the stylsheet
+ */
+ private void readTemplates()
+ throws IOException, TransformerConfigurationException {
+ // WARN: Don't use the StreamSource(File) ctor. It won't work with
+ // xalan prior to 2.2 because of systemid bugs.
+
+ // Use a stream so that you can close it yourself quickly
+ // and avoid keeping the handle until the object is garbaged.
+ // (always keep control), otherwise you won't be able to delete
+ // the file quickly on windows.
+ InputStream xslStream = null;
+ try {
+ xslStream
+ = new BufferedInputStream(new FileInputStream(stylesheet));
+ templatesModTime = stylesheet.lastModified();
+ StreamSource src = new StreamSource(xslStream);
+ // Always set the systemid to the source for imports, includes...
+ // in xsl and xml...
+ src.setSystemId(JAXPUtils.getSystemId(stylesheet));
+ templates = getFactory().newTemplates(src);
+ } finally {
+ if (xslStream != null) {
+ xslStream.close();
+ }
+ }
+ }
+
+ /**
+ * Create a new transformer based on the liaison settings
+ * @return the newly created and configured transformer.
+ * @throws Exception thrown if there is an error during creation.
+ * @see #setStylesheet(java.io.File)
+ * @see #addParam(java.lang.String, java.lang.String)
+ * @see #setOutputProperty(java.lang.String, java.lang.String)
+ */
+ private void createTransformer() throws Exception {
+ if (templates == null) {
+ readTemplates();
+ }
+
+ transformer = templates.newTransformer();
+
+ // configure the transformer...
+ transformer.setErrorListener(this);
+ if (uriResolver != null) {
+ transformer.setURIResolver(uriResolver);
+ }
+ for (int i = 0; i < params.size(); i++) {
+ final String[] pair = (String[]) params.elementAt(i);
+ transformer.setParameter(pair[0], pair[1]);
+ }
+ for (int i = 0; i < outputProperties.size(); i++) {
+ final String[] pair = (String[]) outputProperties.elementAt(i);
+ transformer.setOutputProperty(pair[0], pair[1]);
+ }
+ }
+
+ /**
+ * return the Transformer factory associated to this liaison.
+ * @return the Transformer factory associated to this liaison.
+ * @throws BuildException thrown if there is a problem creating
+ * the factory.
+ * @see #setFactory(String)
+ * @since Ant 1.5.2
+ */
+ private TransformerFactory getFactory() throws BuildException {
+ if (tfactory != null) {
+ return tfactory;
+ }
+ // not initialized yet, so create the factory
+ tfactory = TransformerFactory.newInstance();
+ tfactory.setErrorListener(this);
+
+ if (uriResolver != null) {
+ tfactory.setURIResolver(uriResolver);
+ }
+ return tfactory;
+ }
+
// kept for backwards compatibility
/**
* @deprecated use org.apache.tools.ant.util.JAXPUtils#getSystemId
instead