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.http.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   * <br/>
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   *
47   * @since 4.0
48   */
49  public class VersionInfo {
50  
51      /** A string constant for unavailable information. */
52      public final static String UNAVAILABLE = "UNAVAILABLE";
53  
54      /** The filename of the version information files. */
55      public final static String VERSION_PROPERTY_FILE = "version.properties";
56  
57      // the property names
58      public final static String PROPERTY_MODULE    = "info.module";
59      public final static String PROPERTY_RELEASE   = "info.release";
60      public final static String PROPERTY_TIMESTAMP = "info.timestamp";
61  
62  
63      /** The package that contains the version information. */
64      private final String infoPackage;
65  
66      /** The module from the version info. */
67      private final String infoModule;
68  
69      /** The release from the version info. */
70      private final String infoRelease;
71  
72      /** The timestamp from the version info. */
73      private final String infoTimestamp;
74  
75      /** The classloader from which the version info was obtained. */
76      private final String infoClassloader;
77  
78  
79      /**
80       * Instantiates version information.
81       *
82       * @param pckg      the package
83       * @param module    the module, or <code>null</code>
84       * @param release   the release, or <code>null</code>
85       * @param time      the build time, or <code>null</code>
86       * @param clsldr    the class loader, or <code>null</code>
87       */
88      protected VersionInfo(final String pckg, final String module,
89                            final String release, final String time, final String clsldr) {
90          Args.notNull(pckg, "Package identifier");
91          infoPackage     = pckg;
92          infoModule      = (module  != null) ? module  : UNAVAILABLE;
93          infoRelease     = (release != null) ? release : UNAVAILABLE;
94          infoTimestamp   = (time    != null) ? time    : UNAVAILABLE;
95          infoClassloader = (clsldr  != null) ? clsldr  : UNAVAILABLE;
96      }
97  
98  
99      /**
100      * Obtains the package name.
101      * The package name identifies the module or informal unit.
102      *
103      * @return  the package name, never <code>null</code>
104      */
105     public final String getPackage() {
106         return infoPackage;
107     }
108 
109     /**
110      * Obtains the name of the versioned module or informal unit.
111      * This data is read from the version information for the package.
112      *
113      * @return  the module name, never <code>null</code>
114      */
115     public final String getModule() {
116         return infoModule;
117     }
118 
119     /**
120      * Obtains the release of the versioned module or informal unit.
121      * This data is read from the version information for the package.
122      *
123      * @return  the release version, never <code>null</code>
124      */
125     public final String getRelease() {
126         return infoRelease;
127     }
128 
129     /**
130      * Obtains the timestamp of the versioned module or informal unit.
131      * This data is read from the version information for the package.
132      *
133      * @return  the timestamp, never <code>null</code>
134      */
135     public final String getTimestamp() {
136         return infoTimestamp;
137     }
138 
139     /**
140      * Obtains the classloader used to read the version information.
141      * This is just the <code>toString</code> output of the classloader,
142      * since the version information should not keep a reference to
143      * the classloader itself. That could prevent garbage collection.
144      *
145      * @return  the classloader description, never <code>null</code>
146      */
147     public final String getClassloader() {
148         return infoClassloader;
149     }
150 
151 
152     /**
153      * Provides the version information in human-readable format.
154      *
155      * @return  a string holding this version information
156      */
157     @Override
158     public String toString() {
159         final StringBuilder sb = new StringBuilder
160             (20 + infoPackage.length() + infoModule.length() +
161              infoRelease.length() + infoTimestamp.length() +
162              infoClassloader.length());
163 
164         sb.append("VersionInfo(")
165             .append(infoPackage).append(':').append(infoModule);
166 
167         // If version info is missing, a single "UNAVAILABLE" for the module
168         // is sufficient. Everything else just clutters the output.
169         if (!UNAVAILABLE.equals(infoRelease)) {
170             sb.append(':').append(infoRelease);
171         }
172         if (!UNAVAILABLE.equals(infoTimestamp)) {
173             sb.append(':').append(infoTimestamp);
174         }
175 
176         sb.append(')');
177 
178         if (!UNAVAILABLE.equals(infoClassloader)) {
179             sb.append('@').append(infoClassloader);
180         }
181 
182         return sb.toString();
183     }
184 
185 
186     /**
187      * Loads version information for a list of packages.
188      *
189      * @param pckgs     the packages for which to load version info
190      * @param clsldr    the classloader to load from, or
191      *                  <code>null</code> for the thread context classloader
192      *
193      * @return  the version information for all packages found,
194      *          never <code>null</code>
195      */
196     public final static VersionInfo[] loadVersionInfo(final String[] pckgs,
197                                                       final ClassLoader clsldr) {
198         Args.notNull(pckgs, "Package identifier array");
199         final List<VersionInfo> vil = new ArrayList<VersionInfo>(pckgs.length);
200         for (final String pckg : pckgs) {
201             final VersionInfo vi = loadVersionInfo(pckg, clsldr);
202             if (vi != null) {
203                 vil.add(vi);
204             }
205         }
206 
207         return vil.toArray(new VersionInfo[vil.size()]);
208     }
209 
210 
211     /**
212      * Loads version information for a package.
213      *
214      * @param pckg      the package for which to load version information,
215      *                  for example "org.apache.http".
216      *                  The package name should NOT end with a dot.
217      * @param clsldr    the classloader to load from, or
218      *                  <code>null</code> for the thread context classloader
219      *
220      * @return  the version information for the argument package, or
221      *          <code>null</code> if not available
222      */
223     public final static VersionInfo loadVersionInfo(final String pckg,
224                                                     ClassLoader clsldr) {
225         Args.notNull(pckg, "Package identifier");
226         if (clsldr == null) {
227             clsldr = Thread.currentThread().getContextClassLoader();
228         }
229 
230         Properties vip = null; // version info properties, if available
231         try {
232             // org.apache.http      becomes
233             // org/apache/http/version.properties
234             final InputStream is = clsldr.getResourceAsStream
235                 (pckg.replace('.', '/') + "/" + VERSION_PROPERTY_FILE);
236             if (is != null) {
237                 try {
238                     final Properties props = new Properties();
239                     props.load(is);
240                     vip = props;
241                 } finally {
242                     is.close();
243                 }
244             }
245         } catch (final IOException ex) {
246             // shamelessly munch this exception
247         }
248 
249         VersionInfo result = null;
250         if (vip != null) {
251             result = fromMap(pckg, vip, clsldr);
252         }
253 
254         return result;
255     }
256 
257 
258     /**
259      * Instantiates version information from properties.
260      *
261      * @param pckg      the package for the version information
262      * @param info      the map from string keys to string values,
263      *                  for example {@link java.util.Properties}
264      * @param clsldr    the classloader, or <code>null</code>
265      *
266      * @return  the version information
267      */
268     protected final static VersionInfo fromMap(final String pckg, final Map<?, ?> info,
269                                                final ClassLoader clsldr) {
270         Args.notNull(pckg, "Package identifier");
271         String module = null;
272         String release = null;
273         String timestamp = null;
274 
275         if (info != null) {
276             module = (String) info.get(PROPERTY_MODULE);
277             if ((module != null) && (module.length() < 1)) {
278                 module = null;
279             }
280 
281             release = (String) info.get(PROPERTY_RELEASE);
282             if ((release != null) && ((release.length() < 1) ||
283                                       (release.equals("${pom.version}")))) {
284                 release = null;
285             }
286 
287             timestamp = (String) info.get(PROPERTY_TIMESTAMP);
288             if ((timestamp != null) &&
289                 ((timestamp.length() < 1) ||
290                  (timestamp.equals("${mvn.timestamp}")))
291                 ) {
292                 timestamp = null;
293             }
294         } // if info
295 
296         String clsldrstr = null;
297         if (clsldr != null) {
298             clsldrstr = clsldr.toString();
299         }
300 
301         return new VersionInfo(pckg, module, release, timestamp, clsldrstr);
302     }
303 
304     /**
305      * Sets the user agent to {@code "<name>/<release> (Java 1.5 minimum; Java/<java.version>)"}.
306      * <p/>
307      * For example:
308      * <pre>"Apache-HttpClient/4.3 (Java 1.5 minimum; Java/1.6.0_35)"</pre>
309      *
310      * @param name the component name, like "Apache-HttpClient".
311      * @param pkg
312      *            the package for which to load version information, for example "org.apache.http". The package name
313      *            should NOT end with a dot.
314      * @param cls
315      *            the class' class loader to load from, or <code>null</code> for the thread context class loader
316      * @since 4.3
317      */
318     public static String getUserAgent(final String name, final String pkg, final Class<?> cls) {
319         // determine the release version from packaged version info
320         final VersionInfo vi = VersionInfo.loadVersionInfo(pkg, cls.getClassLoader());
321         final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
322         final String javaVersion = System.getProperty("java.version");
323         return name + "/" + release + " (Java 1.5 minimum; Java/" + javaVersion + ")";
324     }
325 
326 } // class VersionInfo