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

run.smt.ktest.db.registry.TestDataRegistry.kt Maven / Gradle / Ivy

There is a newer version: 1.0.0
Show newest version
package run.smt.ktest.db.registry

import run.smt.ktest.util.reflection.canBeAssignedTo
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import kotlin.reflect.KClass

/**
 * Represents test resources that must be cleanly loaded into some storage
 */
abstract class TestDataRegistry {
    private val registry: ConcurrentMap = ConcurrentHashMap()

    abstract fun  load(clazz: KClass, identifier: String): T?
    abstract fun  loadAll(clazz: KClass, identifier: String): List
    protected abstract fun  save(data: T)
    protected abstract fun  remove(data: T)

    /**
     * Drop previous values, load fresh once and return result
     */
    inline operator fun  get(identifier: String): T = get(T::class, identifier)

    inline fun  getAll(identifier: String): List = getAll(T::class, identifier)

    /**
     * Same as `get` but without returning
     */
    inline fun  setup(identifier: String) {
        get(identifier)
    }

    inline fun  setupAll(identifier: String) {
        getAll(identifier)
    }

    /**
     * Only return value extracted from resources
     */
    inline fun  load(identifier: String): T? = load(T::class, identifier)

    inline fun  loadAll(identifier: String): List = loadAll(T::class, identifier)

    fun  get(clazz: KClass, identifier: String): T {
        val result = registry.computeIfAbsent(identifier) {
            val loaded = load(clazz, it) ?: throw NoValueException("Can not load value with identifier \"$identifier\"")

            remove(loaded)
            save(loaded)

            loaded
        }

        if (result.javaClass canBeAssignedTo clazz) {
            @Suppress("UNCHECKED_CAST") return result as T
        }

        throw NoValueException("Requested type for element with identifier \"$identifier\" don't match actual!")
    }

    fun  getAll(clazz: KClass, identifier: String): List {
        val result = registry.computeIfAbsent(identifier) {
            val loaded = loadAll(clazz, it)

            loaded.forEach {
                remove(it)
                save(it)
            }

            loaded
        }

        return result as? List ?: throw NoValueException("Requested type for element with identifier \"$identifier\" don't match actual!")
    }

    companion object {
        class NoValueException(message: String) : RuntimeException(message)
        class SaveException(message: String) : RuntimeException(message)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy