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.android.quicksearchbox.google.GoogleSuggestionProvider.java

/**
 * Queries for a given search term and returns a cursor containing
 * suggestions ordered by best match.//  ww  w  . j  a v  a 2  s .  co  m
 */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    String query = getQuery(uri);
    if (TextUtils.isEmpty(query)) {
        return null;
    }
    if (!isNetworkConnected()) {
        Log.i(LOG_TAG, "Not connected to network.");
        return null;
    }
    try {
        query = URLEncoder.encode(query, "UTF-8");
        // NOTE:  This code uses resources to optionally select the search Uri, based on the
        // MCC value from the SIM.  iThe default string will most likely be fine.  It is
        // paramerterized to accept info from the Locale, the language code is the first
        // parameter (%1$s) and the country code is the second (%2$s).  This code *must*
        // function in the same way as a similar lookup in
        // com.android.browser.BrowserActivity#onCreate().  If you change
        // either of these functions, change them both.  (The same is true for the underlying
        // resource strings, which are stored in mcc-specific xml files.)
        if (mSuggestUri == null) {
            Locale l = Locale.getDefault();
            String language = l.getLanguage();
            String country = l.getCountry().toLowerCase();
            // Chinese and Portuguese have two langauge variants.
            if ("zh".equals(language)) {
                if ("cn".equals(country)) {
                    language = "zh-CN";
                } else if ("tw".equals(country)) {
                    language = "zh-TW";
                }
            } else if ("pt".equals(language)) {
                if ("br".equals(country)) {
                    language = "pt-BR";
                } else if ("pt".equals(country)) {
                    language = "pt-PT";
                }
            }
            mSuggestUri = getContext().getResources().getString(R.string.google_suggest_base, language, country)
                    + "json=true&q=";
        }

        String suggestUri = mSuggestUri + query;
        if (DBG)
            Log.d(LOG_TAG, "Sending request: " + suggestUri);
        HttpGet method = new HttpGet(suggestUri);
        HttpResponse response = mHttpClient.execute(method);
        if (response.getStatusLine().getStatusCode() == 200) {

            /* Goto http://www.google.com/complete/search?json=true&q=foo
             * to see what the data format looks like. It's basically a json
             * array containing 4 other arrays. We only care about the middle
             * 2 which contain the suggestions and their popularity.
             */
            JSONArray results = new JSONArray(EntityUtils.toString(response.getEntity()));
            JSONArray suggestions = results.getJSONArray(1);
            JSONArray popularity = results.getJSONArray(2);
            if (DBG)
                Log.d(LOG_TAG, "Got " + suggestions.length() + " results");
            return new SuggestionsCursor(suggestions, popularity);
        } else {
            if (DBG)
                Log.d(LOG_TAG, "Request failed " + response.getStatusLine());
        }
    } catch (UnsupportedEncodingException e) {
        Log.w(LOG_TAG, "Error", e);
    } catch (IOException e) {
        Log.w(LOG_TAG, "Error", e);
    } catch (JSONException e) {
        Log.w(LOG_TAG, "Error", e);
    }
    return null;
}

From source file:com.trenako.web.tags.LocalizedTextAreaTags.java

protected String getName(Locale loc) throws JspException {
    String expression = getBindStatus().getExpression();
    if (expression == null) {
        return "";
    }/*from  w ww . j a va 2s .  c o  m*/

    return new StringBuilder().append(expression).append("['").append(loc.getLanguage()).append("']")
            .toString();
}

From source file:alfio.manager.NotificationManager.java

