Apache Ant - SPLessons

ANT Tips

Chapter 14

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

ANT Tips

ANT Tips

shape Introduction

ANT is a build tool and has rich set of pre-defined tasks. The current chapter gives some ANT Tips which would be helpful while building projects.

Duplication

shape Tip-1

The basic principle to be followed while using ANT is to avoid data redundancy. This problem occurs while supplying parameters to ANT Targets.

<target name="component1">
<javac nowarn="on" srcdir=".">
</javac>
</target>

<target name="component2">
<javac nowarn="on" srcdir=".">
</javac>
</target>

In the above example, two separate compilation targets are present in a single build file. The script works, however, to find the compilation warnings or to change the source code location, multiple changes need to be done to the build file. So, it is better to write using property task as shown below:

<property name="src" value="."/>
<property name="nowarn" value="on"/>

<target name=component1>
  <javac nowarn="${nowarn}" srcdir="${src}"/>
</target> 

<target name=component2>
  <javac nowarn="${nowarn}" srcdir="${src}"/>
</target>

Converting Paths

shape Tip-2

ANT lets the user to convert relative paths to absolute paths.

<!-- Location of a configuration -->
<property name="my.config" value="../my-config.xml"/>
<makeurl file="${my.config}" property="my.config.url"/> 

The above property can be later used as a parameter.

<param name="highlight.xslthl.config" expression="${my.config.url}"/> 

When a build is to be run on other environments, it is better to use relative paths instead of absolute paths to edit the script and make it work.

Regular Expressions

shape Tip-3

ANT can replace the text with expressions.

<target name="regular-expressions">
  <!-- Replace tabs with two spaces -->
  <replaceregexp flags="gs">
    <regexp pattern="(\t)" />
    <substitution expression=" " />
    <fileset dir="${outputtmp.dir}/">
      <include name="**/*" />
    </fileset>
  </replaceregexp>
</target> 

In the above example, tab is replaced with double spaces.

Default target

shape Tip-4

Default target has to be used to avoid errors while entering ant in the command line. It is better to run the default target, as it depends on the compile target, which compiles automatically.

<project name="myproject" default="run">
<property name="main.class" value="com.splessons.myclass"/>

<target name="compile">
  <javac src="whatever"/>
</target>

<target name="run" depends="compile">
  <java classname="${main.class}" fork="yes"/>
</target>
</project>

Summary

shape Key Points

  • Property task can avoid duplication.
  • Do not use absolute path names.
  • It is better to use default target.