001
014
015 package com.liferay.portlet.translator.util;
016
017 import com.liferay.portal.kernel.exception.SystemException;
018 import com.liferay.portal.kernel.language.LanguageUtil;
019 import com.liferay.portal.kernel.util.PrefsPropsUtil;
020 import com.liferay.portal.kernel.util.PropsKeys;
021 import com.liferay.portal.kernel.util.StringPool;
022 import com.liferay.portal.kernel.webcache.WebCacheException;
023 import com.liferay.portal.kernel.webcache.WebCacheItem;
024 import com.liferay.portlet.translator.model.Translation;
025
026 import java.util.Comparator;
027 import java.util.HashMap;
028 import java.util.Locale;
029 import java.util.Map;
030 import java.util.TreeMap;
031
032
036 public class TranslatorUtil {
037
038 public static String[] getFromAndToLanguageIds(
039 String translationId, Map<String, String> languageIdsMap) {
040
041 try {
042 int pos = translationId.indexOf(StringPool.UNDERLINE);
043
044 String fromLanguageId = translationId.substring(0, pos);
045
046 if (!languageIdsMap.containsKey(fromLanguageId)) {
047 pos = translationId.indexOf(StringPool.UNDERLINE, pos + 1);
048
049 fromLanguageId = translationId.substring(0, pos);
050
051 if (!languageIdsMap.containsKey(fromLanguageId)) {
052 return null;
053 }
054 }
055
056 String toLanguageId = translationId.substring(pos + 1);
057
058 if (!languageIdsMap.containsKey(fromLanguageId)) {
059 return null;
060 }
061
062 return new String[] {fromLanguageId, toLanguageId};
063 }
064 catch (Exception e) {
065 }
066
067 return null;
068 }
069
070 public static Map<String, String> getLanguageIdsMap(Locale locale)
071 throws SystemException {
072
073 Map<String, String> languageIdsMap = new HashMap<String, String>();
074
075 String[] languageIds = PrefsPropsUtil.getStringArray(
076 PropsKeys.TRANSLATOR_LANGUAGES, StringPool.COMMA);
077
078 for (String languageId : languageIds) {
079 languageIdsMap.put(
080 languageId, LanguageUtil.get(locale, "language." + languageId));
081 }
082
083 Map<String, String> sortedLanguageIdsMap = new TreeMap<String, String>(
084 new ValueComparator(languageIdsMap));
085
086 sortedLanguageIdsMap.putAll(languageIdsMap);
087
088 return sortedLanguageIdsMap;
089 }
090
091 public static Translation getTranslation(
092 String fromLanguageId, String toLanguageId, String fromText)
093 throws WebCacheException {
094
095 WebCacheItem wci = new TranslationWebCacheItem(
096 fromLanguageId, toLanguageId, fromText);
097
098 return (Translation)wci.convert("");
099 }
100
101 private static class ValueComparator implements Comparator<Object> {
102
103 public ValueComparator(Map<String, String> map) {
104 _map = map;
105 }
106
107 @Override
108 public int compare(Object obj1, Object obj2) {
109 String value1 = _map.get(obj1);
110 String value2 = _map.get(obj2);
111
112 return value1.compareTo(value2);
113 }
114
115 private Map<String, String> _map;
116
117 }
118
119 }