Friday, June 12, 2009

How to generate class-path variable in Manifest file of a jar

The project has dependency on some external jar files. To create a build file in such a way that build.xml doesn’t need to be modified when a new jar file is added to the lib folder.

For that we need to generate Class-Path attribute in the MANIFEST.MF dynamically. The following code shows how to do that.


1. Define a path element say, classpath

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

The above code will set the absolute path of all the jar files in the lib folder to the path element 'classpath'

2. Convert the path element values into relative path and store it in a string property, say jar.classpath

<pathconvert property="jar.classpath" refid="classpath" pathsep=" ">
<mapper>
<chainedmapper>
<flattenmapper/>
<globmapper from="*.jar" to="lib/*.jar"/>
</chainedmapper>
</mapper>
</pathconvert>


3. Use the property 'jar.classpath' to define the manifest file while creating the jar.

<target name="jar" depends="clean,compile">
<mkdir dir="${jar.dir}"/>
<mkdir dir="${jar.lib.dir}"/>
<!-- Copying the external libraries to build/jar/lib folder. -->
<copy todir="${jar.lib.dir}">
<fileset dir="${lib.dir}" excludes="**/*.svn"/>
</copy>
<jar destfile="${jar.dir}/${jar.file}" basedir="${classes.dir}" excludes="**/*.svn">
<manifest>
<attribute name="Class-Path" value=". ${jar.classpath}" />
</manifest>
</jar>
</target>

Note :- The lib directory with the external jar files should be in the same directory as that of the project jar file.

We can't put the external jar files inside the project jar files with the above method.

No comments:

Post a Comment