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.

tutorial-tasks-filesets-properties.html 42 KiB

7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  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. <link rel="stylesheet" type="text/css" href="stylesheets/style.css">
  18. <title>Tutorial: Tasks using Properties, Filesets &amp; Paths</title>
  19. </head>
  20. <body>
  21. <h1>Tutorial: Tasks using Properties, Filesets &amp; Paths</h1>
  22. <p>After reading the tutorial about <a href="tutorial-writing-tasks.html">writing tasks [1]</a> this tutorial explains
  23. how to get and set properties and how to use nested filesets and paths. Finally it explains how to contribute tasks to
  24. Apache Ant.</p>
  25. <h2>Content</h2>
  26. <ul>
  27. <li><a href="#goal">The goal</a></li>
  28. <li><a href="#buildenvironment">Build environment</a></li>
  29. <li><a href="#propertyaccess">Property access</a></li>
  30. <li><a href="#filesets">Using filesets</a></li>
  31. <li><a href="#path">Using nested paths</a></li>
  32. <li><a href="#returning-list">Returning a list</a></li>
  33. <li><a href="#documentation">Documentation</a></li>
  34. <li><a href="#contribute">Contribute the new task</a></li>
  35. <li><a href="#resources">Resources</a></li>
  36. </ul>
  37. <h2 id="goal">The goal</h2>
  38. <p>The goal is to write a task, which searches in a path for a file and saves the location of that file in a
  39. property.</p>
  40. <h2 id="buildenvironment">Build environment</h2>
  41. <p>We can use the buildfile from the other tutorial and modify it a little bit. That's the advantage of using
  42. properties&mdash;we can reuse nearly the whole script. :-)</p>
  43. <pre>
  44. &lt;?xml version="1.0" encoding="UTF-8"?&gt;
  45. &lt;project name="<b>FindTask</b>" basedir="." default="test"&gt;
  46. ...
  47. &lt;target name="use.init" description="Taskdef's the <b>Find</b>-Task" depends="jar"&gt;
  48. &lt;taskdef name="<b>find</b>" classname="<b>Find</b>" classpath="${ant.project.name}.jar"/&gt;
  49. &lt;/target&gt;
  50. <b>&lt;!-- the other use.* targets are deleted --&gt;</b>
  51. ...
  52. &lt;/project&gt;</pre>
  53. <p>The buildfile is in the
  54. archive <a href="tutorial-tasks-filesets-properties.zip">tutorial-tasks-filesets-properties.zip [2]</a>
  55. in <samp>/build.xml.01-propertyaccess</samp> (future version saved as *.02..., final version as <samp>build.xml</samp>;
  56. same for sources).</p>
  57. <h2 id="propertyaccess">Property access</h2>
  58. <p>Our first step is to set a property to a value and print the value of that property. So
  59. our scenario would be</p>
  60. <pre>
  61. &lt;find property="test" value="test-value"/&gt;
  62. &lt;find print="test"/&gt;</pre>
  63. <p>Ok, it can be rewritten with the core tasks</p>
  64. <pre>
  65. &lt;property name="test" value="test-value"/&gt;
  66. &lt;echo message="${test}"/&gt;</pre>
  67. <p>but I have to start on known ground :-)</p>
  68. <p>So what to do? Handling three attributes (<var>property</var>, <var>value</var>, <var>print</var>) and an execute
  69. method. Because this is only an introduction example I don't do much checking:</p>
  70. <pre>
  71. import org.apache.tools.ant.BuildException;
  72. public class Find extends Task {
  73. private String property;
  74. private String value;
  75. private String print;
  76. public void setProperty(String property) {
  77. this.property = property;
  78. }
  79. // setter for value and print
  80. public void execute() {
  81. if (print != null) {
  82. String propValue = <b>getProject().getProperty(print)</b>;
  83. log(propValue);
  84. } else {
  85. if (property == null) throw new BuildException("property not set");
  86. if (value == null) throw new BuildException("value not set");
  87. <b>getProject().setNewProperty(property, value)</b>;
  88. }
  89. }
  90. }</pre>
  91. <p>As said in the other tutorial, the property access is done via <code class="code">Project</code> instance. We get
  92. this instance via the public <code class="code">getProject()</code> method which we inherit
  93. from <code class="code">Task</code> (more precisely from <code class="code">ProjectComponent</code>). Reading a property
  94. is done via <code class="code">getProperty(<i>propertyname</i>)</code> (very simple, isn't it?). This property returns
  95. the value as <code>String</code> or <code>null</code> if not set.<br/> Setting a property is ... not really difficult,
  96. but there is more than one setter. You can use the <code class="code">setProperty()</code> method which will do the job
  97. as expected. But there is a golden rule in Ant: <em>properties are immutable</em>. And this method sets the property to
  98. the specified value&mdash;whether it has a value before that or not. So we use another
  99. way. <code class="code">setNewProperty()</code> sets the property only if there is no property with that name. Otherwise
  100. a message is logged.</p>
  101. <p><em>(By the way, a short explanation of Ant's "namespaces"&mdash;not to be confused with XML namespaces:
  102. an <code>&lt;antcall&gt;</code> creates a new space for property names. All properties from the caller are passed to the
  103. callee, but the callee can set its own properties without notice by the caller.)</em></p>
  104. <p>There are some other setters, too (but I haven't used them, so I can't say something to them, sorry :-)</p>
  105. <p>After putting our two line example from above into a target names <code>use.simple</code> we can call that from our
  106. test case:</p>
  107. <pre>
  108. import org.junit.Assert;
  109. import org.junit.Before;
  110. import org.junit.Rule;
  111. import org.junit.Test;
  112. import org.apache.tools.ant.BuildFileRule;
  113. public class FindTest {
  114. @Rule
  115. public final BuildFileRule buildRule = new BuildFileRule();
  116. @Before
  117. public void setUp() {
  118. configureProject("build.xml");
  119. }
  120. @Test
  121. public void testSimple() {
  122. buildRule.executeTarget("useSimple");
  123. <b>Assert.assertEquals("test-value", buildRule.getLog());</b>
  124. }
  125. }</pre>
  126. <p>and all works fine.</p>
  127. <h2 id="filesets">Using filesets</h2>
  128. <p>Ant provides a common way of bundling files: the fileset. Because you are reading this tutorial I think you know them
  129. and I don't have to spend more explanations about their usage in buildfiles. Our goal is to search for a file in
  130. path. And in this step the path is simply a fileset (or more precise: a collection of filesets). So our usage would
  131. be</p>
  132. <pre>
  133. &lt;find file="ant.jar" location="location.ant-jar"&gt;
  134. &lt;fileset dir="${ant.home}" includes="**/*.jar"/&gt;
  135. &lt;/find&gt;</pre>
  136. <p>What do we need? A task with two attributes (<var>file</var>, <var>location</var>) and nested filesets. Because we
  137. had attribute handling already explained in the example above and the handling of nested elements is described in the
  138. other tutorial, the code should be very easy:</p>
  139. <pre>
  140. public class Find extends Task {
  141. private String file;
  142. private String location;
  143. private List&lt;FileSet&gt; filesets = new ArrayList&lt;&gt;();
  144. public void setFile(String file) {
  145. this.file = file;
  146. }
  147. public void setLocation(String location) {
  148. this.location = location;
  149. }
  150. public void addFileset(FileSet fileset) {
  151. filesets.add(fileset);
  152. }
  153. public void execute() {
  154. }
  155. }</pre>
  156. <p>Ok&mdash;that task wouldn't do very much, but we can use it in the described manner without failure. In the next step
  157. we have to implement the execute method. And before that we will implement the appropriate test cases (TDD&mdash;test
  158. driven development).</p>
  159. <p>In the other tutorial we have reused the already written targets of our buildfile. Now we will configure most of the
  160. test cases via Java code (sometimes it's much easier to write a target than doing it via Java coding). What can be
  161. tested?</p>
  162. <ul>
  163. <li>invalid configuration of the task (missing file, missing location, missing fileset)</li>
  164. <li>don't find a present file</li>
  165. <li>behaviour if file can't be found</li>
  166. </ul>
  167. <p>Maybe you find some more test cases. But this is enough for now.<br/> For each of these points we create
  168. a <code class="code">testXX</code> method.</p>
  169. <pre>
  170. public class FindTest {
  171. @Rule
  172. public final BuildFileRule buildRule = new BuildFileRule();
  173. @Rule
  174. public ExpectedException tried = ExpectedException.none();
  175. ... // constructor, setUp as above
  176. @Test
  177. public void testMissingFile() {
  178. tried.expect(BuildException.class);
  179. tried.expectMessage("file not set");
  180. <b>Find find = new Find();</b>
  181. <b>find.execute();</b>
  182. }
  183. @Test
  184. public void testMissingLocation() {
  185. tried.expect(BuildException.class);
  186. tried.expectMessage("location not set");
  187. Find find = new Find();
  188. <b>find.setFile("ant.jar");</b>
  189. find.execute();
  190. }
  191. @Test
  192. public void testMissingFileset() {
  193. tried.expect(BuildException.class);
  194. tried.expectMessage("fileset not set");
  195. Find find = new Find();
  196. find.setFile("ant.jar");
  197. find.setLocation("location.ant-jar");
  198. }
  199. @Test
  200. public void testFileNotPresent() {
  201. buildRule.executeTarget("testFileNotPresent");
  202. String result = buildRule.getProject().getProperty("location.ant-jar");
  203. assertNull("Property set to wrong value.", result);
  204. }
  205. @Test
  206. public void testFilePresent() {
  207. buildRule.executeTarget("testFilePresent");
  208. String result = buildRule.getProject().getProperty("location.ant-jar");
  209. assertNotNull("Property not set.", result);
  210. assertTrue("Wrong file found.", result.endsWith("ant.jar"));
  211. }
  212. }</pre>
  213. <p>If we run this test class all test cases (except <code class="code">testFileNotPresent</code>) fail. Now we can
  214. implement our task, so that these test cases will pass.</p>
  215. <pre>
  216. protected void validate() {
  217. if (file == null) throw new BuildException("file not set");
  218. if (location == null) throw new BuildException("location not set");
  219. if (filesets.size() &lt; 1) throw new BuildException("fileset not set");
  220. }
  221. public void execute() {
  222. validate(); // 1
  223. String foundLocation = null;
  224. for (FileSet fs : filesets) { // 2
  225. DirectoryScanner ds = fs.getDirectoryScanner(getProject()); // 3
  226. for (String includedFile : ds.getIncludedFiles()) {
  227. String filename = includedFile.replace('\\','/'); // 4
  228. filename = filename.substring(filename.lastIndexOf("/") + 1);
  229. if (foundLocation == null &amp;&amp; file.equals(filename)) {
  230. File base = ds.getBasedir(); // 5
  231. File found = new File(base, includedFile);
  232. foundLocation = found.getAbsolutePath();
  233. }
  234. }
  235. }
  236. if (foundLocation != null) // 6
  237. getProject().setNewProperty(location, foundLocation);
  238. }</pre>
  239. <p>On <strong>//1</strong> we check the prerequisites for our task. Doing that in a <code class="code">validate()</code>
  240. method is a common way, because we separate the prerequisites from the real work. On <strong>//2</strong> we iterate
  241. over all nested filesets. If we don't want to handle multiple filesets, the <code class="code">addFileset()</code>
  242. method has to reject the further calls. We can get the result of a fileset via
  243. its <code class="code">DirectoryScanner</code> like done in <strong>//3</strong>. After that we create a platform
  244. independent String representation of the file path (<strong>//4</strong>, can be done in other ways of course). We have
  245. to do the <code class="code">replace()</code>, because we work with a simple string comparison. Ant itself is platform
  246. independent and can therefore run on filesystems with slash (<q>/</q>, e.g. Linux) or backslash (<q>\</q>, e.g. Windows)
  247. as path separator. Therefore we have to unify that. If we find our file, we create an absolute path representation
  248. on <strong>//5</strong>, so that we can use that information without knowing the <var>basedir</var>. (This is very
  249. important on use with multiple filesets, because they can have different <var>basedir</var>s and the return value of the
  250. directory scanner is relative to its <var>basedir</var>.) Finally we store the location of the file as property, if we
  251. had found one (<strong>//6</strong>).</p>
  252. <p>Ok, much more easier in this simple case would be to add the <var>file</var> as additional <code>include</code>
  253. element to all filesets. But I wanted to show how to handle complex situations without being complex :-)</p>
  254. <p>The test case uses the Ant property <code>ant.home</code> as reference. This property is set by
  255. the <code class="code">Launcher</code> class which starts ant. We can use that property in our buildfiles as
  256. a <a href="properties.html#built-in-props">build-in property [3]</a>. But if we create a new Ant environment we have to
  257. set that value for our own. And we use the <code>&lt;junit&gt;</code> task in <var>fork</var> mode. Therefore we have
  258. do modify our buildfile:</p>
  259. <pre>
  260. &lt;target name="junit" description="Runs the unit tests" depends="jar"&gt;
  261. &lt;delete dir="${junit.out.dir.xml}"/&gt;
  262. &lt;mkdir dir="${junit.out.dir.xml}"/&gt;
  263. &lt;junit printsummary="yes" haltonfailure="no"&gt;
  264. &lt;classpath refid="classpath.test"/&gt;
  265. <b>&lt;sysproperty key="ant.home" value="${ant.home}"/&gt;</b>
  266. &lt;formatter type="xml"/&gt;
  267. &lt;batchtest fork="yes" todir="${junit.out.dir.xml}"&gt;
  268. &lt;fileset dir="${src.dir}" includes="**/*Test.java"/&gt;
  269. &lt;/batchtest&gt;
  270. &lt;/junit&gt;
  271. &lt;/target&gt;</pre>
  272. <h2 id="path">Using nested paths</h2>
  273. <p>A task providing support for filesets is a very comfortable one. But there is another possibility of bundling files:
  274. the <code>&lt;path&gt;</code>. Filesets are easy if the files are all under a common base directory. But if this is not
  275. the case, you have a problem. Another disadvantage is its speed: if you have only a few files in a huge directory
  276. structure, why not use a <code>&lt;filelist&gt;</code> instead? <code>&lt;path&gt;</code>s combines these datatypes in
  277. that way that a path contains other paths, filesets, dirsets and filelists. This is
  278. why <a href="http://ant-contrib.sourceforge.net/" target="_top">Ant-Contrib [4]</a> <code>&lt;foreach&gt;</code> task is
  279. modified to support paths instead of filesets. So we want that, too.</p>
  280. <p>Changing from fileset to path support is very easy:</p>
  281. <em><strong>Change Java code from:</strong></em>
  282. <pre>
  283. private List&lt;FileSet&gt; filesets = new ArrayList&lt;&gt;();
  284. public void addFileset(FileSet fileset) {
  285. filesets.add(fileset);
  286. }</pre>
  287. <em><strong>to:</strong></em>
  288. <pre>
  289. private List&lt;Path&gt; paths = new ArrayList&lt;&gt;(); *1
  290. public void add<b>Path</b>(<b>Path</b> path) { *2
  291. paths.add(path);
  292. }</pre>
  293. <em><strong>and build file from:</strong></em>
  294. <pre>
  295. &lt;find file="ant.jar" location="location.ant-jar"&gt;
  296. &lt;fileset dir="${ant.home}" includes="**/*.jar"/&gt;
  297. &lt;/find&gt;</pre>
  298. <em><strong>to:</strong></em>
  299. <pre>
  300. &lt;find file="ant.jar" location="location.ant-jar"&gt;
  301. <b>&lt;path&gt;</b> *3
  302. &lt;fileset dir="${ant.home}" includes="**/*.jar"/&gt;
  303. &lt;/path&gt;
  304. &lt;/find&gt;</pre>
  305. <p>On <strong>*1</strong> we rename only the list. It's just for better reading the source. On <strong>*2</strong> we
  306. have to provide the right method: an <code>add<i>Name</i>(<i>Type</i> t)</code>. Therefore replace the fileset with path
  307. here. Finally we have to modify our buildfile on <strong>*3</strong> because our task doesn't support nested filesets
  308. any longer. So we wrap the fileset inside a path.</p>
  309. <p>And now we modify the test case. Oh, not very much to do :-) Renaming
  310. the <code class="code">testMissingFileset()</code> (not really a <em>must-be</em> but better it's named like the thing
  311. it does) and update the <var>expected</var>-String in that method (now a <samp>path not set</samp> message is
  312. expected). The more complex test cases base on the build script. So the targets <var>testFileNotPresent</var>
  313. and <var>testFilePresent</var> have to be modified in the manner described above.</p>
  314. <p>The test are finished. Now we have to adapt the task implementation. The easiest modification is in
  315. the <code class="code">validate()</code> method where we change the last line to <code class="code">if
  316. (paths.size()&lt;1) throw new BuildException("path not set");</code>. In the <code class="code">execute()</code> method
  317. we have a little more work. ... mmmh ... in reality it's less work, because the <code class="code">Path</code> class
  318. does the whole <code class="code">DirectoryScanner</code>-handling and creating-absolute-paths stuff for us. So the
  319. execute method becomes just:</p>
  320. <pre>
  321. public void execute() {
  322. validate();
  323. String foundLocation = null;
  324. for (Path path : paths) { // 1
  325. for (String includedFile : <b>path.list()</b>) { // 2
  326. String filename = includedFile.replace('\\','/');
  327. filename = filename.substring(filename.lastIndexOf("/") + 1);
  328. if (foundLocation == null &amp;&amp; file.equals(filename)) {
  329. <b>foundLocation = includedFile;</b> // 3
  330. }
  331. }
  332. }
  333. if (foundLocation != null)
  334. getProject().setNewProperty(location, foundLocation);
  335. }
  336. </pre>
  337. <p>Of course we have to iterate through paths on <strong>//1</strong>. On <strong>//2</strong> and <strong>//3</strong>
  338. we see that the Path class does the work for us: no DirectoryScanner (was at 2) and no creating of the absolute path
  339. (was at 3).</p>
  340. <h2 id="returning-list">Returning a list</h2>
  341. <p>So far so good. But could a file be on more than one place in the path?&mdash;Of course.<br/>
  342. And would it be good to get all of them?&mdash;It depends ...<p>
  343. <p>In this section we will extend that task to support returning a list of all files. Lists as property values are not
  344. supported by Ant natively. So we have to see how other tasks use lists. The most famous task using lists is
  345. Ant-Contrib's <code>&lt;foreach&gt;</code>. All list elements are concatenated and separated with a customizable
  346. separator (default <q>,</q>).</p>
  347. <p>So we do the following:</p>
  348. <pre>&lt;find ... <b>delimiter=""</b>/&gt; ... &lt;/find&gt;</pre>
  349. <p>if the delimiter is set, we will return all found files as list with that delimiter.</p>
  350. <p>Therefore we have to</p>
  351. <ul>
  352. <li>provide a new attribute</li>
  353. <li>collect more than the first file</li>
  354. <li>delete duplicates</li>
  355. <li>create the list if necessary</li>
  356. <li>return that list</li>
  357. </ul>
  358. <p>So we add as test case:</p>
  359. <strong><em>in the buildfile:</em></strong>
  360. <pre>
  361. &lt;target name="test.init"&gt;
  362. &lt;mkdir dir="test1/dir11/dir111"/&gt; *1
  363. &lt;mkdir dir="test1/dir11/dir112"/&gt;
  364. ...
  365. &lt;touch file="test1/dir11/dir111/test"/&gt;
  366. &lt;touch file="test1/dir11/dir111/not"/&gt;
  367. ...
  368. &lt;touch file="test1/dir13/dir131/not2"/&gt;
  369. &lt;touch file="test1/dir13/dir132/test"/&gt;
  370. &lt;touch file="test1/dir13/dir132/not"/&gt;
  371. &lt;touch file="test1/dir13/dir132/not2"/&gt;
  372. &lt;mkdir dir="test2"/&gt;
  373. &lt;copy todir="test2"&gt; *2
  374. &lt;fileset dir="test1"/&gt;
  375. &lt;/copy&gt;
  376. &lt;/target&gt;
  377. &lt;target name="testMultipleFiles" depends="use.init,<b>test.init</b>"&gt; *3
  378. &lt;find file="test" location="location.test" <b>delimiter=";"</b>&gt;
  379. &lt;path&gt;
  380. &lt;fileset dir="test1"/&gt;
  381. &lt;fileset dir="test2"/&gt;
  382. &lt;/path&gt;
  383. &lt;/find&gt;
  384. &lt;delete&gt; *4
  385. &lt;fileset dir="test1"/&gt;
  386. &lt;fileset dir="test2"/&gt;
  387. &lt;/delete&gt;
  388. &lt;/target&gt;</pre>
  389. <strong><em>in the test class:</em></strong>
  390. <pre>
  391. public void testMultipleFiles() {
  392. executeTarget("testMultipleFiles");
  393. String result = getProject().getProperty("location.test");
  394. assertNotNull("Property not set.", result);
  395. assertTrue("Only one file found.", result.indexOf(";") &gt; -1);
  396. }</pre>
  397. <p>Now we need a directory structure where we CAN find files with the same name in different directories. Because we
  398. can't sure to have one we create one on <strong>*1</strong> and <strong>*2</strong>. And of course we clean up that
  399. on <strong>*4</strong>. The creation can be done inside our test target or in a separate one, which will be better for
  400. reuse later (<strong>*3</strong>).
  401. <p>The task implementation is modified as followed:</p>
  402. <pre>
  403. private List&lt;String&gt; foundFiles = new ArrayList&lt;&gt;();
  404. ...
  405. private String delimiter = null;
  406. ...
  407. public void setDelimiter(String delim) {
  408. delimiter = delim;
  409. }
  410. ...
  411. public void execute() {
  412. validate();
  413. // find all files
  414. for (Path path : paths) {
  415. for (File includedFile : path.list()) {
  416. String filename = includedFile.replace('\\','/');
  417. filename = filename.substring(filename.lastIndexOf("/")+1);
  418. if (file.equals(filename) &amp;&amp; <b>!foundFiles.contains(includedFile)</b>) { // 1
  419. foundFiles.add(includedFile);
  420. }
  421. }
  422. }
  423. // create the return value (list/single)
  424. String rv = null;
  425. if (!foundFiles.isEmpty()) { // 2
  426. if (delimiter == null) {
  427. // only the first
  428. rv = foundFiles.get(0);
  429. } else {
  430. // create list
  431. StringBuilder list = new StringBuilder();
  432. for (String file : foundFiles) { // 3
  433. list.append(it.next());
  434. if (<b>list.length() > 0</b>) list.append(delimiter); // 4
  435. }
  436. rv = list.toString();
  437. }
  438. }
  439. // create the property
  440. if (rv != null)
  441. getProject().setNewProperty(location, rv);
  442. }</pre>
  443. <p>The algorithm does: finding all files, creating the return value depending on the users wish, returning the value as
  444. property. On <strong>//1</strong> we eliminates the duplicates. <strong>//2</strong> ensures that we create the return
  445. value only if we have found one file. On <strong>//3</strong> we iterate over all found files and <strong>//4</strong>
  446. ensures that the last entry has no trailing delimiter.</p>
  447. <p>Ok, first searching for all files and then returning only the first one ... You can tune the performance of your own
  448. :-)</p>
  449. <h2 id="documentation">Documentation</h2>
  450. <p>A task is useless if the only who is able to code the buildfile is the task developer (and he only the next few weeks
  451. :-). So documentation is also very important. In which form you do that depends on your favourite. But inside Ant there
  452. is a common format and it has advantages if you use that: all task users know that form, this form is requested if you
  453. decide to contribute your task. So we will doc our task in that form.</p>
  454. <p>If you have a look at the manual page of the <a href="Tasks/java.html">Java task [5]</a> you will see that it:</p>
  455. <ul>
  456. <li>is plain html</li>
  457. <li>starts with the name</li>
  458. <li>has sections: description, parameters, nested elements, (maybe return codes) and (most important :-) examples</li>
  459. <li>parameters are listed in a table with columns for attribute name, its description and whether it's required (if you
  460. add a feature after an Ant release, provide a <em>since Ant xx</em> statement when it's introduced)</li>
  461. <li>describe the nested elements (since-statement if necessary)</li>
  462. <li>provide one or more useful examples; first code, then description.</li>
  463. </ul>
  464. <p>As a template we have:</p>
  465. <pre>
  466. &lt;html&gt;
  467. &lt;head&gt;
  468. &lt;meta http-equiv="Content-Language" content="en-us"&gt;
  469. &lt;title&gt;<b>Taskname</b> Task&lt;/title&gt;
  470. &lt;/head&gt;
  471. &lt;body&gt;
  472. &lt;h2 id=&quot;<b>taskname</b>&quot;&gt;<b>Taskname</b>&lt;/h2&gt;
  473. &lt;h3&gt;Description&lt;/h3&gt;
  474. &lt;p&gt;<b>Describe the task.</b>&lt;/p&gt;
  475. &lt;h3&gt;Parameters&lt;/h3&gt;
  476. &lt;table class=&quot;attr&quot;&gt;
  477. &lt;tr&gt;
  478. &lt;th&gt;Attribute&lt;/th&gt;
  479. &lt;th&gt;Description&lt;/th&gt;
  480. &lt;th&gt;Required&lt;/th&gt;
  481. &lt;/tr&gt;
  482. <b>do this html row for each attribute (including inherited attributes)</b>
  483. &lt;tr&gt;
  484. &lt;td&gt;classname&lt;/td&gt;
  485. &lt;td&gt;the Java class to execute.&lt;/td&gt;
  486. &lt;td&gt;Either jar or classname&lt;/td&gt;
  487. &lt;/tr&gt;
  488. &lt;/table&gt;
  489. &lt;h3&gt;Parameters specified as nested elements&lt;/h3&gt;
  490. <b>Describe each nested element (including inherited)</b>
  491. &lt;h4&gt;<b>your nested element</b>&lt;/h4&gt;
  492. &lt;p&gt;<b>description</b>&lt;/p&gt;
  493. &lt;p&gt;&lt;em&gt;since Ant 1.6&lt;/em&gt;.&lt;/p&gt;
  494. &lt;h3&gt;Examples&lt;/h3&gt;
  495. &lt;pre&gt;
  496. <b>A code sample; don't forget to escape the &lt; of the tags with &amp;lt;</b>
  497. &lt;/pre&gt;
  498. <b>What should that example do?</b>
  499. &lt;/body&gt;
  500. &lt;/html&gt;</pre>
  501. <p>Here is an example documentation page for our task:</p>
  502. <pre>
  503. &lt;html&gt;
  504. &lt;head&gt;
  505. &lt;meta http-equiv="Content-Language" content="en-us"&gt;
  506. &lt;title&gt;Find Task&lt;/title&gt;
  507. &lt;/head&gt;
  508. &lt;body&gt;
  509. &lt;h2 id="find"&gt;Find&lt;/h2&gt;
  510. &lt;h3&gt;Description&lt;/h3&gt;
  511. &lt;p&gt;Searches in a given path for a file and returns the absolute to it as property.
  512. If delimiter is set this task returns all found locations.&lt;/p&gt;
  513. &lt;h3&gt;Parameters&lt;/h3&gt;
  514. &lt;table class=&quot;attr&quot;&gt;
  515. &lt;tr&gt;
  516. &lt;th&gt;Attribute&lt;/th&gt;
  517. &lt;th&gt;Description&lt;/th&gt;
  518. &lt;th&gt;Required&lt;/th&gt;
  519. &lt;/tr&gt;
  520. &lt;tr&gt;
  521. &lt;td&gt;file&lt;/td&gt;
  522. &lt;td&gt;The name of the file to search.&lt;/td&gt;
  523. &lt;td&gt;yes&lt;/td&gt;
  524. &lt;/tr&gt;
  525. &lt;tr&gt;
  526. &lt;td&gt;location&lt;/td&gt;
  527. &lt;td&gt;The name of the property where to store the location&lt;/td&gt;
  528. &lt;td&gt;yes&lt;/td&gt;
  529. &lt;/tr&gt;
  530. &lt;tr&gt;
  531. &lt;td&gt;delimiter&lt;/td&gt;
  532. &lt;td&gt;A delimiter to use when returning the list&lt;/td&gt;
  533. &lt;td&gt;only if the list is required&lt;/td&gt;
  534. &lt;/tr&gt;
  535. &lt;/table&gt;
  536. &lt;h3&gt;Parameters specified as nested elements&lt;/h3&gt;
  537. &lt;h4&gt;path&lt;/h4&gt;
  538. &lt;p&gt;The path where to search the file.&lt;/p&gt;
  539. &lt;h3&gt;Examples&lt;/h3&gt;
  540. &lt;pre&gt;
  541. &lt;find file="ant.jar" location="loc"&gt;
  542. &lt;path&gt;
  543. &lt;fileset dir="${ant.home}"/&gt;
  544. &lt;path&gt;
  545. &lt;/find&gt;&lt;/pre&gt;
  546. Searches in Ant's home directory for a file &lt;samp&gt;ant.jar&lt;/samp&gt; and stores its location in
  547. property &lt;code&gt;loc&lt;/code&gt; (should be &lt;samp&gt;ANT_HOME/bin/ant.jar&lt;/samp&gt;).
  548. &lt;pre&gt;
  549. &lt;find file="ant.jar" location="loc" delimiter=";"&gt;
  550. &lt;path&gt;
  551. &lt;fileset dir="C:/"/&gt;
  552. &lt;path&gt;
  553. &lt;/find&gt;
  554. &lt;echo&gt;ant.jar found in: ${loc}&lt;/echo&gt;&lt;/pre&gt;
  555. Searches in Windows C: drive for all &lt;samp&gt;ant.jar&lt;/samp&gt; and stores their locations in
  556. property &lt;code&gt;loc&lt;/code&gt; delimited with &lt;q&gt;;&lt;/q&gt;. (should need a long time :-)
  557. After that it prints out the result (e.g. &lt;samp&gt;C:/ant-1.5.4/bin/ant.jar;C:/ant-1.6/bin/ant.jar&lt;/samp&gt;).
  558. &lt;/body&gt;
  559. &lt;/html&gt;</pre>
  560. <h2 id="contribute">Contribute the new task</h2>
  561. <p>If we decide to contribute our task, we should do some things:</p>
  562. <ul>
  563. <li>is our task welcome? :-) Simply ask on the user list</li>
  564. <li>is the right package used?</li>
  565. <li>does the code conform to the styleguide?</li>
  566. <li>do all tests pass?</li>
  567. <li>does the code compile on JDK 5 (and passes all tests there)?</li>
  568. <li>code under Apache license</li>
  569. <li>create a patch file</li>
  570. <li>publishing that patch file</li>
  571. </ul>
  572. <p>The <a href="https://ant.apache.org/ant_task_guidelines.html" target="_top">Ant Task Guidelines [6]</a> support
  573. additional information on that.</p>
  574. <p>Now we will check the "Checklist before submitting a new task" described in that guideline.</p>
  575. <ul>
  576. <li>Java file begins with Apache license statement. <strong><em>must do that</em></strong></li>
  577. <li>Task does not depend on GPL or LGPL code. <strong><em>ok</em></strong></li>
  578. <li>Source code complies with style guidelines <strong><em>have to check (checkstyle)</em></strong></li>
  579. <li>Code compiles and runs on Java 5 <strong><em>have to try</em></strong></li>
  580. <li>Member variables are private, and provide public accessor methods if access is actually needed. <strong><em>have to
  581. check (checkstyle)</em></strong></li>
  582. <li><em>Maybe</em> Task has <var>failonerror</var> attribute to control failure
  583. behaviour <strong><em>hasn't</em></strong></li>
  584. <li>New test cases written and succeed <strong><em>passed on JDK 8, have to try on JDK 5</em></strong></li>
  585. <li>Documentation page written <strong><em>ok</em></strong></li>
  586. <li>Example task declarations in the documentation tested. <strong><em>ok (used in tests)</em></strong></li>
  587. <li>Message to dev contains [SUBMIT] and task name in subject <strong><em>to do</em></strong></li>
  588. <li>Message body contains a rationale for the task <strong><em>to do</em></strong></li>
  589. <li>Message body contains the URL to GitHub pull request. <strong><em>to do</em></strong></li>
  590. </ul>
  591. <h3>Package / Directories</h3>
  592. <p>This task does not depend on any external library. Therefore we can use this as a core task. This task contains only
  593. one class. So we can use the standard package for core
  594. tasks: <code class="code">org.apache.tools.ant.taskdefs</code>. Implementations are in the
  595. directory <samp>src/main</samp>, tests in <samp>src/testcases</samp> and buildfiles for tests
  596. in <samp>src/etc/testcases</samp>.</p>
  597. <p>Now we integrate our work into Ant distribution. So first we do an update of our Git tree. If not done yet, you
  598. should clone the Ant repository on GitHub[7], then create a local clone:</p>
  599. <pre class="input">git clone https://github.com/<em>your-sig</em>/ant.git</pre>
  600. <p>Now we will build our Ant distribution and do a test. So we can see if there are any tests failing on our
  601. machine. (We can ignore these failing tests on later steps; Windows syntax used here&mdash;translate to UNIX if
  602. needed):</p>
  603. <pre class="input">
  604. ANTREPO&gt; build // 1
  605. ANTREPO&gt; set ANT_HOME=%CD%\dist // 2
  606. ANTREPO&gt; ant test -Dtest.haltonfailure=false // 3</pre>
  607. <p>First we have to build our Ant distribution (<strong>//1</strong>). On <strong>//2</strong> we set
  608. the <code>ANT_HOME</code> environment variable to the directory where the new created distribution is stored
  609. (<code>%CD%</code> is expanded to the current directory on Windows 2000 and later). On <strong>//3</strong> we let Ant
  610. do all the tests (which enforced a compile of all tests) without stopping on first failure.</p>
  611. <p>Next we apply our work onto Ant sources. Because we haven't modified any, this is a relatively simple
  612. step. <em>(Because I have a local Git clone of Ant and usually contribute my work, I work on the local copy just from
  613. the beginning. The advantage: this step isn't necessary and saves a lot of work if you modify existing sources :-)</em>.
  614. <ul>
  615. <li>move the <samp>Find.java</samp> to <samp>ANTREPO/src/main/org/apache/tools/ant/taskdefs/Find.java</samp></li>
  616. <li>move the <samp>FindTest.java</samp> to <samp>ANTREPO/src/testcases/org/apache/tools/ant/taskdefs/FindTest.java</samp></li>
  617. <li>move the <samp>build.xml</samp> to <samp>ANTREPO/src/etc/testcases/taskdefs/<strong>find.xml</strong></samp> (!!! renamed !!!)</li>
  618. <li>add a <code>package org.apache.tools.ant.taskdefs;</code> at the beginning of the two java files</li>
  619. <li>delete all stuff from <samp>find.xml</samp> keeping the
  620. targets <q>testFileNotPresent</q>, <q>testFilePresent</q>, <q>test.init</q> and <q>testMultipleFiles</q></li>
  621. <li>delete the dependency to <q>use.init</q> in the <samp>find.xml</samp></li>
  622. <li>in <samp>FindTest.java</samp> change the line <code>configureProject("build.xml");</code>
  623. to <code>configureProject("src/etc/testcases/taskdefs/find.xml");</code></li>
  624. <li>move the <samp>find.html</samp> to <samp>ANTREPO/docs/manual/Tasks/find.html</samp></li>
  625. <li>add a <code>&lt;a href="Tasks/find.html"&gt;Find&lt;/a&gt;&lt;br&gt;</code> in
  626. the <samp>ANTREPO/docs/manual/tasklist.html</samp></li>
  627. </ul>
  628. <p>Now our modifications are done and we will retest it:</p>
  629. <pre class="input">
  630. ANTREPO&gt; build
  631. ANTREPO&gt; ant run-single-test // 1
  632. -Dtestcase=org.apache.tools.ant.taskdefs.FindTest // 2
  633. -Dtest.haltonfailure=false</pre>
  634. <p>Because we only want to test our new class, we use the target for single tests, specify the test to use and configure
  635. not to halt on the first failure&mdash;we want to see all failures of our own test (<strong>//1 + 2</strong>).</p>
  636. <p>And ... oh, all tests fail: <em>Ant could not find the task or a class this task relies upon.</em></p>
  637. <p>Ok: in the earlier steps we told Ant to use the Find class for the <code>&lt;find&gt;</code> task (remember
  638. the <code>&lt;taskdef&gt;</code> statement in the <q>use.init</q> target). But now we want to introduce that task as a
  639. core task. And nobody wants to <code>taskdef</code> the <code>javac</code>, <code>echo</code>, ... So what to do? The
  640. answer is the <samp>src/main/.../taskdefs/default.properties</samp>. Here is the mapping between taskname and
  641. implementing class done. So we add a <code>find=org.apache.tools.ant.taskdefs.Find</code> as the last core task (just
  642. before the <code># optional tasks</code> line). Now a second try:</p>
  643. <pre class="input">
  644. ANTREPO&gt; build // 1
  645. ANTREPO&gt; ant run-single-test
  646. -Dtestcase=org.apache.tools.ant.taskdefs.FindTest
  647. -Dtest.haltonfailure=false</pre>
  648. <p>We have to rebuild (<strong>//1</strong>) Ant because the test look in the <samp>%ANT_HOME%\lib\ant.jar</samp> (more
  649. precise: on the classpath) for the properties file. And we have only modified it in the source path. So we have to
  650. rebuild that jar. But now all tests pass and we check whether our class breaks some other tests.</p>
  651. <pre class="input">ANTREPO&gt; ant test -Dtest.haltonfailure=false</pre>
  652. <p>Because there are a lot of tests this step requires a little bit of time. So use the <q>run-single-test</q> during
  653. development and do the <q>test</q> only at the end (maybe sometimes during development too). We use
  654. the <kbd>-Dtest.haltonfailure=false</kbd> here because there could be other tests fail and we have to look into
  655. them.</p>
  656. <p>This test run should show us two things: our test will run and the number of failing tests is the same as directly
  657. after <code>git clone</code> (without our modifications).</p>
  658. <h3>Apache license statement</h3>
  659. <p>Simply copy the license text from one the other source from the Ant source tree.</p>
  660. <h3>Test on JDK 5</h3>
  661. <p>Ant 1.10 uses Java 8 for development, but Ant 1.9 is actively maintained, too. That means that Ant code must be able
  662. to run on a JDK 5. So we have to test that. You can download older JDKs
  663. from <a href="https://www.oracle.com/technetwork/java/archive-139210.html" target="_top">Oracle [8]</a>.</p>
  664. <p>Clean the <code>ANT_HOME</code> variable, delete the <samp>build</samp>, <samp>bootstrap</samp> and <samp>dist</samp>
  665. directories, and point <code>JAVA_HOME</code> to the JDK 5 home directory. Then create the patch with your commit,
  666. checkout 1.9.x branch in Git, apply your patch and do the <code>build</code>, set <code>ANT_HOME</code> and
  667. run <kbd>ant test</kbd> (like above).</p>
  668. <p>Our test should pass.</p>
  669. <h3>Checkstyle</h3>
  670. <p>There are many things we have to ensure. Indentation with 4 spaces, blanks here and there, ... (all described in
  671. the <a href="https://ant.apache.org/ant_task_guidelines.html" target="_top">Ant Task Guidelines [6]</a> which includes
  672. the <a href="https://www.oracle.com/technetwork/java/codeconvtoc-136057.html" target="_top">Sun code style
  673. [9]</a>). Because there are so many things we would be happy to have a tool for do the checks. There is one:
  674. checkstyle. Checkstyle is available at <a href="http://checkstyle.sourceforge.net/" target="_top">Sourceforge [10]</a>
  675. and Ant provides with the <samp>check.xml</samp> a buildfile which will do the job for us.</p>
  676. <p>Download it and put the <samp>checkstyle-*-all.jar</samp> into your <samp>%USERPROFILE%\.ant\lib</samp> directory.
  677. All jar's stored there are available to Ant so you haven't to add it to you <samp>%ANT_HOME%\lib</samp> directory (this
  678. feature is available <em>since Ant 1.6</em>).</p>
  679. <p>So we will run the tests with</p>
  680. <pre class="input">ANTREPO&gt; ant -f check.xml checkstyle htmlreport</pre>
  681. <p>I prefer the HTML report because there are lots of messages and we can navigate faster. Open
  682. the <samp>ANTREPO/build/reports/checkstyle/html/index.html</samp> and navigate to the <samp>Find.java</samp>. Now we see
  683. that there are some errors: missing whitespaces, unused imports, missing javadocs. So we have to do that.</p>
  684. <p>Hint: start at the <strong>bottom</strong> of the file so the line numbers in the report will keep up to date and you
  685. will find the next error place much more easier without redoing the checkstyle.</p>
  686. <p>After cleaning up the code according to the messages we delete the reports directory and do a second checkstyle
  687. run. Now our task isn't listed. That's fine :-)</p>
  688. <h3>Publish the task</h3>
  689. <p>Finally we publish that archive. As described in the <a href="https://ant.apache.org/ant_task_guidelines.html"
  690. target="_top">Ant Task Guidelines [7]</a> we can announce it on the developer mailing list, create a BugZilla entry and
  691. open a GitHub pull request. For both we need some information:</p>
  692. <table>
  693. <tr>
  694. <!-- this is an empty "table head" -->
  695. </tr>
  696. <tr>
  697. <th>subject</th>
  698. <td><em>short description</em></td>
  699. <td>Task for finding files in a path</td>
  700. </tr>
  701. <tr>
  702. <th>body</th>
  703. <td><em>more details about the path</em></td>
  704. <td>This new task looks inside a nested <code>&lt;path/&gt;</code> for occurrences of a file and stores all locations
  705. as a property. See the included manual for details.</td>
  706. </tr>
  707. <tr>
  708. <th>pull request reference</th>
  709. <td><em>GitHub pull request URL</em></td>
  710. <td>https://github.com/apache/ant/pull/0</td>
  711. </tr>
  712. </table>
  713. <p>Sending an email with this information is very easy and I think I haven't to describe that. BugZilla is slightly
  714. more difficult. But the advantage is that entries will not be forgotten (a report is generated once every weekend). So
  715. I will describe the process.</p>
  716. <p>First, you must have a BugZilla account. So open the <a href="https://issues.apache.org/bugzilla/"
  717. target="_top">BugZilla Main Page [11]</a> and follow the
  718. link <a href="https://issues.apache.org/bugzilla/createaccount.cgi" target="_top">Open a new Bugzilla account [12]</a>
  719. and the steps described there if you haven't one.</p>
  720. <ol>
  721. <li>From the BugZilla main page choose <a href="https://issues.apache.org/bugzilla/enter_bug.cgi" target="_top">Enter a
  722. new bug report [13]</a></li>
  723. <li>Choose "Ant" as product</li>
  724. <li>Version is the last "Alpha (nightly)" (at this time 1.10)</li>
  725. <li>Component is "Core tasks"</li>
  726. <li>Platform and Severity are ok with "Other" and "Normal"</li>
  727. <li>Initial State is ok with "New"</li>
  728. <li>Same with the empty "Assigned to"</li>
  729. <li>It is not required to add yourself as CC, because you are the reporter and therefore will be informed on
  730. changes</li>
  731. <li>URL: GitHub pull request URL</li>
  732. <li>Summary: add the <var>subject</var> from the table</li>
  733. <li>Description: add the <var>body</var> from the table</li>
  734. <li>Then press "Commit"</li>
  735. </ol>
  736. <p>Now the new task is registered in the bug database.</p>
  737. <h2 id="resources">Resources</h2>
  738. <ol class="refs">
  739. <li><a href="tutorial-writing-tasks.html">tutorial-writing-tasks.html</a></li>
  740. <li><a href="tutorial-tasks-filesets-properties.zip">tutorial-tasks-filesets-properties.zip</a></li>
  741. <li><a href="properties.html#built-in-props">properties.html#built-in-props</a></li>
  742. <li><a href="http://ant-contrib.sourceforge.net/" target="_top">http://ant-contrib.sourceforge.net/</a></li>
  743. <li><a href="Tasks/java.html">Tasks/java.html</a></li>
  744. <li><a href="https://ant.apache.org/ant_task_guidelines.html"
  745. target="_top">https://ant.apache.org/ant_task_guidelines.html</a></li>
  746. <li><a href="https://github.com/apache/ant" target="_top">https://github.com/apache/ant</a></li>
  747. <li><a href="https://www.oracle.com/technetwork/java/archive-139210.html"
  748. target="_top">https://www.oracle.com/technetwork/java/archive-139210.html</a></li>
  749. <li><a href="https://www.oracle.com/technetwork/java/codeconvtoc-136057.html"
  750. target="_top">https://www.oracle.com/technetwork/java/codeconvtoc-136057.html</a></li>
  751. <li><a href="http://checkstyle.sourceforge.net/" target="_top">http://checkstyle.sourceforge.net/</a></li>
  752. <li><a href="https://issues.apache.org/bugzilla/" target="_top">https://issues.apache.org/bugzilla/</a></li>
  753. <li><a href="https://issues.apache.org/bugzilla/createaccount.cgi"
  754. target="_top">https://issues.apache.org/bugzilla/createaccount.cgi</a></li>
  755. <li><a href="https://issues.apache.org/bugzilla/enter_bug.cgi"
  756. target="_top">https://issues.apache.org/bugzilla/enter_bug.cgi</a></li>
  757. </ol>
  758. </body>
  759. </html>