Script

Description

Execute a script in a Apache BSF supported language.

Note: This task depends on external libraries not included in the Ant distribution. See Library Dependencies for more information.

All items (tasks, targets, etc) of the running project are accessible from the script, using either their name or id attributes (as long as their names are considered valid Java identifiers, that is). The name "project" is a pre-defined reference to the Project, which can be used instead of the project name. The name "self" is a pre-defined reference to the actual <script>-Task instance.
From these objects you have access to the Ant Java API, see the JavaDoc (especially for Project and Script) for more information.

If you are using JavaScript a good resource is http://www.mozilla.org/rhino/doc.html as we are using their JavaScript interpreter.

Scripts can do almost anything a task written in Java could do.

Rhino provides a special construct - the JavaAdapter. With that you can create an object which implements several interfaces, extends classes and for which you can overwrite methods. Because this is an undocumented feature (yet), here is the link to an explanation: Groups@Google: "Rhino, enum.js, JavaAdapter?" by Norris Boyd in the newsgroup netscape.public.mozilla.jseng.

Parameters

Attribute Description Required
language The programming language the script is written in. Must be a supported Apache BSF language Yes
src The location of the script as a file, if not inline No

Examples

The following snippet shows use of five different languages:
    <property name="message" value="Hello world"/>

    <script language="groovy">
      println("message is " + message)
    </script>

    <script language="beanshell">
      System.out.println("message is " + message);
    </script>

    <script language="judoscript">
        println 'message is ', message
    </script>

    <script language="ruby">
        print 'message is ', $message, "\n"
    </script>

    <script language="jython">
print "message is %s" % message
    </script>

Note that for the jython example, the script contents must start on the first column.

The following script shows a little more complicated jruby example:

<script language="ruby">
  xmlfiles = Dir.new(".").entries.delete_if { |i| ! (i =~ /\.xml$/) }
  xmlfiles.sort.each { |i| $self.log(i) }
</script>

The same example in groovy is:

<script language="groovy">
  xmlfiles = new java.io.File(".").listFiles().findAll{ it =~ "\.xml$"}
  xmlfiles.sort().each { self.log(it.toString())}
</script>

The following script uses javascript to create a number of echo tasks and execute them.

<project name="squares" default="main" basedir=".">

  <target name="main">

    <script language="javascript"> <![CDATA[

      for (i=1; i<=10; i++) {
        echo = squares.createTask("echo");
        echo.setMessage(i*i);
        echo.perform();
      }

    ]]> </script>

  </target>

</project>

generates

main:
1
4
9
16
25
36
49
64
81
100

BUILD SUCCESSFUL

Another example, using references by id and two different scripting languages:

<project name="testscript" default="main">
  <target name="sub">
    <echo id="theEcho"/>
  </target>

  <target name="sub1">
    <script language="netrexx"><![CDATA[
      theEcho.setMessage("In sub1")
      sub.execute
    ]]></script>
  </target>

  <target name="sub2">
    <script language="javascript"><![CDATA[
      theEcho.setMessage("In sub2");
      sub.execute();
    ]]></script>
  </target>

  <target name="main" depends="sub1,sub2"/>
</project>

generates

sub1:
In sub1

sub2:
In sub2

main:

BUILD SUCCESSFUL

Now a more complex example using the Java API and the Ant API. The goal is to list the filesizes of all files a <fileset/> caught.


<?xml version="1.0" encoding="ISO-8859-1"?>
<project name="MyProject" basedir="." default="main">

  <property name="fs.dir" value="src"/>
  <property name="fs.includes" value="**/*.txt"/>
  <property name="fs.excludes" value="**/*.tmp"/>

  <target name="main">
    <script language="javascript"> <![CDATA[

      // import statements
      // importPackage(java.io);
      importClass(java.io.File);

      // Access to Ant-Properties by their names
      dir      = project.getProperty("fs.dir");
      includes = MyProject.getProperty("fs.includes");
      excludes = self.getProject()  .getProperty("fs.excludes");

      // Create a <fileset dir="" includes=""/>
      fs = project.createDataType("fileset");
      fs.setDir( new File(dir) );
      fs.setIncludes(includes);
      fs.setExcludes(excludes);

      // Get the files (array) of that fileset
      ds = fs.getDirectoryScanner(project);
      srcFiles = ds.getIncludedFiles();

      // iterate over that array
      for (i=0; i<srcFiles.length; i++) {

        // get the values via Java API
        var basedir  = fs.getDir(project);
        var filename = srcFiles[i];
        var file = new File(basedir, filename);
        var size = file.length();

        // create and use a Task via Ant API
        echo = MyProject.createTask("echo");
        echo.setMessage(filename + ": " + size + " byte");
        echo.perform();
      }
    ]]></script>
  </target>
</project>

We want to use the Java API. Because we don't want always typing the package signature we do an import. Rhino knows two different methods for import statements: one for packages and one for a single class. By default only the java packages are available, so java.lang.System can be directly imported with importClass/importPackage. For other packages you have to prefix the full classified name with Packages. For example Ant's FileUtils class can be imported with importClass(Packages.org.apache.tools.ant.util.FileUtils)
The <script> task populates the Project instance under the name project, so we can use that reference. Another way is to use its given name or getting its reference from the task itself.
The Project provides methods for accessing and setting properties, creating DataTypes and Tasks and much more.
After creating a FileSet object we initialize that by calling its set-methods. Then we can use that object like a normal Ant task (<copy> for example).
For getting the size of a file we instantiate a java.io.File. So we are using normal Java API here.
Finally we use the <echo> task for producing the output. The task is not executed by its execute() method, because the perform() method (implemented in Task itself) does the appropriate logging before and after invoking execute().


Copyright © 2000-2004 The Apache Software Foundation. All rights Reserved.