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