View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.hc.core5.util;
29  
30  import java.io.IOException;
31  import java.io.InputStream;
32  import java.util.ArrayList;
33  import java.util.List;
34  import java.util.Map;
35  import java.util.Properties;
36  
37  /**
38   * Provides access to version information for HTTP components.
39   * Static methods are used to extract version information from property
40   * files that are automatically packaged with HTTP component release JARs.
41   * <p>
42   * All available version information is provided in strings, where
43   * the string format is informal and subject to change without notice.
44   * Version information is provided for debugging output and interpretation
45   * by humans, not for automated processing in applications.
46   * </p>
47   *
48   * @since 4.0
49   */
50  public class VersionInfo {
51  
52      /** A string constant for unavailable information. */
53      public final static String UNAVAILABLE = "UNAVAILABLE";
54  
55      /** The filename of the version information files. */
56      public final static String VERSION_PROPERTY_FILE = "version.properties";
57  
58      // the property names
59      public final static String PROPERTY_MODULE    = "info.module";
60      public final static String PROPERTY_RELEASE   = "info.release";
61      public final static String PROPERTY_TIMESTAMP = "info.timestamp";
62  
63  
64      /** The package that contains the version information. */
65      private final String infoPackage;
66  
67      /** The module from the version info. */
68      private final String infoModule;
69  
70      /** The release from the version info. */
71      private final String infoRelease;
72  
73      /** The timestamp from the version info. */
74      private final String infoTimestamp;
75  
76      /** The classloader from which the version info was obtained. */
77      private final String infoClassloader;
78  
79  
80      /**
81       * Instantiates version information.
82       *
83       * @param pckg      the package
84       * @param module    the module, or {@code null}
85       * @param release   the release, or {@code null}
86       * @param time      the build time, or {@code null}
87       * @param clsldr    the class loader, or {@code null}
88       */
89      protected VersionInfo(final String pckg, final String module,
90                            final String release, final String time, final String clsldr) {
91          Args.notNull(pckg, "Package identifier");
92          infoPackage     = pckg;
93          infoModule      = (module  != null) ? module  : UNAVAILABLE;
94          infoRelease     = (release != null) ? release : UNAVAILABLE;
95          infoTimestamp   = (time    != null) ? time    : UNAVAILABLE;
96          infoClassloader = (clsldr  != null) ? clsldr  : UNAVAILABLE;
97      }
98  
99  
100     /**
101      * Obtains the package name.
102      * The package name identifies the module or informal unit.
103      *
104      * @return  the package name, never {@code null}
105      */
106     public final String getPackage() {
107         return infoPackage;
108     }
109 
110     /**
111      * Obtains the name of the versioned module or informal unit.
112      * This data is read from the version information for the package.
113      *
114      * @return  the module name, never {@code null}
115      */
116     public final String getModule() {
117         return infoModule;
118     }
119 
120     /**
121      * Obtains the release of the versioned module or informal unit.
122      * This data is read from the version information for the package.
123      *
124      * @return  the release version, never {@code null}
125      */
126     public final String getRelease() {
127         return infoRelease;
128     }
129 
130     /**
131      * Obtains the timestamp of the versioned module or informal unit.
132      * This data is read from the version information for the package.
133      *
134      * @return  the timestamp, never {@code null}
135      */
136     public final String getTimestamp() {
137         return infoTimestamp;
138     }
139 
140     /**
141      * Obtains the classloader used to read the version information.
142      * This is just the {@code toString} output of the classloader,
143      * since the version information should not keep a reference to
144      * the classloader itself. That could prevent garbage collection.
145      *
146      * @return  the classloader description, never {@code null}
147      */
148     public final String getClassloader() {
149         return infoClassloader;
150     }
151 
152 
153     /**
154      * Provides the version information in human-readable format.
155      *
156      * @return  a string holding this version information
157      */
158     @Override
159     public String toString() {
160         final StringBuilder sb = new StringBuilder
161             (20 + infoPackage.length() + infoModule.length() +
162              infoRelease.length() + infoTimestamp.length() +
163              infoClassloader.length());
164 
165         sb.append("VersionInfo(")
166             .append(infoPackage).append(':').append(infoModule);
167 
168         // If version info is missing, a single "UNAVAILABLE" for the module
169         // is sufficient. Everything else just clutters the output.
170         if (!UNAVAILABLE.equals(infoRelease)) {
171             sb.append(':').append(infoRelease);
172         }
173         if (!UNAVAILABLE.equals(infoTimestamp)) {
174             sb.append(':').append(infoTimestamp);
175         }
176 
177         sb.append(')');
178 
179         if (!UNAVAILABLE.equals(infoClassloader)) {
180             sb.append('@').append(infoClassloader);
181         }
182 
183         return sb.toString();
184     }
185 
186 
187     /**
188      * Loads version information for a list of packages.
189      *
190      * @param pckgs     the packages for which to load version info
191      * @param clsldr    the classloader to load from, or
192      *                  {@code null} for the thread context classloader
193      *
194      * @return  the version information for all packages found,
195      *          never {@code null}
196      */
197     public static VersionInfo[] loadVersionInfo(final String[] pckgs,
198                                                       final ClassLoader clsldr) {
199         Args.notNull(pckgs, "Package identifier array");
200         final List<VersionInfo> vil = new ArrayList<>(pckgs.length);
201         for (final String pckg : pckgs) {
202             final VersionInfo vi = loadVersionInfo(pckg, clsldr);
203             if (vi != null) {
204                 vil.add(vi);
205             }
206         }
207 
208         return vil.toArray(new VersionInfo[vil.size()]);
209     }
210 
211 
212     /**
213      * Loads version information for a package.
214      *
215      * @param pckg      the package for which to load version information,
216      *                  for example "org.apache.http".
217      *                  The package name should NOT end with a dot.
218      * @param clsldr    the classloader to load from, or
219      *                  {@code null} for the thread context classloader
220      *
221      * @return  the version information for the argument package, or
222      *          {@code null} if not available
223      */
224     public static VersionInfo loadVersionInfo(final String pckg, final ClassLoader clsldr) {
225         Args.notNull(pckg, "Package identifier");
226         final ClassLoader cl = clsldr != null ? clsldr : Thread.currentThread().getContextClassLoader();
227 
228         Properties vip = null; // version info properties, if available
229         try {
230             // org.apache.http becomes
231             // org/apache/http/version.properties
232             final InputStream is = cl.getResourceAsStream(pckg.replace('.', '/') + "/" + VERSION_PROPERTY_FILE);
233             if (is != null) {
234                 try {
235                     final Properties props = new Properties();
236                     props.load(is);
237                     vip = props;
238                 } finally {
239                     is.close();
240                 }
241             }
242         } catch (final IOException ex) {
243             // shamelessly munch this exception
244         }
245 
246         VersionInfo result = null;
247         if (vip != null) {
248             result = fromMap(pckg, vip, cl);
249         }
250 
251         return result;
252     }
253 
254     /**
255      * Instantiates version information from properties.
256      *
257      * @param pckg      the package for the version information
258      * @param info      the map from string keys to string values,
259      *                  for example {@link java.util.Properties}
260      * @param clsldr    the classloader, or {@code null}
261      *
262      * @return  the version information
263      */
264     protected static VersionInfo fromMap(final String pckg, final Map<?, ?> info,
265                                                final ClassLoader clsldr) {
266         Args.notNull(pckg, "Package identifier");
267         String module = null;
268         String release = null;
269         String timestamp = null;
270 
271         if (info != null) {
272             module = (String) info.get(PROPERTY_MODULE);
273             if ((module != null) && (module.length() < 1)) {
274                 module = null;
275             }
276 
277             release = (String) info.get(PROPERTY_RELEASE);
278             if ((release != null) && ((release.length() < 1) ||
279                                       (release.equals("${pom.version}")))) {
280                 release = null;
281             }
282 
283             timestamp = (String) info.get(PROPERTY_TIMESTAMP);
284             if ((timestamp != null) &&
285                 ((timestamp.length() < 1) ||
286                  (timestamp.equals("${mvn.timestamp}")))
287                 ) {
288                 timestamp = null;
289             }
290         } // if info
291 
292         String clsldrstr = null;
293         if (clsldr != null) {
294             clsldrstr = clsldr.toString();
295         }
296 
297         return new VersionInfo(pckg, module, release, timestamp, clsldrstr);
298     }
299 
300     /**
301      * Gets software information as {@code "<name>/<release> (Java/<java.version>)"}. If release is
302      * {@link #UNAVAILABLE}, it will be omitted.
303      * <p>
304      * For example:
305      * <pre>"Apache-HttpClient/4.3 (Java/1.6.0_35)"</pre>
306      *
307      * @param name the component name, like "Apache-HttpClient".
308      * @param pkg
309      *            the package for which to load version information, for example "org.apache.http". The package name
310      *            should NOT end with a dot.
311      * @param cls
312      *            the class' class loader to load from, or {@code null} for the thread context class loader
313      * @since 4.3
314      */
315     public static String getSoftwareInfo(final String name, final String pkg, final Class<?> cls) {
316         // determine the release version from packaged version info
317         final VersionInfo vi = VersionInfo.loadVersionInfo(pkg, cls.getClassLoader());
318         final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
319         final String javaVersion = System.getProperty("java.version");
320 
321         String nameAndRelease = name;
322         if (!UNAVAILABLE.equals(release)) {
323             nameAndRelease += "/" + release;
324         }
325 
326         return String.format("%s (Java/%s)", nameAndRelease, javaVersion);
327     }
328 
329 }