Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing parameters into ANT javascript task?

Tags:

javascript

ant

In my ANT scripts, I sometimes write tasks runnning javascript with Rhino.

However, I am at a loss as to how pass parameters into these tasks. Any ideas?

For example... here is an example of such a task:

<script language="javascript"> <![CDATA[
//some nonsense to fake out rhino into thinking we've a dom, etc.
this.document = { "fake":true };
this.window = new Object( );
this.head = new Object( );
eval(''+new String(org.apache.tools.ant.util.FileUtils.readFully(new java.io.FileReader('coolJavascript.js'))));

//... do some stuff

var s = java.io.File.separator;
var fstream = new java.io.FileWriter( ".." + s + "build" + s + "web" + s + "js" + s + "coolChangedJavascript.js" );
var out = new java.io.BufferedWriter( fstream );
out.write( jsCode );
out.close( );
]]> </script>
like image 654
jedierikb Avatar asked Jan 10 '13 19:01

jedierikb


1 Answers

For using scripting to define an ant task you can use the scriptdef task instead of script. With scriptdef there are predefined objects to access the attributes and nested elements in your task.

This works for accessing attributes from javascript in Ant:

<scriptdef name="myFileCheck" language="javascript">
    <attribute name="myAttribute" />
    <![CDATA[
      importClass(java.io.File);
      importClass(java.io.FileReader);
      importClass(java.io.BufferedReader);
      var fileName = attributes.get("myAttribute"); //get attribute for scriptdef
      var reader = new BufferedReader(new FileReader(new File(fileName)));
      //... etc
      project.setProperty("my.result", result));
    ]]> 
</scriptdef>

Then can just go: <myFileCheck myAttribute="./some.file" /> same as you would for a regular ant task.
Also possible to use filesets etc if you want, more details at: http://ant.apache.org/manual/Tasks/scriptdef.html

The nice thing is you can define your tasks inline in your ant script, instead of writing them in Java then having to build and include the class files.

You will need to use Java1.6 (or later), or have apache BSF in your classpath.

like image 115
Tim Avatar answered Oct 23 '22 00:10

Tim