May 4, 2012

Easily search contents of jar files

Every now and then I need to quickly search the contents of jar files. For example, yesterday, I was working to try and integrate Spring 3 Security into a third party app. The app was complaining that it couldn't find the Spring class even though I was sure that Spring Security jars were on the classpath (thanks to maven's mvn dependency:tree command).

The class it was complaining about was named "HttpRequestIntegrationFilter". I was able to quickly figure out what the problem was by changing to the directory containing the spring security jars and running the following:

find . -name '*.jar' -exec grep "HttpRequestIntegrationFilter" {} \; -print

The output from this command lists the paths of any jar's that containa match and looks like this:
Binary file ./spring-security-core/2.0.1/spring-security-core-2.0.1-sources.jar matches
./spring-security-core/2.0.1/spring-security-core-2.0.1-sources.jar
Binary file ./spring-security-core/2.0.1/spring-security-core-2.0.1.jar matches
./spring-security-core/2.0.1/spring-security-core-2.0.1.jar

(btw, it's amazing how fast the results come back from that command!)

That's helpful, but in my case, I needed to find the package name. Here's how:

find . -name '*.jar' -print -exec jar -tvf {} \; | awk '/HttpRequestIntegrationFilter/'

The output looks like this:

3643 Fri May 02 11:15:02 EDT 2008 org/springframework/security/adapters/HttpRequestIntegrationFilter.java
3272 Fri May 02 12:40:30 EDT 2008 org/springframework/security/adapters/HttpRequestIntegrationFilter.class
  
After running this command, and comparing the package name with theexception that the third party app was throwing, I realized that thethird party app was expecting a package from Spring 2 Security, notSpring 3 security. Case closed.

If you do a google search, you might find several free ware GUI "jar explorer" type programs available if you google. But I like the command line solution better than a GUI app because you have so much more control over searching. You can also wrap the command above inside a bash file and have a nice, easy to remember command for searching jar files. Even better, if you use emacs, you can add a key binding to run the shell command effortlessly.

Tags: java maven tech