net.dankito.utils.localization.Localization.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-utils Show documentation
Show all versions of java-utils Show documentation
Some basic utils needed in many projects
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
}
}
}
}