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

net.dankito.utils.localization.Localization.kt Maven / Gradle / Ivy

There is a newer version: 1.0.20
Show newest version
package net.dankito.utils.localization

import org.slf4j.LoggerFactory
import java.util.*


open class Localization(protected val messagesResourceBundleName: String) {

    companion object {
        private val log = LoggerFactory.getLogger(Localization::class.java)
    }


    open var languageLocale: Locale = Locale.getDefault()
        set(value) {
            field = value
            Locale.setDefault(field)

            tryToLoadMessagesResourceBundle(field)
        }

    var messagesResourceBundle: ResourceBundle
        protected set


    init {
        this.messagesResourceBundle = createEmptyResourceBundle()

        tryToLoadMessagesResourceBundle(languageLocale)
    }


    open fun getLocalizedString(resourceKey: String): String {
        try {
            messagesResourceBundle?.let { messagesResourceBundle ->
                return messagesResourceBundle.getString(resourceKey)
            }
        } catch (e: Exception) {
            log.error("Could not get Resource for key {} from String Resource Bundle {}", resourceKey, messagesResourceBundleName)
        }

        return resourceKey
    }

    open fun getLocalizedString(resourceKey: String, vararg formatArguments: Any): String {
        return String.format(getLocalizedString(resourceKey), *formatArguments)
    }


    protected open fun tryToLoadMessagesResourceBundle(languageLocale: Locale) {
        try {
            messagesResourceBundle = ResourceBundle.getBundle(messagesResourceBundleName, languageLocale,
                    UTF8ResourceBundleControl())
        } catch (e: Exception) {
            log.error("Could not load $messagesResourceBundleName. No Strings will now be translated, only their " +
                    "resource keys will be displayed.", e)
        }
    }

    protected open fun createEmptyResourceBundle(): ResourceBundle {
        return object : ResourceBundle() {

            private val emptyEnumeration = Collections.enumeration(emptyList())

            override fun getKeys(): Enumeration {
                return emptyEnumeration
            }

            override fun handleGetObject(key: String?): Any? {
                return null
            }

        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy