Monday 25 March 2013

Apache Ant - Tutorial

1. Build Tools
Build tools are used to automate the repetitive task like compiling source code, generating documentation, running tests, uilding the jar and so on. Some of the well known build tools are Apache Ant, Maven.


2. Overview of Ant

Ant(Another Neat Tool) is the java library and mostly used to building and deploying the java application. Ant provides the built-in tools to compile, build, test and packing the java application. Ant builds are based on three blocks.
Tasks: Task is the unit of work. For example compile, packing.
Targets: Targets can be invoked via Ant.
Extension Points: Extension points are same as targets and it won't any operation and just coordinate the targets.

3. Building the Java Application: Using Apache Ant

Create the build.xml(not as same) in your project root directory. Given below is the sample build xml(self explanatory - comments inline)
<?xml version="1.0" ?>
<project name="nRelate Analytics" >
<!-- 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="lib.dir" location="lib" />

<!--
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, dist directory-->
<target name="clean">
<delete dir="${build.dir}" />
<delete dir="${dist.dir}" />
</target>

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

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

<!--Creates the deployable jar file -->
<target name="createjar" depends="compile">
<jar destfile="${dist.dir}LogNormalizer.jar" basedir="${build.dir}">
<!-- Adding to Manifest file, from which class to start exceution -->
<manifest>
<attribute name="Main-Class" value="test.MainClass" />
</manifest>
</jar>
</target>
</project>

4) Run your Ant build from the command line

Open a command line and switch to your project directory. Type in the following commands.
# Run the build
ant -f build.xml
# build.xml is default you can also use
ant
Specify the target as below.
#Run the build.xml by specifying the target.
ant -f build.xml createjar

The build should finish successfully and generate the build artifacts under the dist directory.

Subscribe to get updates on this article.

No comments:

Post a Comment