简体   繁体   中英

How to get the right manifest from project with multiple modules? [JAVA]

I want to get to read from the Manifest of my Jar file to get the SVNVersion info from there and show it in the UI. I work on a multi-module project that includes a client, a server running on tomcat, some modules of the client and its dependencies.

I wrote the code to access the current thread's manifest and get it's attributes.

Manifest mf = new Manifest();

    mf.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("META-INF/MANIFEST.MF"));

    Attributes atts = mf.getMainAttributes();
    System.out.println(atts.values());
    System.out.println("Version: " + atts.getClass());
    System.out.println("Revision: " + atts.get("SCM-Revision"));
    String scm = (String) atts.get("SCM-Revision");
    String revision = (String) atts.get("Revision-Number");
    return revision + scm;
}

The only thing is that it gets Null values returned because it get's the manifest of a dependency from the local repository that doesn't have the information i need inside of it.

Is there a solution to my problem? to specify a module from the project in a way so it know's to get IT's jar's Manifest and not the one from the dependency? Thank you!

(I deleted my previous answer because it was buggy and unaccurate)

This is the procedure I used to have to get the proper manifest from any class in the classpath: It consists of getting it through a specific URL:

private static URL getManifestUrlForClass(Class<?> cl)
    throws MalformedURLException
{
    URL url=cl.getResource(cl.getSimpleName() + ".class");
    String s=url.toString();
    return new URL(s.substring(0, s.length() - (cl.getName() + ".class").length()) + "META-INF/MANIFEST.MF");

To use it from your code, just replace the first line:

mf.read(getManifestUrlForClass(MyClass.class).openStream());

You get a null because manifests are disabled in maven by default and what you get are values from the Jdk (jar containing the Thread-classfile). You either read

this.getClass().getResourceAsStream("/META-INF/.../pom.properties")

or add the capability to create a manifest (depends on the modul packaging you have to pick the correct build-plugin for that).

Warning: "/META-INF/.../pom.properties" might have the same path in different Jars. Choose the Class first to determin what pom.properties you like to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM