1 5 package com.oreilly.servlet; 6 7 import java.io.*; 8 import java.util.*; 9 10 import com.oreilly.servlet.LocaleToCharsetMap; 11 12 53 public class LocaleNegotiator { 54 55 private ResourceBundle chosenBundle; 56 private Locale chosenLocale; 57 private String chosenCharset; 58 59 67 public LocaleNegotiator(String bundleName, 68 String languages, 69 String charsets) { 70 71 Locale defaultLocale = new Locale("en", "US"); 74 String defaultCharset = "ISO-8859-1"; 75 ResourceBundle defaultBundle = null; 76 try { 77 defaultBundle = ResourceBundle.getBundle(bundleName, defaultLocale); 78 } 79 catch (MissingResourceException e) { 80 } 82 83 if (languages == null) { 86 chosenLocale = defaultLocale; 87 chosenCharset = defaultCharset; 88 chosenBundle = defaultBundle; 89 return; } 91 92 StringTokenizer tokenizer = new StringTokenizer(languages, ","); 94 95 while (tokenizer.hasMoreTokens()) { 96 String lang = tokenizer.nextToken(); 99 100 Locale loc = getLocaleForLanguage(lang); 102 103 ResourceBundle bundle = getBundleNoFallback(bundleName, loc); 106 107 if (bundle == null) continue; 111 String charset = getCharsetForLocale(loc, charsets); 113 114 if (charset == null) continue; 118 chosenLocale = loc; 120 chosenBundle = bundle; 121 chosenCharset = charset; 122 return; } 124 125 chosenLocale = defaultLocale; 127 chosenCharset = defaultCharset; 128 chosenBundle = defaultBundle; 129 } 130 131 136 public ResourceBundle getBundle() { 137 return chosenBundle; 138 } 139 140 145 public Locale getLocale() { 146 return chosenLocale; 147 } 148 149 154 public String getCharset() { 155 return chosenCharset; 156 } 157 158 161 private Locale getLocaleForLanguage(String lang) { 162 Locale loc; 163 int semi, dash; 164 165 if ((semi = lang.indexOf(';')) != -1) { 167 lang = lang.substring(0, semi); 168 } 169 170 lang = lang.trim(); 172 173 if ((dash = lang.indexOf('-')) == -1) { 176 loc = new Locale(lang, ""); } 178 else { 179 loc = new Locale(lang.substring(0, dash), lang.substring(dash+1)); 180 } 181 182 return loc; 183 } 184 185 190 private ResourceBundle getBundleNoFallback(String bundleName, Locale loc) { 191 192 ResourceBundle fallback = null; 197 try { 198 fallback = 199 ResourceBundle.getBundle(bundleName, new Locale("bogus", "")); 200 } 201 catch (MissingResourceException e) { 202 } 204 205 try { 206 ResourceBundle bundle = ResourceBundle.getBundle(bundleName, loc); 208 209 if (bundle != fallback) { 211 return bundle; 213 } 214 else if (bundle == fallback && 218 loc.getLanguage().equals(Locale.getDefault().getLanguage())) { 219 return bundle; 221 } 222 else { 223 } 225 } 226 catch (MissingResourceException e) { 227 } 229 230 return null; } 232 233 242 protected String getCharsetForLocale(Locale loc, String charsets) { 243 return LocaleToCharsetMap.getCharset(loc); 245 } 246 } 247 | Popular Tags |