PageRenderTime 58ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/apache-ant-1.10.2-bin/apache-ant-1.10.2/manual/tutorial-writing-tasks.html

https://bitbucket.org/xcsolutionsqa/dpmc_selenium
HTML | 819 lines | 656 code | 147 blank | 16 comment | 0 complexity | f20b030e8efc5b9fa16c5275ea8f53cb MD5 | raw file
Possible License(s): Apache-2.0
  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. <title>Tutorial: Writing Tasks</title>
  18. <link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
  19. </head>
  20. <body>
  21. <h1>Tutorial: Writing Tasks</h1>
  22. <p>This document provides a step by step tutorial for writing
  23. tasks.</p>
  24. <h2>Content</h2>
  25. <ul>
  26. <li><a href="#buildenvironment">Set up the build environment</a></li>
  27. <li><a href="#write1">Write the Task</a></li>
  28. <li><a href="#use1">Use the Task</a></li>
  29. <li><a href="#TaskAdapter">Integration with TaskAdapter</a></li>
  30. <li><a href="#derivingFromTask">Deriving from Apache Ant's Task</a></li>
  31. <li><a href="#accessTaskProject">Accessing the Task's Project</a></li>
  32. <li><a href="#attributes">Attributes</a></li>
  33. <li><a href="#NestedText">Nested Text</a></li>
  34. <li><a href="#NestedElements">Nested Elements</a></li>
  35. <li><a href="#complex">Our task in a little more complex version</a></li>
  36. <li><a href="#TestingTasks">Test the Task</a></li>
  37. <li><a href="#Debugging">Debugging</a></li>
  38. <li><a href="#resources">Resources</a></li>
  39. </ul>
  40. <a name="buildenvironment"></a>
  41. <h2>Set up the build environment</h2>
  42. <p>Apache Ant builds itself, we are using Ant too (why we would write
  43. a task if not? :-) therefore we should use Ant for our build.</p>
  44. <p>We choose a directory as root directory. All things will be done
  45. here if I say nothing different. I will reference this directory
  46. as <i>root-directory</i> of our project. In this root-directory we
  47. create a text file names <i>build.xml</i>. What should Ant do for us?</p>
  48. <ul>
  49. <li>compiles my stuff</li>
  50. <li>make the jar, so that I can deploy it</li>
  51. <li>clean up everything</li>
  52. </ul>
  53. So the buildfile contains three targets.
  54. <pre class="code">
  55. &lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
  56. &lt;project name="MyTask" basedir="." default="jar"&gt;
  57. &lt;target name="clean" description="Delete all generated files"&gt;
  58. &lt;delete dir="classes"/&gt;
  59. &lt;delete file="MyTasks.jar"/&gt;
  60. &lt;/target&gt;
  61. &lt;target name="compile" description="Compiles the Task"&gt;
  62. &lt;javac srcdir="src" destdir="classes"/&gt;
  63. &lt;/target&gt;
  64. &lt;target name="jar" description="JARs the Task"&gt;
  65. &lt;jar destfile="MyTask.jar" basedir="classes"/&gt;
  66. &lt;/target&gt;
  67. &lt;/project&gt;
  68. </pre>
  69. This buildfile uses often the same value (src, classes, MyTask.jar), so we should rewrite that
  70. using <code>&lt;property&gt;</code>s. On second there are some handicaps: <code>&lt;javac&gt;</code> requires that the destination
  71. directory exists; a call of "clean" with a non existing classes directory will fail; "jar" requires
  72. the execution of some steps before. So the refactored code is:
  73. <pre class="code">
  74. &lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
  75. &lt;project name="MyTask" basedir="." default="jar"&gt;
  76. <b>&lt;property name="src.dir" value="src"/&gt;</b>
  77. <b>&lt;property name="classes.dir" value="classes"/&gt;</b>
  78. &lt;target name="clean" description="Delete all generated files"&gt;
  79. &lt;delete dir="<b>${classes.dir}</b>" <b>failonerror="false"</b>/&gt;
  80. &lt;delete file="<b>${ant.project.name}.jar</b>"/&gt;
  81. &lt;/target&gt;
  82. &lt;target name="compile" description="Compiles the Task"&gt;
  83. <b>&lt;mkdir dir="${classes.dir}"/&gt;</b>
  84. &lt;javac srcdir="<b>${src.dir}</b>" destdir="${classes.dir}"/&gt;
  85. &lt;/target&gt;
  86. &lt;target name="jar" description="JARs the Task" <b>depends="compile"</b>&gt;
  87. &lt;jar destfile="${ant.project.name}.jar" basedir="${classes.dir}"/&gt;
  88. &lt;/target&gt;
  89. &lt;/project&gt;
  90. </pre>
  91. <i>ant.project.name</i> is one of the
  92. <a href="http://ant.apache.org/manual/properties.html#built-in-props" target="_blank">
  93. build-in properties [1]</a> of Ant.
  94. <a name="write1"></a>
  95. <h2>Write the Task</h2>
  96. Now we write the simplest Task - a HelloWorld-Task (what else?). Create a text file
  97. <i>HelloWorld.java</i> in the src-directory with:
  98. <pre class="code">
  99. public class HelloWorld {
  100. public void execute() {
  101. System.out.println("Hello World");
  102. }
  103. }
  104. </pre>
  105. and we can compile and jar it with <tt>ant</tt> (default target is "jar" and via
  106. its <i>depends</i>-clause the "compile" is executed before).
  107. <a name="use1"></a>
  108. <h2>Use the Task</h2>
  109. <p>But after creating the jar we want to use our new Task. Therefore we need a
  110. new target "use". Before we can use our new task we have to declare it with
  111. <a href="http://ant.apache.org/manual/Tasks/taskdef.html" target="_blank">
  112. <code>&lt;taskdef&gt;</code> [2]</a>. And for easier process we change the default clause:</p>
  113. <pre class="code">
  114. &lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
  115. &lt;project name="MyTask" basedir="." default="<b>use</b>"&gt;
  116. ...
  117. <b>&lt;target name="use" description="Use the Task" depends="jar"&gt;
  118. &lt;taskdef name="helloworld" classname="HelloWorld" classpath="${ant.project.name}.jar"/&gt;
  119. &lt;helloworld/&gt;
  120. &lt;/target&gt;</b>
  121. &lt;/project&gt;
  122. </pre>
  123. <p>Important is the <i>classpath</i>-attribute. Ant searches in its /lib directory for
  124. tasks and our task isn't there. So we have to provide the right location. </p>
  125. <p>Now we can type in <tt>ant</tt> and all should work ...</p>
  126. <pre class="output">
  127. Buildfile: build.xml
  128. compile:
  129. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\classes
  130. [javac] Compiling 1 source file to C:\tmp\anttests\MyFirstTask\classes
  131. jar:
  132. [jar] Building jar: C:\tmp\anttests\MyFirstTask\MyTask.jar
  133. use:
  134. [helloworld] Hello World
  135. BUILD SUCCESSFUL
  136. Total time: 3 seconds
  137. </pre>
  138. <a name="TaskAdapter"></a>
  139. <h2>Integration with TaskAdapter</h2>
  140. <p>Our class has nothing to do with Ant. It extends no superclass and implements
  141. no interface. How does Ant know to integrate? Via name convention: our class provides
  142. a method with signature <tt>public void execute()</tt>. This class is wrapped by Ant's
  143. <tt>org.apache.tools.ant.TaskAdapter</tt> which is a task and uses reflection for
  144. setting a reference to the project and calling the <i>execute()</i> method.</p>
  145. <p><i>Setting a reference to the project</i>? Could be interesting. The Project class
  146. gives us some nice abilities: access to Ant's logging facilities getting and setting
  147. properties and much more. So we try to use that class:</p>
  148. <pre class="code">
  149. import org.apache.tools.ant.Project;
  150. public class HelloWorld {
  151. private Project project;
  152. public void setProject(Project proj) {
  153. project = proj;
  154. }
  155. public void execute() {
  156. String message = project.getProperty("ant.project.name");
  157. project.log("Here is project '" + message + "'.", Project.MSG_INFO);
  158. }
  159. }
  160. </pre>
  161. and the execution with <tt>ant</tt> will show us the expected
  162. <pre class="output">
  163. use:
  164. Here is project 'MyTask'.
  165. </pre>
  166. <a name="derivingFromTask"></a>
  167. <h2>Deriving from Ant's Task</h2>
  168. <p>Ok, that works ... But usually you will extend <tt>org.apache.tools.ant.Task</tt>.
  169. That class is integrated in Ant, get's the project-reference, provides documentation
  170. fields, provides easier access to the logging facility and (very useful) gives you
  171. the exact location where <i>in the buildfile</i> this task instance is used.</p>
  172. <p>Oki-doki - let's us use some of these:</p>
  173. <pre class="code">
  174. import org.apache.tools.ant.Task;
  175. public class HelloWorld extends Task {
  176. public void execute() {
  177. // use of the reference to Project-instance
  178. String message = getProject().getProperty("ant.project.name");
  179. // Task's log method
  180. log("Here is project '" + message + "'.");
  181. // where this task is used?
  182. log("I am used in: " + getLocation() );
  183. }
  184. }
  185. </pre>
  186. <p>which gives us when running</p>
  187. <pre class="output">
  188. use:
  189. [helloworld] Here is project 'MyTask'.
  190. [helloworld] I am used in: C:\tmp\anttests\MyFirstTask\build.xml:23:
  191. </pre>
  192. <a name="accessTaskProject"></a>
  193. <h2>Accessing the Task's Project</h2>
  194. <p>The parent project of your custom task may be accessed through method <code>getProject()</code>. However, do not call this from the custom task constructor, as the return value will be null. Later, when node attributes or text are set, or method <code>execute()</code> is called, the Project object is available.</p>
  195. <p>Here are two useful methods from class Project:</p>
  196. <ul>
  197. <li><code>String getProperty(String propertyName)</code></li>
  198. <li>
  199. <code>String replaceProperties(String value)</code>
  200. </li>
  201. </ul>
  202. <p>The method <code>replaceProperties()</code> is discussed further in section <a href="#NestedText">Nested Text</a>.</p>
  203. <a name="attributes"></a>
  204. <h2>Attributes</h2>
  205. <p>Now we want to specify the text of our message (it seems that we are
  206. rewriting the <code>&lt;echo/&gt;</code> task :-). First we well do that with an attribute.
  207. It is very easy - for each attribute provide a <tt>public void set<code>&lt;attributename&gt;</code>(<code>&lt;type&gt;</code>
  208. newValue)</tt> method and Ant will do the rest via reflection.</p>
  209. <pre class="code">
  210. import org.apache.tools.ant.Task;
  211. import org.apache.tools.ant.BuildException;
  212. public class HelloWorld extends Task {
  213. String message;
  214. public void setMessage(String msg) {
  215. message = msg;
  216. }
  217. public void execute() {
  218. if (message==null) {
  219. throw new BuildException("No message set.");
  220. }
  221. log(message);
  222. }
  223. }
  224. </pre>
  225. <p>Oh, what's that in execute()? Throw a <i>BuildException</i>? Yes, that's the usual
  226. way to show Ant that something important is missed and complete build should fail. The
  227. string provided there is written as build-failes-message. Here it's necessary because
  228. the log() method can't handle a <i>null</i> value as parameter and throws a NullPointerException.
  229. (Of course you can initialize the <i>message</i> with a default string.)</p>
  230. <p>After that we have to modify our buildfile:</p>
  231. <pre class="code">
  232. &lt;target name="use" description="Use the Task" depends="jar"&gt;
  233. &lt;taskdef name="helloworld"
  234. classname="HelloWorld"
  235. classpath="${ant.project.name}.jar"/&gt;
  236. &lt;helloworld <b>message="Hello World"</b>/&gt;
  237. &lt;/target&gt;
  238. </pre>
  239. <p>That's all.</p>
  240. <p>Some background for working with attributes: Ant supports any of these datatypes as
  241. arguments of the set-method:</p><ul>
  242. <li>elementary data type like <i>int</i>, <i>long</i>, ...</li>
  243. <li>its wrapper classes like <i>java.lang.Integer</i>, <i>java.lang.Long</i>, ...</li>
  244. <li><i>java.lang.String</i></li>
  245. <li>some more classes (e.g. <i>java.io.File</i>; see
  246. <a href="develop.html#set-magic">Manual
  247. 'Writing Your Own Task' [3]</a>)</li>
  248. <li>Any Java Object parsed from Ant 1.8's <a href="Tasks/propertyhelper.html">Property
  249. Helper</a></li>
  250. </ul>
  251. Before calling the set-method all properties are resolved. So a <tt>&lt;helloworld message="${msg}"/&gt;</tt>
  252. would not set the message string to "${msg}" if there is a property "msg" with a set value.
  253. <a name="NestedText"></a>
  254. <h2>Nested Text</h2>
  255. <p>Maybe you have used the <code>&lt;echo&gt;</code> task in a way like <tt>&lt;echo&gt;Hello World&lt;/echo&gt;</tt>.
  256. For that you have to provide a <tt>public void addText(String text)</tt> method.</p>
  257. <pre class="code">
  258. ...
  259. public class HelloWorld extends Task {
  260. private String message;
  261. ...
  262. public void addText(String text) {
  263. message = text;
  264. }
  265. ...
  266. }
  267. </pre>
  268. <p>But here properties are <b>not</b> resolved! For resolving properties we have to use
  269. Project's <tt>replaceProperties(String propname) : String</tt> method which takes the
  270. property name as argument and returns its value (or ${propname} if not set).</p>
  271. <p>Thus, to replace properties in the nested node text, our method <code>addText()</code> can be written as:</p>
  272. <pre class="code">
  273. public void addText(String text) {
  274. message = getProject().replaceProperties(text);
  275. }
  276. </pre>
  277. <a name="NestedElements"></a>
  278. <h2>Nested Elements</h2>
  279. <p>There are several ways for inserting the ability of handling nested elements. See
  280. the <a href="http://ant.apache.org/manual/develop.html#nested-elements">Manual [4]</a> for other.
  281. We use the first way of the three described ways. There are several steps for that:</p><ol>
  282. <li>We create a class for collecting all the info the nested element should contain.
  283. This class is created by the same rules for attributes and nested elements
  284. as for the task (<code>set&lt;attributename&gt;</code>() methods). </li>
  285. <li>The task holds multiple instances of this class in a list.</li>
  286. <li>A factory method instantiates an object, saves the reference in the list
  287. and returns it to Ant Core.</li>
  288. <li>The execute() method iterates over the list and evaluates its values.</li>
  289. </ol>
  290. <pre class="code">
  291. import java.util.Vector;
  292. import java.util.Iterator;
  293. ...
  294. public void execute() {
  295. if (message!=null) log(message);
  296. for (Iterator it=messages.iterator(); it.hasNext(); ) { <b>// 4</b>
  297. Message msg = (Message)it.next();
  298. log(msg.getMsg());
  299. }
  300. }
  301. Vector messages = new Vector(); <b>// 2</b>
  302. public Message createMessage() { <b>// 3</b>
  303. Message msg = new Message();
  304. messages.add(msg);
  305. return msg;
  306. }
  307. public class Message { <b>// 1</b>
  308. public Message() {}
  309. String msg;
  310. public void setMsg(String msg) { this.msg = msg; }
  311. public String getMsg() { return msg; }
  312. }
  313. ...
  314. </pre>
  315. <p>Then we can use the new nested element. But where is xml-name for that defined?
  316. The mapping XML-name : classname is defined in the factory method:
  317. <tt>public <i>classname</i> create<i>XML-name</i>()</tt>. Therefore we write in
  318. the buildfile</p>
  319. <pre class="code">
  320. &lt;helloworld&gt;
  321. &lt;message msg="Nested Element 1"/&gt;
  322. &lt;message msg="Nested Element 2"/&gt;
  323. &lt;/helloworld&gt;
  324. </pre>
  325. <p>Note that if you choose to use methods 2 or 3, the class that represents the nested
  326. element must be declared as <code>static</code></p>
  327. <a name="complex"></a>
  328. <h2>Our task in a little more complex version</h2>
  329. <p>For recapitulation now a little refactored buildfile:</p>
  330. <pre class="code">
  331. &lt;?xml version="1.0" encoding="ISO-8859-1"?&gt;
  332. &lt;project name="MyTask" basedir="." default="use"&gt;
  333. &lt;property name="src.dir" value="src"/&gt;
  334. &lt;property name="classes.dir" value="classes"/&gt;
  335. &lt;target name="clean" description="Delete all generated files"&gt;
  336. &lt;delete dir="${classes.dir}" failonerror="false"/&gt;
  337. &lt;delete file="${ant.project.name}.jar"/&gt;
  338. &lt;/target&gt;
  339. &lt;target name="compile" description="Compiles the Task"&gt;
  340. &lt;mkdir dir="${classes.dir}"/&gt;
  341. &lt;javac srcdir="${src.dir}" destdir="${classes.dir}"/&gt;
  342. &lt;/target&gt;
  343. &lt;target name="jar" description="JARs the Task" depends="compile"&gt;
  344. &lt;jar destfile="${ant.project.name}.jar" basedir="${classes.dir}"/&gt;
  345. &lt;/target&gt;
  346. &lt;target name="use.init"
  347. description="Taskdef the HelloWorld-Task"
  348. depends="jar"&gt;
  349. &lt;taskdef name="helloworld"
  350. classname="HelloWorld"
  351. classpath="${ant.project.name}.jar"/&gt;
  352. &lt;/target&gt;
  353. &lt;target name="use.without"
  354. description="Use without any"
  355. depends="use.init"&gt;
  356. &lt;helloworld/&gt;
  357. &lt;/target&gt;
  358. &lt;target name="use.message"
  359. description="Use with attribute 'message'"
  360. depends="use.init"&gt;
  361. &lt;helloworld message="attribute-text"/&gt;
  362. &lt;/target&gt;
  363. &lt;target name="use.fail"
  364. description="Use with attribute 'fail'"
  365. depends="use.init"&gt;
  366. &lt;helloworld fail="true"/&gt;
  367. &lt;/target&gt;
  368. &lt;target name="use.nestedText"
  369. description="Use with nested text"
  370. depends="use.init"&gt;
  371. &lt;helloworld&gt;nested-text&lt;/helloworld&gt;
  372. &lt;/target&gt;
  373. &lt;target name="use.nestedElement"
  374. description="Use with nested 'message'"
  375. depends="use.init"&gt;
  376. &lt;helloworld&gt;
  377. &lt;message msg="Nested Element 1"/&gt;
  378. &lt;message msg="Nested Element 2"/&gt;
  379. &lt;/helloworld&gt;
  380. &lt;/target&gt;
  381. &lt;target name="use"
  382. description="Try all (w/out use.fail)"
  383. depends="use.without,use.message,use.nestedText,use.nestedElement"
  384. /&gt;
  385. &lt;/project&gt;
  386. </pre>
  387. And the code of the task:
  388. <pre class="code">
  389. import org.apache.tools.ant.Task;
  390. import org.apache.tools.ant.BuildException;
  391. import java.util.Vector;
  392. import java.util.Iterator;
  393. /**
  394. * The task of the tutorial.
  395. * Print a message or let the build fail.
  396. * @since 2003-08-19
  397. */
  398. public class HelloWorld extends Task {
  399. /** The message to print. As attribute. */
  400. String message;
  401. public void setMessage(String msg) {
  402. message = msg;
  403. }
  404. /** Should the build fail? Defaults to <i>false</i>. As attribute. */
  405. boolean fail = false;
  406. public void setFail(boolean b) {
  407. fail = b;
  408. }
  409. /** Support for nested text. */
  410. public void addText(String text) {
  411. message = text;
  412. }
  413. /** Do the work. */
  414. public void execute() {
  415. // handle attribute 'fail'
  416. if (fail) throw new BuildException("Fail requested.");
  417. // handle attribute 'message' and nested text
  418. if (message!=null) log(message);
  419. // handle nested elements
  420. for (Iterator it=messages.iterator(); it.hasNext(); ) {
  421. Message msg = (Message)it.next();
  422. log(msg.getMsg());
  423. }
  424. }
  425. /** Store nested 'message's. */
  426. Vector messages = new Vector();
  427. /** Factory method for creating nested 'message's. */
  428. public Message createMessage() {
  429. Message msg = new Message();
  430. messages.add(msg);
  431. return msg;
  432. }
  433. /** A nested 'message'. */
  434. public class Message {
  435. // Bean constructor
  436. public Message() {}
  437. /** Message to print. */
  438. String msg;
  439. public void setMsg(String msg) { this.msg = msg; }
  440. public String getMsg() { return msg; }
  441. }
  442. }
  443. </pre>
  444. And it works:
  445. <pre class="output">
  446. C:\tmp\anttests\MyFirstTask&gt;ant
  447. Buildfile: build.xml
  448. compile:
  449. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\classes
  450. [javac] Compiling 1 source file to C:\tmp\anttests\MyFirstTask\classes
  451. jar:
  452. [jar] Building jar: C:\tmp\anttests\MyFirstTask\MyTask.jar
  453. use.init:
  454. use.without:
  455. use.message:
  456. [helloworld] attribute-text
  457. use.nestedText:
  458. [helloworld] nested-text
  459. use.nestedElement:
  460. [helloworld]
  461. [helloworld]
  462. [helloworld]
  463. [helloworld]
  464. [helloworld] Nested Element 1
  465. [helloworld] Nested Element 2
  466. use:
  467. BUILD SUCCESSFUL
  468. Total time: 3 seconds
  469. C:\tmp\anttests\MyFirstTask&gt;ant use.fail
  470. Buildfile: build.xml
  471. compile:
  472. jar:
  473. use.init:
  474. use.fail:
  475. BUILD FAILED
  476. C:\tmp\anttests\MyFirstTask\build.xml:36: Fail requested.
  477. Total time: 1 second
  478. C:\tmp\anttests\MyFirstTask&gt;
  479. </pre>
  480. Next step: test ...
  481. <a name="TestingTasks"></a>
  482. <h2>Test the Task</h2>
  483. <p>We have written a test already: the use.* tasks in the buildfile. But its
  484. difficult to test that automatically. Common (and in Ant) used is JUnit for
  485. that. For testing tasks Ant provides a JUnit Rule <tt>org.apache.tools.ant.BuildFileRule</tt>.
  486. This class provides some for testing tasks useful methods:
  487. initialize Ant, load a buildfile, execute targets, capturing debug and run logs ...</p>
  488. <p>In Ant it is usual that the testcase has the same name as the task with a prepending
  489. <i>Test</i>, therefore we will create a file <i>HelloWorldTest.java</i>. Because we
  490. have a very small project we can put this file into <i>src</i> directory (Ant's own
  491. testclasses are in /src/testcases/...). Because we have already written our tests
  492. for "hand-test" we can use that for automatic tests, too. But there is one little
  493. problem we have to solve: all test supporting classes are not part of the binary
  494. distribution of Ant. So you can build the special jar file from source distro with
  495. target "test-jar" or you can download a nightly build from
  496. <a href="http://gump.covalent.net/jars/latest/ant/ant-testutil.jar">
  497. http://gump.covalent.net/jars/latest/ant/ant-testutil.jar [5]</a>.</p>
  498. <p>For executing the test and creating a report we need the optional tasks <code>&lt;junit&gt;</code>
  499. and <code>&lt;junitreport&gt;</code>. So we add to the buildfile:</p>
  500. <pre class="code">
  501. ...
  502. <font color="#9F9F9F">&lt;project name="MyTask" basedir="." </font>default="test"<font color="#9F9F9F">&gt;</font>
  503. ...
  504. &lt;property name="ant.test.lib" value="ant-testutil.jar"/&gt;
  505. &lt;property name="report.dir" value="report"/&gt;
  506. &lt;property name="junit.out.dir.xml" value="${report.dir}/junit/xml"/&gt;
  507. &lt;property name="junit.out.dir.html" value="${report.dir}/junit/html"/&gt;
  508. &lt;path id="classpath.run"&gt;
  509. &lt;path path="${java.class.path}"/&gt;
  510. &lt;path location="${ant.project.name}.jar"/&gt;
  511. &lt;/path&gt;
  512. &lt;path id="classpath.test"&gt;
  513. &lt;path refid="classpath.run"/&gt;
  514. &lt;path location="${ant.test.lib}"/&gt;
  515. &lt;/path&gt;
  516. &lt;target name="clean" description="Delete all generated files"&gt;
  517. &lt;delete failonerror="false" includeEmptyDirs="true"&gt;
  518. &lt;fileset dir="." includes="${ant.project.name}.jar"/&gt;
  519. &lt;fileset dir="${classes.dir}"/&gt;
  520. &lt;fileset dir="${report.dir}"/&gt;
  521. &lt;/delete&gt;
  522. &lt;/target&gt;
  523. <font color="#9F9F9F">&lt;target name="compile" description="Compiles the Task"&gt;
  524. &lt;mkdir dir="${classes.dir}"/&gt;
  525. &lt;javac srcdir="${src.dir}" destdir="${classes.dir}" </font>classpath="${ant.test.lib}"<font color="#9F9F9F">/&gt;
  526. &lt;/target&gt;</font>
  527. ...
  528. &lt;target name="junit" description="Runs the unit tests" depends="jar"&gt;
  529. &lt;delete dir="${junit.out.dir.xml}"/&gt;
  530. &lt;mkdir dir="${junit.out.dir.xml}"/&gt;
  531. &lt;junit printsummary="yes" haltonfailure="no"&gt;
  532. &lt;classpath refid="classpath.test"/&gt;
  533. &lt;formatter type="xml"/&gt;
  534. &lt;batchtest fork="yes" todir="${junit.out.dir.xml}"&gt;
  535. &lt;fileset dir="${src.dir}" includes="**/*Test.java"/&gt;
  536. &lt;/batchtest&gt;
  537. &lt;/junit&gt;
  538. &lt;/target&gt;
  539. &lt;target name="junitreport" description="Create a report for the rest result"&gt;
  540. &lt;mkdir dir="${junit.out.dir.html}"/&gt;
  541. &lt;junitreport todir="${junit.out.dir.html}"&gt;
  542. &lt;fileset dir="${junit.out.dir.xml}"&gt;
  543. &lt;include name="*.xml"/&gt;
  544. &lt;/fileset&gt;
  545. &lt;report format="frames" todir="${junit.out.dir.html}"/&gt;
  546. &lt;/junitreport&gt;
  547. &lt;/target&gt;
  548. &lt;target name="test"
  549. depends="junit,junitreport"
  550. description="Runs unit tests and creates a report"
  551. /&gt;
  552. ...
  553. </pre>
  554. <p>Back to the <i>src/HelloWorldTest.java</i>. We create a class with a public
  555. <i>BuildFileRule</i> field annotated with JUnit's <i>@Rule</i> annotation. As per
  556. conventional JUnit4 tests, this class should have no constructors, or a default no-args
  557. constructor, setup methods should be annotated with <i>@Before</i>, tear down methods
  558. annotated with <i>@After</i> and any test method annotated with <i>@Test</i>.
  559. <pre class="code">
  560. import org.apache.tools.ant.BuildFileRule;
  561. import org.junit.Assert;
  562. import org.junit.Test;
  563. import org.junit.Before;
  564. import org.junit.Rule;
  565. import org.apache.tools.ant.AntAssert;
  566. import org.apache.tools.ant.BuildException;
  567. public class HelloWorldTest {
  568. @Rule
  569. public final BuildFileRule buildRule = new BuildFileRule();
  570. @Before
  571. public void setUp() {
  572. // initialize Ant
  573. buildRule.configureProject("build.xml");
  574. }
  575. @Test
  576. public void testWithout() {
  577. buildRule.executeTarget("use.without");
  578. assertEquals("Message was logged but should not.", buildRule.getLog(), "");
  579. }
  580. public void testMessage() {
  581. // execute target 'use.nestedText' and expect a message
  582. // 'attribute-text' in the log
  583. buildRule.executeTarget("use.message");
  584. Assert.assertEquals("attribute-text", buildRule.getLog());
  585. }
  586. @Test
  587. public void testFail() {
  588. // execute target 'use.fail' and expect a BuildException
  589. // with text 'Fail requested.'
  590. try {
  591. buildRule.executeTarget("use.fail");
  592. fail("BuildException should have been thrown as task was set to fail");
  593. } catch (BuildException ex) {
  594. Assert.assertEquals("fail requested", ex.getMessage());
  595. }
  596. }
  597. @Test
  598. public void testNestedText() {
  599. buildRule.executeTarget("use.nestedText");
  600. Assert.assertEquals("nested-text", buildRule.getLog());
  601. }
  602. @Test
  603. public void testNestedElement() {
  604. buildRule.executeTarget("use.nestedElement");
  605. AntAssert.assertContains("Nested Element 1", buildRule.getLog());
  606. AntAssert.assertContains("Nested Element 2", buildRule.getLog());
  607. }
  608. }
  609. </pre>
  610. <p>When starting <tt>ant</tt> we'll get a short message to STDOUT and
  611. a nice HTML-report.</p>
  612. <pre class="output">
  613. C:\tmp\anttests\MyFirstTask&gt;ant
  614. Buildfile: build.xml
  615. compile:
  616. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\classes
  617. [javac] Compiling 2 source files to C:\tmp\anttests\MyFirstTask\classes
  618. jar:
  619. [jar] Building jar: C:\tmp\anttests\MyFirstTask\MyTask.jar
  620. junit:
  621. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\report\junit\xml
  622. [junit] Running HelloWorldTest
  623. [junit] Tests run: 5, Failures: 0, Errors: 0, Time elapsed: 2,334 sec
  624. junitreport:
  625. [mkdir] Created dir: C:\tmp\anttests\MyFirstTask\report\junit\html
  626. [junitreport] Using Xalan version: Xalan Java 2.4.1
  627. [junitreport] Transform time: 661ms
  628. test:
  629. BUILD SUCCESSFUL
  630. Total time: 7 seconds
  631. C:\tmp\anttests\MyFirstTask&gt;
  632. </pre>
  633. <a name="Debugging"></a>
  634. <h2>Debugging</h2>
  635. <p>Try running Ant with the flag <code>-verbose</code>. For more information, try flag <code>-debug</code>.</p>
  636. <p>For deeper issues, you may need to run the custom task code in a Java debugger. First, get the source for Ant and build it with debugging information.</p>
  637. <p>Since Ant is a large project, it can be a little tricky to set the right breakpoints. Here are two important breakpoints for version 1.8:</p>
  638. <ul>
  639. <li>Initial <code>main()</code> function: <code>com.apache.tools.ant.launch.Launcher.main()</code></li>
  640. <li>Task entry point: <code>com.apache.tools.ant.UnknownElement.execute()</code></li>
  641. </ul>
  642. <p>If you need to debug when a task attribute or the text is set, begin by debugging into method <code>execute()</code> of your custom task. Then set breakpoints in other methods. This will ensure the class byte-code has been loaded by the Java VM.</p>
  643. <a name="resources"></a>
  644. <h2>Resources</h2>
  645. <p>This tutorial and its resources are available via
  646. <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=22570">BugZilla [6]</a>.
  647. The ZIP provided there contains</p><ul>
  648. <li>this initial version of this tutorial</li>
  649. <li>the buildfile (last version)</li>
  650. <li>the source of the task (last version)</li>
  651. <li>the source of the unit test (last version)</li>
  652. <li>the ant-testutil.jar (nightly build of 2003-08-18)</li>
  653. <li>generated classes</li>
  654. <li>generated jar</li>
  655. <li>generated reports</li>
  656. </ul>
  657. <p>The last sources and the buildfile are also available
  658. <a href="tutorial-writing-tasks-src.zip">here [7]</a> inside the manual.
  659. </p>
  660. <p>Used Links:<br />
  661. &nbsp;&nbsp;[1] <a href="http://ant.apache.org/manual/properties.html#built-in-props">http://ant.apache.org/manual/properties.html#built-in-props</a><br />
  662. &nbsp;&nbsp;[2] <a href="http://ant.apache.org/manual/Tasks/taskdef.html">http://ant.apache.org/manual/Tasks/taskdef.html</a><br />
  663. &nbsp;&nbsp;[3] <a href="http://ant.apache.org/manual/develop.html#set-magic">http://ant.apache.org/manual/develop.html#set-magic</a><br />
  664. &nbsp;&nbsp;[4] <a href="http://ant.apache.org/manual/develop.html#nested-elements">http://ant.apache.org/manual/develop.html#nested-elements</a><br />
  665. &nbsp;&nbsp;[5] <a href="http://gump.covalent.net/jars/latest/ant/ant-testutil.jar">http://gump.covalent.net/jars/latest/ant/ant-testutil.jar</a><br />
  666. &nbsp;&nbsp;[6] <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=22570">http://issues.apache.org/bugzilla/show_bug.cgi?id=22570</a><br />
  667. &nbsp;&nbsp;[7] <a href="tutorial-writing-tasks-src.zip">tutorial-writing-tasks-src.zip</a><br />
  668. </p>
  669. </body>
  670. </html>