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.

This entry was posted in Java and tagged , , , , . Bookmark the permalink.

2 Responses to Generating Class-Path in Jar Manifest with Ant

  1. MihaiB says:

    Just what I was looking for: good way to get a list of relative paths (and the operation is safe because map’s “from” only matches a prefix, not anywhere in the path).

    I can’t find out how to escape spaces in the paths (I’m passing a list of files as command line parameters to a program invoked from the buildfile).

    Great post,
    Thanks

  2. Great to hear. I suggest having a look at http://stackoverflow.com for more answers. :)

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">