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

cn.authing.core.Utils.kt Maven / Gradle / Ivy

There is a newer version: 4.3.79
Show newest version
package cn.authing.core

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okio.internal.commonAsUtf8ToByteArray
import java.net.URLDecoder
import java.security.MessageDigest
import kotlin.collections.HashMap
import kotlin.random.Random


class Utils {
    val gson = Gson()


    fun  T.serializeToMap(): Map {
        return convert()
    }

    inline fun  Map.toDataClass(): T {
        return convert()
    }

    inline fun  I.convert(): O {
        val json = gson.toJson(this)
        return gson.fromJson(json, object : TypeToken() {}.type)
    }


    fun getQueryUrl(url: String?, params: Map): String {
        val builder = StringBuilder(url)
        var isFirst = true
        for (key in params.keys) {
            if (params[key] != null) {
                if (isFirst) {
                    isFirst = false
                    builder.append("?")
                } else {
                    builder.append("&")
                }
                builder.append(key)
                    .append("=")
                    .append(params[key])
            }
        }
        return builder.toString()
    }

    fun getQueryUrl(params: Map): String {
        return this.getQueryUrl("", params)
    }

    fun getQueryUrl(url: String?, params: Any): String {

        return this.getQueryUrl(url, params.serializeToMap())

    }

    fun randomString(randomLength: Number): String {
        val template = "abcdefhijkmnprstwxyz2345678".toCharArray()


        var returnValue = "";

        for (item in 1..randomLength as Int)
            returnValue += template[Random.nextInt(template.size)]

        return returnValue
    }

    fun getQueryParams(url: String): Map {
        var url = url
        val map: MutableMap = HashMap()
        try {
            val charset = "utf-8"
            url = URLDecoder.decode(url, charset)
            if (url.indexOf('?') != -1) {
                val contents = url.substring(url.indexOf('?') + 1)
                val keyValues = contents.split("&").toTypedArray()
                for (i in keyValues.indices) {
                    val key = keyValues[i].substring(0, keyValues[i].indexOf("="))
                    val value = keyValues[i].substring(keyValues[i].indexOf("=") + 1)
                    map[key] = value
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return map
    }

    fun sha256(str: String): ByteArray {
        val messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(str.commonAsUtf8ToByteArray())
        return messageDigest.digest();
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy