Java Examples for org.apache.commons.lang3.LocaleUtils

The following java examples will help you to understand the usage of org.apache.commons.lang3.LocaleUtils. These source code samples are taken from different open source projects.

Example 1
Project: jeeshop-master  File: LocaleUtil.java View source code
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 2
Project: muikku-master  File: StudyTimeNotificationStrategy.java View source code
@Override
public void sendNotifications() {
    Collection<Long> groups = getGroups();
    if (groups.isEmpty()) {
        return;
    }
    OffsetDateTime studyTimeEndsOdt = OffsetDateTime.now().plusDays(NOTIFICATION_THRESHOLD_DAYS_LEFT);
    OffsetDateTime sendNotificationIfStudentStartedBefore = OffsetDateTime.now().minusDays(DAYS_UNTIL_FIRST_NOTIFICATION);
    Date studyTimeEnds = Date.from(studyTimeEndsOdt.toInstant());
    Date lastNotifiedThresholdDate = Date.from(OffsetDateTime.now().minusDays(NOTIFICATION_THRESHOLD_DAYS_LEFT + 1).toInstant());
    List<SchoolDataIdentifier> studentIdentifierAlreadyNotified = studyTimeLeftNotificationController.listNotifiedSchoolDataIdentifiersAfter(lastNotifiedThresholdDate);
    SearchResult searchResult = studyTimeLeftNotificationController.searchActiveStudentIds(groups, FIRST_RESULT + offset, MAX_RESULTS, studentIdentifierAlreadyNotified, studyTimeEnds);
    if (searchResult.getFirstResult() + MAX_RESULTS >= searchResult.getTotalHitCount()) {
        offset = 0;
    } else {
        offset += MAX_RESULTS;
    }
    for (SchoolDataIdentifier studentIdentifier : getStudentIdentifiers(searchResult)) {
        UserEntity studentEntity = userEntityController.findUserEntityByUserIdentifier(studentIdentifier);
        if (studentEntity != null) {
            User student = userController.findUserByIdentifier(studentIdentifier);
            if (student.getStudyStartDate() == null || student.getStudyStartDate().isAfter(sendNotificationIfStudentStartedBefore)) {
                continue;
            }
            if (student.getStudyTimeEnd() == null || student.getStudyTimeEnd().isAfter(studyTimeEndsOdt) || student.getStudyTimeEnd().isBefore(OffsetDateTime.now())) {
                continue;
            }
            Locale studentLocale = localeController.resolveLocale(LocaleUtils.toLocale(studentEntity.getLocale()));
            Map<String, Object> templateModel = new HashMap<>();
            templateModel.put("internetixStudent", student.hasEvaluationFees());
            templateModel.put("locale", studentLocale);
            templateModel.put("localeHelper", jadeLocaleHelper);
            String notificationContent = renderNotificationTemplate("study-time-notification", templateModel);
            notificationController.sendNotification(localeController.getText(studentLocale, "plugin.timednotifications.notification.category"), localeController.getText(studentLocale, "plugin.timednotifications.notification.studytime.subject"), notificationContent, studentEntity);
            studyTimeLeftNotificationController.createStudyTimeNotification(studentIdentifier);
        } else {
            logger.log(Level.SEVERE, String.format("Cannot send notification to student with identifier %s because UserEntity was not found", studentIdentifier.toId()));
        }
    }
}
Example 3
Project: oxAuth-master  File: LocaleUtil.java View source code
public static Locale localeMatch(List<String> requestedLocales, List<Locale> availableLocales) {
    if (requestedLocales == null || availableLocales == null) {
        return null;
    }
    for (String requestedLocale : requestedLocales) {
        Locale reqInQuestion = LocaleUtils.toLocale(requestedLocale);
        List<Locale> lookupList = LocaleUtils.localeLookupList(reqInQuestion);
        for (Locale localeInQuestion : lookupList) {
            for (Locale availableLocale : availableLocales) {
                if (localeInQuestion.equals(availableLocale)) {
                    return availableLocale;
                }
            }
        }
        for (Locale availableLocale : availableLocales) {
            if (reqInQuestion.getLanguage().equals(availableLocale.getLanguage())) {
                return availableLocale;
            }
        }
    }
    return null;
}
Example 4
Project: uma-master  File: LocaleUtil.java View source code
public static Locale localeMatch(List<String> requestedLocales, List<Locale> availableLocales) {
    if (requestedLocales == null || availableLocales == null) {
        return null;
    }
    for (String requestedLocale : requestedLocales) {
        Locale reqInQuestion = LocaleUtils.toLocale(requestedLocale);
        List<Locale> lookupList = LocaleUtils.localeLookupList(reqInQuestion);
        for (Locale localeInQuestion : lookupList) {
            for (Locale availableLocale : availableLocales) {
                if (localeInQuestion.equals(availableLocale)) {
                    return availableLocale;
                }
            }
        }
        for (Locale availableLocale : availableLocales) {
            if (reqInQuestion.getLanguage().equals(availableLocale.getLanguage())) {
                return availableLocale;
            }
        }
    }
    return null;
}
Example 5
Project: handlebars.java-master  File: StringHelpers.java View source code
@Override
protected CharSequence safeApply(final Object value, final Options options) {
    isTrue(value instanceof Date, "found '%s', expected 'date'", value);
    Date date = (Date) value;
    final DateFormat dateFormat;
    Object pattern = options.param(0, options.hash("format", "medium"));
    String localeStr = options.param(1, Locale.getDefault().toString());
    Locale locale = LocaleUtils.toLocale(localeStr);
    Integer style = styles.get(pattern);
    if (style == null) {
        dateFormat = new SimpleDateFormat(pattern.toString(), locale);
    } else {
        dateFormat = DateFormat.getDateInstance(style, locale);
    }
    Object tz = options.hash("tz");
    if (tz != null) {
        final TimeZone timeZone = tz instanceof TimeZone ? (TimeZone) tz : TimeZone.getTimeZone(tz.toString());
        dateFormat.setTimeZone(timeZone);
    }
    return dateFormat.format(date);
}
Example 6
Project: mayocat-shop-master  File: LoadedAttachmentMapper.java View source code
@Override
public LoadedAttachment map(int index, ResultSet resultSet, StatementContext ctx) throws SQLException {
    LoadedAttachment attachment = new LoadedAttachment();
    attachment.setId((UUID) resultSet.getObject("id"));
    attachment.setTitle(resultSet.getString("title"));
    attachment.setDescription(resultSet.getString("description"));
    attachment.setSlug(resultSet.getString("slug"));
    attachment.setData(new AttachmentData(resultSet.getBinaryStream("data")));
    attachment.setExtension(resultSet.getString("extension"));
    attachment.setParentId((UUID) resultSet.getObject("parent_id"));
    ObjectMapper mapper = new ObjectMapper();
    if (!Strings.isNullOrEmpty(resultSet.getString("metadata"))) {
        try {
            Map<String, Map<String, Object>> metadata = mapper.readValue(resultSet.getString("metadata"), new TypeReference<Map<String, Map<String, Object>>>() {
            });
            attachment.setMetadata(metadata);
        } catch (IOException e) {
            throw new SQLException("Failed to de-serialize localization JSON data", e);
        }
    }
    if (MapperUtils.hasColumn("localization_data", resultSet) && !Strings.isNullOrEmpty(resultSet.getString("localization_data"))) {
        try {
            Map<Locale, Map<String, Object>> localizedVersions = Maps.newHashMap();
            Map[] data = mapper.readValue(resultSet.getString("localization_data"), Map[].class);
            for (Map map : data) {
                localizedVersions.put(LocaleUtils.toLocale((String) map.get("locale")), (Map) map.get("entity"));
            }
            attachment.setLocalizedVersions(localizedVersions);
        } catch (IOException e) {
            throw new SQLException("Failed to de-serialize localization JSON data", e);
        }
    }
    return attachment;
}
Example 7
Project: OCRaptor-master  File: SettingsManager.java View source code
@Override
public void handle(ActionEvent event) {
    String selectedItem = ((String) dropdown.getSelectionModel().getSelectedItem()).split("-")[0].trim();
    if (stringProperty == ConfigString.DEFAULT_LOCALE) {
        final BidiMap<String, String> langs = cfg.getGUILanguageStrings();
        if (langs.containsValue(selectedItem)) {
            selectedItem = langs.getKey(selectedItem);
            Localization.instance().setLocale(LocaleUtils.toLocale(selectedItem));
        }
    }
    if (configFilePath != null) {
        cfg.setProp(configFilePath, stringProperty, selectedItem);
    } else {
        cfg.setProp(stringProperty, selectedItem);
    }
}
Example 8
Project: opoopress-master  File: SiteImpl.java View source code
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 9
Project: ORCID-Source-master  File: NotificationManagerImpl.java View source code
@Override
public void sendDelegationRequestEmail(String managedOrcid, String trustedOrcid, String link) {
    // Create map of template params        
    Map<String, Object> templateParams = new HashMap<String, Object>();
    templateParams.put("baseUri", orcidUrlManager.getBaseUrl());
    templateParams.put("baseUriHttp", orcidUrlManager.getBaseUriHttp());
    templateParams.put("link", link);
    ProfileEntity managedEntity = profileEntityCacheManager.retrieve(managedOrcid);
    ProfileEntity trustedEntity = profileEntityCacheManager.retrieve(trustedOrcid);
    String emailNameForDelegate = deriveEmailFriendlyName(managedEntity);
    String trustedOrcidName = deriveEmailFriendlyName(trustedEntity);
    templateParams.put("emailNameForDelegate", emailNameForDelegate);
    templateParams.put("trustedOrcidName", trustedOrcidName);
    templateParams.put("trustedOrcidValue", trustedOrcid);
    templateParams.put("managedOrcidValue", managedOrcid);
    String primaryEmail = emailManager.findPrimaryEmail(managedOrcid).getEmail();
    if (primaryEmail == null) {
        LOGGER.info("Cant send admin delegate email if primary email is null: {}", managedOrcid);
        return;
    }
    org.orcid.jaxb.model.common_v2.Locale locale = managedEntity.getLocale();
    Locale userLocale = LocaleUtils.toLocale("en");
    if (locale != null) {
        userLocale = LocaleUtils.toLocale(locale.value());
    }
    addMessageParams(templateParams, userLocale);
    String htmlBody = templateManager.processTemplate("admin_delegate_request_html.ftl", templateParams);
    // Send message
    if (apiRecordCreationEmailEnabled) {
        String subject = messages.getMessage("email.subject.admin_as_delegate", new Object[] { trustedOrcidName }, userLocale);
        boolean notificationsEnabled = trustedEntity != null ? trustedEntity.getEnableNotifications() : false;
        if (notificationsEnabled) {
            NotificationCustom notification = new NotificationCustom();
            notification.setNotificationType(NotificationType.CUSTOM);
            notification.setSubject(subject);
            notification.setBodyHtml(htmlBody);
            createNotification(managedOrcid, notification);
        } else {
            mailGunManager.sendEmail(DELEGATE_NOTIFY_ORCID_ORG, primaryEmail, subject, null, htmlBody);
        }
        profileEventDao.persist(new ProfileEventEntity(managedOrcid, ProfileEventType.ADMIN_PROFILE_DELEGATION_REQUEST));
    } else {
        LOGGER.debug("Not sending admin delegate email, because API record creation email option is disabled. Message would have been: {}", htmlBody);
    }
}
Example 10
Project: ovirt-engine-master  File: LocaleFilter.java View source code
/**
     * Check for locale in 4 steps:
     * <ol>
     *   <li>If no cookies exist, then check for a locale parameter and use that.</li>
     *   <li>Check if the cookie exists which selects the locale.</li>
     *   <li>If no locale parameter exists, check the accept headers.</li>
     *   <li>Default to the US locale</li>
     * </ol>
     * @param request The {@code HttpServletRequest}
     * @return The determined {@code Locale}
     */
private Locale determineLocale(final HttpServletRequest request) {
    // Step 1.
    Locale locale = LocaleUtils.getLocaleFromString(request.getParameter(LOCALE));
    // Step 2.
    if (locale == null) {
        // No locale parameter.
        locale = getLocaleFromCookies(request.getCookies());
    }
    // Step 3.
    if (locale == null) {
        // No selected locale in cookies.
        locale = request.getLocale();
    }
    // Step 4.
    if (locale == null) {
        // No accept headers.
        locale = DEFAULT_LOCALE;
    }
    Locale resolvedLocale = lookupSupportedLocale(locale, getLocaleKeys());
    log.debug("Incoming locale '{}'. Filter determined locale to be '{}'", locale.toLanguageTag(), resolvedLocale.toLanguageTag());
    return resolvedLocale;
}
Example 11
Project: play-authenticate-master  File: AuthUser.java View source code
public static Locale getLocaleFromString(final String locale) {
    if (locale != null && !locale.isEmpty()) {
        try {
            return LocaleUtils.toLocale(locale);
        } catch (final java.lang.IllegalArgumentException iae) {
            try {
                return LocaleUtils.toLocale(locale.replace('-', '_'));
            } catch (final java.lang.IllegalArgumentException iae2) {
                return null;
            }
        }
    } else {
        return null;
    }
}
Example 12
Project: vector_health-master  File: AuthUser.java View source code
public static Locale getLocaleFromString(final String locale) {
    if (locale != null && !locale.isEmpty()) {
        try {
            return LocaleUtils.toLocale(locale);
        } catch (final java.lang.IllegalArgumentException iae) {
            try {
                return LocaleUtils.toLocale(locale.replace('-', '_'));
            } catch (final java.lang.IllegalArgumentException iae2) {
                return null;
            }
        }
    } else {
        return null;
    }
}
Example 13
Project: camus-master  File: TimeBasedPartitioner.java View source code
@Override
public void setConf(Configuration conf) {
    if (conf != null) {
        String destPathTopicSubDirFormat = conf.get(ETL_DESTINATION_PATH_TOPIC_SUBDIRFORMAT, DEFAULT_TOPIC_SUB_DIR_FORMAT);
        long partitionDurationMinutes = Long.parseLong(conf.get(ETL_OUTPUT_FILE_TIME_PARTITION_MINS, DEFAULT_PARTITION_DURATION_MINUTES));
        Locale locale = LocaleUtils.toLocale(conf.get(ETL_DESTINATION_PATH_TOPIC_SUBDIRFORMAT_LOCALE, DEFAULT_LOCALE));
        DateTimeZone outputTimeZone = DateTimeZone.forID(conf.get(ETL_DEFAULT_TIMEZONE, DEFAULT_TIME_ZONE));
        long outfilePartitionMs = TimeUnit.MINUTES.toMillis(partitionDurationMinutes);
        init(outfilePartitionMs, destPathTopicSubDirFormat, locale, outputTimeZone);
    }
    super.setConf(conf);
}
Example 14
Project: fess-master  File: SystemHelper.java View source code
@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;
}
Example 15
Project: nuxeo-master  File: DefaultLocaleProvider.java View source code
@Override
public Locale getLocaleWithDefault(String requestedLocale) {
    Locale res = null;
    LoginScreenConfig screenConfig = LoginScreenHelper.getConfig();
    if (screenConfig != null) {
        List<String> supported = screenConfig.getSupportedLocales();
        if (!StringUtils.isBlank(requestedLocale) && supported.contains(requestedLocale)) {
            res = LocaleUtils.toLocale(requestedLocale);
        } else {
            res = LocaleUtils.toLocale(screenConfig.getDefaultLocale());
        }
    }
    if (res == null) {
        return Locale.getDefault();
    }
    return res;
}
Example 16
Project: struts-master  File: Jsr168Dispatcher.java View source code
protected Locale getLocale(PortletRequest request) {
    String defaultLocale = container.getInstance(String.class, StrutsConstants.STRUTS_LOCALE);
    Locale locale;
    if (defaultLocale != null) {
        try {
            locale = LocaleUtils.toLocale(defaultLocale);
        } catch (IllegalArgumentException e) {
            LOG.warn(new ParameterizedMessage("Cannot convert 'struts.locale' = [{}] to proper locale, defaulting to request locale [{}]", defaultLocale, request.getLocale()), e);
            locale = request.getLocale();
        }
    } else {
        locale = request.getLocale();
    }
    return locale;
}
Example 17
Project: testcube-server-master  File: EnvParameterServiceImpl.java View source code
@Override
public Locale getLocale() {
    Locale locale = null;
    String localeStr = getProperty(EnvParametersKeys.class.getName() + "." + EnvParametersKeys.DEFAULT_LOCALE.name());
    if (StringUtils.isNotEmpty(localeStr)) {
        locale = LocaleUtils.toLocale(localeStr);
    }
    return locale == null ? DEFAULT_LOCALE : locale;
}
Example 18
Project: commons-lang-master  File: FastDateParserTest.java View source code
@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 19
Project: gwt-commons-lang3-master  File: FastDateParserTest.java View source code
@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 20
Project: jbake-master  File: ThymeleafTemplateEngine.java View source code
@Override
public void renderDocument(final Map<String, Object> model, final String templateName, final Writer writer) throws RenderingException {
    String localeString = config.getString(Keys.THYMELEAF_LOCALE);
    Locale locale = localeString != null ? LocaleUtils.toLocale(localeString) : Locale.getDefault();
    Context context = new Context(locale, wrap(model));
    lock.lock();
    try {
        @SuppressWarnings("unchecked") Map<String, Object> config = (Map<String, Object>) model.get("config");
        @SuppressWarnings("unchecked") Map<String, Object> content = (Map<String, Object>) model.get("content");
        String mode = "HTML";
        if (config != null && content != null) {
            String key = "template_" + content.get(Attributes.TYPE) + "_thymeleaf_mode";
            String configMode = (String) config.get(key);
            if (configMode != null) {
                mode = configMode;
            }
        }
        initializeTemplateEngine(mode);
        templateEngine.process(templateName, context, writer);
    } finally {
        lock.unlock();
    }
}
Example 21
Project: prime-mvc-master  File: LocaleSelect.java View source code
/**
   * Adds the countries Map and then calls super.
   */
@Override
protected Map<String, Object> makeParameters() {
    LinkedHashMap<String, String> locales = new LinkedHashMap<>();
    String preferred = (String) attributes.get("preferredLocales");
    if (preferred != null) {
        String[] parts = preferred.split(",");
        for (String part : parts) {
            Locale locale = LocaleUtils.toLocale(part);
            locales.put(locale.toString(), locale.getDisplayName(locale));
        }
    }
    boolean includeCountries = attributes.containsKey("includeCountries") ? (Boolean) attributes.get("includeCountries") : true;
    List<Locale> allLocales = new ArrayList<>();
    Collections.addAll(allLocales, Locale.getAvailableLocales());
    allLocales.removeIf(( locale) -> locale.getLanguage().isEmpty() || locale.hasExtensions() || !locale.getScript().isEmpty() || !locale.getVariant().isEmpty() || (!includeCountries && !locale.getCountry().isEmpty()));
    allLocales.sort(( one,  two) -> one.getDisplayName(locale).compareTo(two.getDisplayName(locale)));
    for (Locale locale : allLocales) {
        if (!locales.containsKey(locale.getCountry())) {
            locales.put(locale.toString(), locale.getDisplayName(this.locale));
        }
    }
    attributes.put("items", locales);
    return super.makeParameters();
}
Example 22
Project: uberfire-master  File: GWTLocaleHeaderFilter.java View source code
private Locale getLocale(final ServletRequest request) {
    Locale locale = request.getLocale();
    final String paramLocale = request.getParameter("locale");
    if (paramLocale == null || paramLocale.isEmpty()) {
        return locale;
    }
    try {
        locale = LocaleUtils.toLocale(paramLocale);
    } catch (Exception e) {
    }
    return locale;
}
Example 23
Project: webGrude-master  File: Instantiator.java View source code
@SuppressWarnings("unchecked")
public static <T> T instanceForNode(final Element node, final Selector s, final Class<T> c) {
    final String attribute = s.attr();
    final String format = s.format();
    final String locale = s.locale();
    final String defValue = s.defValue();
    String value;
    try {
        if (c.equals(Element.class)) {
            return (T) node;
        }
        if (attribute != null && !attribute.isEmpty()) {
            if (attribute.equals("html")) {
                value = node.html();
            } else if (attribute.equals("outerHtml")) {
                value = node.outerHtml();
            } else {
                value = node.attr(attribute);
            }
        } else {
            value = node.text();
        }
        if (!c.equals(Date.class) && format != null && !format.equals(Selector.NOVALUE)) {
            final Pattern p = Pattern.compile(format);
            final Matcher matcher = p.matcher(value);
            final boolean found = matcher.find();
            if (found) {
                value = matcher.group(1);
                if (value.isEmpty()) {
                    value = defValue;
                }
            } else {
                value = defValue;
            }
        }
        if (c.equals(String.class)) {
            return (T) value;
        }
        if (c.equals(Date.class)) {
            Locale loc = Locale.getDefault();
            if (!locale.equals(Selector.NOVALUE)) {
                loc = LocaleUtils.toLocale(locale);
            }
            final DateFormat df = new SimpleDateFormat(format, loc);
            return (T) df.parse(value);
        }
        if (c.equals(Integer.class) || c.getSimpleName().equals("int")) {
            return (T) Integer.valueOf(value);
        }
        if (c.equals(Float.class) || c.getSimpleName().equals("float")) {
            if (!locale.equals(Selector.NOVALUE)) {
                Locale loc = LocaleUtils.toLocale(locale);
                final NumberFormat nf = NumberFormat.getInstance(loc);
                Number number = nf.parse(value);
                return (T) Float.valueOf(number.floatValue());
            } else {
                return (T) Float.valueOf(value);
            }
        }
        if (c.equals(Boolean.class) || c.getSimpleName().equals("boolean")) {
            return (T) Boolean.valueOf(value);
        }
    } catch (final Exception e) {
        throw new WrongTypeForField(node, attribute, c, e);
    }
    return (T) value;
}
Example 24
Project: xwiki-platform-master  File: XWiki.java View source code
/**
     * The default locale in the preferences.
     *
     * @param xcontext the XWiki context.
     * @return the default locale
     * @since 5.1M2
     */
public Locale getDefaultLocale(XWikiContext xcontext) {
    // Find out what is the default language from the XWiki preferences settings.
    String defaultLanguage = xcontext.getWiki().getXWikiPreference("default_language", "", xcontext);
    Locale defaultLocale;
    if (StringUtils.isBlank(defaultLanguage)) {
        defaultLocale = Locale.ENGLISH;
    } else {
        try {
            defaultLocale = LocaleUtils.toLocale(Util.normalizeLanguage(defaultLanguage));
        } catch (Exception e) {
            LOGGER.warn("Invalid locale [{}] set as default locale in the preferences", defaultLanguage);
            defaultLocale = Locale.ENGLISH;
        }
    }
    return defaultLocale;
}
Example 25
Project: HippoCocoonToolkit-master  File: HippoRepositoryTransformer.java View source code
@Override
public void setup(final Map<String, Object> parameters) {
    if (parameters == null) {
        return;
    }
    if (parameters.containsKey(PARAM_AVAILABILITY)) {
        try {
            availability = Availability.valueOf((String) parameters.get(PARAM_AVAILABILITY));
        } catch (IllegalArgumentException e) {
            availability = Availability.live;
            LOG.warn("Invalid availability specified, reverting to " + availability, e);
        }
    } else {
        availability = Availability.live;
        LOG.warn("No availability specified, reverting to " + availability);
    }
    Locale defaultLocale;
    if (parameters.containsKey(Settings.ROLE)) {
        final Settings settings = (Settings) parameters.get(Settings.ROLE);
        final String localeString = settings.getProperty("net.tirasa.hct.defaultLocale", Locale.getDefault().getLanguage());
        try {
            defaultLocale = LocaleUtils.toLocale(localeString);
        } catch (IllegalArgumentException e) {
            defaultLocale = Locale.getDefault();
            LOG.error("Could not parse provided '{}' as default Locale", localeString, e);
        }
    } else {
        defaultLocale = Locale.getDefault();
    }
    if (parameters.containsKey(PARAM_LOCALE)) {
        try {
            locale = LocaleUtils.toLocale((String) parameters.get(PARAM_LOCALE));
        } catch (IllegalArgumentException e) {
            locale = defaultLocale;
            LOG.error("Could not parse provided '{}' as Locale", parameters.get(PARAM_LOCALE), e);
        }
    } else {
        locale = defaultLocale;
        LOG.warn("No locale specified, reverting to " + locale);
    }
    state = State.OUTSIDE;
}
Example 26
Project: jspresso-ce-master  File: AbstractBackendController.java View source code
/**
   * {@inheritDoc}
   */
@Override
public void loggedIn(Subject subject) {
    getApplicationSession().setSubject(subject);
    String userPreferredLanguageCode = (String) getApplicationSession().getPrincipal().getCustomProperty(UserPrincipal.LANGUAGE_PROPERTY);
    if (userPreferredLanguageCode != null) {
        getApplicationSession().setLocale(LocaleUtils.toLocale(userPreferredLanguageCode));
    }
    if (getUserPreferencesStore() != null) {
        getUserPreferencesStore().setStorePath(getApplicationSession().getUsername());
    }
}
Example 27
Project: jubula.core-master  File: AbstractStartJavaAut.java View source code
/**
     * Sets -javaagent and JRE arguments as SUN environment variable.
     * @param parameters The parameters for starting the AUT
     * @return the _JAVA_OPTIONS environment variable including -javaagent
     * and jre arguments
     */
protected String setJavaOptions(Map<String, String> parameters) {
    StringBuffer sb = new StringBuffer();
    if (isRunningFromExecutable(parameters)) {
        Locale locale = LocaleUtils.toLocale(parameters.get(AutConfigConstants.AUT_LOCALE));
        // set agent and locals
        sb.append(JAVA_OPTIONS_INTRO);
        if (org.eclipse.jubula.tools.internal.utils.MonitoringUtil.shouldAndCanRunWithMonitoring(parameters)) {
            String monAgent = getMonitoringAgent(parameters);
            if (monAgent != null) {
                sb.append(monAgent).append(StringConstants.SPACE);
            }
        }
        sb.append(StringConstants.QUOTE).append(//$NON-NLS-1$
        "-javaagent:").append(getAbsoluteAgentJarPath()).append(StringConstants.QUOTE);
        if (locale != null) {
            sb.append(StringConstants.SPACE).append(JAVA_COUNTRY_PROPERTY).append(locale.getCountry());
            sb.append(StringConstants.SPACE).append(JAVA_LANGUAGE_PROPERTY).append(locale.getLanguage());
        }
    } else {
        if (org.eclipse.jubula.tools.internal.utils.MonitoringUtil.shouldAndCanRunWithMonitoring(parameters)) {
            String monAgent = getMonitoringAgent(parameters);
            if (monAgent != null) {
                sb.append(JAVA_OPTIONS_INTRO).append(monAgent);
            }
        }
    }
    return sb.toString();
}
Example 28
Project: openengsb-master  File: BundleStrings.java View source code
@Override
public String getString(String key, Locale locale, String... parameters) {
    @SuppressWarnings("unchecked") List<Locale> locales = LocaleUtils.localeLookupList(locale, new Locale(""));
    for (Locale l : locales) {
        Properties p = entries.get(buildEntryFilename(l));
        if (p == null) {
            continue;
        }
        if (p.containsKey(key)) {
            String property = p.getProperty(key);
            String format = MessageFormat.format(property, (Object[]) parameters);
            return format;
        }
    }
    return null;
}
Example 29
Project: qalingo-engine-master  File: Localization.java View source code
public Locale getLocale() {
    Locale locale = null;
    try {
        String stringLocale = "";
        if (StringUtils.isNotEmpty(country) && !country.equalsIgnoreCase(language)) {
            stringLocale = language + "_" + country;
        } else {
            stringLocale = language;
        }
        locale = LocaleUtils.toLocale(stringLocale);
    } catch (Exception e) {
    }
    return locale;
}
Example 30
Project: sling-master  File: FormatFilterExtension.java View source code
private Locale getLocale(RuntimeObjectModel runtimeObjectModel, Map<String, Object> options) {
    String localeOption = null;
    if (options.containsKey(LOCALE_OPTION)) {
        localeOption = runtimeObjectModel.toString(options.get(LOCALE_OPTION));
    }
    if (localeOption == null && options.containsKey(FORMAT_LOCALE_OPTION)) {
        localeOption = runtimeObjectModel.toString(options.get(FORMAT_LOCALE_OPTION));
    }
    if (StringUtils.isNotBlank(localeOption)) {
        return LocaleUtils.toLocale(localeOption);
    }
    return null;
}
Example 31
Project: uPortal-master  File: PortletResourceResponseContextImpl.java View source code
/**
     * Handles resource response specific headers. Returns true if the header was consumed by this
     * method and requires no further processing
     *
     * @return
     */
protected boolean handleResourceHeader(String key, String value) {
    if (ResourceResponse.HTTP_STATUS_CODE.equals(key)) {
        this.portletResourceOutputHandler.setStatus(Integer.parseInt(value));
        return true;
    }
    if ("Content-Type".equals(key)) {
        final ContentType contentType = ContentType.parse(value);
        final Charset charset = contentType.getCharset();
        if (charset != null) {
            this.portletResourceOutputHandler.setCharacterEncoding(charset.name());
        }
        this.portletResourceOutputHandler.setContentType(contentType.getMimeType());
        return true;
    }
    if ("Content-Length".equals(key)) {
        this.portletResourceOutputHandler.setContentLength(Integer.parseInt(value));
        return true;
    }
    if ("Content-Language".equals(key)) {
        final HeaderElement[] parts = BasicHeaderValueParser.parseElements(value, null);
        if (parts.length > 0) {
            final String localeStr = parts[0].getValue();
            final Locale locale = LocaleUtils.toLocale(localeStr);
            this.portletResourceOutputHandler.setLocale(locale);
            return true;
        }
    }
    return false;
}
Example 32
Project: constellation-master  File: AuthController.java View source code
@RequestMapping(value = "/forgotPassword", method = RequestMethod.POST)
@Transactional(rollbackFor = Exception.class)
public ResponseEntity forgotPassword(HttpServletRequest request, @RequestBody final ForgotPassword forgotPassword) throws EmailException {
    final String email = forgotPassword.getEmail();
    String uuid = DigestUtils.sha256Hex(email + System.currentTimeMillis());
    Optional<CstlUser> userOptional = userRepository.findByEmail(email);
    if (userOptional.isPresent()) {
        CstlUser user = userOptional.get();
        user.setForgotPasswordUuid(uuid);
        userRepository.update(user);
        String baseUrl = "http://" + request.getHeader("host") + request.getContextPath();
        String resetPasswordUrl = baseUrl + "/reset-password.html?uuid=" + uuid;
        ResourceBundle bundle = ResourceBundle.getBundle("org/constellation/admin/mail/mail", LocaleUtils.toLocale(user.getLocale()));
        Object[] args = { user.getFirstname(), user.getLastname(), resetPasswordUrl };
        mailService.send(bundle.getString("account.password.reset.subject"), MessageFormat.format(bundle.getString("account.password.reset.body"), args), Collections.singletonList(email));
        return new ResponseEntity(HttpStatus.OK);
    }
    return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
Example 33
Project: heliosearch-master  File: ParseDateFieldUpdateProcessorFactory.java View source code
@Override
public void init(NamedList args) {
    Locale locale = Locale.ROOT;
    String localeParam = (String) args.remove(LOCALE_PARAM);
    if (null != localeParam) {
        locale = LocaleUtils.toLocale(localeParam);
    }
    Object defaultTimeZoneParam = args.remove(DEFAULT_TIME_ZONE_PARAM);
    DateTimeZone defaultTimeZone = DateTimeZone.UTC;
    if (null != defaultTimeZoneParam) {
        defaultTimeZone = DateTimeZone.forID(defaultTimeZoneParam.toString());
    }
    Collection<String> formatsParam = args.removeConfigArgs(FORMATS_PARAM);
    if (null != formatsParam) {
        for (String value : formatsParam) {
            formats.put(value, DateTimeFormat.forPattern(value).withZone(defaultTimeZone).withLocale(locale));
        }
    }
    super.init(args);
}
Example 34
Project: jinjava-master  File: JinjavaInterpreterResolver.java View source code
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(), null, BasicTemplateErrorCategory.UNKNOWN_LOCALE, ImmutableMap.of("date", d.getDate().toString(), "exception", e.getMessage(), "lineNumber", String.valueOf(interpreter.getLineNumber()))));
        }
    }
    return Locale.US;
}
Example 35
Project: lucene-solr-master  File: ParseDateFieldUpdateProcessorFactory.java View source code
@Override
public void init(NamedList args) {
    Locale locale = Locale.ROOT;
    String localeParam = (String) args.remove(LOCALE_PARAM);
    if (null != localeParam) {
        locale = LocaleUtils.toLocale(localeParam);
    }
    Object defaultTimeZoneParam = args.remove(DEFAULT_TIME_ZONE_PARAM);
    DateTimeZone defaultTimeZone = DateTimeZone.UTC;
    if (null != defaultTimeZoneParam) {
        defaultTimeZone = DateTimeZone.forID(defaultTimeZoneParam.toString());
    }
    Collection<String> formatsParam = args.removeConfigArgs(FORMATS_PARAM);
    if (null != formatsParam) {
        for (String value : formatsParam) {
            formats.put(value, DateTimeFormat.forPattern(value).withZone(defaultTimeZone).withLocale(locale));
        }
    }
    super.init(args);
}
Example 36
Project: Magnolia-master  File: Node2BeanTransformerImpl.java View source code
@Override
public Object convertPropertyValue(Class<?> propertyType, Object value) throws Node2BeanException {
    if (Class.class.equals(propertyType)) {
        try {
            return Classes.getClassFactory().forName(value.toString());
        } catch (ClassNotFoundException e) {
            log.error("Can't convert property. Class for type [{}] not found.", propertyType);
            throw new Node2BeanException(e);
        }
    }
    if (Locale.class.equals(propertyType)) {
        if (value instanceof String) {
            String localeStr = (String) value;
            if (StringUtils.isNotEmpty(localeStr)) {
                return LocaleUtils.toLocale(localeStr);
            }
        }
    }
    if (Collection.class.equals(propertyType) && value instanceof Map) {
        // TODO never used ?
        return ((Map) value).values();
    }
    // this is mainly the case when we are flattening node hierarchies
    if (String.class.equals(propertyType) && value instanceof Map && ((Map) value).size() == 1) {
        return ((Map) value).values().iterator().next();
    }
    return value;
}
Example 37
Project: nifi-master  File: TestConvertAvroSchema.java View source code
public void testBasicConversionWithLocale(String localeString) throws IOException {
    TestRunner runner = TestRunners.newTestRunner(ConvertAvroSchema.class);
    runner.assertNotValid();
    runner.setProperty(ConvertAvroSchema.INPUT_SCHEMA, INPUT_SCHEMA.toString());
    runner.setProperty(ConvertAvroSchema.OUTPUT_SCHEMA, OUTPUT_SCHEMA.toString());
    Locale locale = LocaleUtils.toLocale(localeString);
    runner.setProperty(ConvertAvroSchema.LOCALE, localeString);
    runner.setProperty("primaryColor", "color");
    runner.assertValid();
    NumberFormat format = NumberFormat.getInstance(locale);
    // Two valid rows, and one invalid because "free" is not a double.
    Record goodRecord1 = dataBasic("1", "blue", null, null);
    Record goodRecord2 = dataBasic("2", "red", "yellow", format.format(5.5));
    Record badRecord = dataBasic("3", "red", "yellow", "free");
    List<Record> input = Lists.newArrayList(goodRecord1, goodRecord2, badRecord);
    runner.enqueue(streamFor(input));
    runner.run();
    long converted = runner.getCounterValue("Converted records");
    long errors = runner.getCounterValue("Conversion errors");
    Assert.assertEquals("Should convert 2 rows", 2, converted);
    Assert.assertEquals("Should reject 1 rows", 1, errors);
    runner.assertTransferCount("success", 1);
    runner.assertTransferCount("failure", 1);
    MockFlowFile incompatible = runner.getFlowFilesForRelationship("failure").get(0);
    GenericDatumReader<Record> reader = new GenericDatumReader<Record>(INPUT_SCHEMA);
    DataFileStream<Record> stream = new DataFileStream<Record>(new ByteArrayInputStream(runner.getContentAsByteArray(incompatible)), reader);
    int count = 0;
    for (Record r : stream) {
        Assert.assertEquals(badRecord, r);
        count++;
    }
    stream.close();
    Assert.assertEquals(1, count);
    Assert.assertEquals("Should accumulate error messages", FAILURE_SUMMARY, incompatible.getAttribute("errors"));
    GenericDatumReader<Record> successReader = new GenericDatumReader<Record>(OUTPUT_SCHEMA);
    DataFileStream<Record> successStream = new DataFileStream<Record>(new ByteArrayInputStream(runner.getContentAsByteArray(runner.getFlowFilesForRelationship("success").get(0))), successReader);
    count = 0;
    for (Record r : successStream) {
        if (count == 0) {
            Assert.assertEquals(convertBasic(goodRecord1, locale), r);
        } else {
            Assert.assertEquals(convertBasic(goodRecord2, locale), r);
        }
        count++;
    }
    successStream.close();
    Assert.assertEquals(2, count);
}
Example 38
Project: pentaho-platform-master  File: SystemResource.java View source code
/**
   * Apply the selected locale to the user console
   *
   * @param locale (user console's locale)
   *
   * @return
   */
@POST
@Path("/locale")
@Facet(name = "Unsupported")
public Response setLocaleOverride(String locale) {
    IPentahoSession session = PentahoSessionHolder.getSession();
    Locale newLocale = null;
    if (session != null) {
        if (!StringUtils.isEmpty(locale)) {
            // Clean up "en-US" and "en/GB"
            String localeTmp = locale.replaceAll("-|/", "_");
            try {
                newLocale = LocaleUtils.toLocale(localeTmp);
                session.setAttribute("locale_override", localeTmp);
                LocaleHelper.setLocaleOverride(newLocale);
            } catch (IllegalArgumentException ex) {
                return Response.serverError().entity(ex.getMessage()).build();
            }
        } else {
            // empty string or null passed in, unset locale_override variable.
            session.setAttribute("locale_override", null);
            LocaleHelper.setLocaleOverride(null);
        }
    } else {
        LocaleHelper.setLocaleOverride(null);
    }
    return getLocale();
}
Example 39
Project: PermissionsEx-master  File: BukkitMessageFormatter.java View source code
@Override
public BaseComponent tr(Translatable tr) {
    Object[] oldArgs = tr.getArgs();
    Object[] args = new Object[oldArgs.length];
    for (int i = 0; i < oldArgs.length; ++i) {
        args[i] = componentFrom(oldArgs[i]);
    }
    return new TranslatableComponent(tr.translate(sender instanceof Player ? LocaleUtils.toLocale(((Player) sender).spigot().getLocale()) : Locale.getDefault()), args);
}
Example 40
Project: timestamper-plugin-master  File: TimestampsActionQuery.java View source code
/**
   * Create a new {@link TimestampsActionQuery}.
   * 
   * @param query
   *          the query string
   * @return a new query
   */
public static TimestampsActionQuery create(String query) {
    int startLine = 0;
    Optional<Integer> endLine = Optional.absent();
    List<Function<Timestamp, String>> timestampFormats = new ArrayList<Function<Timestamp, String>>();
    boolean appendLogLine = false;
    boolean currentTime = false;
    List<QueryParameter> queryParameters = readQueryString(query);
    Optional<String> timeZoneId = Optional.absent();
    Locale locale = Locale.getDefault();
    for (QueryParameter parameter : queryParameters) {
        if (parameter.name.equalsIgnoreCase("timeZone")) {
            // '+' was replaced with ' ' by URL decoding, so put it back.
            timeZoneId = Optional.of(parameter.value.replace("GMT ", "GMT+"));
        } else if (parameter.name.equalsIgnoreCase("locale")) {
            locale = LocaleUtils.toLocale(parameter.value);
        }
    }
    for (QueryParameter parameter : queryParameters) {
        if (parameter.name.equalsIgnoreCase("time")) {
            timestampFormats.add(new SystemTimestampFormat(parameter.value, timeZoneId, locale));
        } else if (parameter.name.equalsIgnoreCase("elapsed")) {
            timestampFormats.add(new ElapsedTimestampFormat(parameter.value));
        } else if (parameter.name.equalsIgnoreCase("precision")) {
            int precision = readPrecision(parameter.value);
            timestampFormats.add(new PrecisionTimestampFormat(precision));
        } else if (parameter.name.equalsIgnoreCase("appendLog")) {
            appendLogLine = (parameter.value.isEmpty() || Boolean.parseBoolean(parameter.value));
        } else if (parameter.name.equalsIgnoreCase("currentTime")) {
            currentTime = (parameter.value.isEmpty() || Boolean.parseBoolean(parameter.value));
        } else if (parameter.name.equalsIgnoreCase("startLine")) {
            startLine = Integer.parseInt(parameter.value);
        } else if (parameter.name.equalsIgnoreCase("endLine")) {
            endLine = Optional.of(Integer.valueOf(parameter.value));
        }
    }
    if (timestampFormats.isEmpty()) {
        // Default
        timestampFormats.add(new PrecisionTimestampFormat(3));
    }
    return new TimestampsActionQuery(startLine, endLine, timestampFormats, appendLogLine, currentTime);
}
Example 41
Project: gatein-portal-master  File: Utils.java View source code
public static Locale getLocale(ModelObject model, String... names) {
    String string = get(model, ModelString.class, names).getValue();
    if (string != null) {
        try {
            char[] lang = string.toCharArray();
            if (lang.length > 2 && lang[2] == '-') {
                lang[2] = '_';
            }
            return LocaleUtils.toLocale(new String(lang));
        } catch (IllegalArgumentException e) {
            throw invalidValue(string, names);
        }
    }
    return null;
}
Example 42
Project: Hippo-CMS-Konakart-master  File: KKEngineServiceImpl.java View source code
private Locale findPreferredLocale(HstRequestContext requestContext) {
    if (requestContext.getResolvedSiteMapItem() != null) {
        HstSiteMapItem siteMapItem = requestContext.getResolvedSiteMapItem().getHstSiteMapItem();
        if (siteMapItem.getLocale() != null) {
            Locale locale = LocaleUtils.toLocale(siteMapItem.getLocale());
            log.debug("Preferred locale for request is set to '{}' by sitemap item '{}'", siteMapItem.getLocale(), siteMapItem.getId());
            return locale;
        }
    }
    // if we did not yet find a locale, test the Mount
    if (requestContext.getResolvedMount() != null) {
        Mount mount = requestContext.getResolvedMount().getMount();
        if (mount.getLocale() != null) {
            Locale locale = LocaleUtils.toLocale(mount.getLocale());
            log.debug("Preferred locale for request is set to '{}' by Mount '{}'", mount.getLocale(), mount.getName());
            return locale;
        }
    }
    // no locale found
    return null;
}
Example 43
Project: kramerius-master  File: GetKrameriusObjectQueryHandler.java View source code
private Map<String, Map<String, String>> fetchTitles(String pid, RelationModel rels, String locale) throws ActionException {
    try {
        Map<String, Map<String, String>> result = new HashMap<String, Map<String, String>>();
        Locale loc = LocaleUtils.toLocale(locale);
        if (loc == null) {
            loc = Locale.getDefault();
        }
        JSONObject jsonObj = ApiUtilsHelp.item(pid);
        String constructedTitle = ApiUtilsHelp.constructTitle(jsonObj, loc);
        Map<String, JSONObject> objects = new HashMap<String, JSONObject>();
        JSONArray jsonArr = ApiUtilsHelp.children(pid);
        for (int i = 0, ll = jsonArr.length(); i < ll; i++) {
            JSONObject chJSON = (JSONObject) jsonArr.get(i);
            objects.put(chJSON.getString("pid"), chJSON);
        }
        result.put(pid, propertiesJSONObject(jsonObj, constructedTitle));
        for (KrameriusModels relationKind : rels.getRelationKinds()) {
            for (Relation relation : rels.getRelations(relationKind)) {
                JSONObject jsonObject = objects.get(relation.getPID());
                if (jsonObject != null) {
                    result.put(relation.getPID(), propertiesJSONObject(jsonObject, constructedTitle));
                }
            }
        }
        return result;
    } catch (JSONException e) {
        throw new ActionException(e);
    }
}
Example 44
Project: com.activecq.samples-master  File: LocalizedTagTitleExtractorProcessWorkflow.java View source code
/**
     * Derive the locale from the parent path segments (/content/us/en/..)
     *
     * @param resource
     * @return
     */
private Locale getLocaleFromPath(final Resource resource) {
    final String[] segments = StringUtils.split(resource.getPath(), PATH_DELIMITER);
    String country = "";
    String language = "";
    for (final String segment : segments) {
        if (ArrayUtils.contains(Locale.getISOCountries(), segment)) {
            country = segment;
        } else if (ArrayUtils.contains(Locale.getISOLanguages(), segment)) {
            language = segment;
        }
    }
    if (StringUtils.isNotBlank(country) && StringUtils.isNotBlank(language)) {
        return LocaleUtils.toLocale(country + "-" + language);
    } else if (StringUtils.isNotBlank(country)) {
        return LocaleUtils.toLocale(country);
    } else if (StringUtils.isNotBlank(language)) {
        return LocaleUtils.toLocale(language);
    }
    return null;
}
Example 45
Project: converge-1.x-master  File: Concepts.java View source code
public void onReadAvailableLanguages(ActionEvent event) throws IOException {
    this.availableLanguages.clear();
    for (UploadItem item : this.uploadedConcepts) {
        byte[] fileData;
        if (item.isTempFile()) {
            fileData = FileUtils.readFileToByteArray(item.getFile());
        } else {
            fileData = item.getData();
        }
        String xml = new String(fileData);
        String[] languages = metaDataFacade.getLanguagesAvailableForImport(xml);
        for (String lang : languages) {
            lang = lang.replaceAll("-", "_");
            Locale locale = LocaleUtils.toLocale(lang);
            this.availableLanguages.put(locale.getDisplayLanguage(), lang);
        }
    }
}
Example 46
Project: jeffaschenk-commons-master  File: AuthenticationFilter.java View source code
/**
     * <p/>
     * successfulAuthentication
     * Provides Override for additional Successful Authentication Processing.
     */
