Java Code Examples for org.apache.commons.lang3.LocaleUtils#toLocale()

The following examples show how to use org.apache.commons.lang3.LocaleUtils#toLocale() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FastDateParserTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testJpLocales() {

    final Calendar cal= Calendar.getInstance(GMT);
    cal.clear();
    cal.set(2003, Calendar.FEBRUARY, 10);
    cal.set(Calendar.ERA, GregorianCalendar.BC);

    final Locale locale = LocaleUtils.toLocale("zh"); {
        // ja_JP_JP cannot handle dates before 1868 properly

        final SimpleDateFormat sdf = new SimpleDateFormat(LONG_FORMAT, locale);
        final DateParser fdf = getInstance(LONG_FORMAT, locale);

        try {
            checkParse(locale, cal, sdf, fdf);
        } catch(final ParseException ex) {
            Assert.fail("Locale "+locale+ " failed with "+LONG_FORMAT+"\n" + trimMessage(ex.toString()));
        }
    }
}
 
Example 2
Source File: TestSettingManager.java    From line-sdk-android with Apache License 2.0 6 votes vote down vote up
@NonNull
public static TestSetting getSetting(@NonNull Context context, int id) {
    SharedPreferences sharedPreferences =
            context.getSharedPreferences(SHARED_PREFERENCE_KEY, Context.MODE_PRIVATE);
    String channelId = sharedPreferences.getString(DATA_KEY_PREFIX_CHANNEL_ID + id, "");
    if (TextUtils.isEmpty(channelId)) {
        return DEFAULT_SETTING;
    }

    Locale uiLocale;
    try {
        String localeStr = sharedPreferences.getString(DATA_KEY_PREFIX_UI_LOCALE + id, null);
        uiLocale = LocaleUtils.toLocale(localeStr);
    } catch (Exception e) {
        uiLocale = null;
    }

    return new TestSetting(channelId, uiLocale);
}
 
Example 3
Source File: ConfigAwareCookieLocaleResolver.java    From engine with GNU General Public License v3.0 6 votes vote down vote up
protected Locale getDefaultLocaleFromConfig() {
    Configuration config = ConfigUtils.getCurrentConfig();
    if (config != null) {
        Locale defaultLocale = LocaleUtils.toLocale(config.getString(DEFAULT_LOCALE_CONFIG_KEY));
        if (defaultLocale != null && !LocaleUtils.isAvailableLocale(defaultLocale)) {
            if (logger.isDebugEnabled()) {
                logger.debug(defaultLocale + " is not one of the available locales");
            }

            return null;
        }

        return defaultLocale;
    } else {
        return null;
    }
}
 
Example 4
Source File: LegacyMoneyFormatter.java    From template-compiler with Apache License 2.0 6 votes vote down vote up
@Override
public void validateArgs(Arguments args) throws ArgumentsException {
  args.atMost(1);

  String localeStr = getLocaleArg(args);
  if (localeStr != null) {
    Locale locale;
    try {
      // LocaleUtils uses an underscore format (e.g. en_US), but the new Java standard
      // is a hyphenated format (e.g. en-US). This allows us to use LocaleUtils' validation.
      locale = LocaleUtils.toLocale(localeStr.replace('-', '_'));
    } catch (IllegalArgumentException e) {
      throw new ArgumentsException("Invalid locale: " + localeStr);
    }

    args.setOpaque(locale);
  } else {
    args.setOpaque(DEFAULT_LOCALE);
  }
}
 
Example 5
Source File: MTGControler.java    From MtgDesktopCompanion with GNU General Public License v3.0 5 votes vote down vote up
public Locale getLocale() {
	try {
		return LocaleUtils.toLocale(config.getString("locale"));
	} catch (Exception e) {
		logger.error("Could not load " + config.getString("locale"));
		return langService.getDefault();
	}
}
 
Example 6
Source File: Utils.java    From TNT4J with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a {@link Locale} object parsed from provided locale string.
 *
 * @param localeStr
 *            locale string representation
 *
 * @see org.apache.commons.lang3.LocaleUtils#toLocale(String)
 * @return parsed locale object, or {@code null} if can't parse localeStr.
 */
public static Locale getLocale(String localeStr) {
	if (isEmpty(localeStr)) {
		return null;
	}

	// NOTE: adapting to LocaleUtils notation
	String l = localeStr.replace('-', '_');
	return LocaleUtils.toLocale(l);
}
 
