Monday, November 11, 2013

Referring 3rd party Jars within your Jar /lib : MANIFEST.mf Class-Path

As per my current understanding, you cannot refer any third party utility Jars which you placed in your apps /lib folder, when you export it as a Jar. 
Say yourJar.jar has lib/log4j.jar.  But your main class cannot load the log4j classes
http://www.velocityreviews.com/forums/t130458-executable-jar-classpath-problem.html 

The workaround for this situation: Place those utility/thrid party Jars in the same directory or inner directories, where your Jar is placed and making sure that that relative path is mentioned in the Manifest.mf Class-path Header.



<!-- This build script will help you build your own Jar, with utility Jars exported with
and all those Jars added to the MANIFEST.mf Class-Path header
-->
<project
name="buildJar" default="build-jar" basedir=".">
<!-- Add all the jar files in lib folder to the class path -->
<path id="build.classpath">
<fileset dir="${basedir}/">
<include name="lib/*.jar" />
</fileset>
</path>
<!-- Copy all Jars name to the Class-Path; keep an eye on the SPACE seperator -->
<pathconvert property="project.manifest.classpath" pathsep=" lib/">
<path refid="build.classpath" />
<mapper>
<chainedmapper>
<flattenmapper />
<globmapper from="*.jar" to="*.jar" />
</chainedmapper>
</mapper>
</pathconvert>
<target name="clean">
<delete dir="bin" />
<mkdir dir="bin/lib" />
<delete dir="build" />
<mkdir dir="build" />
</target>
<target name="copy-inner-jar-files">
<copy todir="bin/lib" includeemptydirs="false">
<fileset dir="lib" includes="*.jar" />
</copy>
</target>
<target name="copy-non-java-files">
<copy todir="bin" includeemptydirs="false">
<fileset dir="src" includes="**/*" />
</copy>
</target>
<target name="compile-jar-classes" depends="clean,copy-non-java-files, copy-inner-jar-files">
<javac srcdir="src" destdir="bin" classpathref="build.classpath" />
</target>
<target name="build-jar" depends="compile-jar-classes" >
<jar basedir="bin" jarfile="${basedir}/build/MyJar.jar">
<fileset dir="build" />
<manifest>
<attribute name="Main-Class" value="com.sree.test.jar.MyInnerJarTesterMain" />
<!-- <attribute name="Class-Path" value=" . lib/junit-4.10.jar lib/log4j.jar lib/ojdbc14.jar" /> -->
<attribute name="Class-Path" value=". lib/${project.manifest.classpath}" />
</manifest>
</jar>
</target>
>jar -xf MyJar.jar lib
-->
<!-- To take out just the lib/ directory jars out to the same directory as this JAR use below command</project>

<?xml version="1.0"?>

No comments:

Post a Comment