0

Related: Get Maven artifact version at runtime

Contrasting the linked question, that relies on the getPackage() - method on a class in the package, how can the same result be achieved for a package that contains no java - classes, but is only a support library with web resources?

korgmatose
  • 265
  • 4
  • 17
  • 1
    Again, depending on the MANIFEST.MF versus pom.properties. Whichever holds them, you will have to read them in from your classpath and look through them. – Niels Bech Nielsen Jul 21 '17 at 09:28
  • Researching more on reading MANIFEST.MF (whick thankfully gets packaged already in the .jar) halped me to find the right search queries for my problem, thus ending up with the solution below! – korgmatose Jul 21 '17 at 10:21

1 Answers1

0

Using the method found in second answer here: reading MANIFEST.MF file from jar file using JAVA and adding a conditional in the Attributes - checking on the title as presented in MANIFEST.MF returns the proper version.

public static String getManifestInfo() {
        Enumeration resEnum;
        try {
            resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
            while (resEnum.hasMoreElements()) {
                try {
                    URL url = (URL)resEnum.nextElement();
                    InputStream is = url.openStream();
                    if (is != null ) {
                        Manifest manifest = new Manifest(is);
                        Attributes mainAttribs = manifest.getMainAttributes();
                        String version = mainAttribs.getValue("Implementation-Version");
                        String name = mainAttribs.getValue("Implementation-Title");
                        if (version != null && name != null) {
                            if ("packagetitle".equals(name))
                                return version;
                        }
                    }
                }
                catch (Exception e) {
                    // Silently ignore wrong manifests on classpath?
                }
            }
        } catch (IOException e1) {
            // Silently ignore wrong manifests on classpath?
        }
        return null;
    }

This can surely be made even more effectively by skipping the iteration using stream() if knowing details about the package itself, but at least this works as intended.

korgmatose
  • 265
  • 4
  • 17