Friday, March 15, 2013

Dealing with Java Hell using JarJar life boat

Okay, so I wanted to use Hex.encodeHexString method from org.apache.commons.codec.binary.Hex (commons-codec-1.6.jar)library to generate encoded singnature. I was able to do this in plain Java, but not in Android. I googled for a while and found out this ticket about Android not supporting the latest versions of commons-codec-1.6.jar.The solutions was to use magical "jarjar" ! But How ??? Again, I googled and come across this and this, and I came up with solution to solve mystery of using  Hex.encodeHexString method in code running on Android (Dalvik VM). Android uses old version of commons-codec jar which doesn't define org.apache.commons.codec.binary.Hex.encodeHexString method signature. Even if you add new commons-codec-1.6.jar to build path of project, code will try to refer to built-in commons-codec not the new one that you added in build path. But, if you change the package name/namespaces for commons-codec-1.6.jar, then you can easily reference from your code and finally can use Hex.encodeHexString. So, you have to create a custom jar with modified package name structure.

Here is how you can spin a new custom jar, say

Step-1: Create a build.xml like follows:
<project name="generate-jarjar">
    <property name="jarjarfile" value="commons-codec-1.6-jarjar.jar"/>
    <path id="classpath">
      <pathelement location="jarjar-1.4.jar"/>
      <pathelement location="asm-2.2.3.jar"/>
    <taskdef name="jarjar" classname="com.tonicsystems.jarjar.JarJarTask"   classpathref="classpath"/>
    <delete file="${jarjarfile}"/>
    <jarjar destfile="${jarjarfile}">
    <zipfileset src="commons-codec-1.6.jar"/>
    <rule pattern="org.apache.**" result="org.jarjar.apache.@1"/>
Step-2: Run command "ant" from command line. This build script will generate a new jar  commons-codec-1.6-jarjar.jar, which you can add in your build path and use this new jar to import from.

You can download all the files mentioned in above script and build.xml from here.

1 comment:

  1. HI Priyanka ,. Could you please suggest me something on the following .

    I have com.efaxdeveloper.util.jar and there is xrcers package in it used by the other classes in the same jar . There is another verion of xrcers jar in my pom.xml used by other application in my project . This gives conflicts . I replaced the xrcers package in com.efaxdeveloper.util jar with the newer version . now How I change their reference in classes . Or is there any othere solutions to it . Please let me know if there is any confusion.
    Thanks !