/** Returns a Map of the known resources for the given locale. */
  private Map<String, Object> getResourceCache(Locale l) {
    Map<String, Object> values = resourceCache.get(l);

    if (values == null) {
      values = new TextAndMnemonicHashMap();
      for (int i = resourceBundles.size() - 1; i >= 0; i--) {
        String bundleName = resourceBundles.get(i);
        try {
          Control c = CoreResourceBundleControl.getRBControlInstance(bundleName);
          ResourceBundle b;
          if (c != null) {
            b = ResourceBundle.getBundle(bundleName, l, c);
          } else {
            b = ResourceBundle.getBundle(bundleName, l);
          }
          Enumeration keys = b.getKeys();

          while (keys.hasMoreElements()) {
            String key = (String) keys.nextElement();

            if (values.get(key) == null) {
              Object value = b.getObject(key);

              values.put(key, value);
            }
          }
        } catch (MissingResourceException mre) {
          // Keep looking
        }
      }
      resourceCache.put(l, values);
    }
    return values;
  }
Beispiel #2
0
 @Override
 protected Object handleGetObject(String key) {
   if (bundle.containsKey(key)) {
     return bundle.getObject(key);
   }
   // TODO: Workarounds for https://github.com/kohsuke/args4j/issues/70
   // and https://github.com/kohsuke/args4j/issues/71
   return key;
 }
  public String getHtml(HttpServletRequest request, String pluginId, Locale locale) {
    SecurityContextHolder.getContext();
    ResourceBundle resourceBundle =
        ResourceBundle.getBundle("org.jtalks.jcommune.plugin.kaptcha.messages", locale);

    VelocityEngine engine = new VelocityEngine(getProperties());
    engine.init();
    Map<String, Object> model = new HashMap<>();
    model.put(CAPTCHA_LABEL, resourceBundle.getObject("label.tip.captcha"));
    model.put(ALT_CAPTCHA, resourceBundle.getObject("alt.captcha.image"));
    model.put(ALT_REFRESH_CAPTCHA, resourceBundle.getObject("alt.captcha.update"));
    model.put(CAPTCHA_PLUGIN_ID, pluginId);
    model.put(FORM_ELEMENT_ID, getFormElementId(pluginId));
    model.put(BASE_URL, getDeploymentRootUrl(request));
    model.put(DATE, new DateTool());
    return VelocityEngineUtils.mergeTemplateIntoString(
        engine, "org/jtalks/jcommune/plugin/kaptcha/template/captcha.vm", "UTF-8", model);
  }
    @Override
    protected Object handleGetObject(String key) {
      try {
        return null != delegate ? delegate.getObject(key) : null;

      } catch (MissingResourceException e) {
        return null;
      }
    }
 /**
  * Register bean definitions contained in a ResourceBundle.
  *
  * <p>Similar syntax as for a Map. This method is useful to enable standard Java
  * internationalization support.
  *
  * @param rb the ResourceBundle to load from
  * @param prefix match or filter within the keys in the map: e.g. 'beans.' (can be empty or <code>
  *     null</code>)
  * @return the number of bean definitions found
  * @throws BeansException in case of loading or parsing errors
  */
 public int registerBeanDefinitions(ResourceBundle rb, String prefix)
     throws BeanDefinitionStoreException {
   // Simply create a map and call overloaded method.
   Map map = new HashMap();
   Enumeration keys = rb.getKeys();
   while (keys.hasMoreElements()) {
     String key = (String) keys.nextElement();
     map.put(key, rb.getObject(key));
   }
   return registerBeanDefinitions(map, prefix);
 }
  public static String getBasePath() {

    ResourceBundle configuration = ResourceBundle.getBundle("applicationConfig");

    if (configuration.containsKey("FILE.PATH.DIR")) {

      return (String) configuration.getObject("FILE.PATH.DIR");
    }

    return null;
  }
 protected void initResourceBundle(UIDefaults table) {
   // The following line of code does not work, when Quaqua has been loaded with
   // a custom class loader. That's why, we have to inject the labels
   // by ourselves:
   // table.addResourceBundle( "ch.randelshofer.quaqua.Labels" );
   ResourceBundle bundle =
       ResourceBundle.getBundle(
           "ch.randelshofer.quaqua.Labels", Locale.getDefault(), getClass().getClassLoader());
   for (Enumeration i = bundle.getKeys(); i.hasMoreElements(); ) {
     String key = (String) i.nextElement();
     table.put(key, bundle.getObject(key));
   }
 }
    /**
     * Creates a new AggregateBundle.
     *
     * @param bundles A list of source bundles, which shall be merged into one aggregated bundle.
     *     The newly created bundle will contain all keys from all source bundles. In case a key
     *     occurs in multiple source bundles, the value will be taken from the first bundle
     *     containing the key.
     */
    public AggregateBundle(List<ResourceBundle> bundles) {
      if (bundles != null) {

        for (ResourceBundle bundle : bundles) {
          Enumeration<String> keys = bundle.getKeys();
          while (keys.hasMoreElements()) {
            String oneKey = keys.nextElement();
            if (!contents.containsKey(oneKey)) {
              contents.put(oneKey, bundle.getObject(oneKey));
            }
          }
        }
      }
    }
