Using Ant-Contrib with NetBeans builds

Having learned NAnt first, it was dissapointing to realise that Ant lacked certain core tasks that I have become familiar with in NAnt. Luckily a community maintains a library, Ant-Contrib, which you will probably want to use if you are working with complex builds.

The recommended way to use Ant-Contrib is to put it in the lib directory of the Ant installation. If you are using NetBeans, which uses its own internal Ant install, this means putting it in C:\Program Files\NetBeans 6.5.1\java2\ant\lib.

This is bad development practice (unless you are a sole programmer with only one dev machine) because your project build then depends on something (the Ant-Contrib jar) which is tied up to your operating system. I prefer to keep absolutely every dependency you need to build and run your project as part of the project itself, so that you won’t run into conflicts with other projects needing a different version of the same dependency, and anyone can check-out your project from a repository and run / build it on any machine with one click.

To achieve this put Ant-Contrib in {$Project.Root}/tools/Ant/Ant-Contrib/ or wherever it should sit in your project file tree. I like to set up some common properties for my builds to tell me the paths to useful files:

<property name="tools.dir" value="./tools" />
<property name="ant.contrib.jar" value="${tools.dir}/ant-contrib/ant-contrib.jar" />

You can then use the following Ant target at the start of your build process to make all the Ant-Contrib tasks available:

<taskdef resource="net/sf/antcontrib/antcontrib.properties">
    <classpath>
        <pathelement location="${ant.contrib.jar}"/>
    </classpath>
</taskdef>

After that you can use useful stuff like conditional flow with if / then / else blocks which you can’t do with a basic Ant install:

<if>
    <equals arg1="${foo}" arg2="${bar}" />
    <then>
        ... do some stuff	
    </then>
</if>

posted 6 months ago