09 October 2009

Create ant tasks in build.xml from external (jar) file in project

I will show how to use an ant library with ant tasks without adding the external jar file on the classpath on your computer (for some reason, perhaps so everybody in your team can run them without installment on their local computer).

In this example I will use the Ivy library. It is kind of a silly example since Ivy itself is a tool so no jar files needs to exist in the project directory.

Download and place the external jar file in your project directory. I placed the file ivy-2.1.0-rc2.jar in a directory called lib.

Use a zip-program (for example 7Zip) and look in your jar file to see where the file antlib.xml is. For Ivy this is org/apache/ivy/ant/antlib.xml.

The next step is the make up a namespace. I say makeup, because you can use whatever you like. However it is good to use the form antlib:java package. This way it will work when you one day remove the external library from your project and add in the ant-library directory on your local computer (then you wont need the taskdef). For Ivy the namespace is antlib:org.apache.ivy.ant. For more information see http://ant.apache.org/manual/CoreTypes/antlib.html.

Next is to write the build.xml file:
<project name="ivyhgtest" xmlns:ivy="antlib:org.apache.ivy.ant">
 
  <target name="resolve" description="--> retreive dependencies with ivy">
    <path id="ivy.classpath">
      <fileset dir="lib/" includes="ivy*.jar" />
    </path>
  
    <taskdef resource="org/apache/ivy/ant/antlib.xml"
      classpathref="ivy.classpath"
      uri="antlib:org.apache.ivy.ant" />
 
    <ivy:retrieve />
  </target>
</project>

The content of xmlns:ivy="antlib:org.apache.ivy.ant" must match the uri="antlib:org.apache.ivy.ant". The XML namespace xmlns:ivy is arbitrary but it must match the task namespace <ivy:retrieve />.Choose a good namespace that maches your external feature (only one word).

Note how I used a wildcard to reference the ivy-2.1.0-rc2.jar. It can be good if a new version of the jar is published.

I can now access all the tasks defined in the antlib.xml file with the ivy namespace.

No comments:

Post a Comment