Beispiel #9
0
  protected Object handleGetObject(String key) {
    Object result = null;

    // if the key refers to a different bundle, redirect.
    if (isRedirectKey(key)) return getRedirectedObject(key);

    // first try appending the bundle prefix, if present.
    if (bundlePrefix != null)
      try {
        String prefixedKey = bundlePrefix + "." + key;
        result = delegate.getObject(prefixedKey);
      } catch (MissingResourceException mre) {
      }

    // if no prefix, or if prefixed key not found, lookup the plain key.
    if (result == null)
      try {
        result = delegate.getObject(key);
      } catch (MissingResourceException mre) {
      }

    if (result instanceof String) return interpolate((String) result);
    else return result;
  }
Beispiel #10
0
  /**
   * Returns a name for the locale's country that is appropriate for display to the user. If
   * possible, the name returned will be localized according to inLocale. For example, if the locale
   * is fr_FR and inLocale is en_US, getDisplayCountry() will return "France"; if the locale is
   * en_US and inLocale is fr_FR, getDisplayLanguage() will return "Etats-Unis". If the name
   * returned cannot be localized according to inLocale. (say, we don't have a Japanese name for
   * Croatia), this function falls back on the default locale, on the English name, and finally on
   * the ISO code as a last-resort value. If the locale doesn't specify a country, this function
   * returns the empty string.
   */
  public String getDisplayCountry(Locale inLocale) {
    String ctryCode = country;
    if (ctryCode.length() == 0) return "";

    Locale workingLocale = (Locale) inLocale.clone();
    String result = null;
    int phase = 0;
    boolean done = false;

    if (workingLocale.variant.length() == 0) phase = 1;
    if (workingLocale.country.length() == 0) phase = 2;

    while (!done) {
      try {
        ResourceBundle bundle = LocaleData.getLocaleElements(workingLocale);
        result = findStringMatch((String[][]) bundle.getObject("Countries"), ctryCode, ctryCode);
        if (result.length() != 0) done = true;
      } catch (Exception e) {
        // just fall through
      }

      if (!done) {
        switch (phase) {
          case 0:
            workingLocale = new Locale(workingLocale.language, workingLocale.country, "");
            break;

          case 1:
            workingLocale = new Locale(workingLocale.language, "", workingLocale.variant);
            break;

          case 2:
            workingLocale = getDefault();
            break;

          case 3:
            workingLocale = new Locale("", "", "");
            break;

          default:
            return ctryCode;
        }
        phase++;
      }
    }
    return result;
  }
  /**
   * This method initializes a new instance of <code>DateFormatSymbols</code> by loading the date
   * format information for the specified locale.
   *
   * @param locale The locale for which date formatting symbols should be loaded.
   */
  public DateFormatSymbols(Locale locale) throws MissingResourceException {
    ResourceBundle res =
        ResourceBundle.getBundle(
            "gnu.java.locale.LocaleInformation", locale, ClassLoader.getSystemClassLoader());

    ampms = res.getStringArray("ampms");
    eras = res.getStringArray("eras");
    localPatternChars = res.getString("localPatternChars");
    months = res.getStringArray("months");
    shortMonths = res.getStringArray("shortMonths");
    shortWeekdays = res.getStringArray("shortWeekdays");
    weekdays = res.getStringArray("weekdays");
    zoneStrings = (String[][]) res.getObject("zoneStrings");

    dateFormats = formatsForKey(res, "DateFormat");
    timeFormats = formatsForKey(res, "TimeFormat");
  }
