13 April 2012

How-to find a class in a JAR directory using shell scripting

The biggest problems in J2EE applications deployment  come often from classloader hierarchies and potential overlapping between server-provided and application-specific libraries. So, searching classes through collection of JARs is oftwen the main activity in order to identifiy and fix classloader issues.
This is surely a tedious and repetitive task: so, here's a shell script you can use to automate JAR collection traversing and tar command's output analysis to search a pattern, which is provided as script parameter.

Credits: Thanks to sirowain for parameter check and return code related contributions.

#!/bin/bash
# Commonly available under GPL 3 license
# Copyleft Pietro Martinelli - javapeanuts.blogspot.com
if [ -z $1 ]
then
        echo "Usage: $0 <pattern>"
        echo "tar xf's output will be tested against provided <pattern> in order\
          to select matching JARs"
        exit 1
else
        jarsFound=""
        for file in $(find . -name "*.jar"); do
                echo "Processing file ${file} ..."
                out=$(jar tf ${file} | grep ${1})
                if [ "${out}" != "" ]
                then
                        echo "  Found '${1}' in JAR file ${file}"
                        jarsFound="${jarsFound} ${file}"
                fi
        done
        echo "${jarsFound}"
        
        echo ""
        echo "Search result:"
        echo "" 
        
        if [ "${jarsFound}" != "" ]
        then
                echo "${1} found in"
                for file in ${jarsFound}
                do
                        echo "- ${file}"
                done
        else
                echo "${1} not found"
        fi
        exit 0
fi

This script is available on github.com:

4 comments:

  1. I will find this useful. Is there a way to save the jar content info to a flat file and then index it? I only occassionally get new jars and then a routine could check on the new jars to update the index. I thought about creating a database but what we really have is an indexed set of jars.

    ReplyDelete
  2. First i wrote a similar script, then i found this tool:
    http://www.inetfeedback.com/jarscan/

    ReplyDelete
  3. I do love bash and often say that bash is my favorite language to program in. This task does not require a bash script. All that is needed is:

    $ jar -tf someJar.jar | grep SomeClass

    And another tip: as jar files are zip archives, you can also use the zipinfo command on linux to get the same done.

    ReplyDelete
  4. https://gist.github.com/2402770

    ReplyDelete