@Transactional(rollbackFor = { JSONException.class })
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException {
    super.successfulAuthentication(request, response, authResult);
    // and maintain a Security Service Object.
    if ((authResult != null) && (authResult.isAuthenticated())) {
        // *****************************************
        // Proceed with Request.
        log.info("Successful Authentication for Principal:[" + authResult.getPrincipal() + "], of Requested Resource:[" + request.getRequestURI() + "]");
        HttpSession session = request.getSession();
        session.setAttribute(SecuritySessionUserObject.SECURITY_SESSION_USER_OBJECT_NAME, authResult.getDetails());
        if (((SecuritySessionUserObject) authResult.getDetails()).getSecuritySessionProfileObject() != null) {
            Locale locale = LocaleUtils.toLocale(((SecuritySessionUserObject) authResult.getDetails()).getSecuritySessionProfileObject().getUserLocale());
            session.setAttribute("org.springframework.web.servlet.i18n.SessionLocaleResolver.LOCALE", locale);
        }
        // *********************************
        // Generate our Response.
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("success", true);
        } catch (JSONException je) {
            log.error("successfulAuthentication JSONException Encountered:[" + je.getMessage() + "]", je);
        }
        HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(response);
        Writer out = responseWrapper.getWriter();
        out.write(jsonObject.toString());
        out.close();
        // **************************************************
        // Indicate Successful Log-in to the Service Monitor.
        securityServiceMonitor.monitorLogInAttemptRequest(authResult.getPrincipal(), request, true);
    }
}
Example 47
Project: org.liveSense.misc.i18n-master  File: I18nLoader.java View source code
public void install(Bundle bundle, String bundleName) throws Exception {
    // Removes proxy classes
    I18N.resetCache();
    log.info("Registering I18n: " + bundleName);
    i18nService.registerResourceBundle(bundle, bundleName);
    Session session = null;
    try {
        session = repository.loginAdministrative(null);
        // Writing entries to Repository
        String i18nPath = new File(bundleName.replace(".", "/")).getParent();
        String i18nName = new File(bundleName.replace(".", "/")).getName();
        Enumeration entries = bundle.getEntryPaths(i18nPath);
        if (entries != null) {
            while (entries.hasMoreElements()) {
                URL url = bundle.getEntry((String) entries.nextElement());
                String urlFileName = new File(url.getFile()).getName();
                if (urlFileName.endsWith(".properties") && (urlFileName.startsWith(i18nName))) {
                    log.info("Loading " + url + " into JCR repository");
                    String locale = urlFileName.substring(i18nName.length(), urlFileName.length() - ".properties".length());
                    Locale loc = Locale.getDefault();
                    if (StringUtils.isNotEmpty(locale)) {
                        loc = LocaleUtils.toLocale(locale.substring(1));
                        Node n = createPath(session, "/" + path + "/" + bundleName + "/" + loc.toString(), FOLDER_NODE_TYPE);
                        boolean foundType = false;
                        for (NodeType t : n.getMixinNodeTypes()) {
                            if (t.getName().equals(NodeType.MIX_LANGUAGE)) {
                                foundType = true;
                            }
                        }
                        if (!foundType)
                            n.addMixin(NodeType.MIX_LANGUAGE);
                        n.setProperty("jcr:language", loc.toString());
                        n.setProperty("sling:basename", bundleName);
                        java.util.Properties props = new java.util.Properties();
                        InputStream in = url.openStream();
                        props.load(in);
                        in.close();
                        for (Object key : props.keySet()) {
                            if (!n.hasNode((String) key)) {
                                log.info("Creating " + (String) key);
                                Node msgNode = n.addNode((String) key, "sling:MessageEntry");
                                msgNode.setProperty("sling:key", (String) key);
                                msgNode.setProperty("sling:message", props.getProperty((String) key));
                            }
                        }
                    }
                }
            }
        }
        if (session.hasPendingChanges())
            session.save();
    } catch (RepositoryException e) {
        log.error("Cannot get session", e);
    } finally {
        if (session != null && session.isLive()) {
            try {
                session.logout();
            } catch (Exception e) {
            }
        }
    }
}
Example 48
Project: jasperstarter-master  File: Report.java View source code
private Map<String, Object> getCmdLineReportParams() {
    JRParameter[] jrParameterArray = jasperReport.getParameters();
    Map<String, JRParameter> jrParameters = new HashMap<String, JRParameter>();
    Map<String, Object> parameters = new HashMap<String, Object>();
    List<String> params;
    if (config.hasParams()) {
        params = config.getParams();
        for (JRParameter rp : jrParameterArray) {
            jrParameters.put(rp.getName(), rp);
        }
        String paramName = null;
        //String paramType = null;
        String paramValue = null;
        for (String p : params) {
            try {
                paramName = p.split("=")[0];
                paramValue = p.split("=", 2)[1];
                if (config.isVerbose()) {
                    System.out.println("Using report parameter: " + paramName + " = " + paramValue);
                }
            } catch (Exception e) {
                throw new IllegalArgumentException("Wrong report param format! " + p, e);
            }
            if (!jrParameters.containsKey(paramName)) {
                throw new IllegalArgumentException("Parameter '" + paramName + "' does not exist in report!");
            }
            JRParameter reportParam = jrParameters.get(paramName);
            try {
                // ParameterPanel.java
                if (Date.class.equals(reportParam.getValueClass())) {
                    // Date must be in ISO8601 format. Example 2012-12-31
                    DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd");
                    parameters.put(paramName, (Date) dateFormat.parse(paramValue));
                } else if (Image.class.equals(reportParam.getValueClass())) {
                    Image image = Toolkit.getDefaultToolkit().createImage(JRLoader.loadBytes(new File(paramValue)));
                    MediaTracker traker = new MediaTracker(new Panel());
                    traker.addImage(image, 0);
                    try {
                        traker.waitForID(0);
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Image tracker error: " + e.getMessage(), e);
                    }
                    parameters.put(paramName, image);
                } else if (Locale.class.equals(reportParam.getValueClass())) {
                    parameters.put(paramName, LocaleUtils.toLocale(paramValue));
                } else {
                    // handle generic parameters with string constructor
                    try {
                        parameters.put(paramName, reportParam.getValueClass().getConstructor(String.class).newInstance(paramValue));
                    } catch (InstantiationException ex) {
                        throw new IllegalArgumentException("Parameter '" + paramName + "' of type '" + reportParam.getValueClass().getName() + " caused " + ex.getClass().getName() + " " + ex.getMessage(), ex);
                    } catch (IllegalAccessException ex) {
                        throw new IllegalArgumentException("Parameter '" + paramName + "' of type '" + reportParam.getValueClass().getName() + " caused " + ex.getClass().getName() + " " + ex.getMessage(), ex);
                    } catch (InvocationTargetException ex) {
                        Throwable cause = ex.getCause();
                        throw new IllegalArgumentException("Parameter '" + paramName + "' of type '" + reportParam.getValueClass().getName() + " caused " + cause.getClass().getName() + " " + cause.getMessage(), cause);
                    } catch (NoSuchMethodException ex) {
                        throw new IllegalArgumentException("Parameter '" + paramName + "' of type '" + reportParam.getValueClass().getName() + " with value '" + paramValue + "' is not supported by JasperStarter!", ex);
                    }
                }
            } catch (NumberFormatException e) {
                throw new IllegalArgumentException("NumberFormatException: " + e.getMessage() + "\" in \"" + p + "\"", e);
            } catch (java.text.ParseException e) {
                throw new IllegalArgumentException(e.getMessage() + "\" in \"" + p + "\"", e);
            } catch (JRException e) {
                throw new IllegalArgumentException("Unable to load image from: " + paramValue, e);
            }
        }
    }
    return parameters;
}
Example 49
Project: mes-master  File: GeneratedSamplesLoader.java View source code
private String generateWorkingHours(final String locale) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 8);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    long minHours = calendar.getTimeInMillis();
    calendar.set(Calendar.HOUR_OF_DAY, 20);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    long maxHours = calendar.getTimeInMillis();
    long workBeginHours = (long) (RANDOM.nextDouble() * (maxHours / 2 - minHours) + minHours);
    long workEndHours = (long) (RANDOM.nextDouble() * (maxHours - workBeginHours) + workBeginHours);
    Date workBeginDate = new Date(workBeginHours);
    Date workEndDate = new Date(workEndHours);
    StringBuilder workingHours = new StringBuilder();
    SimpleDateFormat hourFormat = new SimpleDateFormat("HH:mm", LocaleUtils.toLocale(locale));
    workingHours.append(hourFormat.format(workBeginDate)).append("-").append(hourFormat.format(workEndDate));
    return workingHours.toString();
}
Example 50
Project: midpoint-master  File: WebModelServiceUtils.java View source code
public static Locale getLocale(UserType user) {
    MidPointPrincipal principal = SecurityUtils.getPrincipalUser();
    Locale locale = null;
    if (principal != null) {
        if (user == null) {
            PrismObject<UserType> userPrismObject = principal.getUser().asPrismObject();
            user = userPrismObject == null ? null : userPrismObject.asObjectable();
        }
        if (user != null && user.getPreferredLanguage() != null && !user.getPreferredLanguage().trim().equals("")) {
            try {
                locale = LocaleUtils.toLocale(user.getPreferredLanguage());
            } catch (Exception ex) {
                LOGGER.debug("Error occurred while getting user locale, " + ex.getMessage());
            }
        }
        if (locale != null && MidPointApplication.containsLocale(locale)) {
            return locale;
        } else {
            String userLocale = user != null ? user.getLocale() : null;
            try {
                locale = userLocale == null ? null : LocaleUtils.toLocale(userLocale);
            } catch (Exception ex) {
                LOGGER.debug("Error occurred while getting user locale, " + ex.getMessage());
            }
            if (locale != null && MidPointApplication.containsLocale(locale)) {
                return locale;
            } else {
                locale = Session.get().getLocale();
                if (locale == null || !MidPointApplication.containsLocale(locale)) {
                    //default locale for web application
                    return MidPointApplication.getDefaultLocale();
                }
                return locale;
            }
        }
    }
    return null;
}
Example 51
Project: opencast-master  File: IncidentServiceEndpoint.java View source code
@GET
@SuppressWarnings("unchecked")
@Produces(MediaType.APPLICATION_JSON)
@Path("localization/{id}")
@RestQuery(name = "getlocalization", description = "Returns the localization of an incident by it's id as JSON", returnDescription = "The localization of the incident as JSON", pathParameters = { @RestParameter(name = "id", isRequired = true, description = "The incident identifiers.", type = Type.INTEGER) }, restParameters = { @RestParameter(name = "locale", isRequired = true, description = "The locale.", type = Type.STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "The localization of the given job incidents."), @RestResponse(responseCode = SC_NOT_FOUND, description = "No job incident with this incident identifier was found.") })
public Response getLocalization(@PathParam("id") final long incidentId, @QueryParam("locale") String locale) throws NotFoundException {
    try {
        IncidentL10n localization = svc.getLocalization(incidentId, LocaleUtils.toLocale(locale));
        JSONObject json = new JSONObject();
        json.put("title", localization.getTitle());
        json.put("description", localization.getDescription());
        return Response.ok(json.toJSONString()).build();
    } catch (IncidentServiceException e) {
        logger.warn("Unable to get job localization of jo incident: {}", e);
        throw new WebApplicationException(INTERNAL_SERVER_ERROR);
    }
}
Example 52
Project: sakai-cle-master  File: ETSUserNotificationProviderImpl.java View source code
private void xmlToTemplate(Element xmlTemplate, String key) {
    String subject = xmlTemplate.getChildText("subject");
    String body = xmlTemplate.getChildText("message");
    String locale = xmlTemplate.getChildText("locale");
    String versionString = xmlTemplate.getChildText("version");
    Locale loc = null;
    if (locale != null && !"".equals(locale)) {
        loc = LocaleUtils.toLocale(locale);
    }
    if (!emailTemplateService.templateExists(key, loc)) {
        EmailTemplate template = new EmailTemplate();
        template.setSubject(subject);
        template.setMessage(body);
        template.setLocale(locale);
        template.setKey(key);
        //setVersion(versionString != null ? Integer.valueOf(versionString) : Integer.valueOf(0));	// set version
        template.setVersion(Integer.valueOf(1));
        template.setOwner("admin");
        template.setLastModified(new Date());
        this.emailTemplateService.saveTemplate(template);
        M_log.info(this + " user notification template " + key + " added");
    } else {
        EmailTemplate existingTemplate = this.emailTemplateService.getEmailTemplate(key, new Locale(locale));
        String oVersionString = existingTemplate.getVersion() != null ? existingTemplate.getVersion().toString() : null;
        if ((oVersionString == null && versionString != null) || (oVersionString != null && versionString != null && !oVersionString.equals(versionString))) {
            existingTemplate.setSubject(subject);
            existingTemplate.setMessage(body);
            existingTemplate.setLocale(locale);
            existingTemplate.setKey(key);
            // set version
            existingTemplate.setVersion(versionString != null ? Integer.valueOf(versionString) : Integer.valueOf(0));
            existingTemplate.setOwner("admin");
            existingTemplate.setLastModified(new Date());
            this.emailTemplateService.updateTemplate(existingTemplate);
            M_log.info(this + " user notification template " + key + " updated to newer version");
        }
    }
}
Example 53
Project: structr-master  File: SecurityContext.java View source code
/**
	 * Determine the effective locale for this request.
	 *
	 * Priority 1: URL parameter "locale"
	 * Priority 2: User locale
	 * Priority 3: Cookie locale
	 * Priority 4: Browser locale
	 * Priority 5: Default locale
	 *
	 * @return locale
	 */
