You are on page 1of 12

FAQ on ANT Building Process by Roseanne Zhang, Java Programmer C...

http://bobcat.webappcabaret.net/javachina/faq/ant_01.htm#ant_abc_Q05

FAQ on ANT Building Process by Roseanne Zhang
scjp, advanced, job tips, xml, ant, c/c++/stl, Algorithm, Ruby The questions and answers here are my selective postings on jGuru, JavaRanch, ChinaJavaWorldProgramFan in order to answer others' questions. After a while of doing this, I realized that a lot of similar questions are being asked again and again. The purpose of creating this page is to let people in the future have a place to look for answers. People don't need to answer the same question again and again. Software reusability is extremely important. OO analysis, design, and programming are invented for this purposes. So does the component-based software. Design patterns are discovered for reusing other's design ideas. This page is created for reusing my own answers. Hopefully, this page will make your learning process a little easier. We all work together to make a difference!

Table of Contents Ant ABC
What is ant? A win-win ant learning method How do I get started to use ant? Can you give me a "Hello World" ant script? How do I copy all top level files but not subdirectories? How to delete files from a directory if it exists? How do I set classpath in ant? How does ant read properties? How to set my property system? How to modify properties in ant? How to use ant-contrib tasks? How to loop on a list or fileset? Why do I get en exception when I use location="D:\Code\include" as attribute of includepath? How to use ant to run commandline command? How to get perl script running result? How do I debug my ant script? Can I put the contents of a classpath or fileset into a property? Where can I find the javadoc for ant API?

Ant Intermediate
How can I use ant to run a Java application? How to exclude multi directories in copy or delete task? How to use Runtime in ant? How to rearrange my directory structure in my jar/war/ear/zip file? Do I need to unarchive them first? Why did I get such warning in ant? How can I write my own ant task? How to copy files without extention? How do I use two different versions of jdk in ant script?

It is a good and simple example for you to learn ant. Ant is easy! The hard part is how to make a very complicated diversified system work very simple and elegant. If you download a small jakarta project. ANT.net/javachina/faq/ant_01. Ant builds! Here is a picture for it. Just kidding! ANT is a Java based building tool. What is ant? A: Ant is a small animal who can build magnificent buildings. A win-win ant learning method A: There is a shortcut.FAQ on ANT Building Process by Roseanne Zhang. Actually. it hangs. which is similar to make. To the top Q.webappcabaret. Why cannot I delete or rename a file/directory in ant? What is a good directory structure for main code and junit test code? Should I use quilt to monitor QA code coverage? What should I use to build J2ME application/games? A creative use of token replacement in ant copy task to handle multi-languages in mobile games. How do I handle two source files with the same pkg/name? How do I find out the relationship between ant task name and Java class in the code? Ant ABC Q. you hit two birds with one stone. http://bobcat. such as Log4J. Java Programmer C. How to do c/c++ build by using ant? A complicated case study. and so much better than make. what a smart name for a building tool.. James Duncan Davidson. which is built by ant..htm#ant_abc_Q05 How to pass -Xlint or -Xlint:unchecked to 1. meant "Another Neat Tool". even the original author of ANT. Knowledge .5 javac task? Can you give me a simple ant xslt task example? How to use ant to do xslt transformation? How do I add elements to an existing path? How to hide password input? How to do conditional statement in ant? Can I change/override ant properties when I use ant-contrib foreach task? Ant advanced Do we have an ant custom task to count source lines? How to let auto-detect platform and use platform specific properties? How to make ant user interactive? I tried to use BufferedReader to get user input.

