001import java.io.IOException;
002import java.io.InputStream;
003import java.util.Properties;
004
005import org.slf4j.Logger;
006import org.slf4j.LoggerFactory;
007
008/**
009 * Utility to surface project version information.
010 *
011 * Reads the {@code /version.properties} file from the classpath and exposes
012 * the {@link #getVersion()} helper. If the file cannot be read, returns
013 * {@code "unknown"}.
014 */
015public class VersionUtil {
016    private static final Logger LOG = LoggerFactory.getLogger(VersionUtil.class);
017
018    /** The path to the properties file containing the version information. */
019    private static final String VERSION_FILE = "/version.properties";
020
021    /** The version of the application, initialized from the properties file. */
022    private static String version;
023
024    /**
025     * Static block to initialize the {@link #version} variable.
026     * <p>
027     * The static block loads the version from the {@code version.properties} file.
028     * If the file cannot be found or an I/O error occurs, the version is set to "unknown".
029     * </p>
030     */
031    static {
032        try (InputStream input = VersionUtil.class.getResourceAsStream(VERSION_FILE)) {
033            Properties properties = new Properties();
034                if (input == null) {
035                    // If the properties file is not found, set version to "unknown"
036                    LOG.warn("Unable to find {}", VERSION_FILE);
037                    version = "unknown";
038                } else {
039                // Load the properties file and set the version
040                properties.load(input);
041                version = properties.getProperty("version", "unknown");
042            }
043        } catch (IOException ex) {
044            // Log the exception and set version to "unknown" in case of an exception
045            LOG.error("Error reading version properties", ex);
046            version = "unknown";
047        }
048    }
049
050    /**
051     * Returns the version of the application.
052     * <p>
053     * This method provides access to the version information that was loaded from the properties file.
054     * If the properties file could not be found or an error occurred, it returns "unknown".
055     * </p>
056     *
057     * @return The version of the application.
058     */
059    public static String getVersion() {
060        return version;
061    }
062
063    /**
064     * Private constructor to prevent instantiation of this utility class.
065     */
066    private VersionUtil() {
067        throw new AssertionError("Not instantiable");
068    }
069}