1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.statistics.examples.distribution;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.net.URL;
22 import java.util.Enumeration;
23 import java.util.jar.Attributes;
24 import java.util.jar.Manifest;
25 import picocli.CommandLine.IVersionProvider;
26
27
28
29
30
31
32
33
34
35 class ManifestVersionProvider implements IVersionProvider {
36
37 private static final String KEY = "Implementation-Title";
38
39
40 @Override
41 public String[] getVersion() throws Exception {
42 final Enumeration<URL> resources = Thread.currentThread().getContextClassLoader()
43 .getResources("META-INF/MANIFEST.MF");
44 while (resources.hasMoreElements()) {
45 final URL url = resources.nextElement();
46 try (InputStream stream = url.openStream()) {
47 final Manifest manifest = new Manifest(stream);
48 if (isApplicableManifest(manifest)) {
49 final Attributes attr = manifest.getMainAttributes();
50 return new String[] {get(attr, KEY) + " version \"" +
51 get(attr, "Implementation-Version") + "\""};
52 }
53 } catch (final IOException ex) {
54 return new String[] {"Unable to read from " + url + ". " + ex};
55 }
56 }
57 return new String[0];
58 }
59
60
61
62
63
64
65
66 private static boolean isApplicableManifest(Manifest manifest) {
67 final Attributes attributes = manifest.getMainAttributes();
68 return "Apache Commons Statistics Distribution Utilities".equals(get(attributes, KEY));
69 }
70
71
72
73
74
75
76
77
78 private static Object get(Attributes attributes, String key) {
79 return attributes.get(new Attributes.Name(key));
80 }
81 }