the build will fail.which.dir}/*. you can use forward slash on windows.. Java Programmer C. Put %JAVA_HOME%/bin.xml <project name="hello" default="say. you need a least maintenance system.4 or above. Then it is not easy now .exists}"> <include name="${classes. you need to optimize the code reusability and flexibility. you need an elegant and simple design.classpath" /> </java> </target> . which exists for sure.> <classpath refid="build.dir}" includes="*.hello" basedir=".classes}" /> </path> <target. How do I get started to use ant? Can you give me a "Hello World" ant script? A: Simple. If dir does not exist.> <javac . Yes.." > <property name="hello.%ANT_HOME%/bin on your Path....hello" > <echo>${hello.net/javachina/faq/ant_01.msg" value="Hello... You should use nested fileset..htm#ant_abc_Q05 about ant is not enough. You should not use implicit fileset.. Install j2sdk 1. See the following fileset.xml located.. Use ${JAVA_HOME}/bin:${ANT_HOME}/bin on UNIX. Download the most recent version of ant from Apache. Set JAVA_HOME and ANT_HOME to the directory your installed them respectively.FAQ on ANT Building Process by Roseanne Zhang. 1.lib}" includes="**/*. you need great naming convention. unzip it some where on your machine. which is deprecated. <delete> <fileset dir="${upperdir.class"/> A: Your code has many problems. How do I set classpath in ant? A: Here is some snippet of code <path id="build. period! 3. World!" /> <target name="say. use a upper level dir. If you are not sure.. Write a "Hello world" build. http://bobcat. To the top Q.jar"/> <fileset dir="${build.classpath"> <fileset dir="${build..msg}</echo> </target> </project> Type ant in the directory your build. How to delete files from a directory if it exists? The following code fails when directory does not exist! <delete quiet="true" dir="${classes. 2.webappcabaret. You are ready to go!!!! To the top Q.class" /> </fileset> </delete> To the top Q.

> <classpath refid="build. It also works in windows environment variables. It also works in XP dos window now! . <target. just copy ant-contrib. This is opposite to your Java setters.properties (personal) yourprojectdir/prj.home}/prj.properties pswd=password In your build-common.. when something is set. How to loop on a list or fileset? A: Use ant-contrib <for> <foreach> tasks General to say..... Store your password in your ${user.. all ant-contrib tasks are now available to you! <taskdef resource="net/sf/antcontrib/antcontrib.FAQ on ANT Building Process by Roseanne Zhang. To the top Q.net/javachina/faq/ant_01. the later same properties cannot overwrite the previous ones. Give you an example here. This give us a good leverage of preset all properties in one place.properties (universal) <cvsnttask password="${pswd} .properties pswd=yourrealpassword In your include directory master prj.. but don't want to share it with your team members. How to use ant-contrib tasks? A: Simple. 4. You need to escape the string to "D:\\Code\\include" or use "D:/Code/include" instead! Believe me or not? Forward slash works on windows in all ant or java code. /> Problem solved! Q. 3.xml read properties files in this order 1. There is a good reason behind this. You need password for a task. It does not work in cmd (dos) window before XP. you can't! Properties in Ant are immutable.htm#ant_abc_Q05 Q. Q. see this FAQ item for more details. Why do I get en exception when I use location="D:\Code\include" as attribute of includepath? A: See here.home}/prj. The commandline will prevail. use <for> is better than use <foreach> since for each is actually open another ant property space. if you use it: ant -Dpswd=newpassword ${user. 2.webappcabaret.. and overwrite only the needed. Java Programmer C.jar to your ant*/lib directory And add this line into your ant script. How does ant read properties? How to set my property system? A: Ant sets properties by order.. use more memory too.. or not the developers outside your team.properties (project team wise) your_master_include_directory/prj.properties" /> To the top Q.> <java . How to modify properties in ant? A: No.classpath" /> </java> </target> http://bobcat.

you must think Unix.target"> <java classname="${run. Where can I find the javadoc for ant API? A: Download apache ant src version. powerful and versatile.java"/> <property name="f1. You will find out what is the problem easily. To the top Q.htm#ant_abc_Q05 Q.class}" fork="yes"> <classpath> <path refid="classpath" /> </classpath> <jvmarg line="${debug.FAQ on ANT Building Process by Roseanne Zhang. to get more information on what it is doing. To the top Ant Intermediate Q.jvmargs}" /> <jvmarg value="-Dname=${name}" /> <jvmarg line="${run.some. since it give you too much information. you might be tired with that pretty soon. and where. Java Programmer C.contents=${f1. This is very similar to the call of Java class toString() method and actually it is calling the toString() method inside ant. <target name="run" depends="some.other.jvmargs}" /> <jvmarg line="${my..contents}</echo> To the top Q.jvmargs}" /> <arg line="${run. Use ant javadocs command to see generated javadoc for ant in build/docs directory. How to use ant to run commandline command? How to get perl script running result? A: Use exec ant task. So does in MS-Windows. If you want ant receive unix command and result.target.webappcabaret. However.contents" refid="fs1"/> <echo>f1. http://bobcat.println() Use project. Ant just helps you to automate the process. How can I use ant to run a Java application? A: Here is a real world example. For example <fileset id="fs1" dir="t1" includes="**/*..log("msg") in your javascript or custom ant task Run Ant with -verbose. Can I put the contents of a classpath or fileset into a property? A: Yes. Don't forget ant is pure Java. Just like the old c printf() or Java System. How do I debug my ant script? A: Many ways Do an echo on where you have doubt.net/javachina/faq/ant_01. That is why ant is so useful. To the top Ant Intermediate . you can.args}" /> </java> </target> To the top Q. or even -debug.

I got huge amount of such warnings because the system timing issue.properties modified in the future.FAQ on ANT Building Process by Roseanne Zhang. Ant have exec task. To the top . http://bobcat. I checked out files from cvs to windows.createTask("exec"). The class name is org.dir}" > <exclude name="dirname1" /> <exclude name="dirname2" /> <exclude name="abc/whatever/dirname3" /> <exclude name="**/dirname4" /> </fileset> </copy> To the top Q.taskdefs. A: System time problem. <copy todir="${to.ant. True enough. ExecTask compile = (ExecTask)project. you don't need to unarchive them first. See the follow example: <jar destfile="${dest}/my. dao\DBDao2. possible reasons: You changed the system time I had the same problem before.java modified in the future.java modified in the future. You can use zipfileset in your jar/war/ear task to extract files from old archive to different directory in your new archive. You can create the task by using the code in your customized ant Task.tools. How to use Runtime in ant? A: You don't need to use Runtime etc. you will get the problem too. somehow.zip" includes="**/*.htm#ant_abc_Q05 Q.properties" prefix="dir_in_new_archive/prop"/> <zipfileset dir="curr_dir/abc" prefix="new_dir_in_archive/xyz"/> </jar> To the top Q. Why did I get such warning in ant? compile: [javac] Warning: [javac] Warning: [javac] Warning: [javac] Warning: commons-logging. How to rearrange my directory structure in my jar/war/ear/zip file? Do I need to unarchive them first? A: No.webappcabaret. How to exclude multi directories in copy or delete task? A: Here is an example. You don't need to unzip the files from archive to put into your destination jar/ear/war files..java modified in the future. To the top Q. If you transfer files from Australia/China/India to the United States.net/javachina/faq/ant_01.ExecTask. dao\DAO.dir}" > <fileset dir="${from. You also can use zipfileset in your jar/war/ear task to send files from local directory to different directory in your new archive. Java Programmer C. and transfer them to a unix machine. dao\HibernateBase.jar"> <zipfileset src="old_archive..apache. I did and met the problem once.

How to copy files without extention? A: If files are in the directory: <include name="a. http://bobcat. set default javac. 2. Don't define java. <compilerarg value="-Xlint"/> <!-.home}/jdk1. 1. How do I use two different versions of jdk in ant script? A: The followings are what I'm doing.bin=${tools.jar" /> </classpath> .properties (read first) jdk13. define it before using it. To the top Q..bin} In my prj. if I need to use 1.3.home}/bin" includes="*. Ant uses an internal one derived from your environment var JAVA_HOME.*"/> To the top Q.home by yourself. How to pass -Xlint or -Xlint:unchecked to 1.exe" To the top Q.1_13/bin jdk14.4 javac. I do the followings: In my build.FAQ on ANT Building Process by Roseanne Zhang.bin} in my javac task executable="${javac.2_08/bin/ In my master properties file (read last). Can you give me a simple ant xslt task example? A: Here is a working one! <xslt style="${xslfile}" in="${infile}" out="${outfile}" > <classpath> <fileset dir="${xml.**/c"/> If you want all files without extension are in the directory or subdirectories: <exclude name="**/*.location=${jdk13.5 javac task? A: pass it as compilerarg nested <compilerarg> to specify. In your own $ANT_HOME/docs/manual directory.location}/javac.net/javachina/faq/ant_01.bin=${tools.properties.c"/> If files are in the directory or subdirectories: <include name="**/a. It is immutable.home}/j2sdk1.or --> <compilerarg value="-Xlint:unchecked"/> Q.location=${jdk14.4.**/b.. How can I write my own ant task? A: Easy! Writing Your Own Task How-To from ant.zip Use them! Use taskdef to define it in your script. Java Programmer C.htm#ant_abc_Q05 Q. there also is tutorial-writing-tasks-src.b.webappcabaret.

then add/modify the lib.net/javachina/faq/ant_01. you can write one too.webappcabaret.. </xslt> http://bobcat.xml. Since target if/unless all depend on some property is defined or not. but a little hard to read. For example: HP-UX-PA_RISC2.properties" /> This will auto-detect your platform.arch}.0. I used a different criteria for XML/configuration files. How to hide password input? A: Override ant Input task. In your major build-include. and put it in use. They work great!!! :) Q. it is possible. you need to write a custom ant task. which in turn depends on your ant property values.FAQ on ANT Building Process by Roseanne Zhang. This makes your ant script very flexible. it works excellent. you can use condition to define different NEW properties. To the top Q. Ant-contrib also has <propertyregex> which can make very complicate decisions. you can pass any property name/value pair to it.properties Windows XP-x86. and add/modify it. However. Java Programmer C. How to let auto-detect platform and use platform specific properties? A: Tell you a great trick. To the top Q.properties SunOS-sparc.includes}/${os. To the top Q. and you write one file for each environment specific variables.. Ant-contrib has <if> <switch> tasks for you to use. put in this line <property file="${antutil. What I am doing is that I define a path reference lib.classpath use my own task. but it works. Not the best. How do I add elements to an existing path dynamically? A: Yes. it hangs. I wrote a custom task by myself and count the lines with semicolons and open braces as a pretty good estimation for Java files. get the path.classpath. How to make ant user interactive? I tried to use BufferedReader to get user input.htm#ant_abc_Q05 To the top Q.properties .. How to do conditional statement in ant? A: There are many ways to solve the problem. Do we have an ant custom task to count source lines? A: See here. Can I change/override ant properties when I use ant-contrib foreach task? A: <foreach> is actually using a different property space. Q. Response every user input with a backspace.name}-${os. Just give you a hint. I don't know if there is one published. . Just use <param> nested tag inside foreach To the top Ant advanced Q. However..

Young-Garner * @author: Roseanne Zhang made improvement. * Thanks to Stefan Reich * for suggesting this implementation.timeout=timeout. Use this class TimedBufferedReader instead of your BufferedReader will work. Java Programmer C.ready()) { try { . import java. } /** * TimedBufferedReader constructor.FAQ on ANT Building Process by Roseanne Zhang. a specified default * string is returned. while (!this.Reader..webappcabaret. The original author is credited in the code. } /** * We use ms internally * @return String */ public String readLine() throws IOException { int waitms = timeout*1000. This is a working one in our installation process.IOException. import java. sz). * @param str String */ public void setDefaultStr(String str) { defaultStr = str.io. int ms = 0. // 1 minute private String defaultStr = "". * @param in Reader * @param sz int Size of the input buffer. } /** * Sets defaultStr to use if no input is read. * @author: Anthony J. /** * Provides a BufferedReader with a readLine method that * blocks for only a specified number of seconds. /** * TimedBufferedReader constructor. * @param in Reader */ TimedBufferedReader(Reader in) { super(in). import java. I've made some improvement. http://bobcat. * @param seconds int */ public void setTimeout(int timeout) { this. } /** * Sets number of seconds to block for input. */ TimedBufferedReader(Reader in.java package setup. the input read is returned. If no * input is read in that time. TimedBufferedReader.io.net/javachina/faq/ant_01. Otherwise.BufferedReader.io.htm#ant_abc_Q05 A: See here.. */ public class TimedBufferedReader extends BufferedReader { private int timeout = 60. int sz) { super(in.

4. Java Programmer C. To the top Q.. it is clear it is "Windose". It is optimized for use with the JUnit unit test package. shut-down your PC. } catch (InterruptedException e) { break. } if (ms >= waitms) { return defaultStr.currentThread(). 5.java |_test |_src |_com |_mycom |_mypkg |_ATest. ms += 10.sleep(10).readLine(). Should I use quilt to monitor QA code coverage? A: My answer is no. Close cmd or cygwin windows Close Windows Explorer. It worked. Thread. Interesting!! . Haha! To the top Q. 3. What is a good directory structure for main code and junit test code? A: Dev |_src | |_com | |_mycom | |_mypkg | |_A.FAQ on ANT Building Process by Roseanne Zhang. if you cannot.. } } http://bobcat.webappcabaret. the Ant Java build facility. How to fight with your "Windose"? Try the followings in order: 1. even it is not always correct. If still not work. count 1 to 10.htm#ant_abc_Q05 To the top Q.java Check/disable your anti-virus software. 2. then start again. then try use your hand to delete it. then reopen. the extent to which unit testing exercises the software under test. and the Maven project management toolkit. I was struggling with similar problems these two days. Close all possible apps use that file/dir. When ant cannot do it. but it is up to you! Quilt here Copied from Quilt site: Quilt is a Java software development tool that measures coverage . } } return super.net/javachina/faq/ant_01. Why cannot I delete or rename a file/directory in ant? A: Windose makes a lot of decisions for you.

