    001// Licensed under the Apache License, Version 2.0 (the "License");
    002// you may not use this file except in compliance with the License.
    003// You may obtain a copy of the License at
    004//
    005//     http://www.apache.org/licenses/LICENSE-2.0
    006//
    007// Unless required by applicable law or agreed to in writing, software
    008// distributed under the License is distributed on an "AS IS" BASIS,
    009// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    010// See the License for the specific language governing permissions and
    011// limitations under the License.
    012
    013package org.apache.tapestry5.commons.util;
    014
    015import java.io.BufferedInputStream;
    016import java.io.IOException;
    017import java.io.InputStream;
    018import java.util.Properties;
    019
    020/**
    021 * Utility methods related to managing framework version numbers.
    022 */
    023public class VersionUtils
    024{
    025
    026    /**
    027     * Reads a version number from a properties file on the classpath.  These files are generally created by Gradle.  For
    028     * example, tapestry-core's properties file is <code>META-INF/gradle/org.apache.tapestry/tapestry-core/pom.properties</code>.
    029     * The Gradle generated properties files include the version and possibly others properties.
    030     *
    031     * The resource is located using the Thread's context class loader.
    032     *
    033     * @param resourcePath the complete path to the resource, including a leading slash.
    034     * @return the version number read from the properties file, or "UNKNOWN" if the version number is not present or
    035     *         the file can not be opened
    036     */
    037    public static String readVersionNumber(String resourcePath)
    038    {
    039        String result = "UNKNOWN";
    040
    041        InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(
    042                resourcePath);
    043
    044
    045        if (stream != null)
    046        {
    047            Properties properties = new Properties();
    048
    049
    050            try
    051            {
    052                stream = new BufferedInputStream(stream);
    053
    054                properties.load(stream);
    055
    056                stream.close();
    057            }
    058            catch (IOException ex)
    059            {
    060                // Just ignore it.
    061            }
    062
    063            String version = properties.getProperty("version");
    064
    065            // Since the file, if it exists, is created by Gradle and will have the key, I can't see
    066            // how version would EVER be null, unless there's a problem reading the properties.
    067
    068            if (version != null) result = version;
    069        }
    070
    071        return result;
    072    }
    073}