aboutsummaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/main/java/org/onap/vid/services/VersionService.kt
blob: 2fb3e0c0878cd6e9a18e710a7edd1ff68fc237d4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package org.onap.vid.services

import com.fasterxml.jackson.module.kotlin.readValue
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.StringUtils.substringAfterLast
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate
import org.onap.portalsdk.core.util.SystemProperties
import org.onap.vid.model.VersionAndFeatures
import org.onap.vid.utils.JACKSON_OBJECT_MAPPER
import org.springframework.stereotype.Service
import java.util.regex.Pattern
import javax.inject.Inject
import javax.servlet.ServletContext

@Service
class VersionService
@Inject
constructor(internal var servletContext: ServletContext) {

    private val Logger = EELFLoggerDelegate.getLogger(VersionService::class.java)

    private val versionAndFeatures: VersionAndFeatures by lazy {
        loadVersionAndFeatures()
    }

    private fun readBuildNumber(): String {
        val resource = servletContext.getResource("/app/vid/scripts/constants/version.json")
        return JACKSON_OBJECT_MAPPER.readValue<Map<String, String>>(resource)["Version"]!!
    }

    //protected so can be easily tested in UT
    protected fun readFeatureSet(): String {
        return SystemProperties.getProperty("features.set.filename")
    }

    //protected so can be easily tested in UT
    protected fun buildDisplayVersion(features: String, build: String): String {
        val matcher = Pattern.compile("([^/]+?)(\\.features|$)").matcher(features)
        val majorByFeatures = if (matcher.find()) matcher.group(1) else features

        val buildByVersion = StringUtils.defaultIfBlank(substringAfterLast(build, "."), build)

        return StringUtils.join(majorByFeatures, ".", buildByVersion)
    }

    fun retrieveVersionAndFeatures(): VersionAndFeatures {
        return try {
            versionAndFeatures
        } catch (exception: Exception) {
            Logger.error("Failed to read build number or feature properties settings from version file", exception)
            VersionAndFeatures.unknown
        }
    }

    private fun loadVersionAndFeatures(): VersionAndFeatures {
        val featureSet = readFeatureSet();
        val build = readBuildNumber();
        val displayVersion = buildDisplayVersion(featureSet, build)
        return VersionAndFeatures(featureSet, build, displayVersion)
    }

    //might throw an exception
    fun retrieveBuildNumber(): String {
        return versionAndFeatures.build
    }
}