All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.infobip.kafkistry.webapp.url.Url.kt Maven / Gradle / Ivy

There is a newer version: 0.8.0
Show newest version
package com.infobip.kafkistry.webapp.url

import java.lang.IllegalArgumentException
import java.net.URLEncoder

data class Url(
        val path: String,
        val params: List = emptyList()
) {

    companion object {
        private val pathVarRegex = Regex("""\{(\w+)}""")
    }

    fun render(vararg data: Pair): String = render(data.associate { it })

    private fun render(data: Map): String {
        val usedPathVariables = mutableListOf()
        return path.replace(pathVarRegex) { match ->
            val key = match.groupValues[1]
            usedPathVariables.add(key)
            val value = data[key] ?: throw IllegalArgumentException("Missing url path variable: '$key'")
            value.encodeUri()
        }.let { url ->
            val paramsUrl = data
                    .nonNullValues()
                    .filterKeys { it !in usedPathVariables }.map { (key, value) ->
                        if (key !in params) {
                            throw IllegalArgumentException("Unknown/unexpected data parameter '$key'")
                        }
                        "$key=" + value.encodeUri()
                    }
                    .joinToString(separator = "&")
                    .let {
                        when (it.isNotEmpty()) {
                            true -> "?$it"
                            false -> it
                        }
                    }
            url + paramsUrl
        }
    }

    private fun  Map.nonNullValues(): Map {
        return this.mapNotNull { (k, v) -> v?.let { k to v } }.associate { it }
    }

    fun String.encodeUri(): String = URLEncoder.encode(this, "UTF-8")

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy