Example usage for java.util Locale getLanguage

List of usage examples for java.util Locale getLanguage

Introduction

In this page you can find the example usage for java.util Locale getLanguage.

Prototype

public String getLanguage() 

Source Link

Document

Returns the language code of this Locale.

Usage

From source file:com.haulmont.cuba.core.sys.AbstractMessages.java

private Locale truncateLocale(Locale locale) {
    if (locale == null || StringUtils.isEmpty(locale.getCountry()))
        return null;
    return Locale.forLanguageTag(locale.getLanguage());
}

From source file:com.doculibre.constellio.spellchecker.SpellChecker.java

private void addSuggestions(String sentence, String collectionName, ListOrderedMap orderedMap,
        NamedList<Object> namedList, Locale locale) {
    if (sentence.length() > 250) {
        throw new IllegalArgumentException("String is too long, rejected by spell checker");
    }//from  www  . jav  a 2s .  c  o m

    RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    RecordCollection collection = collectionServices.get(collectionName);
    if (collection != null && collection.isSpellCheckerActive()) {
        String spellCheckerLanguage;
        if (locale != null) {
            spellCheckerLanguage = locale.getLanguage();
        } else {
            spellCheckerLanguage = collection.getSpellCheckerLanguage();
        }
        DICTIONARIES dictionary;
        if (Locale.ENGLISH.getLanguage().equals(spellCheckerLanguage)) {
            dictionary = DICTIONARIES.en_US;
        } else if ("es".equals(spellCheckerLanguage)) {
            dictionary = DICTIONARIES.es_MX;
        } else {
            dictionary = DICTIONARIES.fr_FR;
        }

        Hunspell.Dictionary hunspellDictionary = this.dictionariesMap.get(dictionary);
        String[] words = sentence.split(" ");
        if (words.length > 0) {
            for (int i = 0; i < words.length; i++) {
                String currentWord = words[i];
                currentWord = StringUtils.remove(currentWord, '(');
                currentWord = StringUtils.remove(currentWord, ')');
                String currentWordWOAccent = AsciiUtils.convertNonAscii(currentWord);
                if (hunspellDictionary.misspelled(currentWord)) {
                    List<String> suggestionsForWord = hunspellDictionary.suggest(currentWord);
                    if (suggestionsForWord.size() > 0) {
                        boolean ignoreSuggestionForWord = false;
                        for (String suggestionForWord : suggestionsForWord) {
                            String sugWOAccent = AsciiUtils.convertNonAscii(suggestionForWord);
                            if (currentWordWOAccent.toLowerCase().equals(sugWOAccent.toLowerCase())) {
                                ignoreSuggestionForWord = true;
                            }
                        }
                        if (orderedMap != null) {
                            orderedMap.put(currentWord, ignoreSuggestionForWord ? null : suggestionsForWord);
                        } else {
                            addNamedList(namedList, currentWord, !ignoreSuggestionForWord,
                                    ignoreSuggestionForWord ? null : suggestionsForWord);
                        }
                    }
                } else {
                    if (orderedMap != null) {
                        orderedMap.put(currentWord, null);
                    } else {
                        addNamedList(namedList, currentWord, false, null);
                    }
                }
            }
        }
    }
}

From source file:net.canadensys.dataportal.occurrence.controller.OccurrenceController.java

/**
 * Resource contact message sending form.
 * //from  ww  w  .j a  va 2s  .  com
 * @param ipt
 *            resource identifier (sourcefileid).
 * @return
 */
@RequestMapping(value = "/occurrences/{auto_id}", method = RequestMethod.POST)
@I18nTranslation(resourceName = "occurrence", translateFormat = "/occurrences/{}")
public ModelAndView handleResourceContactMsg(@PathVariable String auto_id, HttpServletRequest request) {
    OccurrenceModel occModel = occurrenceService.loadOccurrenceModel(auto_id, true);
    ResourceMetadataModel resourceInformationModel = occurrenceService
            .loadResourceMetadataModel(occModel.getSourcefileid());
    // Get resource contacts:
    Set<ContactModel> contacts = resourceInformationModel.getContacts();

    // URL from the previous URL accessed that led to the contact form:
    Locale locale = RequestContextUtils.getLocale(request);
    HashMap<String, Object> modelRoot = new HashMap<String, Object>();

    // Get full URL:
    String occurrenceUrl = I18nUrlBuilder.generateI18nResourcePath(locale.getLanguage(),
            OccurrencePortalConfig.I18N_TRANSLATION_HANDLER.getTranslationFormat("occurrence"),
            new String[] { auto_id });
    String domainName = request.getParameter("domainName");
    occurrenceUrl = domainName + request.getContextPath() + occurrenceUrl;
    // Set common stuff
    ControllerHelper.setPageHeaderVariables(request, "contact", new String[] { auto_id }, appConfig, modelRoot);

    Map<String, Object> templateData = new HashMap<String, Object>();
    ContactModel contact = null;
    for (ContactModel rcm : contacts) {
        if (rcm.getRole().equalsIgnoreCase("contact")) {
            contact = rcm;
            // Add contacts information
            modelRoot.put("contact", contact);
            break;
        }
    }

    String mailto = contact.getEmail();
    String nameto = contact.getName();

    if (mailto != null && !mailto.equalsIgnoreCase("")) {
        String namefrom = request.getParameter("name");
        String mailfrom = request.getParameter("email");
        String message = request.getParameter("message");
        // Later change to fetch from properties file
        // (resourcecontact.subject).
        String subject = request.getParameter("subject");
        templateData.put("subject", subject);
        templateData.put("mailto", mailto);
        templateData.put("nameto", nameto);
        templateData.put("mailfrom", mailfrom);
        templateData.put("namefrom", namefrom);
        templateData.put("message", message);
        templateData.put("occurrenceUrl", occurrenceUrl);
        templateData.put("time", new SimpleDateFormat("EEEE, dd-MM-yyyy HH:mm z", locale).format(new Date()));
        String templateName = appConfig.getContactEmailTemplateName(locale);
        boolean sent = mailSender.sendMessage(mailto, subject, templateData, templateName);
        LOGGER.error("*** Email enviado para o publicador: " + sent);
    }
    // Redirect back to occurrence:

    RedirectView rv = new RedirectView(occurrenceUrl);
    rv.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
    return new ModelAndView(rv);
}

From source file:com.sonicle.webtop.core.sdk.ServiceManifest.java

/**
 * Gets the class name of client-side locale object that applies localized strings.
 * @param locale The required locale.//from   ww  w .  java  2  s.  c  o  m
 * @param full True to include js package.
 * @return The class name.
 */
public String getLocaleJsClassName(Locale locale, boolean full) {
    String cn = "Locale_" + locale.getLanguage();
    return (full) ? LangUtils.buildClassName(jsPackage, cn) : cn;
}

From source file:com.github.mrstampy.gameboot.locale.processor.LocaleProcessorTest.java

private void testCurrent(Locale expected) throws Exception {
    CurrentLocaleMessage cur = new CurrentLocaleMessage();
    cur.setSystemId(SYSTEM_ID_KEY);/*www  . j a  v a  2  s  .  c  om*/

    Response r = current.process(cur);

    assertEquals(ResponseCode.SUCCESS, r.getResponseCode());
    assertNotNull(r.getPayload());
    assertEquals(1, r.getPayload().length);
    assertTrue(r.getPayload()[0] instanceof LocaleBean);

    LocaleBean lb = (LocaleBean) r.getPayload()[0];
    assertEquals(expected.getCountry(), lb.getCountryCode());
    assertEquals(expected.getLanguage(), lb.getLanguageCode());
}

From source file:com.doculibre.constellio.services.ConnectorManagerServicesImpl.java

@Override
public String getConfigFormSnippet(ConnectorManager connectorManager, String connectorType,
        String connectorName, Locale locale) {
    Element xml;//from w  w w .  ja  v a 2s.co  m

    Map<String, String> paramsMap = new HashMap<String, String>();
    paramsMap.put(ServletUtil.QUERY_PARAM_LANG, locale.getLanguage());

    if (connectorName == null) {
        // New connector
        paramsMap.put(ServletUtil.XMLTAG_CONNECTOR_TYPE, connectorType);
        xml = ConnectorManagerRequestUtils.sendGet(connectorManager, "/getConfigForm", paramsMap);
    } else {
        // Existing connector
        paramsMap.put(ServletUtil.XMLTAG_CONNECTOR_NAME, connectorName);
        xml = ConnectorManagerRequestUtils.sendGet(connectorManager, "/getConnectorConfigToEdit", paramsMap);
    }

    Element formSnippet = xml.element(ServletUtil.XMLTAG_CONFIGURE_RESPONSE)
            .element(ServletUtil.XMLTAG_FORM_SNIPPET);
    CDATA cdata = (CDATA) formSnippet.node(0);
    String configFormSnippetText = cdata.getStringValue();

    return configFormSnippetText;
}