Beispiel #12
0
  /**
   * Returns a name for the locale's variant code that is appropriate for display to the user. If
   * possible, the name will be localized for inLocale. If the locale doesn't specify a variant
   * code, this function returns the empty string.
   */
  public String getDisplayVariant(Locale inLocale) {
    if (variant.length() == 0) return "";

    ResourceBundle bundle = LocaleData.getLocaleElements(inLocale);

    String names[] = getDisplayVariantArray(bundle);

    // Get the localized patterns for formatting a list, and use
    // them to format the list.
    String[] patterns;
    try {
      patterns = (String[]) bundle.getObject("LocaleNamePatterns");
    } catch (MissingResourceException e) {
      patterns = null;
    }
    return formatList(patterns, names);
  }
Beispiel #13
0
  /**
   * Return an array of the display names of the variant.
   *
   * @param bundle the ResourceBundle to use to get the display names
   * @return an array of display names, possible of zero length.
   */
  private String[] getDisplayVariantArray(ResourceBundle bundle) {
    // Split the variant name into tokens separated by '_'.
    StringTokenizer tokenizer = new StringTokenizer(variant, "_");
    String[] names = new String[tokenizer.countTokens()];

    // For each variant token, lookup the display name.  If
    // not found, use the variant name itself.
    for (int i = 0; i < names.length; ++i) {
      String token = tokenizer.nextToken();
      try {
        names[i] = (String) bundle.getObject("%%" + token);
      } catch (MissingResourceException e) {
        names[i] = token;
      }
    }

    return names;
  }
 // Lookup the value corresponding to a key found in catalog.getKeys().
 // Here we assume that the catalog returns a non-inherited value for
 // these keys. FIXME: Not true. Better see whether handleGetObject is
 // public - it is in ListResourceBundle and PropertyResourceBundle.
 private Object lookup(String key) {
   Object value = null;
   if (lookupMethod != null) {
     try {
       value = lookupMethod.invoke(catalog, new Object[] {key});
     } catch (IllegalAccessException e) {
       e.printStackTrace();
     } catch (InvocationTargetException e) {
       e.getTargetException().printStackTrace();
     }
   } else {
     try {
       value = catalog.getObject(key);
     } catch (MissingResourceException e) {
     }
   }
   return value;
 }
 Dictionary<String, String> getHeaders(String localeString) {
   if (localeString == null) localeString = Locale.getDefault().toString();
   if (localeString.length() == 0) return rawHeaders;
   boolean isDefaultLocale = localeString.equals(Locale.getDefault().toString());
   Dictionary<String, String> currentDefault = defaultLocaleHeaders;
   if (isDefaultLocale && currentDefault != null) {
     return currentDefault;
   }
   if (generation
       .getRevision()
       .getRevisions()
       .getModule()
       .getState()
       .equals(Module.State.UNINSTALLED)) {
     // defaultLocaleHeaders should have been initialized on uninstall
     if (currentDefault != null) return currentDefault;
     return rawHeaders;
   }
   ResourceBundle localeProperties = getResourceBundle(localeString, isDefaultLocale);
   Enumeration<String> eKeys = this.rawHeaders.keys();
   Headers<String, String> localeHeaders = new Headers<String, String>(this.rawHeaders.size());
   while (eKeys.hasMoreElements()) {
     String key = eKeys.nextElement();
     String value = this.rawHeaders.get(key);
     if (value.startsWith("%") && (value.length() > 1)) { // $NON-NLS-1$
       String propertiesKey = value.substring(1);
       try {
         value =
             localeProperties == null
                 ? propertiesKey
                 : (String) localeProperties.getObject(propertiesKey);
       } catch (MissingResourceException ex) {
         value = propertiesKey;
       }
     }
     localeHeaders.set(key, value);
   }
   localeHeaders.setReadOnly();
   if (isDefaultLocale) {
     defaultLocaleHeaders = localeHeaders;
   }
   return (localeHeaders);
 }
  /**
   * Returns the entry for the specified <code>key</code> in the Locale <code>loc</code>.
   *
   * @param key the key for which we return the value
   * @param loc the locale
   */
  public Object get(Object key, Locale loc) {
    Object obj = null;

    if (super.containsKey(key)) {
      obj = super.get(key);
    } else if (key instanceof String) {
      String keyString = (String) key;
      ListIterator i = bundles.listIterator(0);
      while (i.hasNext()) {
        String bundle_name = (String) i.next();
        ResourceBundle res = ResourceBundle.getBundle(bundle_name, loc);
        if (res != null) {
          try {
            obj = res.getObject(keyString);
            break;
          } catch (MissingResourceException me) {
            // continue, this bundle has no such key
          }
        }
      }
    }

    // now we've found the object, resolve it.
    // nb: LazyValues aren't supported in resource bundles, so it's correct
    // to insert their results in the locale-less hashtable.

    if (obj == null) return null;

    if (obj instanceof LazyValue) {
      Object resolved = ((LazyValue) obj).createValue(this);
      super.remove(key);
      super.put(key, resolved);
      return resolved;
    } else if (obj instanceof ActiveValue) {
      return ((ActiveValue) obj).createValue(this);
    }

    return obj;
  }
 /**
  * @param locale
  * @return
  */
 private static DayAndMonthUtil createDayAndMonthUtil(Locale locale) {
   ResourceBundle bundle =
       ResourceBundle.getBundle(
           "com.vimukti.accounter.web.server.i18n.constants.DateTimeConstantsImpl",
           locale,
           new UTF8Control());
   DummyDateTimeFormatInfo dateTimeFormatInfo = new DummyDateTimeFormatInfo();
   Set<String> keySet = bundle.keySet();
   for (String key : keySet) {
     String[] values = null;
     Object object = bundle.getObject(key);
     if (object instanceof String) {
       String[] split = object.toString().split(",");
       values = new String[split.length];
       for (int i = 0; i < split.length; i++) {
         values[i] = split[i].trim();
       }
     } else {
       values = (String[]) object;
     }
     setValueToObject(dateTimeFormatInfo, key, values);
   }
   return new DayAndMonthUtil(dateTimeFormatInfo);
 }
  static boolean processLine(
      String key, String expectedValue, PrintWriter out, boolean writeNewFile) throws Exception {
    String rbName, localeName, resTag, qualifier;
    String language = "", country = "", variant = "";
    int index, oldIndex;

    index = key.indexOf("/");
    if (index == -1 || index + 1 == key.length())
      throw new Exception("Malformed input file: no slashes in \"" + key + "\"");
    rbName = key.substring(0, index);

    oldIndex = index + 1;
    index = key.indexOf("/", oldIndex);
    if (index == -1 || index + 1 == key.length())
      throw new Exception("Malformed input file: \"" + key + "\" is missing locale name");
    localeName = key.substring(oldIndex, index);
    boolean use_tag = localeName.indexOf("-") != -1;

    if (use_tag == false && localeName.length() > 0) {
      language = localeName.substring(0, 2);
      if (localeName.length() > 3) {
        country = localeName.substring(3, 5);
        if (localeName.length() > 5) variant = localeName.substring(6);
      }
    }

    oldIndex = index + 1;
    index = key.indexOf("/", oldIndex);
    if (index == -1) index = key.length();
    resTag = key.substring(oldIndex, index);

    // TimeZone name may have "/" in it, for example "Asia/Taipei", so use "Asia\/Taipei in
    // LocaleData.
    if (resTag.endsWith("\\")) {
      resTag = resTag.substring(0, resTag.length() - 1);
      oldIndex = index;
      index = key.indexOf("/", oldIndex + 1);
      if (index == -1) index = key.length();
      resTag += key.substring(oldIndex, index);
    }

    if (index < key.length() - 1) qualifier = key.substring(index + 1);
    else qualifier = "";

    String retrievedValue = null;
    Object resource = null;
    try {
      String fullName = null;
      if (rbName.equals("CalendarData")
          || rbName.equals("CurrencyNames")
          || rbName.equals("LocaleNames")
          || rbName.equals("TimeZoneNames")) {
        fullName = "sun.util.resources." + rbName;
      } else {
        fullName = "sun.text.resources." + rbName;
      }
      Locale locale;
      if (use_tag) {
        locale = Locale.forLanguageTag(localeName);
      } else {
        locale = new Locale(language, country, variant);
      }
      ResourceBundle bundle =
          ResourceBundle.getBundle(
              fullName,
              locale,
              ResourceBundle.Control.getNoFallbackControl(Control.FORMAT_DEFAULT));
      resource = bundle.getObject(resTag);
    } catch (MissingResourceException e) {
    }

    if (resource != null) {
      if (resource instanceof String) {
        retrievedValue = (String) resource;
      } else if (resource instanceof String[]) {
        int element = Integer.valueOf(qualifier).intValue();
        String[] stringList = (String[]) resource;
        if (element >= 0 || element < stringList.length) retrievedValue = stringList[element];
      } else if (resource instanceof String[][]) {
        String[][] stringArray = (String[][]) resource;
        int slash = qualifier.indexOf("/");
        if (slash == -1) {
          for (int i = 0; i < stringArray.length; i++) {
            if (stringArray[i][0].equals(qualifier)) retrievedValue = stringArray[i][1];
          }
        } else {
          int row = Integer.valueOf(qualifier.substring(0, slash)).intValue();
          int column = Integer.valueOf(qualifier.substring(slash + 1)).intValue();
          if (row >= 0
              || row < stringArray.length
              || column >= 0
              || column < stringArray[row].length) retrievedValue = stringArray[row][column];
        }
      }
    }

    if (retrievedValue == null || !retrievedValue.equals(expectedValue)) {
      if (retrievedValue == null) retrievedValue = "<MISSING!>";

      if (writeNewFile) out.println(key + "=" + retrievedValue);
      else {
        out.println("Mismatch in " + key + ":");
        out.println("  file = \"" + expectedValue + "\"");
        out.println("   jvm = \"" + retrievedValue + "\"");
      }
      return false;
    } else {
      if (writeNewFile) out.println(key + "=" + expectedValue);
    }
    return true;
  }
