views:

1066

answers:

4

Does anyone have code to detect duplicate JARs in the classpath?

Background: When there are two versions of the same JAR in the classpath, really strange things can happen. This can even happen when using tools like Maven: Change a dependency and build the WAR without cleaning first. Since target/webapp/WEB-INF/lib wasn't cleaned, the dependency will be in there twice.

Is there a safety-net for this?

+1  A: 

I think the simplest way is to simply trash the target directory first. Hopefully copying all the .jar files in isn't going to be time-consuming.

Otherwise you're going to have to somehow compare sizable files (whether directly, via computed checksum or similar). Which doesn't sound very nice at all.

Brian Agnew
A: 

You can write a simple script to compare the md5 sum of every jar file to every other jar file and deleting duplicates along the way.

neesh
two versions means by definition that the md5 sum will not match :-)
Toader Mihai Claudiu
ah sorry, missed the different version part of your question
neesh
+9  A: 

JBoss Tattletale might help you with this.

It's a free tool which scans the JAR files used by your project and gives you a report about them.

Amongst its feature are:

  • Spot if a class is located in multiple JAR files
  • Spot if the same JAR file is located in multiple locations
  • Find similar JAR files that have different version numbers
Dave Webb
+1  A: 

System.getProperty("java.class.path"), split it, sort it, look at it with the human eye :-).

It will not include the classpath derived from manifests inside other jars thou :-(.

Or use http://www.jboss.org/tattletale as one of the posters suggested.

Toader Mihai Claudiu
This assumes that your dupes have the same name. Often the problem is duplicate classes in jars with different names. You'd need more than one pair of eyeballs there.
sal
Usually, the names will be different only in a version somewhere (usually a suffix). Programmatically you could detect and highlight common prefixes.
Software Monkey
You only need some sort of a warning sign in certain cases. What I proposed can be coded in 2 minutes and run as some sort of smoke test to catch "normal/easy" duplicates at the application startup. If you want extensive analysis use a tool like the tattletale proposed :-).
Toader Mihai Claudiu