Do translation from java code within custom SPI

Hi everyone,

I’m quite new to keycloak and have a simple question: How do I translate things in the java code? Is there no convenience functionality, that I could just pass something like a Locale and a translation key, that refers to the theme resources?

Basically I have my own SPI, where I can access mentioned data - but I cannot find an easy way to let keycloak do the translation for me.

I found this piece of code in org.keycloak.forms.login.freemarker.FreeMarkerLoginFormsProvider, but I cannot believe this is as easy as it gets. Do I really have to copy-paste this huge chunk of code to my own API?

    @Override
    public String getMessage(String message, String... parameters) {
        Theme theme;
        try {
            theme = getTheme();
        } catch (IOException e) {
            logger.error("Failed to create theme", e);
            throw new RuntimeException("Failed to create theme");
        }

        Locale locale = session.getContext().resolveLocale(user);
        Properties messagesBundle = handleThemeResources(theme, locale);
        Map<String, String> localizationTexts = realm.getRealmLocalizationTextsByLocale(locale.getCountry());
        messagesBundle.putAll(localizationTexts);
        FormMessage msg = new FormMessage(message, (Object[]) parameters);
        return formatMessage(msg, messagesBundle, locale);
    }

     protected Properties handleThemeResources(Theme theme, Locale locale) {
        Properties messagesBundle;
        try {
            messagesBundle = theme.getMessages(locale);
            attributes.put("msg", new MessageFormatterMethod(locale, messagesBundle));
        } catch (IOException e) {
            logger.warn("Failed to load messages", e);
            messagesBundle = new Properties();
        }

        try {
            attributes.put("properties", theme.getProperties());
        } catch (IOException e) {
            logger.warn("Failed to load properties", e);
        }

        return messagesBundle;
    }

    protected String formatMessage(FormMessage message, Properties messagesBundle, Locale locale) {
        if (message == null)
            return null;
        if (messagesBundle.containsKey(message.getMessage())) {
            return new MessageFormat(messagesBundle.getProperty(message.getMessage()), locale).format(message.getParameters());
        } else {
            return message.getMessage();
        }
    }

Thanks in advance!

Dominik