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 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 static VersionInfo loadVersionInfo(final String pckg,
224                                               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
233                 (pckg.replace('.', '/') + "/" + VERSION_PROPERTY_FILE);
234             if (is != null) {
235                 try {
236                     final Properties props = new Properties();
237                     props.load(is);
238                     vip = props;
239                 } finally {
240                     is.close();
241                 }
242             }
243         } catch (final IOException ex) {
244             // shamelessly munch this exception
245         }
246 
247         VersionInfo result = null;
248         if (vip != null) {
249             result = fromMap(pckg, vip, cl);
250         }
251 
252         return result;
253     }
254 
255 
256     /**
257      * Instantiates version information from properties.
258      *
259      * @param pckg      the package for the version information
260      * @param info      the map from string keys to string values,
261      *                  for example {@link java.util.Properties}
262      * @param clsldr    the classloader, or <code>null</code>
263      *
264      * @return  the version information
265      */
266     protected static VersionInfo fromMap(final String pckg, final Map<?, ?> info,
267                                                final ClassLoader clsldr) {
268         Args.notNull(pckg, "Package identifier");
269         String module = null;
270         String release = null;
271         String timestamp = null;
272 
273         if (info != null) {
274             module = (String) info.get(PROPERTY_MODULE);
275             if ((module != null) && (module.length() < 1)) {
276                 module = null;
277             }
278 
279             release = (String) info.get(PROPERTY_RELEASE);
280             if ((release != null) && ((release.length() < 1) ||
281                                       (release.equals("${pom.version}")))) {
282                 release = null;
283             }
284 
285             timestamp = (String) info.get(PROPERTY_TIMESTAMP);
286             if ((timestamp != null) &&
287                 ((timestamp.length() < 1) ||
288                  (timestamp.equals("${mvn.timestamp}")))
289                 ) {
290                 timestamp = null;
291             }
292         } // if info
293 
294         String clsldrstr = null;
295         if (clsldr != null) {
296             clsldrstr = clsldr.toString();
297         }
298 
299         return new VersionInfo(pckg, module, release, timestamp, clsldrstr);
300     }
301 
302     /**
303      * Sets the user agent to {@code "<name>/<release> (Java 1.5 minimum; Java/<java.version>)"}.
304      * <p/>
305      * For example:
306      * <pre>"Apache-HttpClient/4.3 (Java 1.5 minimum; Java/1.6.0_35)"</pre>
307      *
308      * @param name the component name, like "Apache-HttpClient".
309      * @param pkg
310      *            the package for which to load version information, for example "org.apache.http". The package name
311      *            should NOT end with a dot.
312      * @param cls
313      *            the class' class loader to load from, or <code>null</code> for the thread context class loader
314      * @since 4.3
315      */
316     public static String getUserAgent(final String name, final String pkg, final Class<?> cls) {
317         // determine the release version from packaged version info
318         final VersionInfo vi = VersionInfo.loadVersionInfo(pkg, cls.getClassLoader());
319         final String release = (vi != null) ? vi.getRelease() : VersionInfo.UNAVAILABLE;
320         final String javaVersion = System.getProperty("java.version");
321         return name + "/" + release + " (Java 1.5 minimum; Java/" + javaVersion + ")";
322     }
323 
324 } // class VersionInfo