Beispiel #1
0
  /** @bug 4126880 */
  void Test4126880() {
    String[] test;

    test = Locale.getISOCountries();
    test[0] = "SUCKER!!!";
    test = Locale.getISOCountries();
    if (test[0].equals("SUCKER!!!")) errln("Changed internal country code list!");

    test = Locale.getISOLanguages();
    test[0] = "HAHAHAHA!!!";
    test = Locale.getISOLanguages();
    if (test[0].equals("HAHAHAHA!!!")) // Fixed typo
    errln("Changes internal language code list!");
  }
  /**
   * Produces a java map that maps a {@link Country} to it's ISO 3166 country code.<br>
   * Each map entry consists of:<br>
   *
   * <table border=1>
   * <tr>
   * <td>key:</td>
   * <td>ISO 3166 country code</td>
   * </tr>
   * <tr>
   * <td>value:</td>
   * <td>the corresponding country as {@link Country}-instance</td>
   * </table>
   *
   * @return
   */
  public static Map<String, Country> createCountryMap() {
    // ISO3166-ALPHA-2 codes
    String[] countryCodes = Locale.getISOCountries();

    // Key = CountryCode
    // Value = Country
    Map<String, Country> countries = new HashMap<String, Country>(countryCodes.length);

    for (String cc : countryCodes) {

      Locale.setDefault(Locale.US);
      String countryNameEnglish = new Locale(Locale.US.getLanguage(), cc).getDisplayCountry();

      Locale.setDefault(Locale.GERMANY);
      String countryNameGerman = new Locale(Locale.GERMANY.getLanguage(), cc).getDisplayCountry();

      Country country = new Country(cc.toUpperCase(), countryNameEnglish, countryNameGerman);

      countries.put(cc, country);
    }

    if (logger.isInfoEnabled()) {
      logger.info(
          "Created a country-iso3166Code Map<String, Country> with {} entries.", countries.size());
    }

    return countries;
  }
Beispiel #3
0
  public static List<KeyValue> getCountries() {
    String[] isoCountryCodes = Locale.getISOCountries();
    List<KeyValue> countries = new ArrayList<>();
    for (String countryCode : isoCountryCodes) {
      Locale locale = new Locale("", countryCode);
      String countryName = locale.getDisplayCountry();
      String regionCode = locale.getCountry();
      countries.add(new KeyValue(regionCode, countryName));
    }

    //        Locale[] locales = Locale.getAvailableLocales();
    //        for (Locale locale : locales)
    //        {
    //            String code = locale.getCountry();
    //            String country = locale.getDisplayCountry();
    //            if (code.trim().length() > 0 && !code.contains(code) && country.trim().length() >
    // 0 && !countries.contains(country))
    //            {
    //                countries.add(new KeyValue(code, country));
    //            }
    //        }

    Collections.sort(countries, new KeyValueComparator());
    countries.add(0, new KeyValue("", "Any"));
    return countries;
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    addPreferencesFromResource(R.xml.pref_general);
    showLockScreenControlsPreference =
        (TwoStatePreference) findPreference(getString(R.string.lock_screen_pref_key));
    if (showLockScreenControlsPreference != null) {

      showLockScreenControlsPreference.setEnabled(true);
    }
    showLockScreenControlsPreference.setOnPreferenceChangeListener(
        new Preference.OnPreferenceChangeListener() {
          @Override
          public boolean onPreferenceChange(
              Preference preference, Object showLockScreenControlsObj) {

            SharedPreferences.Editor sharedPrefencesEditor = sharedPreferences.edit();
            sharedPrefencesEditor.putBoolean(
                getString(R.string.lock_screen_controls),
                ((Boolean) showLockScreenControlsObj).booleanValue());
            sharedPrefencesEditor.commit();

            Intent broadcastLockScreenIntent = new Intent();
            broadcastLockScreenIntent.setAction(getString(R.string.is_lock_screen_visible));
            sendBroadcast(broadcastLockScreenIntent);

            return true;
          }
        });

    ListPreference listOfCountriesPreference =
        (ListPreference) findPreference(getString(R.string.country_code_pref_key));
    if (null != listOfCountriesPreference) {
      listOfCountriesPreference.setEntryValues(Locale.getISOCountries());
      String[] countries = new String[listOfCountriesPreference.getEntryValues().length];
      for (int i = 0; i < listOfCountriesPreference.getEntryValues().length; i++) {
        countries[i] = new Locale("", Locale.getISOCountries()[i]).getDisplayCountry();
      }
      listOfCountriesPreference.setEntries(countries);
      listOfCountriesPreference.setDefaultValue(Locale.US);
    }

    bindPreferenceSummaryToValue(findPreference(getString(R.string.country_code_pref_key)));
  }
 @Test
 public void testVALUES() {
   assertNotNull(VALUES);
   assertFalse(VALUES.keySet().contains(null));
   assertFalse(VALUES.values().contains(null));
   for (String cc : VALUES.keySet()) {
     assertEquals(cc, VALUES.get(cc).getValue());
   }
   for (Country c : VALUES.values()) {
     assertTrue(
         "not an ISO country code: \"" + c + "\"",
         (!c.equals(NO_COUNTRY) ? contains(Locale.getISOCountries(), c.getValue()) : true));
   }
   for (String cc : Locale.getISOCountries()) {
     assertNotNull(VALUES.get(cc));
   }
 }
  public List<String> dajVsetkyKrajiny() {
    String[] lokaly = Locale.getISOCountries();
    List<String> krajiny = new ArrayList<String>();
    for (String kodKrajiny : lokaly) {
      Locale lokal = new Locale("", kodKrajiny);
      krajiny.add(lokal.getDisplayCountry());
    }

    return krajiny;
  }
 private void reload() {
   regionTypes.clear();
   RegionType rt = RegionType.of("ISO");
   regionTypes.add(rt);
   for (String country : Locale.getISOCountries()) {
     Locale locale = new Locale("", country);
     ISOCountry region = new ISOCountry(locale, rt);
     regions.put(region.getRegionCode(), region);
     ISO3Country region3 = new ISO3Country(locale, rt);
     regions.put(region.getISO3Code(), region3);
   }
 }
  private static List<Country> getAllCountries() {
    List<Country> countries = new ArrayList<Country>();

    for (String countryCode : Locale.getISOCountries()) {
      Country country = new Country();
      country.code = countryCode;
      country.name = new Locale("", countryCode).getDisplayCountry();
      countries.add(country);
    }

    return countries;
  }
  /**
   * Returns a {@link SortedMap} containing the ISO 3166 code of all countries as the key and the
   * localized name of the country as the value.
   *
   * @param locale The {@link Locale} used to obtain the localized names of the countries
   * @return {@link SortedMap} containing the ISO 3166 code of all countries as the key and the
   *     localized name of the country as the value.
   */
  public static SortedMap<String, String> getCountryList(Locale locale) {
    if (locale == null || locale.getLanguage() == null) {
      return new TreeMap<String, String>(); // return empty map
    }

    SortedMap<String, String> retVal = null;

    if (!countryMap.containsKey(locale.getLanguage())) {
      Map<String, String> map = new HashMap<String, String>(Locale.getISOCountries().length);

      for (String str : Locale.getISOCountries()) {
        map.put(str, new Locale("", str).getDisplayCountry(locale));
      }

      retVal = sortByValues(map);
      countryMap.put(locale.getLanguage(), retVal);
    }

    retVal = countryMap.get(locale.getLanguage());

    return retVal;
  }
Beispiel #10
0
  /**
   * @return the locale representing the language of the source document or <code>null</code> if
   *     there is no language set or the language code is not a valid ISO 639 language code.
   */
  public Locale getLanguage() {
    Locale locale = null;

    if (language != null) {
      String ident = language.getAttributeValue(Attribute.language_ident);

      // try to build a locale with ident
      if (ident != null) {
        String parts[] = ident.split(Pattern.quote("-"));

        // we try to find the language
        String langCode = null;
        String langPart = parts[0].toLowerCase();

        // validate language
        for (String validLangCode : Locale.getISOLanguages()) {
          if (validLangCode.equals(langPart)) {
            langCode = validLangCode;
            break;
          }
        }

        if (langCode != null) {
          // ok we have a valid language

          // try to find the country
          String countryCode = null;
          for (int i = 1; i < parts.length; i++) {
            String countryPart = parts[i].toUpperCase();
            // validate country
            for (String validCountryCode : Locale.getISOCountries()) {
              if (validCountryCode.equals(countryPart)) {
                countryCode = validCountryCode;
                break;
              }
            }
          }

          if (countryCode != null) {
            // ok, locale with language and country
            locale = new Locale(langCode, countryCode);
          } else {
            // no country available
            locale = new Locale(langCode);
          }
        }
      }
    }

    return locale;
  }
Beispiel #11
0
  /** @bug 4106155 4118587 7066203 */
  public void TestGetLangsAndCountries() {
    // It didn't seem right to just do an exhaustive test of everything here, so I check
    // for the following things:
    // 1) Does each list have the right total number of entries?
    // 2) Does each list contain certain language and country codes we think are important
    //     (the G7 countries, plus a couple others)?
    // 3) Does each list have every entry formatted correctly? (i.e., two characters,
    //     all lower case for the language codes, all upper case for the country codes)
    // 4) Is each list in sorted order?
    String[] test = Locale.getISOLanguages();
    String[] spotCheck1 = {
      "en", "es", "fr", "de", "it", "ja", "ko", "zh", "th", "he", "id", "iu", "ug", "yi", "za"
    };

    if (test.length != 188)
      errln("Expected getISOLanguages() to return 188 languages; it returned " + test.length);
    else {
      for (int i = 0; i < spotCheck1.length; i++) {
        int j;
        for (j = 0; j < test.length; j++) if (test[j].equals(spotCheck1[i])) break;
        if (j == test.length || !test[j].equals(spotCheck1[i]))
          errln("Couldn't find " + spotCheck1[i] + " in language list.");
      }
    }
    for (int i = 0; i < test.length; i++) {
      if (!test[i].equals(test[i].toLowerCase())) errln(test[i] + " is not all lower case.");
      if (test[i].length() != 2) errln(test[i] + " is not two characters long.");
      if (i > 0 && test[i].compareTo(test[i - 1]) <= 0)
        errln(test[i] + " appears in an out-of-order position in the list.");
    }

    test = Locale.getISOCountries();
    String[] spotCheck2 = {"US", "CA", "GB", "FR", "DE", "IT", "JP", "KR", "CN", "TW", "TH"};

    if (test.length != 249)
      errln("Expected getISOCountries to return 249 countries; it returned " + test.length);
    else {
      for (int i = 0; i < spotCheck2.length; i++) {
        int j;
        for (j = 0; j < test.length; j++) if (test[j].equals(spotCheck2[i])) break;
        if (j == test.length || !test[j].equals(spotCheck2[i]))
          errln("Couldn't find " + spotCheck2[i] + " in country list.");
      }
    }
    for (int i = 0; i < test.length; i++) {
      if (!test[i].equals(test[i].toUpperCase())) errln(test[i] + " is not all upper case.");
      if (test[i].length() != 2) errln(test[i] + " is not two characters long.");
      if (i > 0 && test[i].compareTo(test[i - 1]) <= 0)
        errln(test[i] + " appears in an out-of-order position in the list.");
    }
  }
Beispiel #12
0
 protected String[] getCountryList() {
   if (countryList == null) {
     String[] c = Locale.getISOCountries();
     ArrayList<String> sortedCountries = new ArrayList<String>();
     for (int i = 0; i < c.length; i++) {
       String country = (new Locale("en", c[i])).getDisplayCountry(Locale.getDefault());
       countries.put(country, c[i]);
       sortedCountries.add(country);
     }
     Collections.sort(sortedCountries, Collator.getInstance(Locale.getDefault()));
     countries.put(ANY_COUNTRY, "");
     sortedCountries.add(0, ANY_COUNTRY);
     countryList = sortedCountries.toArray(new String[sortedCountries.size()]);
   }
   return countryList;
 }
  public void printAvailableLocales(OutputStream os) throws Exception {
    Locale[] locales = Locale.getAvailableLocales();

    String name = null, country = null, lang = null, currencySb = null;
    String countryCd = null, langCd = null, currencyCd = null;
    Currency currency = null;

    PrintWriter pw = null;

    try {
      pw = new PrintWriter(os, true);

      for (Locale locale : locales) {
        name = locale.getDisplayName();
        country = locale.getDisplayCountry();
        countryCd = locale.getISOCountries()[0];
        lang = locale.getDisplayLanguage();
        langCd = locale.getISOLanguages()[0];

        try {
          currency = Currency.getInstance(locale);
          currencySb = currency.getSymbol();
          currencyCd = currency.getCurrencyCode();
        } catch (IllegalArgumentException ex) {
          currencySb = "";
          currencyCd = "";
        }

        pw.print("name : " + name + ", ");
        pw.print("country : " + country + "(" + countryCd + "), ");
        pw.print("lang : " + lang + "(" + langCd + "), ");
        pw.println("currency : " + currencySb + "(" + currencyCd + ")");
      }
    } catch (Exception ex) {
      throw ex;
    } finally {
      if (pw != null && os != (OutputStream) (System.out)) pw.close();
    }
  }
Beispiel #14
0
  public Locale fromExternalLocale(String localeStr) {

    if (localeStr == null) {
      return null;
    }

    String lang = localeStr;
    String country = "";
    String var = "";
    int contryIdx = localeStr.indexOf("_");
    if (contryIdx != -1) {
      lang = localeStr.substring(0, contryIdx);
      country = localeStr.substring(contryIdx + 1);
      int varIdx = country.indexOf("_");
      if (varIdx != -1) {
        var = country.substring(varIdx + 1);
        country = country.substring(0, varIdx);
      }
    }
    boolean isLangValid = isValidLanguage(lang);
    boolean isCountryValid = false;
    if (country.length() == 0) {
      isCountryValid = true;
    } else {
      for (String validCn : Locale.getISOCountries()) {
        if (validCn.equals(country)) {
          isCountryValid = true;
          break;
        }
      }
    }
    if (!isLangValid || !isCountryValid) {
      return null;
    }
    Locale locale = new Locale(lang, country, var);
    return locale;
  }
 /** {@inheritDoc} */
 protected DataResult getDataResult(User user, ActionForm formIn, HttpServletRequest request) {
   List retval = Arrays.asList(Locale.getISOCountries());
   return new DataResult(retval);
 }
/**
 * Utility class for Locales and Countries.
 *
 * @author Asterios Raptis
 * @version 1.0
 */
public class LocaleUtils {

  /** Array with all country codes. */
  public static final String[] COUNTRY_CODES = Locale.getISOCountries();

  /** The Constant LANGUAGE_CODES. */
  public static final String[] LANGUAGE_CODES = Locale.getISOLanguages();

  /**
   * Converts the given {@code String} code like "en", "en_US" or "en_US_win" to <b>new</b> {@code
   * Locale}.
   *
   * @param code the code
   * @return the {@code Locale} object or null.
   */
  public static Locale getLocale(final String code) {
    if (code == null || code.isEmpty()) {
      return null;
    }
    final String[] splitted = code.split("_");
    if (splitted.length == 1) {
      return new Locale(code);
    }
    if (splitted.length == 2) {
      return new Locale(splitted[0], splitted[1]);
    }
    if (splitted.length == 3) {
      return new Locale(splitted[0], splitted[1], splitted[2]);
    }
    return null;
  }

  /**
   * Gets from the given properties file the locale code like "en", "en_US" or "en_US_win". For
   * instance if the filename is resource_en.properties than it will return "en", if the filename is
   * resource_en_US.properties than it will return "en_US". If nothing is found than it returns that
   * the properties file is the "default".
   *
   * @param propertiesFile the properties file
   * @return the locale code
   */
  public static String getLocaleCode(final File propertiesFile) {
    final String filename = FilenameUtils.getFilenameWithoutExtension(propertiesFile);
    final int underscoreIndex = filename.indexOf("_");
    String stringCode = "default";
    if (0 < underscoreIndex) {
      stringCode = filename.substring(underscoreIndex + 1, filename.length());
    }
    return stringCode;
  }

  /**
   * Gets the locale file name suffix that has the format 'language_COUNTRY_variant' for instance
   * 'de_DE' for the Locale.GERMANY.
   *
   * @param locale the locale
   * @return the locale name
   */
  public static String getLocaleFilenameSuffix(final Locale locale) {
    return getLocaleFileSuffix(locale, true, true, false);
  }

  /**
   * Gets the locale file name suffix for instance '_de_DE' for the Locale.GERMANY.
   *
   * @param locale the locale
   * @param withCountry the with country
   * @return the locale file suffix
   */
  public static String getLocaleFileSuffix(final Locale locale, final boolean withCountry) {
    return getLocaleFileSuffix(locale, withCountry, false);
  }

  /**
   * Gets the locale file name suffix for instance '_de_DE' for the Locale.GERMANY.
   *
   * @param locale the locale
   * @param withCountry with country
   * @param withVariant with variant
   * @return the locale file suffix
   */
  public static String getLocaleFileSuffix(
      final Locale locale, final boolean withCountry, final boolean withVariant) {
    return getLocaleFileSuffix(locale, withCountry, withVariant, true);
  }

  /**
   * Gets the locale file name suffix for instance '_de_DE' for the Locale.GERMANY.
   *
   * @param locale the locale
   * @param withCountry with country
   * @param withVariant with variant
   * @param withUnderscorePrefix true if the result has to have the underscore prefix
   * @return the locale file suffix
   */
  public static String getLocaleFileSuffix(
      final Locale locale,
      final boolean withCountry,
      final boolean withVariant,
      final boolean withUnderscorePrefix) {
    final StringBuilder localizedName = new StringBuilder();
    if (locale != null) {
      if (locale.getLanguage() != null && !locale.getLanguage().isEmpty()) {
        if (withUnderscorePrefix) {
          localizedName.append("_");
        }
        localizedName.append(locale.getLanguage());
      }
      if (withCountry && locale.getCountry() != null && !locale.getCountry().isEmpty()) {
        localizedName.append("_");
        localizedName.append(locale.getCountry());
      }
      if (withVariant && locale.getVariant() != null && !locale.getVariant().isEmpty()) {
        localizedName.append("_");
        localizedName.append(locale.getVariant());
      }
    }
    return localizedName.toString().trim();
  }

  /**
   * Gets the locale name for instance 'de_DE' for the Locale.GERMANY.
   *
   * @param locale the locale
   * @return the locale name
   * @deprecated use instead {@link LocaleUtils#getLocaleFilenameSuffix(Locale)}
   */
  @Deprecated
  public static String getLocaleName(final Locale locale) {
    return getLocaleFileSuffix(locale, true, true, false);
  }

  /**
   * Checks the given code if its a valide ISO 3166-1 countrycode.
   *
   * @param code The code to check.
   * @return true if the code is valide otherwise false.
   */
  public static boolean isISOCountryCode(String code) {
    if (code.length() == 2) {
      code = code.toUpperCase();
      final List<String> lc = Arrays.asList(LocaleUtils.COUNTRY_CODES);
      return lc.contains(code);
    } else {
      return false;
    }
  }
}
  public void main(IWContext iwc) throws Exception {
    // TODO eiki cache countries
    // some caching made by aron
    super.main(iwc);
    // System.out.println( "country dropdown main start "+
    // com.idega.util.IWTimestamp.RightNow().toString());
    List localeCountries = Arrays.asList(Locale.getISOCountries());

    // List locales = Arrays.asList( java.util.Locale.getAvailableLocales());
    // List locales = ICLocaleBusiness.listOfAllLocalesJAVA();
    Locale currentLocale = iwc.getCurrentLocale();

    // Iterator iter = locales.iterator();
    Iterator iter = localeCountries.iterator();

    Country country = null;
    String countryDisplayName = null;
    Map countries = new HashMap();
    String lang = currentLocale.getISO3Language();
    Locale locale;
    List smallCountries = new Vector();
    // CountryHome countryHome = getAddressBusiness(iwc).getCountryHome();
    while (iter.hasNext()) {
      // Locale locale = (Locale) iter.next();

      String ISOCountry = (String) iter.next();
      try {
        locale = new Locale(lang, ISOCountry);

        countryDisplayName = locale.getDisplayCountry(currentLocale);
        // country = countryHome.findByIsoAbbreviation(locale.getCountry());
        country = getCountryByISO(locale.getCountry());

        if (countryDisplayName != null
            && country != null
            && !countries.containsKey(country.getPrimaryKey())) {
          countries.put(country.getPrimaryKey(), country); // cache
          SmallCountry sCountry =
              new SmallCountry(
                  (Integer) country.getPrimaryKey(), countryDisplayName, ISOCountry, currentLocale);
          smallCountries.add(sCountry);
          // addMenuElement(((Integer)country.getPrimaryKey()).intValue(),countryDisplayName);
        }
      } catch (Exception e1) {
        // e1.printStackTrace();
      }
    }
    Collections.sort(smallCountries);

    for (Iterator iterator = smallCountries.iterator(); iterator.hasNext(); ) {
      SmallCountry sCountry = (SmallCountry) iterator.next();
      // we dont want the ISO code into the list
      if (!sCountry.name.equalsIgnoreCase(sCountry.code)) {
        addMenuElement(sCountry.getID().intValue(), sCountry.getName());
      }
    }

    try {
      if (!StringUtil.isEmpty(this.selectedCountryName)) {
        this.selectedCountry =
            getAddressBusiness(iwc).getCountryHome().findByCountryName(this.selectedCountryName);
      }
      // we must ensure no external selected country is set
      else if (this.selectedCountry == null && !StringUtil.isEmpty(currentLocale.getCountry())) {
        this.selectedCountry =
            getAddressBusiness(iwc)
                .getCountryHome()
                .findByIsoAbbreviation(currentLocale.getCountry());
      }
    } catch (RemoteException e) {
      e.printStackTrace();
    } catch (EJBException e) {
      e.printStackTrace();
    } catch (FinderException e) {
      e.printStackTrace();
    }

    if (this.selectedCountry != null) {
      setSelectedElement(((Integer) this.selectedCountry.getPrimaryKey()).intValue());
    }
    // System.out.println( "country dropdown main end "+
    // com.idega.util.IWTimestamp.RightNow().toString());
  }
Beispiel #18
0
  /** {@inheritDoc} */
  public boolean isLegalValue(Integer tagID, String value) {
    if (!super.isLegalValue(tagID, value)) return false;
    if (value == null || value.length() == 0) return true;

    switch (tagID) {
      case IPTC_CATEGORY:
        final int categoryLength = value.length();
        return categoryLength >= 1 && categoryLength <= 3;

      case IPTC_COUNTRY_CODE:
        for (String countryCode : java.util.Locale.getISOCountries())
          if (value.equalsIgnoreCase(countryCode)) return true;
        return false;

      case IPTC_ENVELOPE_PRIORITY:
        try {
          final int priority = Integer.parseInt(value);
          return priority >= 1 && priority <= 9;
        } catch (NumberFormatException e) {
          return false;
        }

      case IPTC_LANGUAGE_IDENTIFIER:
        for (String langCode : java.util.Locale.getISOLanguages())
          if (value.equalsIgnoreCase(langCode)) return true;
        return false;

      case IPTC_OBJECT_CYCLE:
        return value.length() == 1 && "apb".contains(value);

      case IPTC_SCENE:
        try {
          Integer.parseInt(value);
          if (value.length() != 6) return false;
          return getTagValuesFor(tagID, false).contains(value);
        } catch (NumberFormatException e) {
          return false;
        }

      case IPTC_SUBJECT_CODE:
        try {
          Integer.parseInt(value);
          if (value.length() != 8) return false;
          return getTagValuesFor(tagID, false).contains(value);
        } catch (NumberFormatException e) {
          return false;
        }

      case IPTC_URGENCY:
        try {
          final int urgency = Integer.parseInt(value);
          return urgency >= 1 && urgency <= 8;
        } catch (NumberFormatException e) {
          return false;
        }

      case IPTC_DIGITAL_CREATION_TIME:
      case IPTC_EXPIRATION_TIME:
      case IPTC_RELEASE_TIME:
      case IPTC_TIME_CREATED:
      case IPTC_TIME_SENT:
        // TODO

      case IPTC_INTELLECTUAL_GENRE:
      case IPTC_SUPPLEMENTAL_CATEGORIES:
        // TODO

      default:
        return true;
    }
  }