How to get the translation of a message from an operation

Hi,

I have an operation that returns some data of a document. I call this operation through Rest API to use it in another application. I want the operation to return the document type, but translated to the language of the user (File -> Fitxategia (in Basque) -> Archivo (in Spanish), etc.). I've tried many different ways to translate the messages but I'm not able to make it work, and I don't see any example of translations in operations (except AddMessage, that doesn't do what i want, and I guess it won't work if you don't use it from the web interface).

Can anyone guide me to the correct answer, please?

Thank you so much,

0 votes

2 answers

2603 views

ANSWER



Hi,

You could try the following inside your custom operations (extracted from some Nuxeo operations):

import org.apache.commons.lang.LocaleUtils;
import org.nuxeo.common.utils.i18n.I18NUtils;

    protected Locale getLocale() {
        if (lang == null) {
            lang = (String) ctx.get("lang");
        }
        if (lang == null) {
            lang = "en";
        }
        return LocaleUtils.toLocale(lang);
    }

    protected String translate(String key) {
        if (key == null) {
            return "";
        }
        return I18NUtils.getMessageString("messages", key, new Object[0], getLocale());
    }
1 votes



Hi Anahide,

thank you for your reply.

I couldn't obtain the locale using ctx.get("lang") as you proposed, but I got what I wanted with this:

protected Locale getLocale() {
        String lang = null;

        NuxeoPrincipal principal = (NuxeoPrincipal) session.getPrincipal();
        UserProfileService userProfileService = Framework.getLocalService(
                UserProfileService.class);
        DocumentModel userProfileDoc = userProfileService.getUserProfileDocument(
                principal.getName(), session);

        if (userProfileDoc.getPropertyValue(
                UserProfileConstants.USER_PROFILE_LOCALE) != null) {
            lang = (String) userProfileDoc.getPropertyValue(
                    UserProfileConstants.USER_PROFILE_LOCALE);
        }

        if (lang == null) {
            lang = "en";
        }
        return LocaleUtils.toLocale(lang);
}

I guess this won't be the best way to do it, but I will stick to this until I get another way. Please anyone tell me if you see anything very very wrong ;)

Thank you very much for showing me the way!

0 votes