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

The following examples show how to use org.apache.commons.lang.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: ConvertAvroSchema.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
    String reason = null;
    if (!value.equals(DEFAULT_LOCALE_VALUE)) {
        try {
            final Locale locale = LocaleUtils.toLocale(value);
            if (locale == null) {
                reason = "null locale returned";
            } else if (!LocaleUtils.isAvailableLocale(locale)) {
                reason = "locale not available";
            }
        } catch (final IllegalArgumentException e) {
            reason = "invalid format for locale";
        }
    }
    return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null).build();
}
 
Example 2
Source File: Platform.java    From zstack with Apache License 2.0 6 votes vote down vote up
private static void initMessageSource() {
    locale = LocaleUtils.toLocale(CoreGlobalProperty.LOCALE);
    logger.debug(String.format("using locale[%s] for i18n logging messages", locale.toString()));

    if (loader == null) {
        throw new CloudRuntimeException("ComponentLoader is null. i18n has not been initialized, you call it too early");
    }

    BeanFactory beanFactory = loader.getSpringIoc();
    if (beanFactory == null) {
        throw new CloudRuntimeException("BeanFactory is null. i18n has not been initialized, you call it too early");
    }

    if (!(beanFactory instanceof MessageSource)) {
        throw new CloudRuntimeException("BeanFactory is not a spring MessageSource. i18n cannot be used");
    }

    messageSource = (MessageSource)beanFactory;
}
 
Example 3
Source File: ConvertAvroSchema.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationResult validate(final String subject, final String value, final ValidationContext context) {
    String reason = null;
    if (!value.equals(DEFAULT_LOCALE_VALUE)) {
        try {
            final Locale locale = LocaleUtils.toLocale(value);
            if (locale == null) {
                reason = "null locale returned";
            } else if (!LocaleUtils.isAvailableLocale(locale)) {
                reason = "locale not available";
            }
        } catch (final IllegalArgumentException e) {
            reason = "invalid format for locale";
        }
    }
    return new ValidationResult.Builder().subject(subject).input(value).explanation(reason).valid(reason == null).build();
}
 
Example 4
Source File: InitMojo.java    From opoopress with Apache License 2.0 6 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (skipInit) {
        getLog().info("Skiping initialize site.");
        return;
    }

    Locale loc = null;
    if (StringUtils.isNotEmpty(locale)) {
        loc = LocaleUtils.toLocale(locale);
    }

    try {
        siteManager.initialize(baseDirectory, loc);
    } catch (Exception e) {
        throw new MojoFailureException(e.getMessage(), e);
    }
}
 
Example 5
Source File: ThemeMojo.java    From opoopress with Apache License 2.0 6 votes vote down vote up
private void updateThemeConfigurationFile(SiteConfigImpl siteConfig, File themeDir) throws MojoFailureException{
    File config = new File(themeDir, "theme.yml");
    if (!config.exists()) {
        throw new MojoFailureException("Config file '" + config + "' not exists.");
    }

    Locale loc = Locale.getDefault();
    //locale from parameter
    String localeString = locale;
    //locale from site configuration
    if(StringUtils.isBlank(localeString)){
        localeString = siteConfig.get("locale");
    }
    if (StringUtils.isNotEmpty(localeString)) {
        loc = LocaleUtils.toLocale(localeString);
    }

    File localeConfig = new File(themeDir, "theme_" + loc.toString() + ".yml");
    if (localeConfig.exists()) {
        config.renameTo(new File(themeDir, "theme-original.yml"));
        localeConfig.renameTo(config);
    }
}
 
Example 6
Source File: ThymeleafTemplateEngine.java    From jbake with MIT License 6 votes vote down vote up
@Override
public void renderDocument(Map<String, Object> model, String templateName, Writer writer) throws RenderingException {

    String localeString = config.getThymeleafLocale();
    Locale locale = localeString != null ? LocaleUtils.toLocale(localeString) : Locale.getDefault();


    lock.lock();
    try {
        initializeContext(locale,model);
        updateTemplateMode(model);
        templateEngine.process(templateName, context, writer);
    } finally {
        lock.unlock();
    }
}
 
Example 7
Source File: I18NWebEventHandler.java    From ymate-platform-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Locale onLocale() {
    String _langStr = null;
    // 先尝试取URL参数变量
    if (WebContext.getContext() != null) {
        IWebMvc _owner = WebContext.getContext().getOwner();
        String _i18nLangKey = _owner.getModuleCfg().getI18nLanguageParamName();
        _langStr = WebContext.getRequestContext().getAttribute(_i18nLangKey);
        if (StringUtils.trimToNull(_langStr) == null) {
            // 再尝试从请求参数中获取
            _langStr = WebContext.getRequest().getParameter(_i18nLangKey);
            if (StringUtils.trimToNull(_langStr) == null) {
                // 最后一次机会,尝试读取Cookies
                _langStr = CookieHelper.bind(_owner).getCookie(_i18nLangKey).toStringValue();
            }
        }
    }
    Locale _locale = null;
    try {
        _locale = LocaleUtils.toLocale(StringUtils.trimToNull(_langStr));
    } catch (IllegalArgumentException e) {
        if (WebContext.getContext() != null) {
            _locale = WebContext.getContext().getLocale();
        }
    }
    return _locale;
}
 
Example 8
Source File: LocaleUtil.java    From jeeshop with Apache License 2.0 5 votes vote down vote up
public static String getLocaleCode(String localeStr) {
    Locale locale = FALLBACK;
    try {
        locale = (localeStr != null)? LocaleUtils.toLocale(localeStr):FALLBACK;
    } catch (IllegalArgumentException e) {
        logger.warn("cannot get locale from {}. Returning fallback locale: "+FALLBACK,localeStr);
    }
    return locale.toString();
}
 
Example 9
Source File: SiteImpl.java    From opoopress with Apache License 2.0 5 votes vote down vote up
void setup() {
    //ensure source not in destination
    for (File source : sources) {
        source = PathUtils.canonical(source);
        if (dest.equals(source) || source.getAbsolutePath().startsWith(dest.getAbsolutePath())) {
            throw new IllegalArgumentException("Destination directory cannot be or contain the Source directory.");
        }
    }

    //locale
    String localeString = config.get("locale");
    if (localeString != null) {
        locale = LocaleUtils.toLocale(localeString);
        log.debug("Set locale: " + locale);
    }

    //date_format
    dateFormatPattern = config.get("date_format");
    if (dateFormatPattern == null) {
        dateFormatPattern = "yyyy-MM-dd";
    } else if ("ordinal".equals(dateFormatPattern)) {
        dateFormatPattern = "MMM d yyyy";
    }

    //object instances
    classLoader = createClassLoader(config, theme);
    taskExecutor = new TaskExecutor(config);
    factory = FactoryImpl.createInstance(this);

    processors = new ProcessorsProcessor(factory.getPluginManager().getProcessors());

    //Construct RendererImpl after initializing all plugins
    renderer = factory.getRenderer();

    processors.postSetup(this);
}
 
Example 10
Source File: TestAvroRecordConverter.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the case where we don't use a mapping file and just map records by
 * name.
 */
@Test
public void testDefaultConversion() throws Exception {
    // We will convert s1 from string to long (or leave it null), ignore s2,
    // convert s3 to from string to double, convert l1 from long to string,
    // and leave l2 the same.
    Schema input = SchemaBuilder.record("Input")
            .namespace("com.cloudera.edh").fields()
            .nullableString("s1", "").requiredString("s2")
            .requiredString("s3").optionalLong("l1").requiredLong("l2")
            .endRecord();
    Schema output = SchemaBuilder.record("Output")
            .namespace("com.cloudera.edh").fields().optionalLong("s1")
            .optionalString("l1").requiredLong("l2").requiredDouble("s3")
            .endRecord();

    AvroRecordConverter converter = new AvroRecordConverter(input, output,
            EMPTY_MAPPING, LocaleUtils.toLocale("en_US"));

    Record inputRecord = new Record(input);
    inputRecord.put("s1", null);
    inputRecord.put("s2", "blah");
    inputRecord.put("s3", "5.5");
    inputRecord.put("l1", null);
    inputRecord.put("l2", 5L);
    Record outputRecord = converter.convert(inputRecord);
    assertNull(outputRecord.get("s1"));
    assertNull(outputRecord.get("l1"));
    assertEquals(5L, outputRecord.get("l2"));
    assertEquals(5.5, outputRecord.get("s3"));

    inputRecord.put("s1", "500");
    inputRecord.put("s2", "blah");
    inputRecord.put("s3", "5.5e-5");
    inputRecord.put("l1", 100L);
    inputRecord.put("l2", 2L);
    outputRecord = converter.convert(inputRecord);
    assertEquals(500L, outputRecord.get("s1"));
    assertEquals("100", outputRecord.get("l1"));
    assertEquals(2L, outputRecord.get("l2"));
    assertEquals(5.5e-5, outputRecord.get("s3"));
}
 
