Friday, March 23, 2007

Shell script to locate a Java class

The following shell script will locate a Java class in CLASSPATH and additional jars, zip files, or directories specified on the command line. For example,

$ CLASSPATH= findClass DataSourceRealm /usr/local/tomcat/server/lib/*.jar
---- Searching for DataSourceRealm
---- Searching in /usr/local/tomcat/server/lib/catalina-ant.jar
---- Searching in /usr/local/tomcat/server/lib/catalina.jar
org/apache/catalina/realm/DataSourceRealm.class
---- Searching in /usr/local/tomcat/server/lib/commons-beanutils.jar
...
**** DataSourceRealm found in /usr/local/tomcat/server/lib/catalina.jar

Source

#!/bin/bash
#****h* bin/findClass
# NAME
# findClass - searches for a Java class in directories, jars, zip files, and CLASSPATH
# ARGUMENTS
# * 1 - Java class name or substring
# * ... - additional directories, jars, zip files
# RETURN VALUE
# * exit code 0, if the class is found
# * exit code 1, if the class is not found
# SOURCE
if [ $# -eq 0 ]; then
echo "Usage: findClass <CLASSNAME> [ FILE ... ]"
exit
fi
class=`echo $1| tr . /`
shift
allDirs="$(echo "$@" $CLASSPATH| perl -F: -ane 'print join(" ",@F);')"
printf -- "---- Searching for %s\n" "$class" >&2
foundIn=()
for dir in $allDirs; do
printf -- "---- Searching in %s\n" "$dir" >&2
case $dir in
*.zip)
unzip -v "$dir" | grep $class && foundIn[${#foundIn}]="$dir"
;;
*.jar)
jar -tf "$dir" | grep $class && foundIn[${#foundIn}]="$dir"
;;
*)
find "$dir" -print | grep $class && foundIn[${#foundIn}]="$dir"
;;
esac
done
if [ ${#foundIn} -eq 0 ]; then
printf -- "**** %s not found\n" "$class" >&2
exit 1
else
printf -- "**** %s found in %s\n" "$class" "${foundIn[*]}" >&2
fi
#****

No comments: