org.apache.commons.lang.LocaleUtils Java Examples

The following examples show how to use org.apache.commons.lang.LocaleUtils. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
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 #7
Source File: ComponentUtilTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void testGetResourceBundleUnknown() throws Exception {
	String locale = "xyz";
	String[] defaultLocaleArray = new String[] {"en", "nl"};
	for (String defaultLocale : defaultLocaleArray) {
		Locale.setDefault(LocaleUtils.toLocale(defaultLocale));
		ResourceBundle resourceBundle = ComponentUtil.getCurrentResourceBundle(locale);
		Assert.assertEquals(defaultLocale.toLowerCase(), resourceBundle.getLocale().toString().toLowerCase());
	}
}
 
Example #8
Source File: ComponentUtil.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns the resource bundle for current Locale, i.e. locale set in the PageComponent.
 * Always create a new instance, this avoids getting the incorrect locale information.
 *
 * @return resourcebundle for internationalized messages
 */
public static ResourceBundle getCurrentResourceBundle(String locale) {
	try {
		if (null != locale && !locale.isEmpty()) {
			return getCurrentResourceBundle(LocaleUtils.toLocale(locale));
		}
	} catch (IllegalArgumentException ex) {
		// do nothing
	}
	return getCurrentResourceBundle((Locale) null);
}
 
Example #9
Source File: UserManagementService.java    From abixen-platform with GNU Lesser General Public License v2.1 5 votes vote down vote up
public UserForm createUser(final UserForm userForm) {
    log.debug("createUser() - userForm: {}", userForm);

    final String userPassword = userService.generatePassword();

    //FIXME - move to IpAddressUtil?
    final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

    final User user =  User.builder()
            .credentials(userForm.getUsername(), userPassword)
            .screenName(userForm.getScreenName())
            .personalData(userForm.getFirstName(), userForm.getMiddleName(), userForm.getLastName())
            .additionalData(userForm.getBirthday(), userForm.getJobTitle(), userForm.getSelectedLanguage(), userForm.getGender())
            .registrationIp(IpAddressUtil.getClientIpAddress(request))
            .build();

    final User createdUser = userService.create(user);
    final UserForm createdUserForm = new UserForm(createdUser);

    final Map<String, String> params = new HashMap<>();
    params.put("email", createdUser.getUsername());
    params.put("password", userPassword);
    params.put("firstName", createdUser.getFirstName());
    params.put("lastName", createdUser.getLastName());
    //FIXME - parametrize url
    params.put("accountActivationUrl", "http://localhost:8080/login#/?activation-key=" + createdUser.getHashKey());

    String subject = messageSource.getMessage(
            "email.userAccountActivation.subject",
            null,
            LocaleUtils.toLocale(createdUserForm.getSelectedLanguage().getSelectedLanguage().toLowerCase()));

    mailService.sendMail(
            createdUser.getUsername(),
            params,
            MailService.USER_ACCOUNT_ACTIVATION_MAIL + "_" + createdUserForm.getSelectedLanguage().getSelectedLanguage().toLowerCase(),
            subject);

    return createdUserForm;
}
 
Example #10
Source File: UserManagementService.java    From abixen-platform with GNU Lesser General Public License v2.1 5 votes vote down vote up
public UserChangePasswordForm changeUserPassword(final UserChangePasswordForm userChangePasswordForm) {
    log.debug("changeUserPassword() - userChangePasswordForm: {}", userChangePasswordForm);

    final User user = userService.find(userChangePasswordForm.getId());

    if (user == null) {
        throw new IllegalArgumentException("User not found");
    }

    user.changePassword(userChangePasswordForm.getCurrentPassword(), userChangePasswordForm.getNewPassword());

    updateUser(user);

    final Map<String, String> params = new HashMap<>();
    params.put("email", user.getUsername());
    params.put("password", userChangePasswordForm.getNewPassword());
    params.put("firstName", user.getFirstName());
    params.put("lastName", user.getLastName());

    final String subject = messageSource.getMessage(
            "email.userPasswordChanged.subject",
            null,
            LocaleUtils.toLocale(user.getSelectedLanguage().getSelectedLanguage().toLowerCase()));

    mailService.sendMail(
            user.getUsername(),
            params,
            MailService.USER_PASSWORD_CHANGE_MAIL + "_" + user.getSelectedLanguage().getSelectedLanguage().toLowerCase(),
            subject);

    //FIXME - make return type void
    return userChangePasswordForm;
}
 
Example #11
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 #12
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 #13
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 #14
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 #15
Source File: TestEnvironmentTest.java    From senbot with MIT License 4 votes vote down vote up
@Test
public void testContructor_locale() {
	TestEnvironment env = new TestEnvironment(null, null, null, "en_US");
	
	assertEquals(LocaleUtils.toLocale("en_US"), env.getLocale());
}
 
Example #16
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 #17
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 #18
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);
}