Tuesday, September 29, 2009

Getting JAR version programmatically

While QAing Ehcache, just to make sure that we have correct JAR loaded and tested, we tried to get the version of JAR from the pom.properties in ehcache-core-xxx.jar. Following code help us accessing the jar file for a particular class, and subsequently the files in it.

 public String getEhcacheVersion(){
String ehcacheVersion = null;
JarInputStream jarIn = null;
File file = null;
try {
file = new File(Ehcache.class.getProtectionDomain()
.getCodeSource().getLocation().toURI());
jarIn = new JarInputStream(new FileInputStream(file));
JarEntry entry;

while ((entry = jarIn.getNextJarEntry()) != null) {
if (entry.getName().toUpperCase().equalsIgnoreCase("META-INF/maven/"
+"net.sf.ehcache/ehcache-core/pom.properties")){

BufferedReader reader = new BufferedReader(new InputStreamReader(jarIn));
String line = null;
while ((line = reader.readLine()) != null) {
if(line.startsWith("version")){
ehcacheVersion=line;
break;
}
}
}
}
}
catch (URISyntaxException e1) {e1.printStackTrace();}
catch (IOException e) {e.printStackTrace();}
finally {
if (jarIn != null)
try { jarIn.close(); } catch (Exception e) {}
}
return
ehcacheVersion;
}
mvn puts data into META-INF/maven/net.sf.ehcache/ehcache-core/pom.properties

#Generated by Maven
#Thu Sep 24 12:20:41 PDT 2009
version=xxx
groupId=net.sf.ehcache
artifactId=ehcache-core

We can also use MANIFEST.MF to get required data.
Post a Comment