Generating Class-Path in Jar Manifest with Ant

I’ve recently started to touch Ant. Well, I’ve used it before, but only on the ant clean all level. Now I wanted to write a small build script for a tiny project. Which went off easily enough with the help of Apache Ant User Manual. Well, until I wanted to deploy to a executable Jar file.

This didn’t look like it was easily done. Googling around I found that this had been answered before, by Dominique Devienne. I’ll summarize below:

First, you’ll need a property specifying where to find the jars. By using the location attribute Ant will expand it to the full path. Then you need to create a path/fileset of all the jars you want to include in the classpath. This will probably be used to copy/zip the deployment.

The trick is to use the canonical location to convert the path for the fileset back to a relative path. Supply the property generated, the referenced id to the path, the path separator (in manifest’s Class-Path this is a space character) and a directory separator (the slash does the trick). Include a map task in the pathconvert, converting from the absolute path, to a relative path supplied.

In the code below there are an example to make the Class-Path string for a jar, with the libraries in the lib folder one level below the jar file.

	<property name="lib.dir" value="lib"/>
	<property name="lib-folder" location="${lib.dir}"/>

	<path id="cp">
		<fileset dir="${lib.dir}" includes="**/*.jar"/>
	</path>

	<pathconvert property="classpath" refid="cp" pathsep=" " dirsep="/">
		<map from="${lib-folder}" to="../${lib.dir}"/>
	</pathconvert>

In Ant 1.7.0 there is a new task, ManifestClassPath. It seems to me a bit strange (needing the folder in which the jar file should reside in to exist), but you don’t need to do the mapping yourself.

Ta.


« Virtual PC
Java Resources »