Esempio n. 1
0
  /**
   * Tries to load the bundle for a given locale, also loads the backup locales with the same
   * language.
   *
   * @param baseName the raw bundle name, without locale qualifiers
   * @param locale the locale
   * @param classLoader the classloader
   * @param wantBase whether a resource bundle made only from the base name (with no locale
   *     information attached) should be returned.
   * @return the resource bundle if it was loaded, otherwise the backup
   */
  private static ResourceBundle tryBundle(
      String baseName, Locale locale, ClassLoader classLoader, boolean wantBase) {
    String language = locale.getLanguage();
    String country = locale.getCountry();
    String variant = locale.getVariant();

    int baseLen = baseName.length();

    // Build up a CPStringBuilder containing the complete bundle name, fully
    // qualified by locale.
    CPStringBuilder sb = new CPStringBuilder(baseLen + variant.length() + 7);

    sb.append(baseName);

    if (language.length() > 0) {
      sb.append('_');
      sb.append(language);

      if (country.length() > 0) {
        sb.append('_');
        sb.append(country);

        if (variant.length() > 0) {
          sb.append('_');
          sb.append(variant);
        }
      }
    }

    // Now try to load bundles, starting with the most specialized name.
    // Build up the parent chain as we go.
    String bundleName = sb.toString();
    ResourceBundle first = null; // The most specialized bundle.
    ResourceBundle last = null; // The least specialized bundle.

    while (true) {
      ResourceBundle foundBundle = tryBundle(bundleName, classLoader);
      if (foundBundle != null) {
        if (first == null) first = foundBundle;
        if (last != null) last.parent = foundBundle;
        foundBundle.locale = locale;
        last = foundBundle;
      }
      int idx = bundleName.lastIndexOf('_');
      // Try the non-localized base name only if we already have a
      // localized child bundle, or wantBase is true.
      if (idx > baseLen || (idx == baseLen && (first != null || wantBase)))
        bundleName = bundleName.substring(0, idx);
      else break;
    }

    return first;
  }