001package org.nuxeo.ecm.platform.forms.layout.io.plugins.helpers;
002
003import java.util.HashMap;
004import java.util.Locale;
005import java.util.Map;
006import java.util.ResourceBundle;
007
008/**
009 * Helper to manage labels translation using the default web message bundles
010 *
011 * @author Tiry (tdelprat@nuxeo.com)
012 * @since 5.5
013 */
014public class TranslationHelper {
015
016    public static final String DEFAULT_LOCALE = "en";
017
018    protected static ResourceBundle getBundle(String lang) {
019        ClassLoader cl = Thread.currentThread().getContextClassLoader();
020        return ResourceBundle.getBundle("messages", new Locale(lang), cl);
021    }
022
023    public static String getTranslation(String key, String lang) {
024        ResourceBundle defaultBundle = null;
025        ResourceBundle bundle = getBundle(lang);
026        if (bundle == null) {
027            defaultBundle = getBundle(DEFAULT_LOCALE);
028            bundle = defaultBundle;
029        }
030        String translation = null;
031        if (bundle != null && bundle.containsKey(key)) {
032            translation = bundle.getString(key);
033        }
034
035        if (translation == null && !lang.equals(DEFAULT_LOCALE)) {
036            if (defaultBundle == null) {
037                defaultBundle = getBundle(DEFAULT_LOCALE);
038            }
039            if (defaultBundle.containsKey(key)) {
040                translation = defaultBundle.getString(key);
041            }
042        }
043
044        if (translation == null) {
045            translation = key;
046        }
047        return translation;
048    }
049
050    public static Map<String, String> getTranslatedLabels(Map<String, String> labels, String lang) {
051        if (labels != null) {
052            Map<String, String> res = new HashMap<String, String>();
053            for (Map.Entry<String, String> label : labels.entrySet()) {
054                res.put(label.getKey(), TranslationHelper.getTranslation(label.getValue(), lang));
055            }
056            return res;
057        }
058        return null;
059    }
060
061}