001/*
002 *  Copyright (c) 2004-2024 QOS.ch
003 *  All rights reserved.
004 *
005 *  Permission is hereby granted, free  of charge, to any person obtaining
006 *  a  copy  of this  software  and  associated  documentation files  (the
007 *  "Software"), to  deal in  the Software without  restriction, including
008 *  without limitation  the rights to  use, copy, modify,  merge, publish,
009 *  distribute,  sublicense, and/or sell  copies of  the Software,  and to
010 *  permit persons to whom the Software  is furnished to do so, subject to
011 *  the following conditions:
012 *
013 *  The  above  copyright  notice  and  this permission  notice  shall  be
014 *  included in all copies or substantial portions of the Software.
015 *
016 *  THE  SOFTWARE IS  PROVIDED  "AS  IS", WITHOUT  WARRANTY  OF ANY  KIND,
017 *  EXPRESS OR  IMPLIED, INCLUDING  BUT NOT LIMITED  TO THE  WARRANTIES OF
018 *  MERCHANTABILITY,    FITNESS    FOR    A   PARTICULAR    PURPOSE    AND
019 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
020 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
021 *  OF CONTRACT, TORT OR OTHERWISE,  ARISING FROM, OUT OF OR IN CONNECTION
022 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
023 */
024
025package org.slf4j.helpers;
026
027import java.lang.module.ModuleDescriptor;
028import java.util.Optional;
029
030/**
031 * Various utility methods
032 *
033 * @since 2.0.14
034 */
035public class Slf4jEnvUtil {
036
037
038    /**
039     * <p>Returns the current version of logback, or null if data is not
040     * available.
041     * </p>
042     *
043     * @return current version or null if missing version data
044     * @since 2.0.14
045     */
046    static public String slf4jVersion() {
047        String moduleVersion = slf4jVersionByModule();
048        if(moduleVersion != null)
049            return moduleVersion;
050
051        Package pkg = Slf4jEnvUtil.class.getPackage();
052        if(pkg == null) {
053            return null;
054        }
055        final String pkgVersion = pkg.getImplementationVersion();
056        return pkgVersion;
057    }
058
059    /**
060     * <p>Returns the current version of logback via class.getModule() or null if data is not
061     * available.
062     * </p>
063     *
064     * @since 2.0.14
065     * @return current version or null if missing version data
066     */
067    static private String slf4jVersionByModule() {
068        Module module = Slf4jEnvUtil.class.getModule();
069        if (module == null)
070            return null;
071
072        ModuleDescriptor md = module.getDescriptor();
073        if (md == null)
074            return null;
075        Optional<String> opt = md.rawVersion();
076        return opt.orElse(null);
077    }
078
079}