1 package org.springframework.samples.countries; 2 3 import java.util.ArrayList ; 4 import java.util.HashMap ; 5 import java.util.Iterator ; 6 import java.util.List ; 7 import java.util.Locale ; 8 import java.util.Map ; 9 10 import org.springframework.beans.factory.InitializingBean; 11 12 16 public class DefaultCountryService implements CountryService, InitializingBean { 17 18 private final Map countriesLists = new HashMap (); 19 20 private final Map countriesMaps = new HashMap (); 21 22 23 public void afterPropertiesSet() { 24 String countries[] = Locale.getISOCountries(); 25 String langs[] = {"fr", "en", "de"}; 26 for (int langId = 0; langId < langs.length; langId++) { 27 String lang = langs[langId]; 28 Locale crtLoc = new Locale (lang, ""); 29 List list = new ArrayList (); 30 Map map = new HashMap (); 31 Country country = null; 32 for (int j = 0; j < countries.length; j++) { 33 String countryCode = countries[j]; 34 Locale countryLoc = new Locale ("en", countryCode); 35 String name = countryLoc.getDisplayCountry(crtLoc); 36 if (!name.equals(countryCode)) { 37 country = new Country(countryCode, name); 38 list.add(country); 39 map.put(countryCode, country); 40 } 41 } 42 this.countriesLists.put(lang, list); 43 this.countriesMaps.put(lang, map); 44 } 45 } 46 47 48 public List getAllCountries(Locale locale) { 49 List countries = (List ) this.countriesLists.get(getLanguage(locale)); 50 if (countries == null) { 51 countries = (List ) this.countriesLists.get(Locale.getDefault().getLanguage()); 52 } 53 return countries; 54 } 55 56 public List getFilteredCountries(String name, String code, Locale locale) { 57 List allCountries = getAllCountries(locale); 58 List countries = new ArrayList (); 59 Iterator it = allCountries.iterator(); 60 while (it.hasNext()) { 61 Country country = (Country) it.next(); 62 if ((name == null || country.getName().startsWith(name)) && 63 (code == null || country.getCode().startsWith(code))) { 64 countries.add(country); 65 } 66 } 67 return countries; 68 } 69 70 public Country getCountry(String code, Locale locale) { 71 return (Country) ((Map ) this.countriesMaps.get(getLanguage(locale))).get(code); 72 } 73 74 private String getLanguage(Locale locale) { 75 if (locale != null) { 76 return locale.getLanguage(); 77 } 78 return Locale.getDefault().getLanguage(); 79 } 80 81 } 82 83 | Popular Tags |