You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

script.html 14 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. <!--
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. -->
  15. <html>
  16. <head>
  17. <meta http-equiv="Content-Language" content="en-us">
  18. <link rel="stylesheet" type="text/css" href="../stylesheets/style.css">
  19. <title>Script Task</title>
  20. </head>
  21. <body>
  22. <h2 id="script">Script</h2>
  23. <h3>Description</h3>
  24. <p>Execute a script in a <a href="https://jakarta.apache.org/bsf" target="_top">Apache BSF</a>
  25. or <a href="https://jcp.org/aboutJava/communityprocess/maintenance/jsr223/223ChangeLog.html">JSR
  26. 223</a> supported language.
  27. </p>
  28. <p><strong>Note</strong>: This task depends on external libraries not included in the Apache Ant
  29. distribution. See <a href="../install.html#librarydependencies">Library Dependencies</a> for more
  30. information.</p>
  31. <p>The task may use the BSF scripting manager or the JSR 223 manager that is included in JDK 6 and
  32. higher. This is controlled by the <var>manager</var> attribute. The JSR 223 scripting manager is
  33. indicated by <q>javax</q>.</p>
  34. <p>All items (tasks, targets, etc) of the running project are accessible from the script, using
  35. either their <var>name</var> or <var>id</var> attributes (as long as their names are considered
  36. valid Java identifiers, that is). This is controlled by the <var>setbeans</var> attribute of the
  37. task. The name <code>project</code> is a pre-defined reference to the Project, which can be used
  38. instead of the project name. The name <code>self</code> is a pre-defined reference to the
  39. actual <code>&lt;script&gt;</code>-Task instance.<br/>From these objects you have access to the Ant
  40. Java API, see the <a href="../api/index.html">JavaDoc</a> (especially
  41. for <a href="../api/org/apache/tools/ant/Project.html">Project</a>
  42. and <a href="../api/org/apache/tools/ant/taskdefs/optional/Script.html">Script</a>) for more
  43. information.</p>
  44. <p>If you are using JavaScript under BSF, a good resource is <a target="_blank"
  45. href="https://www.mozilla.org/rhino/doc.html">https://www.mozilla.org/rhino/doc.html</a> as we are
  46. using their JavaScript interpreter.</p>
  47. <p>Scripts can do almost anything a task written in Java could do.</p>
  48. <p>Rhino provides a special construct&mdash;the <code>JavaAdapter</code>. With that you can create
  49. an object which implements several interfaces, extends classes and for which you can overwrite
  50. methods. Because this is an undocumented feature (yet), here is the link to an
  51. explanation: <a href="https://groups.google.com/forum/#!msg/netscape.public.mozilla.jseng/YlRQE0OvM8c/F8Mvq-XkpxcJ">Google
  52. Groups: "Rhino, enum.js, JavaAdapter?"</a> by Norris Boyd in the
  53. newsgroup <em>netscape.public.mozilla.jseng</em>.</p>
  54. <p>If you are creating Targets programmatically, make sure you set the Location to a useful value.
  55. In particular all targets should have different location values.</p>
  56. <h3>Parameters</h3>
  57. <table class="attr">
  58. <tr>
  59. <th>Attribute</th>
  60. <th>Description</th>
  61. <th>Required</th>
  62. </tr>
  63. <tr>
  64. <td>language</td>
  65. <td>The programming language the script is written in. Must be a supported Apache BSF or JSR
  66. 223 language</td>
  67. <td>Yes</td>
  68. </tr>
  69. <tr>
  70. <td>manager</td>
  71. <td>
  72. <em>Since Ant 1.7</em>. The script engine manager to use. This can have one of three
  73. values: <q>auto</q>, <q>bsf</q> or <q>javax</q>.
  74. <ul>
  75. <li><q>bsf</q> use the BSF scripting manager to run the language.</li>
  76. <li><q>javax</q> use the <code>javax.scripting</code> manager to run the language. (This
  77. will only work for JDK 6 and higher).</li>
  78. <li><q>auto</q> use the BSF engine if it exists, otherwise use
  79. the <code>javax.scripting</code> manager.</li>
  80. </ul>
  81. </td>
  82. <td>No; default is <q>auto</q></td>
  83. </tr>
  84. <tr>
  85. <td>src</td>
  86. <td>The location of the script as a file, if not inline</td>
  87. <td>No</td>
  88. </tr>
  89. <tr>
  90. <td>encoding</td>
  91. <td>The encoding of the script as a file. <em>Since Ant 1.10.2</em>.</td>
  92. <td>No; defaults to default JVM character encoding</td>
  93. </tr>
  94. <tr>
  95. <td>setbeans</td>
  96. <td>This attribute controls whether to set variables for all properties, references and targets
  97. in the running script. If this attribute is <q>false</q>, only the the <code>project</code>
  98. and <code>self</code> variables are set. If this attribute is <q>true</q> all the variables
  99. are set. <em>Since Ant 1.7</em></td>
  100. <td>No; defaults to <q>true</q></td>
  101. </tr>
  102. <tr>
  103. <td>classpath</td>
  104. <td>The classpath to pass into the script. <em>Since Ant 1.7</em></td>
  105. <td>No</td>
  106. </tr>
  107. <tr>
  108. <td>classpathref</td>
  109. <td>The classpath to use, given as a <a href="../using.html#references">reference</a> to a path
  110. defined elsewhere.
  111. <em>Since Ant 1.7</em></td>
  112. <td>No</td>
  113. </tr>
  114. </table>
  115. <h3>Parameters specified as nested elements</h3>
  116. <h4>classpath</h4>
  117. <p><em>Since Ant 1.7</em></p>
  118. <p><code>Script</code>'s <var>classpath</var> attribute is a <a href="../using.html#path">path-like
  119. structure</a> and can also be set via a nestedq <code>&lt;classpath&gt;</code> element.
  120. </p>
  121. <p>If a classpath is set, it will be used as the current thread context classloader, and as the
  122. classloader given to the BSF manager. This means that it can be used to specify the classpath
  123. containing the language implementation for BSF or for JSR 223 managers. This can be useful if one
  124. wants to keep <samp>${user.home}/.ant/lib</samp> free of lots of scripting language specific jar
  125. files.</p>
  126. <p><strong>Note</strong>: (<em>since Ant 1.7.1</em>) This classpath <em>can</em> be used to specify
  127. the location of the BSF jar file and/or languages that have engines in the BSF jar file. This
  128. includes the <q>javascript</q>, <q>jython</q>, <q>netrexx</q> and <q>jacl</q> languages.</p>
  129. <h3>Examples</h3>
  130. <p>The following snippet shows use of five different languages:</p>
  131. <pre>
  132. &lt;property name="message" value="Hello world"/&gt;
  133. &lt;script language="groovy"&gt;
  134. println("message is " + message)
  135. &lt;/script&gt;
  136. &lt;script language="beanshell"&gt;
  137. System.out.println("message is " + message);
  138. &lt;/script&gt;
  139. &lt;script language="judoscript"&gt;
  140. println 'message is ', message
  141. &lt;/script&gt;
  142. &lt;script language="ruby"&gt;
  143. print 'message is ', $message, "\n"
  144. &lt;/script&gt;
  145. &lt;script language="jython"&gt;
  146. print "message is %s" % message
  147. &lt;/script&gt;</pre>
  148. <p>Note that for the <q>jython</q> example, the script contents <strong>must</strong> start on the
  149. first column.</p>
  150. <p>Note also that for the <q>ruby</q> example, the names of the set variables are prefixed by
  151. a <q>$</q>.</p>
  152. <p>The following script shows a little more complicated JRuby example:</p>
  153. <pre>
  154. &lt;script language="ruby"&gt;
  155. xmlfiles = Dir.new(".").entries.delete_if { |i| ! (i =~ /\.xml$/) }
  156. xmlfiles.sort.each { |i| $self.log(i) }
  157. &lt;/script&gt;</pre>
  158. <p>The same example in Groovy is:</p>
  159. <pre>
  160. &lt;script language="groovy"&gt;
  161. xmlfiles = new java.io.File(".").listFiles().findAll{ it =~ "\.xml$"}
  162. xmlfiles.sort().each { self.log(it.toString()) }
  163. &lt;/script&gt;</pre>
  164. <p>The following example shows the use of classpath to specify the location of the beanshell jar
  165. file.</p>
  166. <pre>
  167. &lt;script language="beanshell" setbeans="true"&gt;
  168. &lt;classpath&gt;
  169. &lt;fileset dir="${user.home}/lang/beanshell" includes="*.jar"/&gt;
  170. &lt;/classpath&gt;
  171. System.out.println("Hello world");
  172. &lt;/script&gt;</pre>
  173. <p>
  174. The following script uses JavaScript to create a number of
  175. <code>echo</code> tasks and execute them.
  176. </p>
  177. <pre>
  178. &lt;project name=&quot;squares&quot; default=&quot;main&quot; basedir=&quot;.&quot;&gt;
  179. &lt;target name=&quot;main&quot;&gt;
  180. &lt;script language=&quot;javascript&quot;&gt; &lt;![CDATA[
  181. for (i = 1; i &lt;= 10; i++) {
  182. echo = squares.createTask(&quot;echo&quot;);
  183. echo.setMessage(i*i);
  184. echo.perform();
  185. }
  186. ]]&gt; &lt;/script&gt;
  187. &lt;/target&gt;
  188. &lt;/project&gt;</pre>
  189. <p>generates</p>
  190. <pre>
  191. main:
  192. 1
  193. 4
  194. 9
  195. 16
  196. 25
  197. 36
  198. 49
  199. 64
  200. 81
  201. 100
  202. BUILD SUCCESSFUL</pre>
  203. <p>Now a more complex example using the Java API and the Ant API. The goal is to list the file sizes
  204. of all files a <code>&lt;fileset/&gt;</code> caught.</p>
  205. <pre>
  206. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
  207. &lt;project name="<span style="color:blue">MyProject</span>" basedir="." default="main"&gt;
  208. &lt;property name="fs.dir" value="src"/&gt;
  209. &lt;property name="fs.includes" value="**/*.txt"/&gt;
  210. &lt;property name="fs.excludes" value="**/*.tmp"/&gt;
  211. &lt;target name="main"&gt;
  212. &lt;script language="javascript"&gt; &lt;![CDATA[
  213. // import statements
  214. <span style="color:blue">// importPackage(java.io)</span>;
  215. <span style="color:blue">importClass(java.io.File)</span>;
  216. // Access to Ant-Properties by their names
  217. dir = <span style="color:blue">project</span>.getProperty("fs.dir");
  218. includes = <span style="color:blue">MyProject</span>.getProperty("fs.includes");
  219. excludes = <span style="color:blue">self.getProject()</span>.<span style="color:blue">getProperty("fs.excludes")</span>;
  220. // Create a &lt;fileset dir="" includes=""/&gt;
  221. fs = project.<span style="color:blue">createDataType("fileset")</span>;
  222. fs.setDir(new File(dir));
  223. <span style="color:blue">fs.setIncludes(includes)</span>;
  224. fs.setExcludes(excludes);
  225. // Get the files (array) of that fileset
  226. ds = fs.getDirectoryScanner(project);
  227. srcFiles = ds.getIncludedFiles();
  228. // iterate over that array
  229. for (i = 0; i &lt; srcFiles.length; i++) {
  230. // get the values via Java API
  231. var basedir = fs.getDir(project);
  232. var filename = srcFiles[i];
  233. var file = <span style="color:blue">new File(basedir, filename)</span>;
  234. var size = file.length();
  235. // create and use a Task via Ant API
  236. echo = MyProject.<span style="color:blue">createTask("echo")</span>;
  237. echo.setMessage(filename + ": " + size + " byte");
  238. echo.<span style="color:blue">perform()</span>;
  239. }
  240. ]]&gt;&lt;/script&gt;
  241. &lt;/target&gt;
  242. &lt;/project&gt;</pre>
  243. <p>We want to use the Java API. Because we don't want always typing the package signature we do an
  244. import. Rhino knows two different methods for import statements: one for packages and one for a
  245. single class. By default only the <code>java</code> packages are available,
  246. so <code>java.lang.System</code> can be directly imported
  247. with <code>importClass/importPackage</code>. For other packages you have to prefix the full
  248. classified name with <strong>Packages</strong>. For example Ant's <code>FileUtils</code> class can
  249. be imported
  250. with <code>importClass(<strong>Packages</strong>.org.apache.tools.ant.util.FileUtils)</code><br/>
  251. The <code>&lt;script&gt;</code> task populates the Project instance under the
  252. name <code>project</code>, so we can use that reference. Another way is to use its given name or
  253. getting its reference from the task itself.<br/> The Project provides methods for accessing and
  254. setting properties, creating DataTypes and Tasks and much more.<br/> After creating a FileSet object
  255. we initialize that by calling its set-methods. Then we can use that object like a normal Ant task
  256. (<code>&lt;copy&gt;</code> for example).<br/> For getting the size of a file we instantiate
  257. a <code>java.io.File</code>. So we are using normal Java API here.<br/> Finally we use
  258. the <code>&lt;echo&gt;</code> task for producing the output. The task is not executed by
  259. its <code>execute()</code> method, because the <code>perform()</code> method (implemented in Task
  260. itself) does the appropriate logging before and after invoking <code>execute()</code>.</p>
  261. <p>Here is an example of using beanshell to create an Ant task. This task will add filesets and
  262. paths to a referenced path. If the path does not exist, it will be created.</p>
  263. <pre>
  264. &lt;!--
  265. Define addtopath task
  266. --&gt;
  267. &lt;script language="beanshell"&gt;
  268. import org.apache.tools.ant.Task;
  269. import org.apache.tools.ant.types.Path;
  270. import org.apache.tools.ant.types.FileSet;
  271. public class AddToPath extends Task {
  272. private Path path;
  273. public void setRefId(String id) {
  274. path = getProject().getReference(id);
  275. if (path == null) {
  276. path = new Path(getProject());
  277. getProject().addReference(id, path);
  278. }
  279. }
  280. public void add(Path c) {
  281. path.add(c);
  282. }
  283. public void add(FileSet c) {
  284. path.add(c);
  285. }
  286. public void execute() {
  287. // Do nothing
  288. }
  289. }
  290. project.addTaskDefinition("addtopath", AddToPath.class);
  291. &lt;/script&gt;</pre>
  292. <p>An example of using this task to create a path from a list of directories (using
  293. antcontrib's <a href="http://ant-contrib.sourceforge.net/tasks/tasks/for.html"> &lt;for&gt;</a>
  294. task) follows:</p>
  295. <pre>
  296. &lt;path id="main.path"&gt;
  297. &lt;fileset dir="build/classes"/&gt;
  298. &lt;/path&gt;
  299. &lt;ac:for param="ref" list="commons,fw,lps"
  300. xmlns:ac="antlib:net.sf.antcontrib"&gt;
  301. &lt;sequential&gt;
  302. &lt;addtopath refid="main.path"&gt;
  303. &lt;fileset dir="${dist.dir}/@{ref}/main"
  304. includes="**/*.jar"/&gt;
  305. &lt;/addtopath&gt;
  306. &lt;/sequential&gt;
  307. &lt;/ac:for&gt;</pre>
  308. </body>
  309. </html>