Beispiel #19
0
 public String getProperty(String key) {
   return (String) dataSource.getObject(key);
 }
Beispiel #20
0
  /**
   * Returns a name for the locale that is appropriate for display to the user. This will be the
   * values returned by getDisplayLanguage(), getDisplayCountry(), and getDisplayVariant() assembled
   * into a single string. The display name will have one of the following forms:
   *
   * <p>
   *
   * <blockquote>
   *
   * language (country, variant)
   *
   * <p>language (country)
   *
   * <p>language (variant)
   *
   * <p>country (variant)
   *
   * <p>language
   *
   * <p>country
   *
   * <p>variant
   *
   * <p>
   *
   * </blockquote>
   *
   * depending on which fields are specified in the locale. If the language, country, and variant
   * fields are all empty, this function returns the empty string.
   */
  public String getDisplayName(Locale inLocale) {
    ResourceBundle bundle = LocaleData.getLocaleElements(inLocale);

    String languageName = getDisplayLanguage(inLocale);
    String countryName = getDisplayCountry(inLocale);
    String[] variantNames = getDisplayVariantArray(bundle);

    // Get the localized patterns for formatting a display name.
    String[] patterns;
    try {
      patterns = (String[]) bundle.getObject("LocaleNamePatterns");
    } catch (MissingResourceException e) {
      patterns = null;
    }

    // The display name consists of a main name, followed by qualifiers.
    // Typically, the format is "MainName (Qualifier, Qualifier)" but this
    // depends on what pattern is stored in the display locale.
    String mainName = null;
    String[] qualifierNames = null;

    // The main name is the language, or if there is no language, the country.
    // If there is neither language nor country (an anomalous situation) then
    // the display name is simply the variant's display name.
    if (languageName.length() != 0) {
      mainName = languageName;
      if (countryName.length() != 0) {
        qualifierNames = new String[variantNames.length + 1];
        System.arraycopy(variantNames, 0, qualifierNames, 1, variantNames.length);
        qualifierNames[0] = countryName;
      } else qualifierNames = variantNames;
    } else if (countryName.length() != 0) {
      mainName = countryName;
      qualifierNames = variantNames;
    } else {
      return formatList(patterns, variantNames);
    }

    // Create an array whose first element is the number of remaining
    // elements.  This serves as a selector into a ChoiceFormat pattern from
    // the resource.  The second and third elements are the main name and
    // the qualifier; if there are no qualifiers, the third element is
    // unused by the format pattern.
    Object[] displayNames = {
      new Integer(qualifierNames.length != 0 ? 2 : 1),
      mainName,
      // We could also just call formatList() and have it handle the empty
      // list case, but this is more efficient, and we want it to be
      // efficient since all the language-only locales will not have any
      // qualifiers.
      qualifierNames.length != 0 ? formatList(patterns, qualifierNames) : null
    };

    if (patterns != null) {
      return new MessageFormat(patterns[0]).format(displayNames);
    } else {
      // If we cannot get the message format pattern, then we use a simple
      // hard-coded pattern.  This should not occur in practice unless the
      // installation is missing some core files (LocaleElements etc.).
      StringBuffer result = new StringBuffer();
      result.append((String) displayNames[1]);
      if (displayNames.length > 2) {
        result.append(" (");
        result.append((String) displayNames[2]);
        result.append(")");
      }
      return result.toString();
    }
  }