001/* 002 * (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Thierry Delprat 018 */ 019package org.nuxeo.ecm.platform.forms.layout.io.plugins.helpers; 020 021import java.util.HashMap; 022import java.util.Locale; 023import java.util.Map; 024import java.util.ResourceBundle; 025 026/** 027 * Helper to manage labels translation using the default web message bundles 028 * 029 * @author Tiry (tdelprat@nuxeo.com) 030 * @since 5.5 031 */ 032public class TranslationHelper { 033 034 public static final String DEFAULT_LOCALE = "en"; 035 036 protected static ResourceBundle getBundle(String lang) { 037 ClassLoader cl = Thread.currentThread().getContextClassLoader(); 038 return ResourceBundle.getBundle("messages", new Locale(lang), cl); 039 } 040 041 public static String getTranslation(String key, String lang) { 042 ResourceBundle defaultBundle = null; 043 ResourceBundle bundle = getBundle(lang); 044 if (bundle == null) { 045 defaultBundle = getBundle(DEFAULT_LOCALE); 046 bundle = defaultBundle; 047 } 048 String translation = null; 049 if (bundle != null && bundle.containsKey(key)) { 050 translation = bundle.getString(key); 051 } 052 053 if (translation == null && !lang.equals(DEFAULT_LOCALE)) { 054 if (defaultBundle == null) { 055 defaultBundle = getBundle(DEFAULT_LOCALE); 056 } 057 if (defaultBundle.containsKey(key)) { 058 translation = defaultBundle.getString(key); 059 } 060 } 061 062 if (translation == null) { 063 translation = key; 064 } 065 return translation; 066 } 067 068 public static Map<String, String> getTranslatedLabels(Map<String, String> labels, String lang) { 069 if (labels != null) { 070 Map<String, String> res = new HashMap<String, String>(); 071 for (Map.Entry<String, String> label : labels.entrySet()) { 072 res.put(label.getKey(), TranslationHelper.getTranslation(label.getValue(), lang)); 073 } 074 return res; 075 } 076 return null; 077 } 078 079}