List of usage examples for java.util ResourceBundle getLocale
public Locale getLocale()
From source file:com.mfalaize.ant.LocalizeTask.java
@Override public void execute() throws BuildException { for (ResourceBundle resourceBundle : getAvailableResourceBundles()) { // Create the directory in which store all the files translated for this resourceBundle File directory = new File(targetDirectory + File.separator + resourceBundle.getLocale().getLanguage()); if (!directory.mkdirs()) { log(String.format("Cannot create directory %s.", directory.getAbsolutePath()), Project.MSG_ERR); continue; } else {/*from w ww. j a va 2 s .c om*/ log(String.format("Creating directory for locale %s.", resourceBundle.getLocale().getLanguage()), Project.MSG_VERBOSE); } DirectoryScanner ds = getDirectoryScanner(translateDirectory); String[] files = ds.getIncludedFiles(); log(String.format("Translating %d files for locale %s...", files.length, resourceBundle.getLocale().getLanguage())); for (int i = 0; i < files.length; i++) { File file = new File(translateDirectory + File.separator + files[i]); log(String.format("Translating %s...", files[i]), Project.MSG_VERBOSE); try { String fileString = FileUtils.readFileToString(file, encoding); Pattern pattern = Pattern.compile(LOCALIZE_PATTERN); Matcher matcher = pattern.matcher(fileString); while (matcher.find()) { String key = matcher.group(2); fileString = matcher.replaceFirst(resourceBundle.getString(key)); log(String.format("Replacing occurrence of %s by %s.", matcher.group(), resourceBundle.getString(key)), Project.MSG_DEBUG); matcher = pattern.matcher(fileString); } // localize-task.js inclusion removal matcher = Pattern.compile(LOCALIZE_JS_PATTERN).matcher(fileString); if (matcher.find()) { fileString = matcher.replaceFirst(""); log("Removing the localize-task.js inclusion.", Project.MSG_DEBUG); } String newFilePath = directory.getAbsolutePath() + File.separator + org.apache.tools.ant.util.FileUtils.getRelativePath(projectDirectory, file); FileUtils.writeStringToFile(new File(newFilePath), fileString, encoding); } catch (Throwable ex) { log(String.format("An exception occured : %s", ex.getMessage()), Project.MSG_ERR); throw new BuildException(ex); } } } }
From source file:com.heliosphere.athena.base.resource.bundle.ResourceBundleManager.java
/** * Registers a resource bundle./*from ww w. j a v a2s . c om*/ * <p> * @param bundleClass Class of the resource bundle to register. * @param bundle Resource bundle to register. * @throws ResourceBundleException Thrown if an error occurred while trying * to register a resource bundle. */ @SuppressWarnings("nls") private static final void register(final Class<? extends IBundle> bundleClass, final ResourceBundle bundle) { ResourceBundle previous = null; try { if (!BUNDLES.containsKey(bundleClass)) { BUNDLES.put(bundleClass, bundle); NAMES.put(bundleClass, bundleClass.getEnumConstants()[0].getKey()); setInitialized(true); String filename = bundleClass.getEnumConstants()[0].getKey() + "_" + locale.toString() + ".properties"; int index = filename.indexOf("."); if (index > -1) { filename = filename.substring(index + 1, filename.length()); } log.debug(getMessage(BundleAthenaBase.ResourceBundleRegistered, bundleClass.getSimpleName(), locale.toString(), Integer.valueOf(bundle.keySet().size()), filename)); } else { /* * Case where the bundle class already exists. If the locale is * the same, do nothing but if the locale is different then * replace it with the new one. */ previous = BUNDLES.get(bundleClass); if (previous.getLocale().equals(bundle.getLocale())) { log.debug(getMessage(BundleAthenaBase.ResourceBundleAlreadyRegistered, bundleClass.getSimpleName(), locale.toString())); } else { BUNDLES.put(bundleClass, bundle); log.debug(getMessage(BundleAthenaBase.ResourceBundleReplaced, bundleClass.getSimpleName(), previous.getLocale().toString(), locale.toString(), Integer.valueOf(bundle.keySet().size()))); } } } catch (final Exception e) { log.error(e.getMessage(), e); throw (ResourceBundleException) e; } }
From source file:com.heliosphere.demeter.base.resource.bundle.ResourceBundleManager.java
/** * Registers a resource bundle./* w ww .ja v a 2 s . co m*/ * <p> * @param bundleClass Class of the resource bundle to register. * @param bundle Resource bundle to register. * @throws ResourceBundleException Thrown if an error occurred while trying * to register a resource bundle. */ @SuppressWarnings("nls") private static final void register(final Class<? extends IBundle> bundleClass, final ResourceBundle bundle) { ResourceBundle previous = null; try { if (!BUNDLES.containsKey(bundleClass)) { BUNDLES.put(bundleClass, bundle); NAMES.put(bundleClass, bundleClass.getEnumConstants()[0].getKey()); setInitialized(true); String filename = bundleClass.getEnumConstants()[0].getKey() + "_" + locale.toString() + ".properties"; int index = filename.indexOf("."); if (index > -1) { filename = filename.substring(index + 1, filename.length()); } log.debug(getMessage(BundleDemeterBase.ResourceBundleRegistered, bundleClass.getSimpleName(), locale.toString(), Integer.valueOf(bundle.keySet().size()), filename)); } else { /* * Case where the bundle class already exists. If the locale is * the same, do nothing but if the locale is different then * replace it with the new one. */ previous = BUNDLES.get(bundleClass); if (previous.getLocale().equals(bundle.getLocale())) { log.debug(getMessage(BundleDemeterBase.ResourceBundleAlreadyRegistered, bundleClass.getSimpleName(), locale.toString())); } else { BUNDLES.put(bundleClass, bundle); log.debug(getMessage(BundleDemeterBase.ResourceBundleReplaced, bundleClass.getSimpleName(), previous.getLocale().toString(), locale.toString(), Integer.valueOf(bundle.keySet().size()))); } } } catch (final Exception e) { log.error(e.getMessage(), e); throw (ResourceBundleException) e; } }
From source file:com.evolveum.midpoint.model.impl.validator.ResourceValidatorImpl.java
@NotNull private String getString(ResourceBundle bundle, String key, Object... parameters) { final String resolvedKey; if (key != null) { if (bundle.containsKey(key)) { resolvedKey = bundle.getString(key); } else {/*from w w w. j a va 2 s. com*/ resolvedKey = key; } } else { resolvedKey = ""; } final MessageFormat format = new MessageFormat(resolvedKey, bundle.getLocale()); return format.format(parameters); }
From source file:kg.apc.jmeter.config.redis.RedisDataSet.java
/** * Override the setProperty method in order to convert * the original String calcMode property. * This used the locale-dependent display value, so caused * problems when the language was changed. * Note that the calcMode StringProperty is replaced with an IntegerProperty * so the conversion only needs to happen once. *//*from w ww . j a va 2 s . com*/ @Override public void setProperty(JMeterProperty property) { if (property instanceof StringProperty) { final String pn = property.getName(); if (pn.equals("getMode")) { final Object objectValue = property.getObjectValue(); try { final BeanInfo beanInfo = Introspector.getBeanInfo(this.getClass()); final ResourceBundle rb = (ResourceBundle) beanInfo.getBeanDescriptor() .getValue(GenericTestBeanCustomizer.RESOURCE_BUNDLE); for (Enum<GetMode> e : GetMode.values()) { final String propName = e.toString(); if (objectValue.equals(rb.getObject(propName))) { final int tmpMode = e.ordinal(); if (log.isDebugEnabled()) { log.debug("Converted " + pn + "=" + objectValue + " to mode=" + tmpMode + " using Locale: " + rb.getLocale()); } super.setProperty(pn, tmpMode); return; } } log.warn("Could not convert " + pn + "=" + objectValue + " using Locale: " + rb.getLocale()); } catch (IntrospectionException e) { log.error("Could not find BeanInfo", e); } } else if (pn.equals("whenExhaustedAction")) { final Object objectValue = property.getObjectValue(); try { final BeanInfo beanInfo = Introspector.getBeanInfo(this.getClass()); final ResourceBundle rb = (ResourceBundle) beanInfo.getBeanDescriptor() .getValue(GenericTestBeanCustomizer.RESOURCE_BUNDLE); for (Enum<WhenExhaustedAction> e : WhenExhaustedAction.values()) { final String propName = e.toString(); if (objectValue.equals(rb.getObject(propName))) { final int tmpMode = e.ordinal(); if (log.isDebugEnabled()) { log.debug("Converted " + pn + "=" + objectValue + " to mode=" + tmpMode + " using Locale: " + rb.getLocale()); } super.setProperty(pn, tmpMode); return; } } log.warn("Could not convert " + pn + "=" + objectValue + " using Locale: " + rb.getLocale()); } catch (IntrospectionException e) { log.error("Could not find BeanInfo", e); } } } super.setProperty(property); }
From source file:kg.apc.jmeter.listener.GraphsGeneratorListener.java
/** * Override the setProperty method in order to convert * the original String calcMode property. * This used the locale-dependent display value, so caused * problems when the language was changed. * Note that the calcMode StringProperty is replaced with an IntegerProperty * so the conversion only needs to happen once. *///from w w w. j av a 2s. c o m @Override public void setProperty(JMeterProperty property) { if (property instanceof StringProperty) { final String pn = property.getName(); if (pn.equals("exportMode")) { final Object objectValue = property.getObjectValue(); try { final BeanInfo beanInfo = Introspector.getBeanInfo(this.getClass()); final ResourceBundle rb = (ResourceBundle) beanInfo.getBeanDescriptor() .getValue(GenericTestBeanCustomizer.RESOURCE_BUNDLE); for (Enum<ExportMode> e : ExportMode.values()) { final String propName = e.toString(); if (objectValue.equals(rb.getObject(propName))) { final int tmpMode = e.ordinal(); if (log.isDebugEnabled()) { log.debug("Converted " + pn + "=" + objectValue + " to mode=" + tmpMode + " using Locale: " + rb.getLocale()); } super.setProperty(pn, tmpMode); return; } } log.warn("Could not convert " + pn + "=" + objectValue + " using Locale: " + rb.getLocale()); } catch (IntrospectionException e) { log.error("Could not find BeanInfo", e); } } } super.setProperty(property); }
From source file:com.aurel.track.dbase.InitDatabase.java
/** * Update the message of the day shown on the front page * @param site//from w w w. j a v a 2 s .co m */ private static void setMessageOfTheDay() { Locale[] availableLocales = Locale.getAvailableLocales(); // all on this system ResourceBundle messages = null; Map<String, String> languages = new HashMap<String, String>(); for (int i = 0; i < availableLocales.length; ++i) { Locale locale = availableLocales[i]; locale = new Locale(locale.getLanguage()); // just reduce the locale to the language specific one (no country) messages = ResourceBundle.getBundle("resources.UserInterface.ApplicationResources", locale); Locale theRealLoc = messages.getLocale(); // the existing locale found here String test = languages.get(theRealLoc.getLanguage()); // check if the language has already been treated if (test == null) { languages.put(theRealLoc.getLanguage(), "x"); String motdMessage = messages.getString("motd.message"); String motdTeaser = messages.getString("motd.teaser"); TMotdBean motd = MotdBL.loadMotd(theRealLoc.getLanguage()); try { if (motd == null && motdMessage != null && motdMessage.trim().length() > 0) { motd = new TMotdBean(); motd.setTheLocale(theRealLoc.getLanguage()); motd.setTheMessage(motdMessage); motd.setTeaserText(motdTeaser); MotdBL.saveMotd(motd); LOGGER.info("Created new MOTD for language " + theRealLoc.getLanguage()); } else if (motd != null && motdMessage != null && motdMessage.trim().length() > 0) { motd.setTheMessage(motdMessage + " " + motd.getTheMessage()); motd.setTeaserText(motdTeaser); MotdBL.saveMotd(motd); LOGGER.info("Updated MOTD for language " + theRealLoc.getLanguage()); } } catch (Exception e) { LOGGER.error("Error updating MOTD: " + e.getMessage()); LOGGER.debug(STACKTRACE, e); } } } }
From source file:org.apache.cxf.common.logging.LogUtils.java
/** * Create a logger//ww w .j a v a2 s. c om */ protected static Logger createLogger(Class<?> cls, String name, String loggerName) { ClassLoader orig = getContextClassLoader(); ClassLoader n = getClassLoader(cls); if (n != null) { setContextClassLoader(n); } String bundleName = name; try { Logger logger = null; ResourceBundle b = null; if (bundleName == null) { //grab the bundle prior to the call to Logger.getLogger(...) so the //ResourceBundle can be loaded outside the big sync block that getLogger really is bundleName = BundleUtils.getBundleName(cls); try { b = BundleUtils.getBundle(cls); } catch (MissingResourceException rex) { //ignore } } else { bundleName = BundleUtils.getBundleName(cls, bundleName); try { b = BundleUtils.getBundle(cls, bundleName); } catch (MissingResourceException rex) { //ignore } } if (b != null) { b.getLocale(); } if (loggerClass != null) { try { Constructor<?> cns = loggerClass.getConstructor(String.class, String.class); if (name == null) { try { return (Logger) cns.newInstance(loggerName, bundleName); } catch (InvocationTargetException ite) { if (ite.getTargetException() instanceof MissingResourceException) { return (Logger) cns.newInstance(loggerName, null); } else { throw ite; } } } else { try { return (Logger) cns.newInstance(loggerName, bundleName); } catch (InvocationTargetException ite) { if (ite.getTargetException() instanceof MissingResourceException) { throw (MissingResourceException) ite.getTargetException(); } else { throw ite; } } } } catch (Exception e) { throw new RuntimeException(e); } } try { logger = Logger.getLogger(loggerName, bundleName); //NOPMD } catch (IllegalArgumentException iae) { //likely a mismatch on the bundle name, just return the default logger = Logger.getLogger(loggerName); //NOPMD } catch (MissingResourceException rex) { logger = Logger.getLogger(loggerName); //NOPMD } finally { b = null; } return logger; } finally { if (n != orig) { setContextClassLoader(orig); } } }
From source file:org.apache.jmeter.util.JMeterUtils.java
/** * Changes the current locale: re-reads resource strings and notifies * listeners.// w ww. jav a2 s.c o m * * @param loc - * new locale */ public static void setLocale(Locale loc) { log.info("Setting Locale to " + loc.toString()); /* * See bug 29920. getBundle() defaults to the property file for the * default Locale before it defaults to the base property file, so we * need to change the default Locale to ensure the base property file is * found. */ Locale def = null; boolean isDefault = false; // Are we the default language? if (loc.getLanguage().equals(ENGLISH_LANGUAGE)) { isDefault = true; def = Locale.getDefault(); // Don't change locale from en_GB to en if (!def.getLanguage().equals(ENGLISH_LANGUAGE)) { Locale.setDefault(Locale.ENGLISH); } else { def = null; // no need to reset Locale } } if (loc.toString().equals("ignoreResources")) { // $NON-NLS-1$ log.warn("Resource bundles will be ignored"); ignoreResorces = true; // Keep existing settings } else { ignoreResorces = false; ResourceBundle resBund = ResourceBundle.getBundle("org.apache.jmeter.resources.messages", loc); // $NON-NLS-1$ resources = resBund; locale = loc; final Locale resBundLocale = resBund.getLocale(); if (isDefault || resBundLocale.equals(loc)) {// language change worked // Check if we at least found the correct language: } else if (resBundLocale.getLanguage().equals(loc.getLanguage())) { log.info("Could not find resources for '" + loc.toString() + "', using '" + resBundLocale.toString() + "'"); } else { log.error("Could not find resources for '" + loc.toString() + "'"); } } notifyLocaleChangeListeners(); /* * Reset Locale if necessary so other locales are properly handled */ if (def != null) { Locale.setDefault(def); } }
From source file:org.apache.myfaces.shared_impl.util.MessageUtils.java
/** * @param bundle ResourceBundle to load localized messages * @param messageId id of message/*w w w. j av a 2 s .c o m*/ * @param params parameters to set at localized message * @return generated FacesMessage */ public static FacesMessage getMessage(ResourceBundle bundle, String messageId, Object params[]) { String summary = null; String detail = null; try { summary = bundle.getString(messageId); } catch (MissingResourceException e) { // NoOp } if (summary == null) { summary = messageId; } summary = substituteParams(bundle.getLocale(), summary, params); try { detail = substituteParams(bundle.getLocale(), bundle.getString(messageId + DETAIL_SUFFIX), params); } catch (MissingResourceException e) { // NoOp } return new FacesMessage(summary, detail); }