PageRenderTime 165ms CodeModel.GetById 29ms RepoModel.GetById 2ms app.codeStats 0ms

/tools/apache-ant-1.8.4/manual/tutorial-writing-tasks.html

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