Example 7
Source File: JinjavaInterpreterResolver.java    From jinjava with Apache License 2.0 5 votes vote down vote up
private static Locale getLocale(JinjavaInterpreter interpreter, FormattedDate d) {
  if (!StringUtils.isBlank(d.getLanguage())) {
    try {
      return LocaleUtils.toLocale(d.getLanguage());
    } catch (IllegalArgumentException e) {
      interpreter.addError(
        new TemplateError(
          ErrorType.WARNING,
          ErrorReason.SYNTAX_ERROR,
          ErrorItem.OTHER,
          e.getMessage(),
          null,
          interpreter.getLineNumber(),
          -1,
          null,
          BasicTemplateErrorCategory.UNKNOWN_LOCALE,
          ImmutableMap.of(
            "date",
            d.getDate().toString(),
            "exception",
            e.getMessage(),
            "lineNumber",
            String.valueOf(interpreter.getLineNumber())
          )
        )
      );
    }
  }

  return Locale.US;
}
 
Example 8
Source File: Utils.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * @param localeStr locale string
 * @return a {@link Locale} instance from a locale string.
 */
public static Locale getLocale(String localeStr) {
	try {
		return LocaleUtils.toLocale(localeStr);
	} catch (Exception e) {
		return Locale.US;
	}
}
 
Example 9
Source File: LocaleResolver.java    From cuba with Apache License 2.0 5 votes vote down vote up
/**
 * @param localeString the locale String or language tag.
 * @return The locale that best represents the language tag or locale string.
 * @throws NullPointerException if {@code localeString} is {@code null}
 */
public static Locale resolve(String localeString) {
    Locale result;
    if (localeString.contains("-")) {
        result = Locale.forLanguageTag(localeString);
    } else {
        result = LocaleUtils.toLocale(localeString);
    }
    return result;
}
 
Example 10
Source File: ParseNumericFieldUpdateProcessorFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void init(@SuppressWarnings({"rawtypes"})NamedList args) {
  String localeParam = (String)args.remove(LOCALE_PARAM);
  if (null != localeParam) {
    locale = LocaleUtils.toLocale(localeParam);
  }
  super.init(args);
}
 
Example 11
Source File: ParseDateFieldUpdateProcessorFactory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
public void init(@SuppressWarnings({"rawtypes"})NamedList args) {
  
  Locale locale;
  String localeParam = (String)args.remove(LOCALE_PARAM);
  if (null != localeParam) {
    locale = LocaleUtils.toLocale(localeParam);
  } else {
    locale = Locale.US; // because well-known patterns assume this
  }

  Object defaultTimeZoneParam = args.remove(DEFAULT_TIME_ZONE_PARAM);
  ZoneId defaultTimeZone = ZoneOffset.UTC;
  if (null != defaultTimeZoneParam) {
    defaultTimeZone = ZoneId.of(defaultTimeZoneParam.toString());
  }

  @SuppressWarnings({"unchecked"})
  Collection<String> formatsParam = args.removeConfigArgs(FORMATS_PARAM);
  if (null != formatsParam) {
    for (String value : formatsParam) {
      DateTimeFormatter formatter = new DateTimeFormatterBuilder().parseLenient().parseCaseInsensitive()
          .appendPattern(value).toFormatter(locale)
          .withResolverStyle(ResolverStyle.LENIENT).withZone(defaultTimeZone);
      validateFormatter(formatter);
      formats.put(value, formatter);
    }
  }
  super.init(args);
}
 
Example 12
Source File: InitializerMessageSource.java    From openmrs-module-initializer with MIT License 5 votes vote down vote up
/**
 * Infers the locale from a message properties file base name.
 * 
 * @param baseName A message properties file base name, eg. "my_properties_file_en_GB"
 * @return The locale, eg. "en_GB"
 * @throws IllegalArgumentException when no locale could be inferred
 */
public Locale getLocaleFromFileBaseName(String baseName) throws IllegalArgumentException {
	String[] parts = baseName.split("_");
	
	if (parts.length == 1) {
		throw new IllegalArgumentException(
		        "'" + baseName + "' is not suffixed with the string representation of a locale.");
	}
	
	String candidate = "";
	for (int i = parts.length - 1; i > 0; i--) {
		
		candidate = parts[i] + (candidate == "" ? "" : "_") + candidate;
		Locale locale;
		try {
			locale = LocaleUtils.toLocale(candidate);
		}
		catch (IllegalArgumentException e) {
			continue;
		}
		
		return locale;
	}
	
	throw new IllegalArgumentException(
	        "No valid locale could be inferred from the following file base name: '" + baseName + "'.");
}
 