the replacement is done automatically by ant copy task. 2. The reasons are: 1. since the byte code is much smaller. and for keeping the reasonable relationship between development and QA. in my case. I did all my native build by myself on 4 different operating systems. . which made code maintenance a lot simpler. What should I use to build J2ME application/games? A: You can use WTK and antenna and Proguard obfuscator.properties. Build games in different languages became as easy as switching one word in the build. "@en. it stopped developing in 2003.. etc. One more thing is wonderful here. we 'd be better off not to use it. A creative use of token replacement in ant copy task to handle multi-languages in mobile games. It would be better if it were a third party product. It is way better than use "if else or switch case statements".htm#ant_abc_Q05 We wrote something similar to the functionality of quilt long time ago.FAQ on ANT Building Process by Roseanne Zhang. less headache!!! You need to use apache ANT to do your build and deployment. However.comment. Even I've not used ant-contrib cc task yet. To the top Q.end@" is replaced by "/*" The cn.webappcabaret.end@ */ // More languages here. To the top Q. we were forced to take them out.comment. since it alters the bitecode. but from rough look at the doc.end@ */ /* @en. Chinese code and all other language code is untouched or still commented out. Advantages 1. it can do more than you want!!! By the way. Took a look.start@ String abc="??". it was considered spying on QA.comment.start@" is replaced by "*/". http://bobcat. when I was working in a Microsoft Solution Provider shop. Q. We only need one code base instead of many.comment. @cn.comment. When we copy the code to the place for build (compile). A: I used a strategy plus ant token replacement in copy task.. @en. When lang=en. /* @cn. 3. then put them in ant to automate the process.net/javachina/faq/ant_01. or English "@en. You basically need to know how to do it without ant.comment. It is quite hack of work. 2. It is stale. I guess what I said would be still true. Java Programmer C.start@ String abc="Source code". It is dangerous. It is especially important when you are building games on mobile devices. We actually could tell how QA did their job. made our game code comment and uncomment out Chinese/English/etc by just needing to change one user defined ant property lang=en lang=cn lang=any other supported languages such as Spanish. How to do c/c++ build by using ant? A: Take a look at ant-contrib cc task.

