コード例 #1
0
  protected void fixElementsDefaultLocale(
      Element element, Locale contentDefaultLocale, Locale contentNewDefaultLocale) {

    for (Element dynamicElementElement : element.elements(_DYNAMIC_ELEMENT)) {

      Element importMetaDataElement =
          (Element)
              dynamicElementElement.selectSingleNode(
                  "meta-data[@locale='" + contentNewDefaultLocale.toString() + "']");

      if (importMetaDataElement == null) {
        Element metaDataElement =
            (Element)
                dynamicElementElement.selectSingleNode(
                    "meta-data[@locale='" + contentDefaultLocale.toString() + "']");

        Element copiedMetadataElement = metaDataElement.createCopy();

        Attribute localeAttribute = copiedMetadataElement.attribute(_LOCALE);

        String contentNewDefaultLanguageId = LocaleUtil.toLanguageId(contentNewDefaultLocale);

        localeAttribute.setValue(contentNewDefaultLanguageId);

        dynamicElementElement.add(copiedMetadataElement);
      }

      fixElementsDefaultLocale(
          dynamicElementElement, contentDefaultLocale, contentNewDefaultLocale);
    }
  }
コード例 #2
0
ファイル: Context.java プロジェクト: pedroigorsilva/is
  /**
   * method to return the Localized version of the file whose name is passed as an argument. The
   * localization is done based on localization subdirectories under the docBase.
   *
   * <p>The method performs a resource lookup in a manner similar to the one used for JavaHelp
   * resources.
   *
   * <p>Search for localized versions of the file are looked for:
   *
   * <p><docBase> + "/" + language1 + "_" + country1 + "_" + variant1 + file <docBase> + "/" +
   * language1 + "_" + country1 + file <docBase> + "/" + language1 + file <docBase> + "/" +
   * language2 + "_" + country2 + "_" + variant1 + file <docBase> + "/" + language2 + "_" + country2
   * + file <docBase> + "/" + language2 + file <docBase> + file
   *
   * <p>Where language1, country1, variant1 are associated with the Locale passed as an argument and
   * language2, country2, variant are associated with the fallback Locale passed as argument.
   *
   * @param path the pathname for the resource whose localized version we are seeking
   * @param loc the Locale we are interested in.
   * @param fbLoc the fallback Locale to use if unsuccessful
   * @param locType the type of localization required "file", "docbase"
   * @return a String with the path of the "best localized match" for the file whose path has been
   *     passed as argument.
   */
  public String getRealPath(String path, Locale reqLocale, Locale fbLocale, String locType) {
    String base = getAbsolutePath();
    if (path == null) path = "";

    String realPath = null;

    if ("file".equals(locType))
      realPath = FileUtil.getLocalizedFile(base, path, reqLocale, fbLocale);
    else if ("docbase".equals(locType))
      realPath = FileUtil.getDocBaseLocalizedFile(base, path, reqLocale, fbLocale);

    if (debug > 5) {
      log(
          "Get real path "
              + path
              + " "
              + realPath
              + " "
              + base
              + reqLocale.toString()
              + " "
              + fbLocale.toString());
    }

    return realPath;
  }
コード例 #3
0
ファイル: LocaleTest.java プロジェクト: OzkanCiftci/jdk7u-jdk
  /**
   * @bug 4122371 Confirm that Euro support works. This test is pretty rudimentary; all it does is
   *     check that any locales with the EURO variant format a number using the Euro currency
   *     symbol.
   *     <p>ASSUME: All locales encode the Euro character "\u20AC". If this is changed to use the
   *     single-character Euro symbol, this test must be updated.
   *     <p>DON'T ASSUME: Any specific countries support the Euro. Instead, iterate through all
   *     locales.
   */
  public void TestEuroSupport() {
    final String EURO_VARIANT = "EURO";
    final String EURO_CURRENCY = "\u20AC"; // Look for this string in formatted Euro currency

    Locale[] locales = NumberFormat.getAvailableLocales();
    for (int i = 0; i < locales.length; ++i) {
      Locale loc = locales[i];
      if (loc.getVariant().indexOf(EURO_VARIANT) >= 0) {
        NumberFormat nf = NumberFormat.getCurrencyInstance(loc);
        String pos = nf.format(271828.182845);
        String neg = nf.format(-271828.182845);
        if (pos.indexOf(EURO_CURRENCY) >= 0 && neg.indexOf(EURO_CURRENCY) >= 0) {
          logln("Ok: " + loc.toString() + ": " + pos + " / " + neg);
        } else {
          errln(
              "Fail: "
                  + loc.toString()
                  + " formats without "
                  + EURO_CURRENCY
                  + ": "
                  + pos
                  + " / "
                  + neg
                  + "\n*** THIS FAILURE MAY ONLY MEAN THAT LOCALE DATA HAS CHANGED ***");
        }
      }
    }
  }
コード例 #4
0
  private static LocaleData initLocaleData(Locale locale) {
    LocaleData localeData = new LocaleData();
    if (!ICU.initLocaleDataNative(locale.toString(), localeData)) {
      throw new AssertionError("couldn't initialize LocaleData for locale " + locale);
    }

    // Get the "h:mm a" and "HH:mm" 12- and 24-hour time format strings.
    localeData.timeFormat12 = ICU.getBestDateTimePattern("hm", locale.toString());
    localeData.timeFormat24 = ICU.getBestDateTimePattern("Hm", locale.toString());

    // Fix up a couple of patterns.
    if (localeData.fullTimeFormat != null) {
      // There are some full time format patterns in ICU that use the pattern character 'v'.
      // Java doesn't accept this, so we replace it with 'z' which has about the same result
      // as 'v', the timezone name.
      // 'v' -> "PT", 'z' -> "PST", v is the generic timezone and z the standard tz
      // "vvvv" -> "Pacific Time", "zzzz" -> "Pacific Standard Time"
      localeData.fullTimeFormat = localeData.fullTimeFormat.replace('v', 'z');
    }
    if (localeData.numberPattern != null) {
      // The number pattern might contain positive and negative subpatterns. Arabic, for
      // example, might look like "#,##0.###;#,##0.###-" because the minus sign should be
      // written last. Macedonian supposedly looks something like "#,##0.###;(#,##0.###)".
      // (The negative subpattern is optional, though, and not present in most locales.)
      // By only swallowing '#'es and ','s after the '.', we ensure that we don't
      // accidentally eat too much.
      localeData.integerPattern = localeData.numberPattern.replaceAll("\\.[#,]*", "");
    }
    localeData.shortDateFormat4 = localeData.shortDateFormat.replaceAll("\\byy\\b", "y");
    return localeData;
  }
コード例 #5
0
  public static void importI18NEditorLanguages() throws Exception {

    Locale[] availableLocales = LanguageUtil.getAvailableLocales();
    String bundleName = RcsConstants.I18N_EDITOR_BUNDLE_NAME;

    _logger.info("Number of available locales is " + availableLocales.length);

    for (int i = 1; i <= availableLocales.length; i++) {

      Locale locale = availableLocales[i - 1];

      _logger.info(
          "Start importing locale "
              + locale.toString()
              + ", for bundle "
              + "\""
              + bundleName
              + "\""
              + ", #"
              + i);

      Map<String, String> languageMap = getI18NEditorLanguageMap(locale);

      Hashtable hashBundle = new Hashtable(languageMap);
      saveProperties(locale, hashBundle, bundleName);

      // small formatting
      int leftNum = availableLocales.length - i;
      String leftStr = leftNum == 0 ? "nothing" : String.valueOf(leftNum);

      _logger.info("Stop importing locale " + locale.toString() + ", " + leftStr + " left");
    }
  }
コード例 #6
0
 public void onConfigurationChanged(Configuration conf) {
   final Locale systemLocale = conf.locale;
   // If system configuration was changed, update all parameters.
   if (!TextUtils.equals(systemLocale.toString(), mSystemLocale.toString())) {
     updateAllParameters();
   }
 }
コード例 #7
0
ファイル: PermutationSpec.java プロジェクト: eclipse/vjet.vsf
 public List<String> getExternalsWithResolutionOrder(Permutation permutation) {
   if (permutation == null) {
     return null;
   }
   List<String> result = new ArrayList<String>(4);
   result.add(permutation.toExternal());
   Locale locale = permutation.getLocale();
   if (locale != null) {
     String localeStr = locale.toString();
     if (!result.contains(localeStr)) {
       result.add(localeStr);
     }
     if (locale.getVariant() != null && locale.getVariant().length() != 0) {
       Locale localeWithVar = new Locale(locale.getLanguage(), locale.getCountry());
       localeStr = localeWithVar.toString();
       if (!result.contains(localeStr)) {
         result.add(localeStr);
       }
     }
     if (locale.getCountry() != null && locale.getCountry().length() != 0) {
       Locale localeWithCountry = new Locale(locale.getLanguage());
       localeStr = localeWithCountry.toString();
       if (!result.contains(localeStr)) {
         result.add(localeStr);
       }
     }
   }
   result.add("");
   return result;
 }
コード例 #8
0
 /* (non-Javadoc)
  * @see org.sakaiproject.sitestats.api.event.EventRegistry#getEventName(java.lang.String)
  */
 public String getEventName(String eventId) {
   Locale currentUserLocale = getCurrentUserLocale();
   EventLocaleKey key = new EventLocaleKey(eventId, currentUserLocale.toString());
   if (eventNamesCache.containsKey(key.toString())) {
     return (String) eventNamesCache.get(key.toString());
   } else {
     String eventName = null;
     try {
       String prefix = eventIdToEPPrefix.get(eventId);
       Statisticable s = M_epm.getProviderByPrefixAndCapability(prefix, Statisticable.class);
       Map<String, String> eventIdNamesMap = s.getEventNames(currentUserLocale);
       if (eventIdNamesMap != null) {
         for (String thisEventId : eventIdNamesMap.keySet()) {
           EventLocaleKey thisCacheKey =
               new EventLocaleKey(thisEventId, currentUserLocale.toString());
           String thisEventName = eventIdNamesMap.get(thisEventId);
           eventNamesCache.put(thisCacheKey.toString(), thisEventName);
           if (thisEventId.equals(eventId)) {
             eventName = thisEventName;
           }
         }
         LOG.debug(
             "Cached event names for EB prefix '" + prefix + "', locale: " + currentUserLocale);
       }
     } catch (Exception e) {
       eventName = null;
     }
     return eventName;
   }
 }
コード例 #9
0
ファイル: LocaleUtils.java プロジェクト: i290618754/httl
 public static String appendLocale(String name, Locale locale) {
   if (locale == null) {
     return name;
   }
   int i = name.lastIndexOf('.');
   return i < 0
       ? name + "_" + locale.toString()
       : name.substring(0, i) + "_" + locale.toString() + name.substring(i);
 }
コード例 #10
0
 /**
  * Get the StringManager for a particular package and Locale. If a manager for a package already
  * exists, it will be reused, else a new StringManager will be created for that Locale and
  * returned.
  *
  * @param packageName
  */
 public static synchronized StringManager getManager(
     String packageName, Locale loc, ClassLoader loader) {
   StringManager mgr = managers.get(packageName + "_" + loc.toString());
   if (mgr == null) {
     mgr = new StringManager(packageName, loc, loader);
     managers.put(packageName + '_' + loc.toString(), mgr);
   }
   return mgr;
 }
コード例 #11
0
 private Map<String, String> getLabels(HttpServletRequest request) {
   // Get access to the localized resource bundle
   Locale locale = request.getLocale();
   Map<String, String> labelMap = localeLabels.get(locale.toString());
   if (labelMap == null) {
     labelMap = getLocaleLabels(locale);
     localeLabels.put(locale.toString(), labelMap);
   }
   return labelMap;
 }
コード例 #12
0
  /**
   * @see
   *     org.opencms.workplace.list.A_CmsListDialog#setColumns(org.opencms.workplace.list.CmsListMetadata)
   */
  @SuppressWarnings("unchecked")
  @Override
  protected void setColumns(final CmsListMetadata metadata) {

    // enforce re-invocation of this method because columns are varying and must not be cached:
    metadata.setVolatile(true);

    // add column for icon
    CmsListColumnDefinition iconCol = new CmsListColumnDefinition(LIST_COLUMN_ICON);
    iconCol.setName(Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_ICON_NAME_0));
    iconCol.setHelpText(Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_ICON_HELP_0));
    iconCol.setAlign(CmsListColumnAlignEnum.ALIGN_LEFT);
    iconCol.setWidth("16");
    iconCol.setSorteable(false);
    metadata.addColumn(iconCol);
    iconCol.setPrintable(true);

    // add column for name
    CmsListColumnDefinition nameCol = new CmsListColumnDefinition(LIST_COLUMN_PATH);
    nameCol.setName(Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_PATH_NAME_0));
    nameCol.setHelpText(Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_PATH_HELP_0));
    nameCol.setAlign(CmsListColumnAlignEnum.ALIGN_LEFT);
    nameCol.setSorteable(true);
    metadata.addColumn(nameCol);
    nameCol.setPrintable(true);

    // add column for resource type
    CmsListColumnDefinition typeCol = new CmsListColumnDefinition(LIST_COLUMN_RESOURCETYPE);
    typeCol.setName(
        Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_RESOURCETYPE_NAME_0));
    typeCol.setHelpText(
        Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_RESOURCETYPE_HELP_0));
    typeCol.setAlign(CmsListColumnAlignEnum.ALIGN_LEFT);
    typeCol.setSorteable(true);
    metadata.addColumn(typeCol);
    typeCol.setPrintable(true);

    // add columns for languages:
    List<Locale> sysLocales = OpenCms.getLocaleManager().getAvailableLocales();
    CmsListColumnDefinition langCol;
    for (Locale locale : sysLocales) {
      langCol = new CmsListColumnDefinition(locale.toString());
      langCol.setName(
          Messages.get()
              .container(
                  Messages.GUI_LIST_LANGUAGECOPY_COL_LANGUAGE_NAME_1,
                  new Object[] {locale.toString()}));
      langCol.setHelpText(
          Messages.get().container(Messages.GUI_LIST_LANGUAGECOPY_COL_LANGUAGE_HELP_0));
      langCol.setAlign(CmsListColumnAlignEnum.ALIGN_LEFT);
      langCol.setSorteable(false);
      metadata.addColumn(langCol);
      langCol.setPrintable(true);
    }
  }
コード例 #13
0
 /* (non-Javadoc)
  * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
  */
 @Override
 public void actionPerformed(ActionEvent e) {
   if (e.getSource() == jbValider) {
     if (federation == null)
       federation = new Federation(jtfFederatonName.getText(), jtfFederatonSigle.getText());
     else {
       federation.setNomFederation(jtfFederatonName.getText());
       federation.setSigleFederation(jtfFederatonSigle.getText());
     }
     federation.setCodeCountry(
         ((Country) ccbCountryFederation.getSelectedItem()).getCode().toLowerCase());
     federation.getCompetitionLevels().clear();
     boolean first = true;
     for (String level : jtfFederationNiveau.getText().split(",")) { // $NON-NLS-1$
       CompetitionLevel cl = new CompetitionLevel();
       cl.setDefaut(first);
       first = false;
       cl.setLang(profile.getConfiguration().getLangue());
       cl.setLibelle(level);
       federation.addCompetitionLevel(cl);
     }
     for (Entry<String, JTextField> le : mTraduction.entrySet()) {
       first = true;
       for (String level : le.getValue().getText().split(",")) { // $NON-NLS-1$
         CompetitionLevel cl = new CompetitionLevel();
         cl.setDefaut(first);
         first = false;
         cl.setLang(le.getKey());
         cl.setLibelle(level);
         federation.addCompetitionLevel(cl);
       }
     }
     try {
       federation.save();
     } catch (ObjectPersistenceException e1) {
       federation = null;
       DisplayableErrorHelper.displayException(e1);
       e1.printStackTrace();
     }
     setVisible(false);
   } else if (e.getSource() == jbAnnuler) {
     setVisible(false);
   } else if (e.getSource() == jbAddLocale) {
     Locale loc = (Locale) jcbAvailableLocale.getSelectedItem();
     addLocaleLevelField(loc.toString());
     mTraduction.get(loc.toString()).setText(jtfFederationNiveau.getText());
     jcbAvailableLocale.removeItem(loc);
     if (jcbAvailableLocale.getItemCount() == 0) {
       jcbAvailableLocale.setEnabled(false);
       jbAddLocale.setEnabled(false);
     }
     jlAddLocaleInfo.setVisible(true);
     redimDialog();
   }
 }
コード例 #14
0
 public String getMessage(String code, Object args[], String defaultMessage, Locale locale) {
   try {
     return messageSource.getMessage(code, args, defaultMessage, locale);
   } catch (Exception e) {
     LOG.error(
         "This message key doesn't exist: " + code + ", for this locale: " + locale.toString());
     if (BooleanUtils.negate(locale.toString().equalsIgnoreCase(Constants.DEFAULT_LOCALE_CODE))) {
       return getMessage(code, args, defaultMessage, new Locale(Constants.DEFAULT_LOCALE_CODE));
     }
   }
   return null;
 }
コード例 #15
0
 /*
  * (non-Javadoc)
  *
  * @see
  * org.hoteia.qalingo.core.i18n.message.CoreMessageSource#getMessage(java
  * .lang.String, java.lang.Object[], java.util.Locale)
  */
 public String getMessage(final String code, final Object args[], final Locale locale)
     throws NoSuchMessageException {
   try {
     return messageSource.getMessage(code, args, locale);
   } catch (Exception e) {
     logger.info(
         "This message key doesn't exist: " + code + ", for this locale: " + locale.toString());
     if (BooleanUtils.negate(locale.toString().equalsIgnoreCase(Constants.DEFAULT_LOCALE_CODE))) {
       return getMessage(code, args, new Locale(Constants.DEFAULT_LOCALE_CODE));
     }
   }
   return null;
 }
コード例 #16
0
ファイル: Context.java プロジェクト: pombredanne/spacewalk-1
  /**
   * set the Locale for this thread
   *
   * @param localeIn Locale for this thread.
   */
  public void setLocale(Locale localeIn) {
    this.locale = localeIn;
    LocalizationService ls = LocalizationService.getInstance();

    if (ls.hasMessage("preferences.jsp.lang." + localeIn.toString())) {
      activeLocaleLabel = ls.getMessage("preferences.jsp.lang." + localeIn.toString(), localeIn);
    } else {
      // default to en_US
      // the localeIn will be default to en_US if the LS doesn't
      // find a supported bundle, so we're safe there.
      activeLocaleLabel = ls.getMessage("preferences.jsp.lang.en_US", localeIn);
    }
  }
コード例 #17
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_ejemplo);

    textView = (TextView) findViewById(R.id.textView1);
    Button button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(this);
    Locale locale = Locale.getDefault();
    Locale locale1 = getResources().getConfiguration().locale;
    Log.d("EjemploActivity", "El locale es: ".concat(locale.toString()));
    Log.d("EjemploActivity", "El locale1 es: ".concat(locale1.toString()));
  }
コード例 #18
0
  /**
   * schedule timer task to save/update the bundle data. We are using Timer to offload the work,
   * otherwise intial loads of tools will appear very slow, this way it happens in the background.
   * In the original rSmart impl JMS was used, but since the MessageService is in contrib not core
   * we need another solution to avoid that dependency. Currently we are using a java.util.Timer and
   * scheduled Timer task to queue up and process the calls to this method. This is a similar
   * strategy to that used in BaseDigestService.
   *
   * @param baseName
   * @param moduleName
   * @param newBundle
   * @param loc
   */
  public void saveOrUpdate(
      String baseName, String moduleName, ResourceBundle newBundle, Locale loc) {
    String keyName = getIndexKeyName(baseName, moduleName, loc.toString());
    if (indexedList.contains(keyName)) {
      logger.debug("skip saveOrUpdate() as its already happened once for :" + keyName);
      return;
    }

    if (scheduleSaves) {
      queueBundle(baseName, moduleName, convertResourceBundleToMap(newBundle), loc);
    } else {
      saveOrUpdateInternal(
          baseName, moduleName, convertResourceBundleToMap(newBundle), loc.toString());
    }
  }
コード例 #19
0
  /**
   * Creates an NL fragment project along with the locale specific properties files.
   *
   * @throws CoreException
   * @throws IOException
   * @throws InvocationTargetException
   * @throws InterruptedException
   */
  private void internationalizePlugins(List plugins, List locales, Map overwrites)
      throws CoreException, IOException, InvocationTargetException, InterruptedException {

    Set created = new HashSet();

    for (Iterator it = plugins.iterator(); it.hasNext(); ) {
      IPluginModelBase plugin = (IPluginModelBase) it.next();

      for (Iterator iter = locales.iterator(); iter.hasNext(); ) {
        Locale locale = (Locale) iter.next();

        IProject project = getNLProject(plugin, locale);
        if (created.contains(project)
            || overwriteWithoutAsking
            || !project.exists()
            || OVERWRITE == overwrites.get(project.getName())) {
          if (!created.contains(project) && project.exists()) {
            project.delete(true, getProgressMonitor());
          }

          if (!created.contains(project)) {
            createNLFragment(plugin, project, locale);
            created.add(project);
            project.getFolder(RESOURCE_FOLDER_PARENT).create(false, true, getProgressMonitor());
          }

          project
              .getFolder(RESOURCE_FOLDER_PARENT)
              .getFolder(locale.toString())
              .create(true, true, getProgressMonitor());
          createLocaleSpecificPropertiesFile(project, plugin, locale);
        }
      }
    }
  }
