下面列出了怎么用org.apache.commons.lang3.LocaleUtils的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
@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);
}
}
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
BeanDefinitionRegistry registry) {
if (registry instanceof BeanFactory) {
final Environment environment = ((BeanFactory) registry).getBean(Environment.class);
final String defaultLocale = environment.getProperty("dataprep.locale", "en-US");
Locale locale = new Locale.Builder().setLanguageTag(defaultLocale).build();
if (LocaleUtils.isAvailableLocale(locale)) {
LOGGER.debug("Setting default JVM locale to configured {}", locale);
} else {
LOGGER.debug("Configured JVM Locale {} is not available. Defaulting to {}", locale, Locale.US);
locale = Locale.US;
}
Locale.setDefault(locale);
LOGGER.info("JVM Default locale set to: '{}'", locale);
} else {
LOGGER.warn("Unable to set default locale (unexpected bean registry of type '{}')",
registry.getClass().getName());
}
}
@Override
public List<String> getAvailableTargetIds() {
String[] availableTargetIds = SiteProperties.getAvailableTargetIds();
if (ArrayUtils.isEmpty(availableTargetIds)) {
List<Locale> availableLocales = LocaleUtils.availableLocaleList();
List<String> availableLocaleStrs = new ArrayList<>(availableLocales.size());
for (Locale locale : availableLocales) {
String localeStr = locale.toString();
// Ignore empty ROOT locale
if (StringUtils.isNotEmpty(localeStr)) {
availableLocaleStrs.add(StringUtils.lowerCase(localeStr));
}
}
return availableLocaleStrs;
} else {
return Arrays.asList(availableTargetIds);
}
}
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;
}
}
@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()));
}
}
}
@Test
void testExecuteWithNonDefaultLocale()
{
mockGetCurrentDate();
dateExpressionProcessor.setLocale(LocaleUtils.toLocale("be_BY"));
String actual = dateExpressionProcessor.execute("P4D(d MMMM EEEE)").get();
assertEquals("5 студзеня пятніца", actual);
}
public static Friend readFriend(ByteBuf byteBuf) {
String username = readString(byteBuf);
UUID uuid = readUUID(byteBuf);
String status = readString(byteBuf);
int onlineOrdinal = readVarIntFromBuffer(byteBuf);
if (onlineOrdinal < 0 || onlineOrdinal >= Friend.OnlineStatus.values().length)
throw new IllegalArgumentException("Received Integer is out of enum range.");
Friend.OnlineStatus online = Friend.OnlineStatus.values()[onlineOrdinal];
long lastOnline = 0;
if (online == Friend.OnlineStatus.OFFLINE) {
lastOnline = byteBuf.readLong();
}
Rank rank = readRank(byteBuf);
long firstOnline = byteBuf.readLong();
boolean favorite = byteBuf.readBoolean();
String modVersion = readString(byteBuf);
String locale = readString(byteBuf);
Friend friend = new Friend(username, uuid);
friend.setStatusMessage(status);
friend.setStatus(online);
if (online == Friend.OnlineStatus.OFFLINE) {
friend.setLastOnline(lastOnline);
}
friend.setRank(rank);
friend.setFirstOnline(firstOnline);
friend.setModVersion(modVersion);
friend.setLocale(locale.isEmpty() ? null : LocaleUtils.toLocale(locale));
friend.setFavorite(favorite);
return friend;
}
@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);
}
}
/**
* 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;
}
/**
* 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 + "'.");
}
public BundleRegexLocale() {
final List<String> languages = PreferencesFactory.get().getList("AppleLanguages");
if(!languages.isEmpty()) {
try {
fallback.setDefault(
LocaleUtils.toLocale(StringUtils.replace(languages.iterator().next(), "-", "_")).getLanguage());
}
catch(IllegalArgumentException e) {
log.warn(String.format("Failure to parse default language set. %s", e.getMessage()));
}
}
}
@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);
}
@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);
}
/**
* @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;
}
@Test
public void testScriptAndVariant() throws Exception {
Messages messages = AppBeans.get(Messages.class);
Map<String, Locale> availableLocales = AppBeans.get(Configuration.class).getConfig(GlobalConfig.class).getAvailableLocales();
assertTrue(availableLocales.containsValue(LocaleUtils.toLocale("sr")));
assertTrue(availableLocales.containsValue(Locale.forLanguageTag("sr-Latn")));
assertTrue(availableLocales.containsValue(LocaleUtils.toLocale("ja")));
assertTrue(availableLocales.containsValue(LocaleUtils.toLocale("ja_JP_JP")));
assertEquals(LocaleResolver.resolve("sr-Latn"), Locale.forLanguageTag("sr-Latn"));
assertEquals(LocaleResolver.resolve("ja_JP_JP"), LocaleUtils.toLocale("ja_JP_JP"));
boolean localeLanguageOnly = messages.getTools().useLocaleLanguageOnly();
assertFalse(localeLanguageOnly);
String msg;
msg = messages.getMessage("com.haulmont.cuba.core.mp_test", "fullMsg", Locale.forLanguageTag("sr-Latn"));
assertEquals("Full Message sr-Latn", msg);
msg = messages.getMessage("com.haulmont.cuba.core.mp_test", "languageMsg", LocaleUtils.toLocale("sr"));
assertEquals("Language Message sr", msg);
msg = messages.getMessage("com.haulmont.cuba.core.mp_test", "languageMsg", Locale.forLanguageTag("sr-Latn"));
assertEquals("Language Message sr", msg);
msg = messages.getMessage("com.haulmont.cuba.core.mp_test", "fullMsg", LocaleUtils.toLocale("ja_JP_JP"));
assertEquals("Full Message ja_JP_JP", msg);
msg = messages.getMessage("com.haulmont.cuba.core.mp_test", "languageMsg", LocaleUtils.toLocale("ja"));
assertEquals("Language Message ja", msg);
msg = messages.getMessage("com.haulmont.cuba.core.mp_test", "languageMsg", LocaleUtils.toLocale("ja_JP_JP"));
assertEquals("Language Message ja", msg);
}
public Locale getLocale() {
try {
return LocaleUtils.toLocale(config.getString("locale"));
} catch (Exception e) {
logger.error("Could not load " + config.getString("locale"));
return langService.getDefault();
}
}
/**
* @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;
}
}
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;
}
/**
* 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);
}
/**
* Tries to get the name for the country
*
* @param code language code, for example en
* @return the country name or the code
*/
public static String getCountryName(@NonNull String code) {
try {
return LocaleUtils.toLocale("en_" + code.toUpperCase(Locale.ENGLISH)).getDisplayCountry();
} catch (IllegalArgumentException ex) {
if (DEBUG) {
Log.i(TAG, "couldn't resolve " + code, ex);
}
return code;
}
}
@Override
public OptionalThing<Locale> findBusinessLocale(final ActionRuntime runtimeMeta, final RequestManager requestManager) {
final FessConfig fessConfig = ComponentUtil.getFessConfig();
final String name = fessConfig.getQueryBrowserLangParameterName();
if (StringUtil.isNotBlank(name)) {
try {
return requestManager.getParameter(name).filter(StringUtil::isNotBlank).map(LocaleUtils::toLocale);
} catch (final Exception e) {
logger.debug("Failed to parse a value of {}.", name, e);
}
}
return OptionalObject.empty();
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
storeAdapter = new TargetedContentStoreAdapterDecorator();
storeAdapter.setActualStoreAdapter(createActualStoreAdapter());
storeAdapter.setCandidateTargetedUrlsResolver(createCandidateTargetedUrlsResolver());
LocaleContextHolder.setLocale(LocaleUtils.toLocale("en"));
}
@Override
public Locale convert(String source)
{
return LocaleUtils.toLocale(source);
}
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";
}
/**
* 将对象转成 {@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!");
}
@Override
public Object toObjectValue(final ValueMapping vm, final Object val) {
return Optional.ofNullable(val).map(o -> LocaleUtils.toLocale((String) o)).orElse(null);
}
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";
}
@PostConstruct
public void init() {
if (logger.isDebugEnabled()) {
logger.debug("Initialize {}", this.getClass().getSimpleName());
}
final Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(2021, 12 - 1, 18); // EOL Date
eolTime = cal.getTimeInMillis();
if (isEoled()) {
logger.error("Your system is out of support. See https://fess.codelibs.org/eol.html");
}
updateSystemProperties();
final FessConfig fessConfig = ComponentUtil.getFessConfig();
filterPathEncoding = fessConfig.getPathEncoding();
supportedLanguages = fessConfig.getSupportedLanguagesAsArray();
langItemsCache =
CacheBuilder.newBuilder().maximumSize(20).expireAfterAccess(1, TimeUnit.HOURS)
.build(new CacheLoader<String, List<Map<String, String>>>() {
@Override
public List<Map<String, String>> load(final String key) throws Exception {
final ULocale uLocale = new ULocale(key);
final Locale displayLocale = uLocale.toLocale();
final List<Map<String, String>> langItems = new ArrayList<>(supportedLanguages.length);
final String msg = ComponentUtil.getMessageManager().getMessage(displayLocale, "labels.allLanguages");
final Map<String, String> defaultMap = new HashMap<>(2);
defaultMap.put(Constants.ITEM_LABEL, msg);
defaultMap.put(Constants.ITEM_VALUE, "all");
langItems.add(defaultMap);
for (final String lang : supportedLanguages) {
final Locale locale = LocaleUtils.toLocale(lang);
final String label = locale.getDisplayName(displayLocale);
final Map<String, String> map = new HashMap<>(2);
map.put(Constants.ITEM_LABEL, label);
map.put(Constants.ITEM_VALUE, lang);
langItems.add(map);
}
return langItems;
}
});
ComponentUtil.doInitProcesses(Runnable::run);
parseProjectProperties();
}