private static Function<Map<String, String>, byte[]> generateICS(EventRepository eventRepository,
        EventDescriptionRepository eventDescriptionRepository,
        TicketCategoryRepository ticketCategoryRepository) {
    return (model) -> {
        Event event;/*from w  w  w  . j a v a  2  s . c o m*/
        Locale locale;
        Integer categoryId;
        if (model.containsKey("eventId")) {
            //legacy branch, now we generate the ics as a reinterpreted ticket
            event = eventRepository.findById(Integer.valueOf(model.get("eventId"), 10));
            locale = Json.fromJson(model.get("locale"), Locale.class);
            categoryId = null;
        } else {
            Ticket ticket = Json.fromJson(model.get("ticket"), Ticket.class);
            event = eventRepository.findById(ticket.getEventId());
            locale = Locale.forLanguageTag(ticket.getUserLanguage());
            categoryId = ticket.getCategoryId();
        }
        TicketCategory category = Optional.ofNullable(categoryId).map(ticketCategoryRepository::getById)
                .orElse(null);
        String description = eventDescriptionRepository.findDescriptionByEventIdTypeAndLocale(event.getId(),
                EventDescription.EventDescriptionType.DESCRIPTION, locale.getLanguage()).orElse("");
        return EventUtil.getIcalForEvent(event, category, description).orElse(null);
    };
}

From source file:eu.trentorise.smartcampus.permissionprovider.auth.internal.RegistrationController.java

/**
 * Register the user and redirect to the 'registersuccess' page
 * @param model/*from  w  w w .  j av a2s  . c  om*/
 * @param reg
 * @param result
 * @param req
 * @return
 */
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Model model, @ModelAttribute("reg") @Valid RegistrationBean reg, BindingResult result,
        HttpServletRequest req) {
    if (result.hasErrors()) {
        return "registration/register";
    }
    try {
        Locale locale = LocaleContextHolder.getLocale();
        manager.register(reg.getName(), reg.getSurname(), reg.getEmail(), reg.getPassword(),
                locale.getLanguage());
        return "registration/regsuccess";
    } catch (RegistrationException e) {
        model.addAttribute("error", e.getClass().getSimpleName());
        return "registration/register";
    } catch (Exception e) {
        e.printStackTrace();
        model.addAttribute("error", RegistrationException.class.getSimpleName());
        return "registration/register";
    }
}

From source file:com.phonemetra.turbo.lockclock.weather.OpenWeatherMapProvider.java

private String getLanguageCode() {
    Locale locale = mContext.getResources().getConfiguration().locale;
    String selector = locale.getLanguage() + "-" + locale.getCountry();

    for (Map.Entry<String, String> entry : LANGUAGE_CODE_MAPPING.entrySet()) {
        if (selector.startsWith(entry.getKey())) {
            return entry.getValue();
        }//from w  w w .  j  av a 2s . c o m
    }

    return "en";
}

From source file:fr.free.movierenamer.scrapper.impl.movie.TMDbScrapper.java

@Override
protected List<Movie> searchMedia(String query, Locale language) throws Exception {
    URL searchUrl = new URL("http", apiHost, "/" + version + "/search/movie" + "?api_key=" + apikey
            + "&language=" + language.getLanguage() + "&query=" + URIRequest.encode(query));
    return searchMedia(searchUrl, language);
}

From source file:com.bdaum.zoom.gps.naming.google.internal.GoogleGeonamingService.java

public WaypointArea[] findLocation(String address)
        throws IOException, WebServiceException, SAXException, ParserConfigurationException {
    List<WaypointArea> pnts = new ArrayList<WaypointArea>();
    Locale locale = Locale.getDefault();
    try (InputStream in = openGoogleService(NLS.bind(
            "https://maps.googleapis.com/maps/api/geocode/xml?address={0}&region={1}&language={2}", //$NON-NLS-1$
            new Object[] { URLEncoder.encode(address, "UTF-8"), locale.getCountry(), locale.getLanguage() }))) { //$NON-NLS-1$
        new GoogleGeoCodeParser(in).parse(pnts);
    } catch (DoneParsingException e) {
        // everything okay
    }/*w w  w .  j  av  a2 s.  c o m*/
    return pnts.toArray(new WaypointArea[pnts.size()]);
}

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

/**
 * statusId permalink page request.//from  w w w  . j  av  a 2 s . com
 * expected http request is '/tweet/username/1234567890.html'
 */
