ant-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Ivan Mikushin" <i...@vismech.ru>
Subject Proposal for a new task <xslt> (different semantics than <style>)
Date Tue, 30 Jan 2001 22:17:50 GMT
I encountered a need for a new task which I named <xslt> for a number of
good reasons:
 - one may need to specify XSLT transforms not bound to basedir for the
<style> task instances
 - one may need to supply parameters to an XSL transform
 - <style> has a redundant attribute 'processor' which is unneeded when TrAX
interfaces (seems to become standard) are used
 - XSLT transforms are not necessarily used for styling: you may use it to
generate code, and whatever, so it's reasonable to name the task <xslt> and
to indicate XSLT file with 'transform' attribute.

I rewrote XSLTProcess class (mine is named XSLTProcess2) to meet these
issues (actually took XSLTProcess and changed it a little).

<xslt> task supports inner elements <env> just like <exec> task, doesn't
support 'processor' attribute, and you specify XSLT transform with
'transform' attribute.

I also added a new line to my
org/apache/tools/ant/taskdefs/default.properties file:

xslt=org.apache.tools.ant.taskdefs.XSLTProcess2


The following is the source code of XSLTProcess2

/////////////////////////////////////////////////////////////////////

package org.apache.tools.ant.taskdefs;

import org.apache.tools.ant.*;

import java.io.File;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.xml.transform.Templates;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.tools.ant.types.Environment;

public class XSLTProcess2 extends MatchingTask {

 private File destDir = null;

 private File baseDir = null;

 private File transformFile = null;

 private String targetExtension = ".html";

 private Transformer transformer = null;

 private Environment env = new Environment();

 /**
  * Creates a new XSLTProcess Task.
 **/
 public XSLTProcess2() {
 } //  XSLTProcess2

 /**
  * Executes the task.
  */
 public void execute() throws BuildException {

  DirectoryScanner scanner;
  String[]         list;
  String[]         dirs;

  if (baseDir == null)
   baseDir = project.resolveFile(".");
   //  make sure Source directory exists...
  if (destDir == null ) {
   String msg = "destdir attributes must be set!";
   throw new BuildException(msg);
  }
  scanner = getDirectoryScanner(baseDir);
  log("Transforming into "+destDir, Project.MSG_INFO);

  TransformerFactory tFactory = null;
  try {
   tFactory = TransformerFactory.newInstance();
  } catch( Throwable e ) {
   String msg = "TrAX implementation not found!";
   throw new BuildException(msg);
  }

  long styleSheetLastModified = 0;
  if (transformFile != null) {
   styleSheetLastModified = transformFile.lastModified();
   log( "Loading stylesheet " + transformFile, Project.MSG_INFO);
  } else {
   String msg = "transform attribute must be set!";
   throw new BuildException( msg );
  }

  try {
   // Create a new XSL processor with the specified stylesheet
   transformer = tFactory
    .newTemplates( new StreamSource( transformFile ) )
    .newTransformer();
   log("Using TrAX interfaces for XSLT processing", Project.MSG_VERBOSE);
   String[] vars = env.getVariables();
   if( vars != null ) {
    for (int i = 0; i < vars.length; ++i) {
     int eIndex = vars[i].indexOf( '=' );
     transformer.setParameter(
      vars[i].substring( 0, eIndex ),
      vars[i].substring( eIndex + 1 )
     );
    }
   }
  } catch (Exception ex) {
   log("Failed to read stylesheet " + transformFile, Project.MSG_INFO);
   throw new BuildException(ex);
  }

  // Process all the files marked for styling
  list = scanner.getIncludedFiles();
  for (int i = 0;i < list.length; ++i) {
   process( baseDir, list[i], destDir, styleSheetLastModified );
  }

  // Process all the directoried marked for styling
  dirs = scanner.getIncludedDirectories();
  for (int j = 0;j < dirs.length;++j) {
   list=new File(baseDir,dirs[j]).list();
   for (int i = 0;i < list.length;++i)
    process( baseDir, list[i], destDir, styleSheetLastModified );
  }
 } //  execute

 /**
  * Set the base directory.
 **/
 public void setBasedir(File dir) {
  baseDir = dir;
 } //  setSourceDir

 /**
  * Set the destination directory into which the XSL result
  * files should be copied to
  * @param dirName the name of the destination directory
 **/
 public void setDestdir(File dir) {
  destDir = dir;
 } //  setDestDir

 /**
  * Set the desired file extension to be used for the target
  * @param name the extension to use
 **/
 public void setExtension(String name) {
  targetExtension = name;
 } //  setDestDir

 /**
  * Sets the file to use for styling (*NOT* relative to baseDir).
  */
 public void setTransform(File file) {
  transformFile = file;
 }

 /**
  * Add a nested env element - an environment variable.
  */
 public void addEnv( Environment.Variable variable ) {
  env.addVariable( variable );
 }

 /**
  * Processes the given input XML file and stores the result
  * in the given resultFile.
 **/
 private void process(File baseDir, String xmlFile, File destDir,
       long styleSheetLastModified)
  throws BuildException {

  String fileExt=targetExtension;
  File   outFile=null;
  File   inFile=null;

  try {
   inFile = new File(baseDir,xmlFile);
   outFile = new
File(destDir,xmlFile.substring(0,xmlFile.lastIndexOf('.'))+fileExt);
   if (inFile.lastModified() > outFile.lastModified() ||
     styleSheetLastModified > outFile.lastModified()) {
    ensureDirectoryFor( outFile );
    //  command line status
    log("Processing " + xmlFile + " to " + outFile, Project.MSG_VERBOSE);
    transformer.transform(
     new StreamSource( inFile ),
     new StreamResult( outFile )
    );
   }
  }
  catch (Exception ex) {
   // If failed to process document, must delete target document,
   // or it will not attempt to process it the second time
   log("Failed to process " + inFile, Project.MSG_INFO);
   outFile.delete();
   throw new BuildException(ex);
  }

 } //  processXML

 private void ensureDirectoryFor( File targetFile ) throws BuildException {
  File directory = new File( targetFile.getParent() );
  if (!directory.exists()) {
   if (!directory.mkdirs()) {
    throw new BuildException("Unable to create directory: "
           + directory.getAbsolutePath() );
   }
  }
 }
} //  XSLTProcess2



Mime
View raw message