Example 13
Source File: LocalizedHeader.java    From openmrs-module-initializer with MIT License 5 votes vote down vote up
/**
 * From a set of i18n headers, such as 'Name:en', 'Name:km_KH', 'Description:en',
 * 'Description:km_KH' it returns a map with the localized name as keys, so here: 'Name' and
 * 'Description' and {@link LocalizedHeader} instances as values. Each {@link LocalizedHeader}
 * carries the link between a localized name and the possible locales that where found for that
 * name.
 * 
 * @param headerLine
 */
public static Map<String, LocalizedHeader> getLocalizedHeadersMap(String[] headerLine) {
	
	Map<String, LocalizedHeader> l10nHeaderMap = new HashMap<String, LocalizedHeader>();
	
	for (String i18nHeader : headerLine) {
		if (i18nHeader.startsWith(BaseLineProcessor.METADATA_PREFIX)) {
			continue;
		}
		
		String[] parts = StringUtils.split(i18nHeader, LOCALE_SEPARATOR);
		if (parts.length == 2) {
			String header = parts[0].trim().toLowerCase();
			if (!l10nHeaderMap.containsKey(header)) {
				l10nHeaderMap.put(header, new LocalizedHeader(header));
			}
			LocalizedHeader l10nHeader = l10nHeaderMap.get(header);
			Locale locale = LocaleUtils.toLocale(parts[1]);
			if (l10nHeader.getLocales().contains(locale)) {
				throw new IllegalArgumentException(
				        "The CSV header line cannot contains twice the same header: '" + i18nHeader + "'");
			}
			l10nHeader.getLocales().add(locale);
			
		}
	}
	return l10nHeaderMap;
}
 
Example 14
Source File: MenuFragment.java    From line-sdk-android with Apache License 2.0 5 votes vote down vote up
@Nullable
private Locale getSelectedUILocale() {
    final String uiLocale = (String) uiLocaleSpinner.getSelectedItem();
    if (StringUtils.equals(uiLocale, LOCALE_USE_DEFAULT)) {
        // use default locale
        return null;
    } else {
        return LocaleUtils.toLocale(uiLocale);
    }
}
 
Example 15
Source File: StringToLocaleConverter.java    From vividus with Apache License 2.0 4 votes vote down vote up
@Override
public Locale convert(String source)
{
    return LocaleUtils.toLocale(source);
}
 
Example 16
Source File: EmailTemplateLocator.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public String saveAll() {
 log.debug("Saving all!");
 for (Iterator<String> it = delivered.keySet().iterator(); it.hasNext();) {
      String key = it.next();
      log.debug("got key: " + key);
      
      EmailTemplate emailTemplate = (EmailTemplate) delivered.get(key);

      if (StringUtils.isBlank(emailTemplate.getLocale())) {
     	 emailTemplate.setLocale(EmailTemplate.DEFAULT_LOCALE);
      }

      // check to see if this template already exists
      Locale loc = null;
      if (!StringUtils.equals(emailTemplate.getLocale(), EmailTemplate.DEFAULT_LOCALE)) {
          try {
                  loc = LocaleUtils.toLocale(emailTemplate.getLocale());
          }
          catch (IllegalArgumentException ie) {
     	         messages.addMessage(new TargettedMessage("error.invalidlocale", new Object[]{}, TargettedMessage.SEVERITY_ERROR));
          }
      }

      //key can't be null
      if (StringUtils.isBlank(emailTemplate.getKey())) {
     	 messages.addMessage(new TargettedMessage("error.nokey", new Object[]{}, TargettedMessage.SEVERITY_ERROR));
      }
      else if (StringUtils.startsWith(key, NEW_PREFIX) && emailTemplateService.templateExists(emailTemplate.getKey(), loc)) {
          messages.addMessage(new TargettedMessage("error.duplicatekey", new Object[]{}, TargettedMessage.SEVERITY_ERROR));
      }
      
      if (StringUtils.isBlank(emailTemplate.getSubject())) {
     	 messages.addMessage(new TargettedMessage("error.nosubject", new Object[]{}, TargettedMessage.SEVERITY_ERROR));
      }
      
      if (StringUtils.isBlank(emailTemplate.getMessage())) {
     	 messages.addMessage(new TargettedMessage("error.nomessage", new Object[]{}, TargettedMessage.SEVERITY_ERROR));
      }
      
      if (messages.isError()) {
     	 return "failure";
      }
      
      emailTemplateService.saveTemplate(emailTemplate);
      messages.addMessage( new TargettedMessage("template.saved.message",
            new Object[] { emailTemplate.getKey(), emailTemplate.getLocale() }, 
            TargettedMessage.SEVERITY_INFO));
   }
 return "success";
}
 
