vogella.de

Follow me on twitter
About Lars Vogel
Flattr this

Apache Ant - Tutorial

Lars Vogel

Version 0.9

02.02.2010

Revision History
Revision 0.130.11.2008Lars Vogel
Created
Revision 0.212.01.2009Lars Vogel
Added installation
Revision 0.329.01.2009Lars Vogel
Added Junit with Ant
Revision 0.429.01.2009Lars Vogel
Added: How to print the classpath of an Ant Task
Revision 0.503.02.2009Lars Vogel
Added: subversion with ant
Revision 0.617.04.2009Lars Vogel
How to extend the ant class under Eclipse
Revision 0.720.07.2009Lars Vogel
Minor rework
Revision 0.803.01.2010Lars Vogel
Fixed incorrect package in ant example
Revision 0.902.02.2010Lars Vogel
Improved installation description, Apache Ant from the command line

Apache Ant

This article describes how to install, configure and use Apache Ant as a build tool to compile Java code, pack this code into an executable jar and how to create Javadoc. The usage of Ant is demonstrated within Eclipse and from the command line. This tutorial is based on Apache Ant 1.7.x.


Table of Contents

1. Overview
2. Installation
2.1. Linux (Ubuntu / Debian)
2.2. Windows
3. Using Apache Ant
3.1. Overview
3.2. Create example Java project
3.3. Create build.xml
3.4. Run your Ant build from Eclipse
3.5. Run your Ant build from the command line
4. Apache Ant classpath
4.1. Setting the Ant classpath
4.2. Print
5. Running JUnit Tests via Ant
6. Subversion (svn) with Ant
7. Eclipse Ant Editor
8. Thank you
9. Questions and Discussion
10. Links and Literature
10.1. Source Code
10.2. General

1. Overview

Apache Ant (Another Neat Tool) is a build tool, mainly for Java projects. A build tool can be used to automate certain repetitive tasks, e.g. compiling source code, running software tests, creating jar files, javadocs, etc.

A build process typically includes:

  • the compilation of the Java source code into Java bytecode
  • creation of the .jar file for the distribution of the code
  • creation of the Javadoc documentation

Ant uses a xml file for its configuration. This file is usually called "build.xml". Within this build file you specify the targets for ant. A target is a step which ant will perform. You also can specific dependencies. If target A depends on target B, ant will first do B and then A. Also you specify the main target. This target is the target ant will try to execute per default. If this target depends on other targets then ant will automatically perform these task first and so on and so on.

2. Installation

2.1. Linux (Ubuntu / Debian)

On Debian /Ubuntu use "apt-get install ant" to install it.

2.2. Windows

Download Apache Ant from http://ant.apache.org/ .

Extract the zip file into a directory structure of your choice. Set the "ANT_HOME" environment variable to this location and include the "ANT_HOME/bin" directory in your path.

Tip

Make sure that also the JAVA_HOME environment variable is set to the JDK. This is required for running Ant.

Check your installation by opening a command line and typing "ant" into the commend line. The system should find the ant and complain about a missing "build.xml" file.

3. Using Apache Ant

3.1.  Overview

The following will give a small example for performing task with Ant. Using Apache Ant we will:

  • compile Java classes

  • create an executable .jar file

  • create the javadoc

3.2. Create example Java project

Create a Java Project "de.vogella.build.ant.first" in Eclipse. See Using Eclipse in case you need help in using Eclipse.

Create a package called "math" and create the following class.

				
package math;

public class MyMath {
	public int multi(int number1, int number2) {
		return number1 * number2;
	}
}

			

Create a package called "test" and create the following class.

				
package test;

import math.MyMath;

public class Main {
	public static void main(String[] args) {
		MyMath math = new MyMath();
		System.out.println("Result is: " + math.multi(5, 10));
	}
}

			

3.3. Create build.xml

Create a new File through File -> New -> File and call the file "build.xml"

