View Javadoc

1   package org.appfuse.webapp.services;
2   
3   import org.slf4j.Logger;
4   import org.slf4j.LoggerFactory;
5   import org.springframework.stereotype.Service;
6   
7   import java.util.*;
8   
9   /**
10   * CountryService implementation (for simplified Wicket mechanism) based on Locale.getAvailableLocales() from JDK.
11   *
12   * Manual map caching could be a premature optimisation. Maybe it is worth to use @Cacheable from Spring or
13   * some other mechanism?
14   *
15   * TODO: Add sorting by the country name instead of code and rewrite it using data from http://cldr.unicode.org/
16   *       (and maybe https://wicket.apache.org/guide/guide/chapter13.html#chapter13_4 for Wicket)
17   *
18   * @author Marcin ZajÄ…czkowski, 2013-11-19
19   */
20  @Service("simpleCountryService")
21  public class JavaLocaleSimpleCountryService implements SimpleCountryService {
22  
23      private final static Logger log = LoggerFactory.getLogger(JavaLocaleSimpleCountryService.class);
24  
25      private final static Map<String, Map<String, String>> mmm = new HashMap<>(Locale.getAvailableLocales().length);
26  
27      @Override
28      public List<String> getAvailableCountryCodesInLocale(Locale locale) {
29          return new ArrayList<>(getAvailableCountryMapInLocale(locale).keySet());
30      }
31  
32      private Map<String, String> getAvailableCountryMapInLocale(Locale locale) {
33          String languageTag = locale.getLanguage();
34          if (mmm.get(languageTag) == null) {
35              mmm.put(languageTag, Collections.unmodifiableMap(createSortedSet(locale)));
36          }
37          return mmm.get(languageTag);
38      }
39  
40      @Override
41      public String getCountryNameInLocaleByCode(String code, Locale locale) {
42          for (Map.Entry<String, String> entry : getAvailableCountryMapInLocale(locale).entrySet()) {
43              if (code.equals(entry.getKey())) {
44                  return entry.getValue();
45              }
46          }
47          return null;
48      }
49  
50      private Map<String, String> createSortedSet(Locale requestedLocale) {
51          final String EMPTY = "";
52          Locale[] availableLocales = Locale.getAvailableLocales();
53          Map<String, String> countryMap = new TreeMap<>();
54  
55          for (Locale locale : availableLocales) {
56              String name = locale.getDisplayCountry(requestedLocale);
57              String iso = locale.getCountry();
58              if (!EMPTY.equals(name) && !EMPTY.equals(iso)) {
59                  countryMap.put(iso, name);
60              }
61          }
62          log.debug("Number of countries added: " + countryMap.size());
63  
64          return countryMap;
65      }
66  }