Used JARs During Program Execution

Hi. In a Java project of mine, I link to the large open source project soapUI, which in turn links to approx. 50 jars. But I only use a very small subset of soapUI. And because of this, I do not want to include all the 50 jars into my own application. But which of these 50 jars of soapUI are actually used through my application? If you have had a similar problem, read ahead as I show you how you can determine which jars are actually used during a program run.

First, to get the data which classes are loaded from which jars, I had to start my program on the JVM via the -verbose:class parameter. This automatically prints out using the format [Loaded CLASS from JAR] on the console while the program is running. The following snippet shows such a line.

$ java -verbose:class -jar app.jar
...
[Loaded java.io.FileInputStream from C:\Program Files\Java\jdk1.8.0_102\jre\lib\rt.jar]
...

Second, I captured the console output of my program in a text file so I can work with the console output.

$ java -verbose:class -jar app.jar > stdout.txt

Third, I had to capture the lines using the format [Loaded CLASS from JAR] only. For this, I used a regular expression in the form of \[Loaded .* from .*\.jar\] and the linux command line tool grep.

$ grep --extended-regexp --only-matching "\[Loaded .* from .*\.jar\]" stdout.txt > verbose-classes-log.txt

Fourth, I had to extract the paths of the jars to read them. For that, I use a group \[Loaded .* from .(*\.jar)\] and extract the group with sed.

$ sed --regexp-extended --silent 's/\[Loaded .* from (.*\.jar)\]/\1/p' verbose-classes-log.txt > loaded-jars.txt

Last, I sort them, remove duplicates and count the usage, as well as sort it again.

$ cat loaded-jars.txt | sort | uniq --count | sort > loaded-jars-sorted-by-usage.txt

In summary, we can do this in one step as well using pipes.

$ java -verbose:class -jar app.jar | grep --extended-regexp --only-matching "\[Loaded .* from .*\.jar\]" | sed --regexp-extended --silent 's/\[Loaded .* from (.*\.jar)\]/\1/p' | sort | uniq --count | sort

Hope, this helps!

 •  0 comments  •  flag
Share on Twitter
Published on September 22, 2016 09:10
No comments have been added yet.