Reputation: 13089
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>
Upvotes: 5
Views: 4755
Reputation: 966
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.
Upvotes: 9
Reputation: 78135
Two suggestions come to mind. First, you can access Ant properties from within the javascript. There are examples in the documentation you refer to:
var x = project.getProperty( "my.property" );
can be used in the script to get the value of a property set in the XML, perhaps like this:
<property name="my.property" value="x" />
Second, you might consider using a scriptdef
, which will allow you to define attributes and child elements that you can easily access from the javascript.
Upvotes: 2