The sanbox would have the same name source code. default. I copied the source code need to compile to that directory. A complicated case study. no other people knew the new code yet. and set overwrite="true". Java Programmer C. To the top Q. then compile.htm#ant_abc_Q05 To the top Q.. before compiling.. Writing it down might help you think further. To sandbox developer. All Rights Reserved [JavaChina] . then copying the sandbox/src second. http://bobcat. Of course. In my case. We had developers work in a sandbox. when you download the source code.. copy task copies according to timestamps. You javac from build/tmp/src to build/classes.. which might be different from the mainstream same name code.. but the working developer. To mainstream developer. my case was way more complicated then. otherwise. In this way. I even wrote my own copy task which called CopyWithDependencies.2007 Roseanne Zhang.FAQ on ANT Building Process by Roseanne Zhang. When you want to build a custom ant task. How do I handle two source files with the same pkg/name? A: A friend asked a question at JavaRanch Exclude sources in javac task My answer: I had a good reason to do the similar like you said here when I was working in another company.webappcabaret. the javadoc is included. when the sandbox built.properties. this is out of the range of our discussion here. copying mainstream src was enough. your problem would be solved.net/javachina/faq/ant_01. Actually. copying mainstream src first. I need to have a look at ant source code ant javadoc. How did I handle it? I had a build/tmp/src directory.. How do I find out the relationship between ant task name and Java class in the code? A: They are mapped in default.properties under ant source code To the top last updated: 03-11-2007 Copyright © 1999 . very important. the mainstream would be your src2.