コード例 #20
0
 @Test
 public void testParseLocaleStringSunnyDay() throws Exception {
   Locale expectedLocale = Locale.UK;
   Locale locale = StringUtils.parseLocaleString(expectedLocale.toString());
   assertNotNull("When given a bona-fide Locale string, must not return null.", locale);
   assertEquals(expectedLocale, locale);
 }
コード例 #21
0
 /**
  * Remove any token which is not in [:alpha:] character class. It also removes the tokens with a
  * length less than minimum size. However, a minimum size of 0 implies any length restriction.
  *
  * @param minimumSize Minimum size of accepted tokens. If it equals 0, all the tokens will be
  *     accepted
  */
 public void removeNonAlphabetic(int minimumSize) {
   CHK.CHECK_NOT_NULL(minimumSize);
   CHK.CHECK(minimumSize >= 0, "No negative values are accepted");
   String pattern;
   if (language.toString().equalsIgnoreCase("ar")) {
     pattern = String.format("[\\p{IsArabic}\\p{Alpha}]{%d,}", minimumSize);
   } else if (language.toString().equalsIgnoreCase("el")) {
     pattern = String.format("[\\p{IsGreek}\\p{Alpha}]{%d,}", minimumSize);
   } else if (language.toString().equalsIgnoreCase("bg")) {
     pattern = String.format("[\\p{IsCyrillic}\\p{Alpha}]{%d,}", minimumSize);
   } else {
     pattern = String.format("[\\p{Alpha}]{%d,}", minimumSize);
   }
   Pattern p = Pattern.compile(pattern);
   removePattern(p);
 }
コード例 #22
0
 private void initializeLanguageDialog() {
   TreeMap<String, String> items = new TreeMap<String, String>();
   for (String localeCode : mAppLanguages) {
     Locale loc;
     if (localeCode.length() > 2) {
       loc = new Locale(localeCode.substring(0, 2), localeCode.substring(3, 5));
     } else {
       loc = new Locale(localeCode);
     }
     items.put(loc.getDisplayName(), loc.toString());
   }
   mLanguageDialogLabels = new CharSequence[items.size() + 1];
   mLanguageDialogValues = new CharSequence[items.size() + 1];
   mLanguageDialogLabels[0] = getResources().getString(R.string.language_system);
   mLanguageDialogValues[0] = "";
   int i = 1;
   for (Map.Entry<String, String> e : items.entrySet()) {
     mLanguageDialogLabels[i] = e.getKey();
     mLanguageDialogValues[i] = e.getValue();
     i++;
   }
   mLanguageSelection = (ListPreference) getPreferenceScreen().findPreference("language");
   mLanguageSelection.setEntries(mLanguageDialogLabels);
   mLanguageSelection.setEntryValues(mLanguageDialogValues);
 }
コード例 #23
0
  protected String buildStatsUrl(StatsParameters searchParameters, String baseUrl, Locale locale)
      throws UnsupportedEncodingException {
    URLCodec encoder = new URLCodec();
    StringBuilder url = new StringBuilder();
    String languageUrlFragment = extractLanguageFragment(searchParameters.getLanguage());

    url.append(baseUrl);
    url.append("/").append(languageUrlFragment);
    url.append("?wt=").append(encoder.encode("json", "UTF-8"));
    url.append("&locale=").append(encoder.encode(locale.toString(), "UTF-8"));

    url.append(buildSortParameters(searchParameters, encoder));

    url.append("&stats=true");
    url.append("&rows=0");
    if (!StringUtils.isBlank(searchParameters.getFilterQuery())) {
      url.append("?fq=").append(encoder.encode(searchParameters.getFilterQuery(), "UTF-8"));
    }

    for (Entry<String, String> entry : searchParameters.getStatsParameters().entrySet()) {
      url.append("&stats.")
          .append(entry.getKey())
          .append("=")
          .append(encoder.encode(entry.getValue(), "UTF-8"));
    }

    return url.toString();
  }
