List of usage examples for org.json JSONObject getJSONArray
public JSONArray getJSONArray(String key) throws JSONException
From source file:com.ledger.android.u2f.bridge.MainActivity.java
private U2FContext parseU2FContextRegister(JSONObject json) { try {//from ww w. ja v a 2 s. co m byte[] challenge = null; String appId = json.getString(TAG_JSON_APPID); int requestId = json.getInt(TAG_JSON_REQUESTID); JSONArray array = json.getJSONArray(TAG_JSON_REGISTER_REQUESTS); for (int i = 0; i < array.length(); i++) { // TODO : only handle USB transport if several are present JSONObject registerItem = array.getJSONObject(i); if (!registerItem.getString(TAG_JSON_VERSION).equals(VERSION_U2F_V2)) { Log.e(TAG, "Invalid register version"); return null; } challenge = Base64.decode(registerItem.getString(TAG_JSON_CHALLENGE), Base64.URL_SAFE); } return new U2FContext(appId, challenge, null, requestId, false); } catch (JSONException e) { Log.e(TAG, "Error decoding request"); return null; } }
From source file:com.jellymold.boss.ImageSearch.java
protected void parseResults(JSONObject jobj) throws JSONException { if (jobj != null) { setResponseCode(jobj.getInt("responsecode")); if (jobj.has("nextpage")) setNextPage(jobj.getString("nextpage")); if (jobj.has("prevpage")) setPrevPage(jobj.getString("prevpage")); setTotalResults(jobj.getLong("totalhits")); long count = jobj.getLong("count"); setPagerCount(count);/* w w w. j a v a 2 s . c o m*/ setPagerStart(jobj.getLong("start")); this.setResults(new ArrayList<ImageSearchResult>((int) count)); if (jobj.has("resultset_images")) { JSONArray res = jobj.getJSONArray("resultset_images"); for (int i = 0; i < res.length(); i++) { JSONObject thisResult = res.getJSONObject(i); ImageSearchResult imageSearchResult = new ImageSearchResult(); imageSearchResult.setDescription(thisResult.getString("abstract")); imageSearchResult.setClickUrl(thisResult.getString("clickurl")); imageSearchResult.setDate(thisResult.getString("date")); imageSearchResult.setTitle(thisResult.getString("title")); imageSearchResult.setUrl(thisResult.getString("url")); imageSearchResult.setSize(thisResult.getLong("size")); imageSearchResult.setFilename(thisResult.getString("filename")); imageSearchResult.setFormat(thisResult.getString("format")); imageSearchResult.setHeight(thisResult.getLong("height")); imageSearchResult.setMimeType(thisResult.getString("mimetype")); imageSearchResult.setRefererClickUrl(thisResult.getString("refererclickurl")); imageSearchResult.setRefererUrl(thisResult.getString("refererurl")); imageSearchResult.setThumbnailHeight(thisResult.getLong("thumbnail_height")); imageSearchResult.setThumbnailWidth(thisResult.getLong("thumbnail_width")); imageSearchResult.setThumbnailUrl(thisResult.getString("thumbnail_url")); this.getResults().add(imageSearchResult); } } } }
From source file:edu.txstate.dmlab.clusteringwiki.sources.AbsSearchResultCol.java
/** * Creates a collection of results from JSON response * Note that firstPosition must be set before adding * results as result ids depend on that value. * @param res/*from w w w . j a va2 s. c o m*/ */ public AbsSearchResultCol(JSONObject res) { if (res == null) return; JSONObject search = null; try { search = res.getJSONObject("search"); JSONArray errors = search.getJSONArray("errors"); if (errors != null && errors.length() > 0) { for (int i = 0; i < errors.length(); i++) { String error = errors.getString(i); addError("AbS API exception: " + error); } return; } } catch (JSONException e) { addError("AbS API exception: " + e.getMessage()); } try { totalResults = search.getInt("totalResults"); firstPosition = search.getInt("firstPosition"); JSONArray j = search.getJSONArray("results"); returnedCount = j.length(); for (int i = 0; i < j.length(); i++) { ICWSearchResult r = new AbsSearchResult(j.getJSONObject(i)); r.setIndex(i); addResult(r); } } catch (JSONException e) { addError("Could not retrieve AbS results: " + e.getMessage()); } }
From source file:test.Testing.java
public static void main(String[] args) throws Exception { //////////////////////////////////////////////////////////////////////////////////////////// // Setup/* w w w .j ava 2 s .co m*/ //////////////////////////////////////////////////////////////////////////////////////////// String key = "CHANGEME: YOUR_API_KEY"; String secret = "CHANGEME: YOUR_API_SECRET"; String version = "preview1"; String practiceid = "000000"; APIConnection api = new APIConnection(version, key, secret, practiceid); api.authenticate(); // If you want to set the practice ID after construction, this is how. // api.setPracticeID("000000"); //////////////////////////////////////////////////////////////////////////////////////////// // GET without parameters //////////////////////////////////////////////////////////////////////////////////////////// JSONArray customfields = (JSONArray) api.GET("/customfields"); System.out.println("Custom fields:"); for (int i = 0; i < customfields.length(); i++) { System.out.println("\t" + customfields.getJSONObject(i).get("name")); } //////////////////////////////////////////////////////////////////////////////////////////// // GET with parameters //////////////////////////////////////////////////////////////////////////////////////////// SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); Calendar today = Calendar.getInstance(); Calendar nextyear = Calendar.getInstance(); nextyear.roll(Calendar.YEAR, 1); Map<String, String> search = new HashMap<String, String>(); search.put("departmentid", "82"); search.put("startdate", format.format(today.getTime())); search.put("enddate", format.format(nextyear.getTime())); search.put("appointmenttypeid", "2"); search.put("limit", "1"); JSONObject open_appts = (JSONObject) api.GET("/appointments/open", search); System.out.println(open_appts.toString()); JSONObject appt = open_appts.getJSONArray("appointments").getJSONObject(0); System.out.println("Open appointment:"); System.out.println(appt.toString()); // add keys to make appt usable for scheduling appt.put("appointmenttime", appt.get("starttime")); appt.put("appointmentdate", appt.get("date")); //////////////////////////////////////////////////////////////////////////////////////////// // POST with parameters //////////////////////////////////////////////////////////////////////////////////////////// Map<String, String> patient_info = new HashMap<String, String>(); patient_info.put("lastname", "Foo"); patient_info.put("firstname", "Jason"); patient_info.put("address1", "123 Any Street"); patient_info.put("city", "Cambridge"); patient_info.put("countrycode3166", "US"); patient_info.put("departmentid", "1"); patient_info.put("dob", "6/18/1987"); patient_info.put("language6392code", "declined"); patient_info.put("maritalstatus", "S"); patient_info.put("race", "declined"); patient_info.put("sex", "M"); patient_info.put("ssn", "*****1234"); patient_info.put("zip", "02139"); JSONArray new_patient = (JSONArray) api.POST("/patients", patient_info); String new_patient_id = new_patient.getJSONObject(0).getString("patientid"); System.out.println("New patient id:"); System.out.println(new_patient_id); //////////////////////////////////////////////////////////////////////////////////////////// // PUT with parameters //////////////////////////////////////////////////////////////////////////////////////////// Map<String, String> appointment_info = new HashMap<String, String>(); appointment_info.put("appointmenttypeid", "82"); appointment_info.put("departmentid", "1"); appointment_info.put("patientid", new_patient_id); JSONArray booked = (JSONArray) api.PUT("/appointments/" + appt.getString("appointmentid"), appointment_info); System.out.println("Booked:"); System.out.println(booked.toString()); //////////////////////////////////////////////////////////////////////////////////////////// // POST without parameters //////////////////////////////////////////////////////////////////////////////////////////// JSONObject checked_in = (JSONObject) api .POST("/appointments/" + appt.getString("appointmentid") + "/checkin"); System.out.println("Check-in:"); System.out.println(checked_in.toString()); //////////////////////////////////////////////////////////////////////////////////////////// // DELETE with parameters //////////////////////////////////////////////////////////////////////////////////////////// Map<String, String> delete_params = new HashMap<String, String>(); delete_params.put("departmentid", "1"); JSONObject chart_alert = (JSONObject) api.DELETE("/patients/" + new_patient_id + "/chartalert", delete_params); System.out.println("Removed chart alert:"); System.out.println(chart_alert.toString()); //////////////////////////////////////////////////////////////////////////////////////////// // DELETE without parameters //////////////////////////////////////////////////////////////////////////////////////////// JSONObject photo = (JSONObject) api.DELETE("/patients/" + new_patient_id + "/photo"); System.out.println("Removed photo:"); System.out.println(photo.toString()); //////////////////////////////////////////////////////////////////////////////////////////// // There are no PUTs without parameters //////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// // Error conditions //////////////////////////////////////////////////////////////////////////////////////////// JSONObject bad_path = (JSONObject) api.GET("/nothing/at/this/path"); System.out.println("GET /nothing/at/this/path:"); System.out.println(bad_path.toString()); JSONObject missing_parameters = (JSONObject) api.GET("/appointments/open"); System.out.println("Missing parameters:"); System.out.println(missing_parameters.toString()); //////////////////////////////////////////////////////////////////////////////////////////// // Testing token refresh // // NOTE: this test takes an hour, so it's disabled by default. Change false to true to run. //////////////////////////////////////////////////////////////////////////////////////////// if (false) { String old_token = api.getToken(); System.out.println("Old token: " + old_token); JSONObject before_refresh = (JSONObject) api.GET("/departments"); // Wait 3600 seconds = 1 hour for token to expire. try { Thread.sleep(3600 * 1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } JSONObject after_refresh = (JSONObject) api.GET("/departments"); System.out.println("New token: " + api.getToken()); } }
From source file:it.moondroid.chatbot.alice.Sraix.java
public static String sraixPannous(String input, String hint, Chat chatSession) { try {//w ww . j av a 2 s . c o m String rawInput = input; if (hint == null) hint = MagicStrings.sraix_no_hint; input = " " + input + " "; input = input.replace(" point ", "."); input = input.replace(" rparen ", ")"); input = input.replace(" lparen ", "("); input = input.replace(" slash ", "/"); input = input.replace(" star ", "*"); input = input.replace(" dash ", "-"); // input = chatSession.bot.preProcessor.denormalize(input); input = input.trim(); input = input.replace(" ", "+"); int offset = CalendarUtils.timeZoneOffset(); //System.out.println("OFFSET = "+offset); String locationString = ""; if (chatSession.locationKnown) { locationString = "&location=" + chatSession.latitude + "," + chatSession.longitude; } // https://weannie.pannous.com/api?input=when+is+daylight+savings+time+in+the+us&locale=en_US&login=pandorabots&ip=169.254.178.212&botid=0&key=CKNgaaVLvNcLhDupiJ1R8vtPzHzWc8mhIQDFSYWj&exclude=Dialogues,ChatBot&out=json // exclude=Dialogues,ChatBot&out=json&clientFeatures=show-images,reminder,say&debug=true String url = "https://ask.pannous.com/api?input=" + input + "&locale=en_US&timeZone=" + offset + locationString + "&login=" + MagicStrings.pannous_login + "&ip=" + NetworkUtils.localIPAddress() + "&botid=0&key=" + MagicStrings.pannous_api_key + "&exclude=Dialogues,ChatBot&out=json&clientFeatures=show-images,reminder,say&debug=true"; MagicBooleans.trace("in Sraix.sraixPannous, url: '" + url + "'"); String page = NetworkUtils.responseContent(url); //MagicBooleans.trace("in Sraix.sraixPannous, page: " + page); String text = ""; String imgRef = ""; String urlRef = ""; if (page == null || page.length() == 0) { text = MagicStrings.sraix_failed; } else { JSONArray outputJson = new JSONObject(page).getJSONArray("output"); //MagicBooleans.trace("in Sraix.sraixPannous, outputJson class: " + outputJson.getClass() + ", outputJson: " + outputJson); if (outputJson.length() == 0) { text = MagicStrings.sraix_failed; } else { JSONObject firstHandler = outputJson.getJSONObject(0); //MagicBooleans.trace("in Sraix.sraixPannous, firstHandler class: " + firstHandler.getClass() + ", firstHandler: " + firstHandler); JSONObject actions = firstHandler.getJSONObject("actions"); //MagicBooleans.trace("in Sraix.sraixPannous, actions class: " + actions.getClass() + ", actions: " + actions); if (actions.has("reminder")) { //MagicBooleans.trace("in Sraix.sraixPannous, found reminder action"); Object obj = actions.get("reminder"); if (obj instanceof JSONObject) { if (MagicBooleans.trace_mode) System.out.println("Found JSON Object"); JSONObject sObj = (JSONObject) obj; String date = sObj.getString("date"); date = date.substring(0, "2012-10-24T14:32".length()); if (MagicBooleans.trace_mode) System.out.println("date=" + date); String duration = sObj.getString("duration"); if (MagicBooleans.trace_mode) System.out.println("duration=" + duration); Pattern datePattern = Pattern.compile("(.*)-(.*)-(.*)T(.*):(.*)"); Matcher m = datePattern.matcher(date); String year = "", month = "", day = "", hour = "", minute = ""; if (m.matches()) { year = m.group(1); month = String.valueOf(Integer.parseInt(m.group(2)) - 1); day = m.group(3); hour = m.group(4); minute = m.group(5); text = "<year>" + year + "</year>" + "<month>" + month + "</month>" + "<day>" + day + "</day>" + "<hour>" + hour + "</hour>" + "<minute>" + minute + "</minute>" + "<duration>" + duration + "</duration>"; } else text = MagicStrings.schedule_error; } } else if (actions.has("say") && !hint.equals(MagicStrings.sraix_pic_hint) && !hint.equals(MagicStrings.sraix_shopping_hint)) { MagicBooleans.trace("in Sraix.sraixPannous, found say action"); Object obj = actions.get("say"); //MagicBooleans.trace("in Sraix.sraixPannous, obj class: " + obj.getClass()); //MagicBooleans.trace("in Sraix.sraixPannous, obj instanceof JSONObject: " + (obj instanceof JSONObject)); if (obj instanceof JSONObject) { JSONObject sObj = (JSONObject) obj; text = sObj.getString("text"); if (sObj.has("moreText")) { JSONArray arr = sObj.getJSONArray("moreText"); for (int i = 0; i < arr.length(); i++) { text += " " + arr.getString(i); } } } else { text = obj.toString(); } } if (actions.has("show") && !text.contains("Wolfram") && actions.getJSONObject("show").has("images")) { MagicBooleans.trace("in Sraix.sraixPannous, found show action"); JSONArray arr = actions.getJSONObject("show").getJSONArray("images"); int i = (int) (arr.length() * Math.random()); //for (int j = 0; j < arr.length(); j++) System.out.println(arr.getString(j)); imgRef = arr.getString(i); if (imgRef.startsWith("//")) imgRef = "http:" + imgRef; imgRef = "<a href=\"" + imgRef + "\"><img src=\"" + imgRef + "\"/></a>"; //System.out.println("IMAGE REF="+imgRef); } if (hint.equals(MagicStrings.sraix_shopping_hint) && actions.has("open") && actions.getJSONObject("open").has("url")) { urlRef = "<oob><url>" + actions.getJSONObject("open").getString("url") + "</oob></url>"; } } if (hint.equals(MagicStrings.sraix_event_hint) && !text.startsWith("<year>")) return MagicStrings.sraix_failed; else if (text.equals(MagicStrings.sraix_failed)) return AIMLProcessor.respond(MagicStrings.sraix_failed, "nothing", "nothing", chatSession); else { text = text.replace("'", "'"); text = text.replace("'", "'"); text = text.replaceAll("\\[(.*)\\]", ""); String[] sentences; sentences = text.split("\\. "); //System.out.println("Sraix: text has "+sentences.length+" sentences:"); String clippedPage = sentences[0]; for (int i = 1; i < sentences.length; i++) { if (clippedPage.length() < 500) clippedPage = clippedPage + ". " + sentences[i]; //System.out.println(i+". "+sentences[i]); } clippedPage = clippedPage + " " + imgRef + " " + urlRef; clippedPage = clippedPage.trim(); log(rawInput, clippedPage); return clippedPage; } } } catch (Exception ex) { ex.printStackTrace(); System.out.println("Sraix '" + input + "' failed"); } return MagicStrings.sraix_failed; }
From source file:org.b3log.solo.processor.util.Filler.java
/** * Fills articles in index.ftl./*w w w.j a va 2s .c om*/ * * @param dataModel data model * @param currentPageNum current page number * @param preference the specified preference * @throws ServiceException service exception */ public void fillIndexArticles(final Map<String, Object> dataModel, final int currentPageNum, final JSONObject preference) throws ServiceException { Stopwatchs.start("Fill Index Articles"); try { final int pageSize = preference.getInt(Preference.ARTICLE_LIST_DISPLAY_COUNT); final int windowSize = preference.getInt(Preference.ARTICLE_LIST_PAGINATION_WINDOW_SIZE); final JSONObject statistic = statisticQueryService.getStatistic(); final int publishedArticleCnt = statistic.getInt(Statistic.STATISTIC_PUBLISHED_ARTICLE_COUNT); final int pageCount = (int) Math.ceil((double) publishedArticleCnt / (double) pageSize); final Query query = new Query().setCurrentPageNum(currentPageNum).setPageSize(pageSize) .setPageCount(pageCount) .setFilter(new PropertyFilter(Article.ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, PUBLISHED)) .addSort(Article.ARTICLE_PUT_TOP, SortDirection.DESCENDING).index(Article.ARTICLE_PERMALINK); if (preference.getBoolean(Preference.ENABLE_ARTICLE_UPDATE_HINT)) { query.addSort(Article.ARTICLE_UPDATE_DATE, SortDirection.DESCENDING); } else { query.addSort(Article.ARTICLE_CREATE_DATE, SortDirection.DESCENDING); } final JSONObject result = articleRepository.get(query); final List<Integer> pageNums = Paginator.paginate(currentPageNum, pageSize, pageCount, windowSize); if (0 != pageNums.size()) { dataModel.put(Pagination.PAGINATION_FIRST_PAGE_NUM, pageNums.get(0)); dataModel.put(Pagination.PAGINATION_LAST_PAGE_NUM, pageNums.get(pageNums.size() - 1)); } dataModel.put(Pagination.PAGINATION_PAGE_COUNT, pageCount); dataModel.put(Pagination.PAGINATION_PAGE_NUMS, pageNums); final List<JSONObject> articles = org.b3log.latke.util.CollectionUtils .jsonArrayToList(result.getJSONArray(Keys.RESULTS)); final boolean hasMultipleUsers = Users.getInstance().hasMultipleUsers(); if (hasMultipleUsers) { setArticlesExProperties(articles, preference); } else { if (!articles.isEmpty()) { final JSONObject author = articleUtils.getAuthor(articles.get(0)); setArticlesExProperties(articles, author, preference); } } dataModel.put(Article.ARTICLES, articles); } catch (final JSONException e) { LOGGER.log(Level.SEVERE, "Fills index articles failed", e); throw new ServiceException(e); } catch (final RepositoryException e) { LOGGER.log(Level.SEVERE, "Fills index articles failed", e); throw new ServiceException(e); } finally { Stopwatchs.end(); } }
From source file:org.b3log.solo.processor.util.Filler.java
/** * Fills links./*from w ww. j av a2 s .com*/ * * @param dataModel data model * @throws ServiceException service exception */ public void fillLinks(final Map<String, Object> dataModel) throws ServiceException { Stopwatchs.start("Fill Links"); try { final Map<String, SortDirection> sorts = new HashMap<String, SortDirection>(); sorts.put(Link.LINK_ORDER, SortDirection.ASCENDING); final Query query = new Query().addSort(Link.LINK_ORDER, SortDirection.ASCENDING).setPageCount(1); final JSONObject linkResult = linkRepository.get(query); final List<JSONObject> links = org.b3log.latke.util.CollectionUtils .jsonArrayToList(linkResult.getJSONArray(Keys.RESULTS)); dataModel.put(Link.LINKS, links); } catch (final JSONException e) { LOGGER.log(Level.SEVERE, "Fills links failed", e); throw new ServiceException(e); } catch (final RepositoryException e) { LOGGER.log(Level.SEVERE, "Fills links failed", e); throw new ServiceException(e); } finally { Stopwatchs.end(); } Stopwatchs.end(); }
From source file:org.b3log.solo.processor.util.Filler.java
/** * Fills header.ftl./*from w w w. j a va 2 s . c o m*/ * * @param request the specified HTTP servlet request * @param dataModel data model * @param preference the specified preference * @throws ServiceException service exception */ public void fillBlogHeader(final HttpServletRequest request, final Map<String, Object> dataModel, final JSONObject preference) throws ServiceException { Stopwatchs.start("Fill Header"); try { LOGGER.fine("Filling header...."); dataModel.put(Preference.ARTICLE_LIST_DISPLAY_COUNT, preference.getInt(Preference.ARTICLE_LIST_DISPLAY_COUNT)); dataModel.put(Preference.ARTICLE_LIST_PAGINATION_WINDOW_SIZE, preference.getInt(Preference.ARTICLE_LIST_PAGINATION_WINDOW_SIZE)); dataModel.put(Preference.LOCALE_STRING, preference.getString(Preference.LOCALE_STRING)); dataModel.put(Preference.BLOG_TITLE, preference.getString(Preference.BLOG_TITLE)); dataModel.put(Preference.BLOG_SUBTITLE, preference.getString(Preference.BLOG_SUBTITLE)); dataModel.put(Preference.HTML_HEAD, preference.getString(Preference.HTML_HEAD)); dataModel.put(Preference.META_KEYWORDS, preference.getString(Preference.META_KEYWORDS)); dataModel.put(Preference.META_DESCRIPTION, preference.getString(Preference.META_DESCRIPTION)); dataModel.put(Common.YEAR, String.valueOf(Calendar.getInstance().get(Calendar.YEAR))); final String noticeBoard = preference.getString(Preference.NOTICE_BOARD); dataModel.put(Preference.NOTICE_BOARD, noticeBoard); final Query query = new Query().setPageCount(1); final JSONObject result = userRepository.get(query); final JSONArray users = result.getJSONArray(Keys.RESULTS); final List<JSONObject> userList = CollectionUtils.jsonArrayToList(users); dataModel.put(User.USERS, userList); for (final JSONObject user : userList) { user.remove(User.USER_EMAIL); } final String skinDirName = (String) request.getAttribute(Keys.TEMAPLTE_DIR_NAME); dataModel.put(Skin.SKIN_DIR_NAME, skinDirName); Keys.fillServer(dataModel); Keys.fillRuntime(dataModel); fillMinified(dataModel); fillPageNavigations(dataModel); fillStatistic(dataModel); } catch (final JSONException e) { LOGGER.log(Level.SEVERE, "Fills blog header failed", e); throw new ServiceException(e); } catch (final RepositoryException e) { LOGGER.log(Level.SEVERE, "Fills blog header failed", e); throw new ServiceException(e); } finally { Stopwatchs.end(); } }
From source file:org.softcatala.corrector.LanguageToolParsing.java
public Suggestion[] GetSuggestions(String jsonText) { ArrayList<Suggestion> suggestions = new ArrayList<Suggestion>(); try {//from ww w . j av a 2s .c o m JSONObject json = new JSONObject(jsonText); JSONArray matches = json.getJSONArray("matches"); for (int i = 0; i < matches.length(); i++) { JSONObject match = matches.getJSONObject(i); JSONArray replacements = match.getJSONArray("replacements"); JSONObject rule = match.getJSONObject("rule"); String ruleId = rule.getString("id"); // Since we process fragments we need to skip the upper case // suggestion if (ruleId.equals("UPPERCASE_SENTENCE_START") == true) continue; Suggestion suggestion = new Suggestion(); if (replacements.length() == 0) { String message = match.getString("message"); String msgText = String.format("(%s)", message); suggestion.Text = new String[] { msgText }; } else { ArrayList<String> list = new ArrayList<String>(); for (int r = 0; r < replacements.length(); r++) { JSONObject replacement = replacements.getJSONObject(r); String value = replacement.getString("value"); list.add(value); } suggestion.Text = list.toArray(new String[list.size()]); } suggestion.Position = match.getInt("offset"); suggestion.Length = match.getInt("length"); suggestions.add(suggestion); Log.d(TAG, "Request result: " + suggestion.Position + " Len:" + suggestion.Length); } } catch (Exception e) { Log.e(TAG, "GetSuggestions", e); } return suggestions.toArray(new Suggestion[0]); }
From source file:com.bw.hawksword.wiktionary.ExtendedWikiHelper.java
/** * Query the Wiktionary API to pick a random dictionary word. Will try * multiple times to find a valid word before giving up. * * @return Random dictionary word, or null if no valid word was found. * @throws ApiException If any connection or server error occurs. * @throws ParseException If there are problems parsing the response. *//*from www . j a v a 2 s .c o m*/ public static String getRandomWord() throws ApiException, ParseException { // Keep trying a few times until we find a valid word int tries = 0; while (tries++ < RANDOM_TRIES) { // Query the API for a random word String content = getUrlContent(WIKTIONARY_RANDOM); try { // Drill into the JSON response to find the returned word JSONObject response = new JSONObject(content); JSONObject query = response.getJSONObject("query"); JSONArray random = query.getJSONArray("random"); JSONObject word = random.getJSONObject(0); String foundWord = word.getString("title"); // If we found an actual word, and it wasn't rejected by our invalid // filter, then accept and return it. if (foundWord != null && !sInvalidWord.matcher(foundWord).find()) { return foundWord; } } catch (JSONException e) { throw new ParseException("Problem parsing API response", e); } } // No valid word found in number of tries, so return null return null; }