public Locale getEffectiveLocale() {
    // Priority 5: Default locale
    Locale locale = Locale.getDefault();
    boolean userHasLocaleString = false;
    if (cachedUser != null) {
        // Priority 2: User locale
        final String userLocaleString = cachedUser.getProperty(Principal.locale);
        if (userLocaleString != null) {
            userHasLocaleString = true;
            try {
                locale = LocaleUtils.toLocale(userLocaleString);
            } catch (IllegalArgumentException e) {
                locale = Locale.forLanguageTag(userLocaleString);
            }
        }
    }
    if (request != null) {
        if (!userHasLocaleString) {
            // Priority 4: Browser locale
            locale = request.getLocale();
            final Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                // Priority 3: Cookie locale
                for (Cookie c : cookies) {
                    if (c.getName().equals(LOCALE_KEY)) {
                        final String cookieLocaleString = c.getValue();
                        try {
                            locale = LocaleUtils.toLocale(cookieLocaleString);
                        } catch (IllegalArgumentException e) {
                            locale = Locale.forLanguageTag(cookieLocaleString);
                        }
                    }
                }
            }
        }
        // Priority 1: URL parameter locale
        String requestedLocaleString = request.getParameter(LOCALE_KEY);
        if (StringUtils.isNotBlank(requestedLocaleString)) {
            try {
                locale = LocaleUtils.toLocale(requestedLocaleString);
            } catch (IllegalArgumentException e) {
                locale = Locale.forLanguageTag(requestedLocaleString);
            }
        }
    }
    return locale;
}
Example 54
Project: logging-log4j2-master  File: FastDateParserTest.java View source code
@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 55
Project: OG-Platform-master  File: UserForm.java View source code
/**
   * Validates and adds the proposed user to the master.
   * 
   * @param userMaster  the user master, not null
   * @param pwService  the password service
   * @param add  true if adding, false if updating
   * @return the added user
   * @throws UserFormException if the proposed user is invalid
   */
