https://kotlinlang.org logo
#http4k
Title
# http4k
c

Cosmin Marginean

02/29/2024, 12:28 PM
Hi, we're interested in loading an
Environment
from a
.yaml
in the classpath, but I see there's only
Environment.fromYaml(file: File)
and classpath support can only be used for
.properties
files. Is there a way to do this that I might be missing?
d

DanielZ

02/29/2024, 7:03 PM
It doesn’t exist so far, you could implement your own extension, like the one
Environment.fromYaml(file: File)
Copy code
//Completely untested:
fun Environment.Companion.fromYamlResource(resource: String): Environment {
    val map = Companion::class.java.getResourceAsStream("/${resource.removePrefix("/")}")
        ?.let { r -> JacksonYaml.asA<Map<String, Any>>(r.reader().use { it.readText() }) } 
        ?: throw FileNotFoundException(resource)

    fun Map<*, *>.flatten(): List<Pair<String, String>> {
        fun convert(key: Any?, value: Any?): List<Pair<String, String>> {
            val keyString = (key ?: "").toString()

            return when (value) {
                is List<*> -> listOf(keyString to value.flatMap { convert(null, it) }.joinToString(",") { it.second })
                is Map<*, *> -> value.flatten().map { "$keyString.${it.first}" to it.second }
                else -> listOf((keyString to (value ?: "").toString()))
            }
        }

        return entries.fold(listOf()) { acc, (key, value) -> acc + convert(key, value) }
    }

    return MapEnvironment.from(map.flatten().toMap().toProperties())
}
it’s not nice since it’s copied from several function within cloudnativ module - so it doesn’t qualifies a PR, maybe I’ll have some time later on
c

Cosmin Marginean

02/29/2024, 9:13 PM
No worries, thanks!
d

DanielZ

02/29/2024, 9:26 PM
Created a PR.
🙌 1