Example 11
Source File: DataTypeMismatchHighlightingTask.java    From nb-springboot with Apache License 2.0 4 votes vote down vote up
private boolean checkType(String type, String text, ClassLoader cl) throws IllegalArgumentException {
    Class<?> clazz = ClassUtils.resolveClassName(type, cl);
    if (clazz != null) {
        try {
            parser.parseType(text, clazz);
        } catch (Exception e1) {
            if (clazz.isEnum()) {
                // generate and try relaxed variants of value
                for (String relaxedName : new RelaxedNames(text)) {
                    try {
                        parser.parseType(relaxedName, clazz);
                        return true;
                    } catch (Exception e2) {
                        // try another variant
                    }
                    if (canceled) {
                        break;
                    }
                }
                return false;
            } else {
                try {
                    // handle a few specific cases where no direct constructor from string or converter exist
                    switch (type) {
                        case "java.nio.file.Path":
                            Paths.get(text);
                            return true;
                        case "java.util.Locale":
                            LocaleUtils.toLocale(text);
                            return true;
                        case "java.time.Duration":
                            DurationStyle.detectAndParse(text);
                            return true;
                        case "org.springframework.util.unit.DataSize":
                            DataSize.parse(text);
                            return true;
                        case "java.lang.Class":
                            cl.loadClass(text);
                            return true;
                        default:
                            return false;
                    }
                } catch (Exception e3) {
                    return false;
                }
            }
        }
    }
    // unresolvable/unknown class, assume user knows what is doing
    return true;
}
 
Example 12
Source File: TestAvroRecordConverter.java    From nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Tests the case where we don't use a mapping file and just map records by
 * name.
 */
@Test
public void testDefaultConversion() throws Exception {
    // We will convert s1 from string to long (or leave it null), ignore s2,
    // convert s3 to from string to double, convert l1 from long to string,
    // and leave l2 the same.
    Schema input = SchemaBuilder.record("Input")
            .namespace("com.cloudera.edh").fields()
            .nullableString("s1", "").requiredString("s2")
            .requiredString("s3").optionalLong("l1").requiredLong("l2")
            .endRecord();
    Schema output = SchemaBuilder.record("Output")
            .namespace("com.cloudera.edh").fields().optionalLong("s1")
            .optionalString("l1").requiredLong("l2").requiredDouble("s3")
            .endRecord();

    AvroRecordConverter converter = new AvroRecordConverter(input, output,
            EMPTY_MAPPING, LocaleUtils.toLocale("en_US"));

    Record inputRecord = new Record(input);
    inputRecord.put("s1", null);
    inputRecord.put("s2", "blah");
    inputRecord.put("s3", "5.5");
    inputRecord.put("l1", null);
    inputRecord.put("l2", 5L);
    Record outputRecord = converter.convert(inputRecord);
    assertNull(outputRecord.get("s1"));
    assertNull(outputRecord.get("l1"));
    assertEquals(5L, outputRecord.get("l2"));
    assertEquals(5.5, outputRecord.get("s3"));

    inputRecord.put("s1", "500");
    inputRecord.put("s2", "blah");
    inputRecord.put("s3", "5.5e-5");
    inputRecord.put("l1", 100L);
    inputRecord.put("l2", 2L);
    outputRecord = converter.convert(inputRecord);
    assertEquals(500L, outputRecord.get("s1"));
    assertEquals("100", outputRecord.get("l1"));
    assertEquals(2L, outputRecord.get("l2"));
    assertEquals(5.5e-5, outputRecord.get("s3"));
}
 
Example 13
Source File: TestEnvironment.java    From senbot with MIT License 3 votes vote down vote up
/**
 * Constructor
 * 
 * @param aBrowser
 *            The browser name
 * @param aBrowserVersion
 *            The browserVersion, i.e. the name of the configuration of the
 *            Selenium Node
 * @param aOS
 *            The operating system
 * @param locale
 *            Optionally the locale the browser should be using
 */
public TestEnvironment(String aBrowser, String aBrowserVersion, Platform aOS, String locale) {
	
	log.debug("TestEnvironment initiated with: browser: " + aBrowser + ", browserVersion: " + aBrowserVersion + ", OS: " + aOS + ", locale: " + locale);
	
	browser = aBrowser;
	browserVersion = aBrowserVersion;
	os = aOS;
	this.locale = StringUtils.isBlank(locale) ? null : LocaleUtils.toLocale(locale) ;
	
	threadedWebDriver = new WebDriverThreadLocale(this);
}