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

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