protected ManageableUser validate(UserMaster userMaster, PasswordService pwService, boolean add) {
    userMaster = ArgumentChecker.notNull(userMaster, "userMaster");
    pwService = ArgumentChecker.notNull(pwService, "pwService");
    String userName = StringUtils.trimToNull(getUserName());
    String password = StringUtils.trimToNull(getPasswordRaw());
    String email = StringUtils.trimToNull(getEmailAddress());
    String displayName = StringUtils.trimToNull(getDisplayName());
    String localeStr = StringUtils.trimToNull(getLocale());
    String zoneStr = StringUtils.trimToNull(getZone());
    String dateStyleStr = StringUtils.trimToNull(getDateStyle());
    String timeStyleStr = StringUtils.trimToNull(getTimeStyle());
    List<UserFormError> errors = new ArrayList<>();
    // user name
    if (userName == null) {
        errors.add(UserFormError.USERNAME_MISSING);
    } else if (isUserNameTooShort(userName)) {
        errors.add(UserFormError.USERNAME_TOO_SHORT);
    } else if (isUserNameTooLong(userName)) {
        errors.add(UserFormError.USERNAME_TOO_LONG);
    } else if (isUserNameInvalid(userName)) {
        errors.add(UserFormError.USERNAME_INVALID);
    } else {
        if (add && userMaster.nameExists(userName)) {
            errors.add(UserFormError.USERNAME_ALREADY_IN_USE);
        }
    }
    // password
    String passwordHash = null;
    if (password == null) {
        if (getBaseUser() != null) {
            passwordHash = getBaseUser().getPasswordHash();
        }
        if (passwordHash == null) {
            errors.add(UserFormError.PASSWORD_MISSING);
        }
    } else if (isPasswordTooShort(password)) {
        errors.add(UserFormError.PASSWORD_TOO_SHORT);
    } else if (isPasswordTooLong(password)) {
        errors.add(UserFormError.PASSWORD_TOO_LONG);
    } else if (isPasswordWeak(userName, password)) {
        errors.add(UserFormError.PASSWORD_WEAK);
    } else {
        passwordHash = pwService.encryptPassword(password);
    }
    // email
    if (email == null) {
        errors.add(UserFormError.EMAIL_MISSING);
    } else if (isEmailAddressTooLong(email)) {
        errors.add(UserFormError.EMAIL_TOO_LONG);
    } else if (isEmailAddressInvalid(email)) {
        errors.add(UserFormError.EMAIL_INVALID);
    }
    // display name
    if (displayName == null) {
        errors.add(UserFormError.DISPLAYNAME_MISSING);
    } else if (isDisplayNameTooLong(displayName)) {
        errors.add(UserFormError.DISPLAYNAME_TOO_LONG);
    } else if (isDisplayNameInvalid(displayName)) {
        errors.add(UserFormError.DISPLAYNAME_INVALID);
    }
    // locale
    Locale locale = Locale.ENGLISH;
    if (localeStr != null) {
        try {
            locale = LocaleUtils.toLocale(localeStr);
        } catch (RuntimeException ex) {
            errors.add(UserFormError.LOCALE_INVALID);
        }
    }
    // time zone
    ZoneId zoneId = OpenGammaClock.getZone();
    if (zoneStr != null) {
        try {
            zoneId = ZoneId.of(zoneStr);
        } catch (RuntimeException ex) {
            errors.add(UserFormError.TIMEZONE_INVALID);
        }
    }
    // date style
    DateStyle dateStyle = DateStyle.TEXTUAL_MONTH;
    if (dateStyleStr != null) {
        try {
            dateStyle = DateStyle.valueOf(dateStyleStr);
        } catch (RuntimeException ex) {
            errors.add(UserFormError.DATESTYLE_INVALID);
        }
    }
    // time style
    TimeStyle timeStyle = TimeStyle.ISO;
    if (timeStyleStr != null) {
        try {
            timeStyle = TimeStyle.valueOf(timeStyleStr);
        } catch (RuntimeException ex) {
            errors.add(UserFormError.TIMESTYLE_INVALID);
        }
    }
    // errors
    if (errors.size() > 0) {
        throw new UserFormException(errors);
    }
    // build user object
    ManageableUser user = getBaseUser();
    if (user == null) {
        user = new ManageableUser(userName);
    } else {
        user.setUserName(userName);
    }
    user.setPasswordHash(passwordHash);
    user.setEmailAddress(email);
    user.getProfile().setDisplayName(displayName);
    user.getProfile().setLocale(locale);
    user.getProfile().setZone(zoneId);
    user.getProfile().setDateStyle(dateStyle);
    user.getProfile().setTimeStyle(timeStyle);
    return user;
}
Example 56
Project: zstack-master  File: Platform.java View source code
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 57
Project: flex-falcon-master  File: DebugCLI.java View source code
public void processArgs(String[] args) {
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        //			System.out.println("arg["+i+"]= '"+arg+"'");
        if (arg.charAt(0) == '-') {
            // its an option
            if (// unit-testing mode //$NON-NLS-1$
            arg.equals("-unit")) {
                //$NON-NLS-1$ //$NON-NLS-2$
                System.setProperty("fdbunit", "");
            } else if (//$NON-NLS-1$ //$NON-NLS-2$
            arg.equals("-fullname") || arg.equals("-f")) {
                // emacs mode
                m_fullnameOption = // emacs mode
                true;
            } else if (//$NON-NLS-1$
            arg.equals(//$NON-NLS-1$
            "-cd")) {
                // consume the path
                if (i + 1 < args.length)
                    m_cdPath = args[i++];
            } else if (//$NON-NLS-1$
            arg.equals(//$NON-NLS-1$
            "-p")) {
                // consume the port
                if (i + 1 < args.length)
                    m_connectPort = args[++i];
            } else if (//$NON-NLS-1$
            arg.equals(//$NON-NLS-1$
            "-ide")) {
                m_isIde = true;
            } else if (//$NON-NLS-1$
            arg.equals(//$NON-NLS-1$
            "-lang")) {
                if (i + 1 < args.length)
                    getLocalizationManager().setLocale(LocaleUtils.toLocale(args[++i]));
            } else {
                err(//$NON-NLS-1$
                "Unknown command-line argument: " + //$NON-NLS-1$
                arg);
            }
        } else {
            // its a URI to run
            StringReader sr = new //$NON-NLS-1$
            StringReader(//$NON-NLS-1$
            "run " + arg + m_newline);
            pushStream(new LineNumberReader(sr));
        }
    }
}
Example 58
Project: i2m-jsf-master  File: LocaleConverter.java View source code
public Object getAsObject(FacesContext ctx, UIComponent comp, String value) throws ConverterException {
    System.out.println("GEtting Locale as object: " + value);
    String localeValue = value.replaceAll("-", "_");
    Locale locale = LocaleUtils.toLocale(localeValue);
    return locale;
}
Example 59
Project: Local-GSM-Backend-master  File: LocaleUtil.java View source code
/**
     * 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;
    }
}
Example 60
Project: primefaces-extensions-master  File: LocaleConverter.java View source code
@Override
public Object getAsObject(final FacesContext context, final UIComponent component, final String value) {
    try {
        return LocaleUtils.toLocale(value);
    } catch (IllegalArgumentException e) {
        throw new ConverterException(e.getMessage(), e);
    }
}
Example 61
Project: xwiki-commons-master  File: LocaleConverter.java View source code
@Override
protected Locale convertToType(Type type, Object value) {
    Locale locale = null;
    if (value != null) {
        String valueString = value.toString();
        if (valueString.length() == 0) {
            locale = Locale.ROOT;
        } else {
            locale = LocaleUtils.toLocale(valueString);
        }
    }
    return locale;
}
Example 62
Project: asta4d-master  File: LocalizeUtil.java View source code
public static Locale getLocale(String localeStr) {
    if (StringUtils.isEmpty(localeStr)) {
        return null;
    }
    try {
        return LocaleUtils.toLocale(localeStr);
    } catch (IllegalArgumentException e) {
        return null;
    }
}
Example 63
Project: elasticsearch-akka-master  File: ElasticSearchIndexConfig.java View source code
public Locale getLocale() {
    return LocaleUtils.toLocale(supportedLocale.getText());
}
Example 64
Project: searchanalytics-bigdata-master  File: ElasticSearchIndexConfig.java View source code
public Locale getLocale() {
    return LocaleUtils.toLocale(supportedLocale.getText());
}
Example 65
Project: MULE-master  File: AbstractInstant.java View source code
@Override
public Instant withLocale(String locale) {
    this.locale = LocaleUtils.toLocale(locale);
    Calendar newCalendar = Calendar.getInstance(calendar.getTimeZone(), this.locale);
    newCalendar.setTime(calendar.getTime());
    this.calendar = newCalendar;
    return this;
}
Example 66
Project: netxilia-master  File: NumberFormatter.java View source code
/**
	 * this should be called before using the formatter!
	 */
public void init() {
    this.localeObject = locale != null ? LocaleUtils.toLocale(locale) : Locale.getDefault();
}
Example 67
Project: senbot-master  File: TestEnvironmentTest.java View source code
@Test
public void testContructor_locale() {
    TestEnvironment env = new TestEnvironment(null, null, null, "en_US");
    assertEquals(LocaleUtils.toLocale("en_US"), env.getLocale());
}
Example 68
Project: optaplanner-master  File: ScoreDifferencePercentage.java View source code
public String toString(String locale) {
    return toString(LocaleUtils.toLocale(locale));
}
Example 69
Project: pyramus-master  File: ImportAPI.java View source code
public Faker getFaker(String locale) {
    return new Faker(LocaleUtils.toLocale(locale));
}
Example 70
Project: buildmetadata-maven-plugin-master  File: AbstractReportMojo.java View source code
/**
   * Determines the locale to use. The plugin allows the user to override the
   * locale provided by Maven.
   *
   * @return the locale to use for this report.
   */
private Locale determineLocale() {
    return StringUtils.isNotBlank(this.locale) ? LocaleUtils.toLocale(this.locale) : Locale.getDefault();
}
Example 71
Project: Crud2Go-master  File: AbstractParser.java View source code
private Locale effectiveLocale(HttpResponse response, ReSTAttributeConfig attr) {
    Locale locale = response.getLocale();
    if (attr.getLocale() != null) {
        locale = LocaleUtils.toLocale(attr.getLocale());
    }
    return locale;
}
Example 72
Project: eGov-master  File: User.java View source code
public Locale locale() {
    return LocaleUtils.toLocale(locale);
}
Example 73
Project: TNT4J-master  File: Utils.java View source code
/**
	 * Constructs a {@code 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 (StringUtils.isEmpty(localeStr)) {
        return null;
    }
    // NOTE: adapting to LocaleUtils notation
    String l = localeStr.replace('-', '_');
    return LocaleUtils.toLocale(l);
}
Example 74
Project: krail-master  File: I18NModule.java View source code
/**
     * Converts String to Locale, strictly
     *
     * @param localeString
     *         the String to convert, see {@link LocaleUtils#toLocale(String)} for format
     *
     * @return selected Locale
     *
     * @throws IllegalArgumentException
     *         if the {@code localeString} is not valid
     */
protected Locale localeFromString(String localeString) {
    return LocaleUtils.toLocale(localeString);
}
Example 75
Project: para-master  File: Utils.java View source code
/**
	 * @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;
    }
}