List of usage examples for org.json JSONObject getJSONObject
public JSONObject getJSONObject(String key) throws JSONException
From source file:de.schildbach.wallet.data.ExchangeRatesProvider.java
private Map<String, ExchangeRate> requestExchangeRates() { final Stopwatch watch = Stopwatch.createStarted(); final Request.Builder request = new Request.Builder(); request.url(BITCOINAVERAGE_URL); request.header("User-Agent", userAgent); final Call call = Constants.HTTP_CLIENT.newCall(request.build()); try {// w w w . ja v a2 s . c o m final Response response = call.execute(); if (response.isSuccessful()) { final String content = response.body().string(); final JSONObject head = new JSONObject(content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); if (currencyCode.startsWith("BTC")) { final String fiatCurrencyCode = currencyCode.substring(3); if (!fiatCurrencyCode.equals(MonetaryFormat.CODE_BTC) && !fiatCurrencyCode.equals(MonetaryFormat.CODE_MBTC) && !fiatCurrencyCode.equals(MonetaryFormat.CODE_UBTC)) { final JSONObject exchangeRate = head.getJSONObject(currencyCode); final JSONObject averages = exchangeRate.getJSONObject("averages"); try { final Fiat rate = parseFiatInexact(fiatCurrencyCode, averages.getString("day")); if (rate.signum() > 0) rates.put(fiatCurrencyCode, new ExchangeRate( new org.bitcoinj.utils.ExchangeRate(rate), BITCOINAVERAGE_SOURCE)); } catch (final IllegalArgumentException x) { log.warn("problem fetching {} exchange rate from {}: {}", currencyCode, BITCOINAVERAGE_URL, x.getMessage()); } } } } watch.stop(); log.info("fetched exchange rates from {}, {} chars, took {}", BITCOINAVERAGE_URL, content.length(), watch); return rates; } else { log.warn("http status {} when fetching exchange rates from {}", response.code(), BITCOINAVERAGE_URL); } } catch (final Exception x) { log.warn("problem fetching exchange rates from " + BITCOINAVERAGE_URL, x); } return null; }
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 www .j a v a 2 s .c om */ 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:it.moondroid.chatbot.alice.Sraix.java
public static String sraixPannous(String input, String hint, Chat chatSession) { try {/*from ww w. j a v a2 s .c om*/ 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.stockchart.series.LinearSeries.java
public void fromJSONObject(JSONObject j) throws JSONException { super.fromJSONObject(j); fPointSizeInPercents = (float) j.getDouble("pointSize"); fPointStyle = PointStyle.valueOf(j.getString("pointStyle")); fPointsVisible = j.getBoolean("pointsVisible"); fPointAppearance.fromJSONObject(j.getJSONObject("pointAppearance")); }
From source file:org.softcatala.corrector.LanguageToolParsing.java
public Suggestion[] GetSuggestions(String jsonText) { ArrayList<Suggestion> suggestions = new ArrayList<Suggestion>(); try {/* w w w . j ava 2 s.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.norman0406.slimgress.API.Item.ItemFlipCard.java
public ItemFlipCard(JSONArray json) throws JSONException { super(ItemType.FlipCard, json); JSONObject item = json.getJSONObject(2); JSONObject flipCard = item.getJSONObject("flipCard"); if (flipCard.getString("flipCardType").equals("JARVIS")) mVirusType = FlipCardType.Jarvis; else if (flipCard.getString("flipCardType").equals("ADA")) mVirusType = FlipCardType.Ada;//from w w w .j a v a 2 s . c o m else System.out.println("unknown virus type"); }
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. *//* w ww . ja v a 2 s . c om*/ 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; }
From source file:org.brickred.socialauth.provider.FourSquareImpl.java
private Profile getProfile() throws Exception { LOG.debug("Obtaining user profile"); Profile profile = new Profile(); Response serviceResponse;/*from ww w .j a v a2s . c om*/ try { serviceResponse = authenticationStrategy.executeFeed(PROFILE_URL); } catch (Exception e) { throw new SocialAuthException("Failed to retrieve the user profile from " + PROFILE_URL, e); } String res; try { res = serviceResponse.getResponseBodyAsString(Constants.ENCODING); } catch (Exception exc) { throw new SocialAuthException("Failed to read response from " + PROFILE_URL, exc); } JSONObject jobj = new JSONObject(res); JSONObject rObj; JSONObject uObj; if (jobj.has("response")) { rObj = jobj.getJSONObject("response"); } else { throw new SocialAuthException("Failed to parse the user profile json : " + res); } if (rObj.has("user")) { uObj = rObj.getJSONObject("user"); } else { throw new SocialAuthException("Failed to parse the user profile json : " + res); } if (uObj.has("id")) { profile.setValidatedId(uObj.getString("id")); } if (uObj.has("firstName")) { profile.setFirstName(uObj.getString("firstName")); } if (uObj.has("lastName")) { profile.setLastName(uObj.getString("lastName")); } if (uObj.has("photo")) { profile.setProfileImageURL(uObj.getString("photo")); } if (uObj.has("gender")) { profile.setGender(uObj.getString("gender")); } if (uObj.has("homeCity")) { profile.setLocation(uObj.getString("homeCity")); } if (uObj.has("contact")) { JSONObject cobj = uObj.getJSONObject("contact"); if (cobj.has("email")) { profile.setEmail(cobj.getString("email")); } } profile.setProviderId(getProviderId()); userProfile = profile; return profile; }
From source file:org.brickred.socialauth.provider.FourSquareImpl.java
/** * Gets the list of contacts of the user. * /* ww w . j a v a 2s.c om*/ * @return List of contact objects representing Contacts. Only name and * profile URL will be available */ @Override public List<Contact> getContactList() throws Exception { LOG.info("Fetching contacts from " + CONTACTS_URL); Response serviceResponse; try { serviceResponse = authenticationStrategy.executeFeed(CONTACTS_URL); } catch (Exception e) { throw new SocialAuthException("Error while getting contacts from " + CONTACTS_URL, e); } if (serviceResponse.getStatus() != 200) { throw new SocialAuthException("Error while getting contacts from " + CONTACTS_URL + "Status : " + serviceResponse.getStatus()); } String respStr; try { respStr = serviceResponse.getResponseBodyAsString(Constants.ENCODING); } catch (Exception exc) { throw new SocialAuthException("Failed to read response from " + CONTACTS_URL, exc); } LOG.debug("User Contacts list in JSON " + respStr); JSONObject resp = new JSONObject(respStr); List<Contact> plist = new ArrayList<Contact>(); JSONArray items = new JSONArray(); if (resp.has("response")) { JSONObject robj = resp.getJSONObject("response"); if (robj.has("friends")) { JSONObject fobj = robj.getJSONObject("friends"); if (fobj.has("items")) { items = fobj.getJSONArray("items"); } } else { throw new SocialAuthException("Failed to parse the user profile json : " + respStr); } } else { throw new SocialAuthException("Failed to parse the user profile json : " + respStr); } LOG.debug("Contacts Found : " + items.length()); for (int i = 0; i < items.length(); i++) { JSONObject obj = items.getJSONObject(i); Contact c = new Contact(); if (obj.has("firstName")) { c.setFirstName(obj.getString("firstName")); } if (obj.has("lastName")) { c.setLastName(obj.getString("lastName")); } if (obj.has("id")) { c.setProfileUrl(VIEW_PROFILE_URL + obj.getString("id")); c.setId(obj.getString("id")); } plist.add(c); } return plist; }
From source file:com.sdspikes.fireworks.FireworksTurn.java
static public FireworksTurn unpersist(JSONObject obj) { FireworksTurn retVal = new FireworksTurn(); try {/*from w ww .ja v a 2 s . c o m*/ if (!obj.has("state")) { return null; } else { retVal.state = new GameState(obj.getJSONObject("state")); } if (obj.has("turn")) { retVal.turnCounter = obj.getInt("turn"); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return retVal; }