I often have to find a class (or its different occurrences) in a list of jars located in a folder (or its sub-folders). The Jython script below parses all the jars in a location, and display the name of all the jars containing the class I’m looking for. Stick it into a file called “searchjar.py.”
import os, sys, traceback
from os.path import isdir,join
from java.util.zip import *
from java.util.jar import *
from java.io import *
def scan_directory(class_name, directory=’.’):
for f in os.listdir(directory):
if os.path.isdir(join(directory, f)):
scan_directory(class_name, join(directory, f))
if os.path.basename(f).lower().endswith(’.jar’) > 0 \\
and not os.path.isdir(join(directory, f)):
scan_jar(class_name, join(directory, f))
def scan_jar(class_name, jar_file):
try:
jar = JarFile(jar_file)
entries = jar.entries()
while entries.hasMoreElements():
entry = entries.nextElement()
if entry.toString().find(class_name) >= 0:
print ‘%s: %s’ \\
% (os.path.abspath(jar_file), entry)
except ZipException:
print ‘Error trying to open %s’ % jar_file
traceback.print_exc(file=sys.stdout)
if name ’__main__’:
if not len(sys.argv) 3:
print “Usage: jython search_jar.py “
sys.exit(1)
scan_directory(sys.argv[1] + ’.class’, sys.argv[2])
It can be called as follows:
jython search_jar.py MyNiceStub C:\\application_server\\lib
This script is quite handy when investigating issues related to ClassNotFoundException, or ClassCastException, or classloading-related problems. Watch out, the script appends “.class” to the name of the class you’re passing to the script, so if you’re looking for something other than a class (a resource file, for example), it won’t find it. It doesn’t look for classes which are not in jars either – but adding this to the script is trivial!