List of usage examples for java.util Locale getLanguage
public String getLanguage()
From source file:com.android.quicksearchbox.google.GoogleSuggestClient.java
/** * Queries for a given search term and returns a cursor containing * suggestions ordered by best match.//w w w. j ava 2 s .c o m */ private SourceResult query(String query) { 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); } 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 GoogleSuggestCursor(this, query, 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:org.alfresco.grid.WebDriverFactory.java
/** * Converts locale to string. /* ww w.j a v a 2 s.c o m*/ * @param locale {@link Locale} locale * @return String locale in string */ private String formatLocale(Locale locale) { if (locale == null) { throw new IllegalArgumentException("Locale value is required"); } return locale.getCountry().isEmpty() ? locale.getLanguage() : locale.getLanguage() + "-" + locale.getCountry().toLowerCase(); }
From source file:com.cleanwiz.applock.ui.activity.SplashActivity.java
public void checkVersion() { requestQueue = Volley.newRequestQueue(this); String url = "http://www.toolwiz.com/android/checkfiles.php"; final String oldVersionString = getApplicationVersion(); Locale locale = getResources().getConfiguration().locale; String language = locale.getLanguage(); Uri.Builder builder = Uri.parse(url).buildUpon(); builder.appendQueryParameter("uid", AndroidUtil.getUdid(this)); builder.appendQueryParameter("version", oldVersionString); builder.appendQueryParameter("action", "checkfile"); builder.appendQueryParameter("app", "locklocker"); builder.appendQueryParameter("language", language); jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, builder.toString(), null, new Response.Listener<JSONObject>() { @SuppressLint("NewApi") @Override//from w w w. j a v a 2s. com public void onResponse(JSONObject arg0) { // TODO Auto-generated method stub LogUtil.e("colin", "success"); if (arg0.has("status")) { try { String status = arg0.getString("status"); if (Integer.valueOf(status) == 1) { JSONObject msgJsonObject = arg0.getJSONObject("msg"); double version = msgJsonObject.getDouble("version"); downLoadFileUrl = msgJsonObject.getString("url"); fileSize = msgJsonObject.getString("size"); if (Double.valueOf(oldVersionString) < version && !downLoadFileUrl.isEmpty()) { // ??? String intro = msgJsonObject.getString("intro"); LogUtil.e("colin", "........" + intro); showUpdateDialog(intro); } else { LogUtil.e("colin", "check update status is same not to update"); SplashHandler handler = new SplashHandler(); Message msg = new Message(); msg.what = CHECKVERSION_EOOR; handler.sendMessage(msg); } } else { LogUtil.e("colin", "check update status is error"); SplashHandler handler = new SplashHandler(); Message msg = new Message(); msg.what = CHECKVERSION_EOOR; handler.sendMessage(msg); } } catch (JSONException e) { // TODO Auto-generated catch block SplashHandler handler = new SplashHandler(); Message msg = new Message(); msg.what = CHECKVERSION_EOOR; handler.sendMessage(msg); e.printStackTrace(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError arg0) { // TODO Auto-generated method stub SplashHandler handler = new SplashHandler(); Message msg = new Message(); msg.what = CHECKVERSION_EOOR; handler.sendMessage(msg); } }); requestQueue.add(jsonObjectRequest); }
From source file:com.salesmanager.central.catalog.ProductReviewAction.java
public String reviewProduct() { super.setPageTitle("label.product.review"); try {// www. j a v a2 s . c o m if (this.getProduct() == null) { return "unauthorized"; } Locale locale = super.getLocale(); super.setSize(size); super.setPageStartNumber(); SearchReviewCriteria criteria = new SearchReviewCriteria(); criteria.setProductId(this.getProduct().getProductId()); criteria.setLanguageId(LanguageUtil.getLanguageNumberCode(locale.getLanguage())); criteria.setQuantity(this.getSize()); criteria.setStartindex(this.getPageCriteriaIndex()); CatalogService cservice = (CatalogService) ServiceFactory.getService(ServiceFactory.CatalogService); SearchReviewResponse response = cservice.searchProductReviewsByProduct(criteria); reviews = response.getReviews(); super.setListingCount(response.getCount()); super.setRealCount(reviews.size()); super.setPageElements(); LocaleUtil.setLocaleToEntityCollection(reviews, super.getLocale()); } catch (Exception e) { log.error(e); } return SUCCESS; }
From source file:fr.free.movierenamer.scrapper.impl.movie.TMDbScrapper.java
@Override protected MovieInfo fetchMediaInfo(Movie movie, Locale language) throws Exception { URL searchUrl = new URL("http", apiHost, "/" + version + "/movie/" + movie.getId() + "?api_key=" + apikey + "&language=" + language.getLanguage() + "&append_to_response=releases,keywords"); JSONObject json = URIRequest.getJsonDocument(searchUrl.toURI()); Map<MovieProperty, String> fields = new EnumMap<MovieProperty, String>(MovieProperty.class); Map<MovieInfo.MovieMultipleProperty, List<?>> multipleFields = new EnumMap<MovieInfo.MovieMultipleProperty, List<?>>( MovieInfo.MovieMultipleProperty.class); fields.put(MovieProperty.title, JSONUtils.selectString("title", json)); fields.put(MovieProperty.rating, JSONUtils.selectString("vote_average", json)); fields.put(MovieProperty.votes, JSONUtils.selectString("vote_count", json)); fields.put(MovieProperty.originalTitle, JSONUtils.selectString("original_title", json)); fields.put(MovieProperty.releasedDate, JSONUtils.selectString("release_date", json)); fields.put(MovieProperty.overview, JSONUtils.selectString("overview", json)); fields.put(MovieProperty.runtime, JSONUtils.selectString("runtime", json)); fields.put(MovieProperty.budget, JSONUtils.selectString("budget", json)); fields.put(MovieProperty.tagline, JSONUtils.selectString("tagline", json)); JSONObject collection = JSONUtils.selectObject("belongs_to_collection", json); fields.put(MovieProperty.collection, collection != null ? JSONUtils.selectString("name", collection) : ""); List<IdInfo> ids = new ArrayList<IdInfo>(); ids.add(new IdInfo(JSONUtils.selectInteger("id", json), ScrapperUtils.AvailableApiIds.TMDB)); String imdbId = JSONUtils.selectString("imdb_id", json); if (imdbId != null) { ids.add(new IdInfo(Integer.parseInt(imdbId.substring(2)), ScrapperUtils.AvailableApiIds.IMDB)); }//from w ww. jav a2 s .c om for (JSONObject jsonObj : JSONUtils.selectList("countries", json)) { if (JSONUtils.selectString("iso_3166_1", jsonObj).equals("US")) { fields.put(MovieProperty.certificationCode, JSONUtils.selectString("certification", jsonObj)); break; } } List<String> genres = new ArrayList<String>(); for (JSONObject jsonObj : JSONUtils.selectList("genres", json)) { genres.add(JSONUtils.selectString("name", jsonObj)); } List<Locale> countries = new ArrayList<Locale>(); for (JSONObject jsonObj : JSONUtils.selectList("production_countries", json)) { countries.add(new Locale("", JSONUtils.selectString("iso_3166_1", jsonObj))); } List<String> studios = new ArrayList<String>(); for (JSONObject jsonObj : JSONUtils.selectList("production_companies", json)) { studios.add(JSONUtils.selectString("name", jsonObj)); } List<String> tags = new ArrayList<String>(); JSONObject keywords = JSONUtils.selectObject("keywords", json); if (keywords != null) { for (JSONObject jsonObj : JSONUtils.selectList("keywords", keywords)) { tags.add(JSONUtils.selectString("name", jsonObj)); } } multipleFields.put(MovieInfo.MovieMultipleProperty.ids, ids); multipleFields.put(MovieInfo.MovieMultipleProperty.studios, studios); multipleFields.put(MovieInfo.MovieMultipleProperty.tags, tags); multipleFields.put(MovieInfo.MovieMultipleProperty.countries, countries); multipleFields.put(MovieInfo.MovieMultipleProperty.genres, genres); MovieInfo movieInfo = new MovieInfo(fields, multipleFields); return movieInfo; }
From source file:com.doculibre.constellio.wicket.panels.admin.user.AddEditUserPanel.java
public AddEditUserPanel(String id, ConstellioUser user) { super(id, true); this.userModel = new ReloadableEntityModel<ConstellioUser>(user); Form form = getForm();/*from w w w. j a v a 2 s. c om*/ form.setModel(new CompoundPropertyModel(userModel)); TextField username = new RequiredTextField("username"); form.add(username); password = new PasswordTextField("password", new Model()); form.add(password); password.setRequired(user.getId() == null); PasswordTextField passwordConfirmation = new PasswordTextField("passwordConfirmation", new Model()); form.add(passwordConfirmation); passwordConfirmation.setRequired(user.getId() == null); TextField firstName = new RequiredTextField("firstName"); form.add(firstName); TextField lastName = new RequiredTextField("lastName"); form.add(lastName); IModel languagesModel = new LoadableDetachableModel() { @Override protected Object load() { List<String> supportedLanguages = new ArrayList<String>(); List<Locale> supportedLocales = ConstellioSpringUtils.getSupportedLocales(); for (Locale supportedLocale : supportedLocales) { supportedLanguages.add(supportedLocale.getLanguage()); } return supportedLanguages; } }; IChoiceRenderer languagesRenderer = new ChoiceRenderer() { @Override public Object getDisplayValue(Object object) { return new Locale((String) object).getDisplayLanguage(getLocale()); } }; DropDownChoice languageField = new DropDownChoice("localeCode", languagesModel, languagesRenderer); form.add(languageField); languageField.setRequired(true); languageField.setNullValid(false); CheckBox admin = new CheckBox("admin"); form.add(admin); CheckBox collaborator = new CheckBox("collaborator"); form.add(collaborator); form.add(new EqualPasswordInputValidator(password, passwordConfirmation)); visibleCredentialGroupsModel = new LoadableDetachableModel() { @Override protected Object load() { Set<CredentialGroup> visibleCredentialGroups = new HashSet<CredentialGroup>(); ConstellioUser user = userModel.getObject(); RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices(); FederationServices federationServices = ConstellioSpringUtils.getFederationServices(); for (RecordCollection collection : collectionServices.list()) { if (user.hasSearchPermission(collection)) { Collection<CredentialGroup> searchCredentialGroups; if (collection.isFederationOwner()) { searchCredentialGroups = federationServices.listCredentialGroups(collection); } else { searchCredentialGroups = collection.getCredentialGroups(); } for (CredentialGroup credentialGroup : searchCredentialGroups) { visibleCredentialGroups.add(credentialGroup); } } } return new ArrayList<CredentialGroup>(visibleCredentialGroups); } }; credentialGroupsListView = new ListView("credentialGroups", visibleCredentialGroupsModel) { @Override protected void populateItem(ListItem item) { CredentialGroup credentialGroup = (CredentialGroup) item.getModelObject(); RecordCollection collection = credentialGroup.getRecordCollection(); Locale displayLocale = collection.getDisplayLocale(getLocale()); ConstellioUser user = userModel.getObject(); String credentialGroupLabel = credentialGroup.getName() + " (" + collection.getTitle(displayLocale) + ")"; EntityModel<UserCredentials> userCredentialsModel = userCredentialsModelMap .get(credentialGroup.getId()); if (userCredentialsModel == null) { UserCredentials userCredentials = user.getUserCredentials(credentialGroup); if (userCredentials == null) { userCredentials = new UserCredentials(); } userCredentialsModel = new EntityModel<UserCredentials>(userCredentials); userCredentialsModelMap.put(credentialGroup.getId(), userCredentialsModel); } final TextField usernameField = new TextField("username", new PropertyModel(userCredentialsModel, "username")); final EntityModel<UserCredentials> finalUserCredentialsModel = userCredentialsModel; PasswordTextField encrypedPasswordField = new PasswordTextField("encryptedPassword", new Model() { @Override public Object getObject() { UserCredentials userCredentials = finalUserCredentialsModel.getObject(); return EncryptionUtils.decrypt(userCredentials.getEncryptedPassword()); } @Override public void setObject(Object object) { UserCredentials userCredentials = finalUserCredentialsModel.getObject(); String encryptedPassword = EncryptionUtils.encrypt((String) object); if (encryptedPassword != null || StringUtils.isEmpty(usernameField.getInput())) { userCredentials.setEncryptedPassword(encryptedPassword); } } }); encrypedPasswordField.setRequired(false); TextField domainField = new TextField("domain", new PropertyModel(userCredentialsModel, "domain")); item.add(new Label("name", credentialGroupLabel)); item.add(usernameField); item.add(encrypedPasswordField); item.add(domainField); } @SuppressWarnings("unchecked") @Override public boolean isVisible() { boolean visible = super.isVisible(); if (visible) { List<CredentialGroup> credentialGroups = (List<CredentialGroup>) visibleCredentialGroupsModel .getObject(); visible = !credentialGroups.isEmpty(); } return visible; } }; form.add(credentialGroupsListView); }
From source file:com.puppycrawl.tools.checkstyle.TreeWalkerTest.java
@Test public void testCacheFile() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); final DefaultConfiguration treeWalkerConfig = createCheckConfig(TreeWalker.class); treeWalkerConfig.addAttribute("cacheFile", temporaryFolder.newFile().getPath()); treeWalkerConfig.addChild(checkConfig); final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration"); checkerConfig.addAttribute("charset", "UTF-8"); checkerConfig.addChild(treeWalkerConfig); final Checker checker = new Checker(); final Locale locale = Locale.ROOT; checker.setLocaleCountry(locale.getCountry()); checker.setLocaleLanguage(locale.getLanguage()); checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); checker.configure(checkerConfig);/*from w w w . j a v a2s .co m*/ checker.addListener(new BriefLogger(stream)); final String pathToEmptyFile = temporaryFolder.newFile("file.java").getPath(); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verify(checker, pathToEmptyFile, pathToEmptyFile, expected); // one more time to reuse cache verify(checker, pathToEmptyFile, pathToEmptyFile, expected); }
From source file:com.erudika.scoold.controllers.SigninController.java
@ResponseBody @GetMapping("/scripts/globals.js") public ResponseEntity<String> globals(HttpServletRequest req, HttpServletResponse res) { res.setContentType("text/javascript"); StringBuilder sb = new StringBuilder(); sb.append("APPID = \"").append(Config.getConfigParam("access_key", "app:scoold").substring(4)) .append("\"; "); sb.append("ENDPOINT = \"").append(pc.getEndpoint()).append("\"; "); sb.append("CONTEXT_PATH = \"").append(CONTEXT_PATH).append("\"; "); sb.append("CSRF_COOKIE = \"").append(CSRF_COOKIE).append("\"; "); sb.append("FB_APP_ID = \"").append(Config.FB_APP_ID).append("\"; "); sb.append("GOOGLE_CLIENT_ID = \"").append(Config.getConfigParam("google_client_id", "")).append("\"; "); sb.append("GOOGLE_ANALYTICS_ID = \"").append(Config.getConfigParam("google_analytics_id", "")) .append("\"; "); sb.append("GITHUB_APP_ID = \"").append(Config.GITHUB_APP_ID).append("\"; "); sb.append("LINKEDIN_APP_ID = \"").append(Config.LINKEDIN_APP_ID).append("\"; "); sb.append("TWITTER_APP_ID = \"").append(Config.TWITTER_APP_ID).append("\"; "); sb.append("MICROSOFT_APP_ID = \"").append(Config.MICROSOFT_APP_ID).append("\"; "); sb.append("OAUTH2_ENDPOINT = \"").append(Config.getConfigParam("security.oauth.authz_url", "")) .append("\"; "); sb.append("OAUTH2_APP_ID = \"").append(Config.getConfigParam("oa2_app_id", "")).append("\"; "); sb.append("OAUTH2_SCOPE = \"").append(Config.getConfigParam("security.oauth.scope", "")).append("\"; "); Locale currentLocale = utils.getCurrentLocale(utils.getLanguageCode(req), req); sb.append("RTL_ENABLED = ").append(utils.isLanguageRTL(currentLocale.getLanguage())).append("; "); String result = sb.toString(); return ResponseEntity.ok().cacheControl(CacheControl.maxAge(1, TimeUnit.HOURS)).eTag(Utils.md5(result)) .body(result);/*from ww w .j av a 2s . co m*/ }
From source file:com.puppycrawl.tools.checkstyle.TreeWalkerTest.java
@Test public void testCacheFileChangeInConfig() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); final DefaultConfiguration treeWalkerConfig = createCheckConfig(TreeWalker.class); treeWalkerConfig.addAttribute("cacheFile", temporaryFolder.newFile().getPath()); treeWalkerConfig.addChild(checkConfig); final DefaultConfiguration checkerConfig = new DefaultConfiguration("configuration"); checkerConfig.addAttribute("charset", "UTF-8"); checkerConfig.addChild(treeWalkerConfig); Checker checker = new Checker(); final Locale locale = Locale.ROOT; checker.setLocaleCountry(locale.getCountry()); checker.setLocaleLanguage(locale.getLanguage()); checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); checker.configure(checkerConfig);/*www.java 2 s. co m*/ checker.addListener(new BriefLogger(stream)); final String pathToEmptyFile = temporaryFolder.newFile("file.java").getPath(); final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; verify(checker, pathToEmptyFile, pathToEmptyFile, expected); // update Checker config //checker.destroy(); //checker.configure(checkerConfig); Checker otherChecker = new Checker(); otherChecker.setLocaleCountry(locale.getCountry()); otherChecker.setLocaleLanguage(locale.getLanguage()); otherChecker.setModuleClassLoader(Thread.currentThread().getContextClassLoader()); otherChecker.configure(checkerConfig); otherChecker.addListener(new BriefLogger(stream)); // here is diff with previous checker checkerConfig.addAttribute("fileExtensions", "java,javax"); // one more time on updated config verify(otherChecker, pathToEmptyFile, pathToEmptyFile, expected); }