Thursday, June 30, 2011

Compare binary two jar files

Compare two jar files, included the binary content (it will be created an hex dump).

Third-party dependency: jar (openJdk), hexdump, meld
#!/bin/sh

export TEMP="/tmp"

print_usage() {
  echo "$0  " 
}

# Validate the args. Two arguments are expected.
validate_args() {
  if [[ $1 == "" ]]; then
    print_usage
    exit -1
  fi
  
  if [[ $2 == "" ]]; then
    print_usage
    exit -1
  fi
}

# Extract the jar to the $TEMP dir and do a hex dump for 
# the binary files (the original file is deleted).
#
# arg1: the path to the jar file
extract_jar() {
  basename1=`basename $1`
  dir1="$TEMP/$basename1.d"
  rm -fR $dir1
  mkdir -p $dir1
  cp $1 $dir1
  cd $dir1 && jar -xf "$dir1/$basename1" && cd -
  rm -f "$dir1/$basename1"
  
  find "$dir1" -type f | while read filename
   do
     # retrieve the mime type
     mime=`file -bi "$filename"`
     encoding=`echo $mime | cut -d "=" -f2`
     
     # hex dump for binary files
     if [[ $encoding == "binary" ]]; then
       hexdump -C "$filename" > "$filename.hex"
       rm -f "$filename"
     fi
   done
}
validate_args $1 $2
echo "Compare '$1' with '$2'"
extract_jar $1
extract_jar $2

#Compare with MELD
basename1=`basename $1`
dir1="$TEMP/$basename1.d"
basename2=`basename $2`
dir2="$TEMP/$basename2.d"

meld "$dir1" "$dir2"