@RequestMapping(value = "/tweet/{userName}/{statusId}.html", method = RequestMethod.GET)
public String doTweetPermalink(@PathVariable String userName, @PathVariable String statusId,
        @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) {
    LOG.debug("called.");
    try {
        // TODO: debug
        LOG.debug("userName: " + userName);
        LOG.debug("statusId: " + statusId);

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

        // get the form.
        TweetForm tweetForm = getForm(userId, screenName, locale, responseListMode, userListName);

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

        // get the service object.
        PermalinkService permalinkService = (PermalinkService) context.getBean(PERMALINK_SERVICE_BEAN_ID);

        // get the tweet.
        TweetDto tweetDto = permalinkService.getTweetByStatusId(Long.valueOf(statusId));
        LOG.debug("tweetDto statusId: " + tweetDto.getStatusId());

        // map the object.
        List<TweetModel> tweetModelList = new ArrayList<TweetModel>();
        TweetModel tweetModel = context.getBean(TweetModel.class);
        // map the dto-object to the model-object.
        mapper.map(tweetDto, tweetModel);
        tweetModelList.add(tweetModel);

        // set the list-object to the model. 
        model.addAttribute(tweetModelList);
        model.addAttribute("statusId", tweetModel.getStatusId());

        if (isValidParameterOfGet(oauthToken, oauthTokenSecret, userId, screenName)) {
            // get the profile.
            ProfileModel profileModel = getProfile(oauthToken, oauthTokenSecret, responseListMode, userListName,
                    screenName);

            // set the profile model.
            model.addAttribute(profileModel);
        }

        // return view name.
        return "permalink";

    } catch (Exception e) {
        LOG.fatal(e.getMessage());
        return "error";
    }
}

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

/**
 * word permalink page request./*from   w  ww.  ja  v  a2  s  .  co m*/
 * expected http request is '/tweet/username/word.html'
 */
@RequestMapping(value = "/word/{userName}/{word}.html", method = RequestMethod.GET)
public String doWordPermalink(@PathVariable String userName, @PathVariable String word,
        @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) {
    LOG.debug("called.");
    try {
        // TODO: debug
        LOG.debug("userName: " + userName);
        LOG.debug("word: " + word);

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

        // get the form.
        TweetForm tweetForm = getForm(userId, screenName, locale, responseListMode, userListName);

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

        // get the service object.
        PermalinkService permalinkService = (PermalinkService) context.getBean(PERMALINK_SERVICE_BEAN_ID);

        // get the tweet.
        List<TweetDto> tweetDtoList = permalinkService.getTweetListByWord(userName, word);
        LOG.debug("tweetDtoList size: " + tweetDtoList.size());

        // map the object.
        List<TweetModel> tweetModelList = new ArrayList<TweetModel>();
        for (TweetDto tweetDto : tweetDtoList) {
            TweetModel tweetModel = context.getBean(TweetModel.class);
            // map the dto-object to the model-object.
            mapper.map(tweetDto, tweetModel);
            tweetModelList.add(tweetModel);
        }

        // set the list-object to the model. 
        model.addAttribute(tweetModelList);
        model.addAttribute(word);

        if (isValidParameterOfGet(oauthToken, oauthTokenSecret, userId, screenName)) {
            // get the profile.
            ProfileModel profileModel = getProfile(oauthToken, oauthTokenSecret, responseListMode, userListName,
                    screenName);

            // set the profile model.
            model.addAttribute(profileModel);
        }

        // return view name.
        return "permalink";

    } catch (Exception e) {
        LOG.fatal(e.getMessage());
        return "error";
    }
}

From source file:com.erudika.para.i18n.LanguageUtils.java

/**
 * Default constructor.//from  www  .j av  a2s  .c  o m
 * @param search a core search instance
 * @param dao a core persistence instance
 */
@Inject
public LanguageUtils(Search search, DAO dao) {
    this.search = search;
    this.dao = dao;
    for (Object loc : LocaleUtils.availableLocaleList()) {
        Locale locale = new Locale(((Locale) loc).getLanguage());
        String locstr = locale.getLanguage();
        if (!StringUtils.isBlank(locstr)) {
            allLocales.put(locstr, locale);
            progressMap.put(locstr, 0);
        }
    }
}