コード例 #24
0
  private static String initGeckoEnvironment() {
    final Context context = GeckoAppShell.getApplicationContext();
    GeckoLoader.loadMozGlue(context);
    setState(State.MOZGLUE_READY);

    final Locale locale = Locale.getDefault();
    final Resources res = context.getResources();
    if (locale.toString().equalsIgnoreCase("zh_hk")) {
      final Locale mappedLocale = Locale.TRADITIONAL_CHINESE;
      Locale.setDefault(mappedLocale);
      Configuration config = res.getConfiguration();
      config.locale = mappedLocale;
      res.updateConfiguration(config, null);
    }

    String[] pluginDirs = null;
    try {
      pluginDirs = GeckoAppShell.getPluginDirectories();
    } catch (Exception e) {
      Log.w(LOGTAG, "Caught exception getting plugin dirs.", e);
    }

    final String resourcePath = context.getPackageResourcePath();
    GeckoLoader.setupGeckoEnvironment(context, pluginDirs, context.getFilesDir().getPath());

    GeckoLoader.loadSQLiteLibs(context, resourcePath);
    GeckoLoader.loadNSSLibs(context, resourcePath);
    GeckoLoader.loadGeckoLibs(context, resourcePath);
    setState(State.LIBS_READY);

    return resourcePath;
  }
コード例 #25
0
  @Test
  public void testLocale() throws Exception {
    Locale locale = getLocale();
    String filename =
        "org/jboss/resteasy/plugins/providers/multipart/i18n/Messages.i18n_"
            + locale.toString()
            + ".properties";
    if (!before(locale, filename)) {
      System.out.println(getClass() + ": " + filename + " not found.");
      return;
    }

    Assert.assertEquals(
        getExpected(BASE + "00", "couldFindNoContentDispositionHeader"),
        Messages.MESSAGES.couldFindNoContentDispositionHeader());
    Assert.assertEquals(
        getExpected(BASE + "05", "couldNotParseContentDisposition", field),
        Messages.MESSAGES.couldNotParseContentDisposition(field));
    Assert.assertEquals(
        getExpected(BASE + "20", "hadToWriteMultipartOutput", multipartOutput, writer, getClass()),
        Messages.MESSAGES.hadToWriteMultipartOutput(multipartOutput, writer, getClass()));
    Assert.assertEquals(
        getExpected(
            BASE + "35",
            "receivedGenericType",
            reader,
            getClass().getGenericSuperclass(),
            getClass()),
        Messages.MESSAGES.receivedGenericType(
            reader, getClass().getGenericSuperclass(), getClass()));
    Assert.assertEquals(
        getExpected(BASE + "60", "urlEncoderDoesNotSupportUtf8"),
        Messages.MESSAGES.urlEncoderDoesNotSupportUtf8());
  }
コード例 #26
0
ファイル: TimeZoneNames.java プロジェクト: ZeerDonker/robovm
    @Override
    protected String[][] create(Locale locale) {
      long start = System.currentTimeMillis();

      // Set up the 2D array used to hold the names. The first column contains the Olson ids.
      String[][] result = new String[availableTimeZoneIds.length][5];
      for (int i = 0; i < availableTimeZoneIds.length; ++i) {
        result[i][0] = availableTimeZoneIds[i];
      }

      long nativeStart = System.currentTimeMillis();
      fillZoneStrings(locale.toString(), result);
      long nativeEnd = System.currentTimeMillis();

      internStrings(result);
      // Ending up in this method too often is an easy way to make your app slow, so we ensure
      // it's easy to tell from the log (a) what we were doing, (b) how long it took, and
      // (c) that it's all ICU's fault.
      long end = System.currentTimeMillis();
      long nativeDuration = nativeEnd - nativeStart;
      long duration = end - start;
      System.logI(
          "Loaded time zone names for \""
              + locale
              + "\" in "
              + duration
              + "ms"
              + " ("
              + nativeDuration
              + "ms in ICU)");
      return result;
    }
コード例 #27
0
ファイル: PluginHandlers.java プロジェクト: phan-pivotal/OSS
  /**
   * This function attempts to calculate a <em>help</em> path with the given locale and classloader.
   * It only succeeds if it is able to confirm a file exists at the generated path as determined by
   * <code>ClassLoader.getResource(path)</code>. The paths checked are the following in this order:
   *
   * <ul>
   *   <li><code>/locale.toString()/help/&lt;resource&gt;</code>
   *   <li><code>/locale.getLanguage()_locale.getCountry()/help/&lt;resource&gt;</code>
   *   <li><code>/locale.getLanguage()/help/&lt;resource&gt;</code>
   * </ul>
   *
   * <p>If all of those fail to yield a file in the classpath, then <code>null</code> will be
   * returned.
   */
  public static String getHelpPathForResource(String resource, Locale locale, ClassLoader cl) {
    String path = "/" + locale.toString() + "/help/" + resource;

    // Try with full locale
    boolean found = (cl.getResource(path) != null);

    // Try with language_COUNTRY
    if (!found) {
      String language = locale.getLanguage();
      String country = locale.getCountry();
      path = "/" + language + "_" + country + "/help/" + resource;
      found = (cl.getResource(path) != null);

      // Try with just language
      if (!found) {
        path = "/" + language + "/help/" + resource;
        found = (cl.getResource(path) != null);
        if (!found) {
          // Still not found, so return null
          path = null;
        }
      }
    }

    return path;
  }
