1 16 17 package org.apache.velocity.tools.view.i18n; 18 19 20 import java.util.Locale ; 21 import javax.servlet.ServletContext ; 22 23 import org.apache.velocity.app.Velocity; 24 import org.apache.velocity.context.Context; 25 26 import org.apache.velocity.tools.view.context.ViewContext; 27 import org.apache.velocity.tools.view.tools.ViewTool; 28 29 42 public class MultiViewsTool implements ViewTool 43 { 44 48 protected static final String DEFAULT_LANGUAGE_KEY = 49 "org.apache.velocity.tools.view.i18n.defaultLanguage"; 50 51 55 protected String defaultLanguage; 56 57 61 public MultiViewsTool() 62 { 63 } 64 65 76 public void init(Object obj) 77 { 78 if (!(obj instanceof ViewContext)) 79 { 80 throw new IllegalArgumentException ("Tool can only be initialized with a ViewContext"); 81 } 82 83 ViewContext context = (ViewContext)obj; 84 Context vc = context.getVelocityContext(); 85 defaultLanguage = (String ) vc.get(DEFAULT_LANGUAGE_KEY); 86 if (defaultLanguage == null || defaultLanguage.trim().equals("")) 87 { 88 ServletContext sc = context.getServletContext(); 89 defaultLanguage = (String ) sc.getAttribute(DEFAULT_LANGUAGE_KEY); 90 if (defaultLanguage == null || defaultLanguage.trim().equals("")) 91 { 92 defaultLanguage = Locale.getDefault().getLanguage(); 94 } 95 } 96 } 97 98 104 public String findLocalizedResource(String name, Locale locale) 105 { 106 return findLocalizedResource(name, locale.getLanguage()); 107 } 108 109 115 public String findLocalizedResource(String name) 116 { 117 return findLocalizedResource(defaultLanguage); 118 } 119 120 142 public String findLocalizedResource(String name, String language) 143 { 144 String localizedName = name + '.' + language; 145 if (!Velocity.templateExists(localizedName)) 147 { 148 String defaultLangSuffix = '.' + defaultLanguage; 150 if (localizedName.endsWith(defaultLangSuffix)) 151 { 152 localizedName = name; 154 } 155 else 156 { 157 localizedName = name + defaultLangSuffix; 158 if (!Velocity.templateExists(localizedName)) 159 { 160 localizedName = name; 161 } 162 } 163 } 164 return localizedName; 165 } 166 167 168 } 169 | Popular Tags |