Implement this code to your build.xml.

				
<?xml version="1.0"?>
<project name="Ant-Test" default="main" basedir=".">
	<!-- Sets variables which can later be used. -->
	<!-- The value of a property is accessed via ${} -->
	<property name="src.dir" location="src" />
	<property name="build.dir" location="build" />
	<property name="dist.dir" location="dist" />
	<property name="docs.dir" location="docs" />

	<!-- Deletes the existing build, docs and dist directory-->
	<target name="clean">
		<delete dir="${build.dir}" />
		<delete dir="${docs.dir}" />
		<delete dir="${dist.dir}" />
	</target>

	<!-- Creates the  build, docs and dist directory-->
	<target name="makedir">
		<mkdir dir="${build.dir}" />
		<mkdir dir="${docs.dir}" />
		<mkdir dir="${dist.dir}" />
	</target>

	<!-- Compiles the java code (including the usage of library for JUnit -->
	<target name="compile" depends="clean, makedir">
		<javac srcdir="${src.dir}" destdir="${build.dir}">
		</javac>

	</target>

	<!-- Creates Javadoc -->
	<target name="docs" depends="compile">
		<javadoc packagenames="src" sourcepath="${src.dir}" destdir="${docs.dir}">
			<!-- Define which files / directory should get included, we include all -->
			<fileset dir="${src.dir}">
				<include name="**" />
			</fileset>
		</javadoc>
	</target>

	<!--Creates the deployable jar file  -->
	<target name="jar" depends="compile">
		<jar destfile="${dist.dir}\de.vogella.build.test.ant.jar" basedir="${build.dir}">
			<manifest>
				<attribute name="Main-Class" value="test.Main" />
			</manifest>
		</jar>
	</target>

	<target name="main" depends="compile, jar, docs">
		<description>Main target</description>
	</target>

</project>
			

The code is documented, you should be able to determine the purpose of the different ant tasks via the documentation in the coding.

3.4. Run your Ant build from Eclipse

Run the build.xml file as an "Ant Build".

After this process your data structure should look like this:

Congratulation! You have successfully used Apache Ant from Eclipse.

3.5. Run your Ant build from the command line

Open a command line and switch to your project directory.Type in "ant" or "ant -f build.xml" to start the build process.

Congratulation! You have successfully used Apache Ant from the command line.

4. Apache Ant classpath

4.1. Setting the Ant classpath

Ant allows to create classpath containers and use them in tasks. The following "build.xml" from project "de.vogella.build.ant.classpath" demonstrates this.

				
<?xml version="1.0"?>
<project name="Ant-Test" default="Main" basedir=".">
	<!-- Sets variables which can later be used. -->
	<!-- The value of a property is accessed via ${} -->
	<property name="src.dir" location="src" />
	<property name="lib.dir" location="lib" />
	<property name="build.dir" location="build" />

	<!--
		Create a classpath container which can be later used in the ant task
	-->
	<path id="build.classpath">
		<fileset dir="${lib.dir}">
			<include name="**/*.jar" />
		</fileset>
	</path>

	<!-- Deletes the existing build directory-->
	<target name="clean">
		<delete dir="${build.dir}" />
	</target>

	<!-- Creates the  build  directory-->
	<target name="makedir">
		<mkdir dir="${build.dir}" />
	</target>

	<!-- Compiles the java code -->
	<target name="compile" depends="clean, makedir">
		<javac srcdir="${src.dir}" destdir="${build.dir}" classpathref="build.classpath" />
	</target>



	<target name="Main" depends="compile">
		<description>Main target</description>
	</target>

</project>

			

4.2. Print

You can use the following statements to write the full classpath to the console. You can use this to easily verify if the classpath is correct.

				
<!-- Write the classpath to the console. Helpful for debugging -->
<!-- Create one line per classpath element-->
<pathconvert pathsep="${line.separator}" property="echo.classpath" refid="junit.class.path">
</pathconvert>
<!-- Write the result to the console -->
<echo message="The following classpath is associated with junit.class.path " />
<echo message="${echo.classpath}" />
			

5. Running JUnit Tests via Ant

Apache Ant allows to run JUnit tests. Ant defines the "junit" task. You only need to include the junit.jar and the compiled classes into the classpath for Ant and then you can run Junit tests. See JUnit Tutorial for an introduction into JUnit.

The following is a JUnit test for the previous example.

Tip

As of Apache Ant 1.7.x you can run JUnit 4.x tests without problems.

			
package test;

import math.MyMath;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class MyMathTest {
	@Test
	public void testMulti() {
		MyMath math = new MyMath();
		assertEquals(50, math.multi(5, 10));
	}
}

		

You can run this JUnit unit test via the following build.xml. This example assumes that the JUnit jar "junit.jar" is in folder "lib".

			
<?xml version="1.0"?>
<project name="Ant-Test" default="main" basedir=".">
	<!-- Sets variables which can later be used. -->
	<!-- The value of a property is accessed via ${} -->
	<property name="src.dir" location="src" />
	
	<property name="build.dir" location="build" />

	<!-- Variables used for JUnit testin -->
	<property name="test.dir" location="src" />
	<property name="test.report.dir" location="testreport" />

	<!-- Define the classpath which includes the junit.jar and the classes after compiling-->
	<path id="junit.class.path">
		<pathelement location="lib/junit.jar" />
		<pathelement location="${build.dir}" />
	</path>


	<!-- Deletes the existing build, docs and dist directory-->
	<target name="clean">
		<delete dir="${build.dir}" />
		<delete dir="${test.report.dir}" />
	</target>

	<!-- Creates the  build, docs and dist directory-->
	<target name="makedir">
		<mkdir dir="${build.dir}" />
		<mkdir dir="${test.report.dir}" />
	</target>

	<!-- Compiles the java code (including the usage of library for JUnit -->
	<target name="compile" depends="clean, makedir">
		<javac srcdir="${src.dir}" destdir="${build.dir}">
			<classpath refid="junit.class.path" />
		</javac>

	</target>

	<!-- Run the JUnit Tests -->
	<!-- Output is XML, could also be plain-->
	<target name="junit" depends="compile">
		<junit printsummary="on" fork="true" haltonfailure="yes">
			<classpath refid="junit.class.path" />
			<formatter type="xml" />
			<batchtest todir="${test.report.dir}">
				<fileset dir="${src.dir}">
					<include name="**/*Test*.java" />
				</fileset>
			</batchtest>
		</junit>
	</target>

	<target name="main" depends="compile, junit">
		<description>Main target</description>
	</target>

</project>
		

6. Subversion (svn) with Ant

Tip

This example will be stored in project de.vogella.build.ant.svn

Apache Ant does not include a standard task which can be used to checkout source code from a subversion repository. You can download an additional ant task for this from the following website: http://subclipse.tigris.org/svnant.html

To use the svn task you have to add svnant.jar and svnClientAdapter.jar, svnjavahl.jar and svnkit.jar to your ant classpath.

The following example will checkout the svnant task source code via the svnant task.

			
<?xml version="1.0"?>
<project name="svn-test" default="Main" basedir=".">
	<!-- Sets variables which can later be used. -->
	<!-- The value of a property is accessed via ${} -->
	<property name="checkout" location="c:\temp\svncheckout\" />
	<!-- Define the classpath which includes the jars that are required for svnant.jar -->
	<path id="svnant.class.path">
		<pathelement location="lib/svnant.jar" />
		<pathelement location="lib/svnClientAdapter.jar" />
		<pathelement location="lib/svnjavahl.jar" />
		<pathelement location="lib/svnkit.jar" />
	</path>

	<typedef resource="org/tigris/subversion/svnant/svnantlib.xml" classpathref="svnant.class.path" />


	<!-- Deletes the existing build, docs and dist directory-->
	<target name="clean">
		<delete dir="${checkout}" />
	</target>

	<!-- Creates the  build, docs and dist directory-->
	<target name="makedir">
		<mkdir dir="${checkout}" />
	</target>


	<!-- Checkout the latest source code of svnant itself-->
	<target name="svn">
		<svn username="guest" password="">
			<checkout url="http://subclipse.tigris.org/svn/subclipse/trunk/svnant/" revision="HEAD" destPath="${checkout}" />
		</svn>
	</target>

	<target name="Main" depends="clean, makedir, svn">
		<description>Main target</description>
	</target>

</project>
		

Tip

If you are behind a proxy you can set this up via setproxy, for example

					
<target name="checkOutWithProxy">
	<setproxy proxyhost="${proxy.host}" proxyport="${proxy.port}" />
	<svn>
		<checkout url="${url.main}" destPath="${targetdir}" />
	</svn>
</target>
				

7. Eclipse Ant Editor

Eclipse has an ant editor which make the editing of ant file very easy by providing syntax checking of the build file. Eclipse has also a ant view. In this view you execute ant files via double-clicking on the target.

Tip

By default Eclipse uses the ant version which ships with Eclipse. Via the preference Ant -> Runtime -> Ant Home you can configure the version of Ant Eclipse should be using.

8. Thank you

Thank you for practicing with this tutorial.

I maintain this tutorial in my private time. If you like the information please help me by using flattr or donating or by recommending this tutorial to other people.

Flattr this

9. Questions and Discussion

Before posting questions, please see the vogella FAQ . If you have questions or find an error in this article please use the www.vogella.de Google Group . I have created a short list how to create good questions which might also help you. .

10. Links and Literature

10.1. Source Code

http://www.vogella.de/code/codejava.html Source Code of Examples

10.2. General

http://ant.apache.org/ Apache Ant Homepage http://subclipse.tigris.org/svnant.html Subversion Ant Task