コード例 #28
0
ファイル: LanguageTest.java プロジェクト: tiennv90/SVN
 private void assertLocale(String code, String language, String country, String variant) {
   Locale locale = Language.getLocale(code);
   assertEquals(code.replaceAll("-", "_"), locale.toString());
   assertEquals(language, locale.getLanguage());
   assertEquals(country, locale.getCountry());
   assertEquals(variant, locale.getVariant());
 }
コード例 #29
0
  /** Creates a new instance of clPrintGraphPanel */
  public clPrintGraphPanel(java.awt.Frame parent, clHauptPanel hp, Locale lc) {
    super(hp.getKn(), hp.getSt(), true);
    this.parent = parent;
    dxf = hp.dxf;
    mechanismusRelKnVersch = hp.mechanismusRelKnVersch;

    Point2D[] zoomPkte = hp.getZoomPkte();
    ZoomPkt1 = zoomPkte[0];
    ZoomPkt2 = zoomPkte[1];
    ZOOMALL = hp.ZOOMALL;
    maxMechSkal = hp.maxMechSkal;

    boolean[] aktiveLayer = hp.getAktiveLayer();
    MIT_KnNr = aktiveLayer[0];
    MIT_StabNr = aktiveLayer[1];
    MIT_Lasten = aktiveLayer[2];
    MIT_Auflagerkräften = aktiveLayer[3];
    MIT_Stabkräften = aktiveLayer[4];
    MIT_Hintergrund = aktiveLayer[5];
    MIT_Mechanismus = aktiveLayer[6];

    maxPfeil = maxPfeil * druckvergr;
    spitzenlängeMax = spitzenlängeMax * druckvergr; // / (0.5d + printskal/2d);
    spitzenlängeMin = spitzenlängeMin * druckvergr; // / (0.5d + printskal/2d);
    lagerhöhe = lagerhöhe * (float) druckvergr; // / (0.5f + ((float)printskal)/2f);

    locale = lc;
    druckRB = ResourceBundle.getBundle("Fachwerk/locales/gui-drucken", locale);
    if (druckRB == null) {
      System.err.println("FEHLER: gui-drucken für " + locale.toString());
    }
  }
コード例 #30
0
 /**
  * Look up the welcome section of the top branding theme. The message keys are translated in the
  * language of the passed in {@code Locale}
  *
  * @param locale The {@code Locale} to use to look up the appropriate messages.
  * @return An HTML string to be placed in the welcome page.
  */
 public String getWelcomeSections(final Locale locale) {
   Map<String, String> messageMap = getMessageMap(WELCOME, locale);
   List<BrandingTheme> brandingThemes = getBrandingThemes();
   StringBuilder templateBuilder = new StringBuilder();
   for (BrandingTheme theme : brandingThemes) {
     String template = theme.getWelcomePageSectionTemplate();
     String replacedTemplate = template;
     Matcher keyMatcher = TEMPLATE_PATTERN.matcher(template);
     while (keyMatcher.find()) {
       String key = keyMatcher.group(1);
       // Don't replace {userLocale} here.
       if (!USER_LOCALE_HOLDER.substring(2, USER_LOCALE_HOLDER.length() - 2).equals(key)
           && messageMap.get(key) != null) {
         replacedTemplate =
             replacedTemplate.replaceAll(
                 "\\{" + key + "\\}", // $NON-NLS-1 //$NON-NLS-2$
                 messageMap.get(key));
       }
     }
     replacedTemplate = replacedTemplate.replaceAll(USER_LOCALE_HOLDER, locale.toString());
     if (theme.shouldReplaceWelcomePageSectionTemplate()) {
       // Clear the template builder as the theme wants to replace instead of append to the
       // template.
       templateBuilder = new StringBuilder();
     }
     templateBuilder.append(replacedTemplate);
   }
   return templateBuilder.toString();
 }