1 24 package org.riotfamily.common.web.view.freemarker; 25 26 import java.util.Locale ; 27 import java.util.Map ; 28 29 import org.springframework.core.GenericCollectionTypeResolver; 30 import org.springframework.core.JdkVersion; 31 32 import freemarker.core.Environment; 33 import freemarker.template.DefaultObjectWrapper; 34 import freemarker.template.TemplateModel; 35 import freemarker.template.TemplateModelException; 36 37 45 public class LocalizedObjectWrapper extends DefaultObjectWrapper { 46 47 private boolean exact = false; 48 49 private Locale fallbackLocale = null; 50 51 56 public void setExact(boolean exact) { 57 this.exact = exact; 58 } 59 60 64 public void setFallbackLocale(Locale fallbackLocale) { 65 this.fallbackLocale = fallbackLocale; 66 } 67 68 public TemplateModel wrap(Object obj) throws TemplateModelException { 69 if (obj instanceof Map ) { 70 Map map = (Map ) obj; 71 if (hasLocaleKey(map)) { 72 return wrapLocalizedEntry(map); 73 } 74 } 75 return super.wrap(obj); 76 } 77 78 private boolean hasLocaleKey(Map map) { 79 if (JdkVersion.isAtLeastJava15()) { 80 Class keyType = GenericCollectionTypeResolver.getMapKeyType( 81 map.getClass()); 82 83 if (keyType != null) { 84 return keyType.isAssignableFrom(Locale .class); 85 } 86 } 87 if (!map.isEmpty()) { 88 Object firstKey = map.keySet().iterator().next(); 89 return firstKey instanceof Locale ; 90 } 91 return false; 92 } 93 94 private TemplateModel wrapLocalizedEntry(Map map) 95 throws TemplateModelException { 96 97 Environment env = Environment.getCurrentEnvironment(); 98 Locale locale = env.getLocale(); 99 return super.wrap(getLocalizedEntry(map, locale)); 100 } 101 102 private Object getLocalizedEntry(Map map, Locale locale) { 103 Object value = map.get(locale); 104 if (value == null && !exact) { 105 Locale lang = new Locale (locale.getLanguage()); 106 value = map.get(lang); 107 } 108 if (value == null && fallbackLocale != null 109 && !fallbackLocale.equals(locale)) { 110 111 value = getLocalizedEntry(map, fallbackLocale); 112 } 113 return value; 114 } 115 116 } 117 | Popular Tags |