Example 17
Source File: ConvertUtil.java    From feilong-core with Apache License 2.0 4 votes vote down vote up
/**
 * 将对象转成 {@link Locale}.
 * 
 * <h3>示例:</h3>
 * 
 * <blockquote>
 * 
 * <pre class="code">
 * ConvertUtil.toLocale(null)       = null
 * ConvertUtil.toLocale("zh_CN")    = Locale.CHINA
 * </pre>
 * 
 * </blockquote>
 *
 * @param locale
 *            可以是 <b>null</b> ,<b>字符串</b> 或者 直接的 {@link Locale}对象
 * @return 如果 <code>locale</code> 是null,返回 null<br>
 *         如果 <code>locale instanceof <span style="color:green">Locale</span></code>,返回 <code>(Locale) locale</code><br>
 *         如果 <code>locale instanceof <span style="color:green">String</span></code>,返回 {@link LocaleUtils#toLocale(String)}<br>
 *         其他的类型,将抛出 {@link UnsupportedOperationException}
 * @see org.apache.commons.lang3.LocaleUtils#toLocale(String)
 * @since 1.7.2
 */
public static Locale toLocale(Object locale){
    if (null == locale){
        return null;
    }

    //---------------------------------------------------------------
    if (locale instanceof Locale){
        return (Locale) locale;
    }
    if (locale instanceof String){
        return LocaleUtils.toLocale((String) locale);
    }

    //---------------------------------------------------------------
    throw new UnsupportedOperationException("input param [locale] type is:[" + locale.getClass().getName() + "] not support!");
}
 
Example 18
Source File: EmailTemplateLocator.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
public String saveAll() {
 log.debug("Saving all!");
 for (Iterator<String> it = delivered.keySet().iterator(); it.hasNext();) {
      String key = it.next();
      log.debug("got key: " + key);
      
      EmailTemplate emailTemplate = (EmailTemplate) delivered.get(key);

      if (StringUtils.isBlank(emailTemplate.getLocale())) {
     	 emailTemplate.setLocale(EmailTemplate.DEFAULT_LOCALE);
      }

      // check to see if this template already exists
      Locale loc = null;
      if (!StringUtils.equals(emailTemplate.getLocale(), EmailTemplate.DEFAULT_LOCALE)) {
          try {
                  loc = LocaleUtils.toLocale(emailTemplate.getLocale());
          }
          catch (IllegalArgumentException ie) {
     	         messages.addMessage(new TargettedMessage("error.invalidlocale", new Object[]{}, TargettedMessage.SEVERITY_ERROR));
          }
      }

      //key can't be null
      if (StringUtils.isBlank(emailTemplate.getKey())) {
     	 messages.addMessage(new TargettedMessage("error.nokey", new Object[]{}, TargettedMessage.SEVERITY_ERROR));
      }
      else if (StringUtils.startsWith(key, NEW_PREFIX) && emailTemplateService.templateExists(emailTemplate.getKey(), loc)) {
          messages.addMessage(new TargettedMessage("error.duplicatekey", new Object[]{}, TargettedMessage.SEVERITY_ERROR));
      }
      
      if (StringUtils.isBlank(emailTemplate.getSubject())) {
     	 messages.addMessage(new TargettedMessage("error.nosubject", new Object[]{}, TargettedMessage.SEVERITY_ERROR));
      }
      
      if (StringUtils.isBlank(emailTemplate.getMessage())) {
     	 messages.addMessage(new TargettedMessage("error.nomessage", new Object[]{}, TargettedMessage.SEVERITY_ERROR));
      }
      
      if (messages.isError()) {
     	 return "failure";
      }
      
      emailTemplateService.saveTemplate(emailTemplate);
      messages.addMessage( new TargettedMessage("template.saved.message",
            new Object[] { emailTemplate.getKey(), emailTemplate.getLocale() }, 
            TargettedMessage.SEVERITY_INFO));
   }
 return "success";
}