Merge from ECOMP's repository
[vid.git] / vid-app-common / src / main / java / org / onap / vid / aai / util / CacheConfig.kt
1 package org.onap.vid.aai.util
2
3 import com.fasterxml.jackson.core.type.TypeReference
4 import com.fasterxml.jackson.databind.ObjectMapper
5 import com.fasterxml.jackson.module.kotlin.KotlinModule
6 import com.google.common.collect.ImmutableMap
7 import org.springframework.stereotype.Component
8
9 //I use a regular kotlin class because I want that when jackson read
10 //a json with null values (or missing fields) they would get default values.
11 //for other cases it's better to use data class for POJO class
12 //for more information you can read here :
13 //https://github.com/FasterXML/jackson-module-kotlin/issues/130
14 class CacheConfig constructor(
15         isActive: Boolean?,
16         expireAfterWriteHours: Long?,
17         refreshAfterWriteSeconds: Long?) {
18     val isActive: Boolean = isActive ?: true
19     val expireAfterWriteHours: Long = expireAfterWriteHours ?: 24L
20     val refreshAfterWriteSeconds: Long = refreshAfterWriteSeconds ?: 10L
21
22     companion object {
23         val defaultCacheConfig = CacheConfig(null, null, null)
24     }
25
26 }
27
28
29 interface CacheConfigProvider {
30     fun getCacheConfig(cacheName:String): CacheConfig
31 }
32
33 @Component
34 class CacheConfigProviderImpl() : CacheConfigProvider {
35     private val mapper = ObjectMapper().apply { registerModule(KotlinModule()) }
36
37     private fun readMapOfCacheConfig(): Map<String, CacheConfig> {
38         val configInputStream = CacheConfigProviderImpl::class.java.classLoader.getResourceAsStream("cacheConfig.json")
39
40         return if (configInputStream == null) {
41             ImmutableMap.of()
42         } else {
43             mapper.readValue(configInputStream, object : TypeReference<Map<String, CacheConfig>>() {})
44         }
45     }
46
47     override fun getCacheConfig(cacheName: String): CacheConfig {
48         return readMapOfCacheConfig()[cacheName] ?: CacheConfig.defaultCacheConfig
49     }
50 }
51
52