From source file:org.examproject.tweet.controller.TweetController.java

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String doLogin(@RequestParam(value = "locale", defaultValue = "") String locale,
        @CookieValue(value = "__exmphangul_request_token", defaultValue = "") String requestToken,
        @CookieValue(value = "__exmphangul_access_token", defaultValue = "") String oauthToken,
        @CookieValue(value = "__exmphangul_token_secret", defaultValue = "") String oauthTokenSecret,
        @CookieValue(value = "__exmphangul_user_id", defaultValue = "") String userId,
        @CookieValue(value = "__exmphangul_screen_name", defaultValue = "") String screenName,
        @CookieValue(value = "__exmphangul_response_list_mode", defaultValue = "") String responseListMode,
        @CookieValue(value = "__exmphangul_user_list_name", defaultValue = "") String userListName,
        Model model) {/*from ww  w  .  ja  va  2s  .  c  o  m*/
    LOG.debug("called.");
    debugOut(oauthToken, oauthTokenSecret, userId, screenName);

    try {
        // get the current local.
        if (locale.equals("")) {
            Locale loc = Locale.getDefault();
            locale = loc.getLanguage();
        }

        // create the form-object.
        TweetForm tweetForm = new TweetForm();

        // set the cookie value to the form-object.
        tweetForm.setUserId(userId);
        tweetForm.setScreenName(screenName);
        tweetForm.setLocale(locale);
        tweetForm.setResponseListMode(responseListMode);
        tweetForm.setUserListName(userListName);

        // set the form-object to the model. 
        model.addAttribute(tweetForm);

        // normally, move to this view.
        return null;

    } catch (Exception e) {
        LOG.fatal(e.getMessage());
        TweetResponse response = (TweetResponse) context.getBean(TWEET_RESPONSE_BEAN_ID, true, e.getMessage());
        model.addAttribute(response);
        return "error";
    }
}

From source file:alfio.controller.EventController.java

private SaleableAdditionalService getSaleableAdditionalService(Event event, Locale locale, AdditionalService as,
        PromoCodeDiscount promoCodeDiscount) {
    return new SaleableAdditionalService(event, as,
            additionalServiceTextRepository.findBestMatchByLocaleAndType(as.getId(), locale.getLanguage(),
                    AdditionalServiceText.TextType.TITLE).getValue(),
            additionalServiceTextRepository.findBestMatchByLocaleAndType(as.getId(), locale.getLanguage(),
                    AdditionalServiceText.TextType.DESCRIPTION).getValue(),
            promoCodeDiscount, 0);/*  w w  w. ja  va  2s. co  m*/
}

From source file:it.cnr.icar.eric.client.ui.thin.UserPreferencesBean.java

/** Sets the locales to 1st supported locale (directly or indirectly). */
private void initLocales() {
    Iterator<?> requestLocales = FacesContext.getCurrentInstance().getExternalContext().getRequestLocales();
    Collection<Locale> supportedLocales = getSupportedUiLocales();
    //iterate though client preferred locales until find supported 
    while (requestLocales.hasNext()) {
        Locale loc = (Locale) requestLocales.next();
        // try direct match
        if (supportedLocales.contains(loc)) {
            init(loc);/*from  www  .  ja va  2s  .com*/
            return;
        }
        // try to use language country, without variant
        if (loc.getVariant() != null && !"".equals(loc.getVariant())) {
            loc = new Locale(loc.getLanguage(), loc.getCountry());
            if (supportedLocales.contains(loc)) {
                init(loc);
                return;
            }
        }
        // try to use language without country and variant
        if (loc.getCountry() != null && !"".equals(loc.getCountry())) {
            loc = new Locale(loc.getLanguage());
            if (supportedLocales.contains(loc)) {
                init(loc);
                return;
            }
        }
    }
    // fall to default locale, from properties (or en_US, if not defined)
    init(getDefaultLocale());
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.candidacies.RefactoredIndividualCandidacyProcessPublicDA.java

private boolean isInEnglishLocale() {
    Locale locale = I18N.getLocale();
    return locale.getLanguage().equals(Locale.ENGLISH.getLanguage());
}