List of usage examples for org.json JSONObject JSONObject
public JSONObject(String source) throws JSONException
From source file:com.phelps.liteweibo.model.weibo.CommentList.java
public static CommentList parse(String jsonString) { if (TextUtils.isEmpty(jsonString)) { return null; }//from w ww. ja v a 2 s . c om CommentList comments = new CommentList(); try { JSONObject jsonObject = new JSONObject(jsonString); comments.previous_cursor = jsonObject.optString("previous_cursor", "0"); comments.next_cursor = jsonObject.optString("next_cursor", "0"); comments.total_number = jsonObject.optInt("total_number", 0); JSONArray jsonArray = jsonObject.optJSONArray("comments"); if (jsonArray != null && jsonArray.length() > 0) { int length = jsonArray.length(); comments.commentList = new ArrayList<Comment>(length); for (int ix = 0; ix < length; ix++) { comments.commentList.add(Comment.parse(jsonArray.optJSONObject(ix))); } } } catch (JSONException e) { e.printStackTrace(); } return comments; }
From source file:it.moondroid.chatbot.alice.Sraix.java
public static String sraixPannous(String input, String hint, Chat chatSession) { try {//www . ja v a 2s .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.softcatala.corrector.LanguageToolParsing.java
public Suggestion[] GetSuggestions(String jsonText) { ArrayList<Suggestion> suggestions = new ArrayList<Suggestion>(); try {//from w ww . j a v a 2 s .co 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. */// www .j a v a2s . 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; }
From source file:org.nuclearbunny.icybee.net.impl.BitlyImpl.java
public String shrinkURL(String url) throws IOException { /**/*from w ww . j av a 2s . c o m*/ * bit.ly provides an elegant REST API that returns results in either JSON * or XML format. See http://bitly.com/app/developers for more information. */ StringBuilder buffer = new StringBuilder(BITLY_URL); buffer.append("?version=2.0.1").append("&format=json").append("&login=").append(BITLY_API_LOGIN) .append("&apiKey=").append(BITLY_API_KEY).append("&longUrl=") .append(URLEncoder.encode(url, "UTF-8")); URL bitlyURL = new URL(buffer.toString()); URLConnection connection = bitlyURL.openConnection(); String newURL = url; try { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); JSONObject jsonObject = new JSONObject(new JSONTokener(in)); if ("OK".equals(jsonObject.opt("statusCode"))) { JSONObject results = (JSONObject) jsonObject.get("results"); results = (JSONObject) results.get(url); newURL = results.get("shortUrl").toString(); } } catch (JSONException e) { e.printStackTrace(System.err); throw new IOException(e.getMessage()); } return newURL; }
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 a2 s .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. * /* w ww. ja v a2 s .c o m*/ * @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.xixicm.de.data.storage.DataBaseTest.java
protected Sentence generateNewSentence(boolean isStar) { SentenceEntity newSentence = new SentenceEntity(); try {// w w w . j a v a 2 s. co m JSONObject result = new JSONObject(MOCK_SENTENCE_CONTENT); newSentence.setDateline(result.optString(SentenceEntityDao.Properties.Dateline.name)); // insert today's or first got sentence newSentence.setSid(result.optString(SentenceEntityDao.Properties.Sid.name)); newSentence.setContent(result.optString(SentenceEntityDao.Properties.Content.name)); newSentence.setAllContent(MOCK_SENTENCE_CONTENT); newSentence.setIsStar(isStar); } catch (JSONException e) { fail("generateNewSentence error"); } return newSentence; }
From source file:test.java.ecplugins.weblogic.TestUtils.java
/** * callRunProcedure//from www . j ava 2 s . c o m * * @param jo * @return the jobId of the job launched by runProcedure */ public static String callRunProcedure(JSONObject jo) throws Exception { props = getProperties(); HttpClient httpClient = new DefaultHttpClient(); JSONObject result = null; try { String encoding = new String( org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils .getBytesUtf8(props.getProperty(StringConstants.COMMANDER_USER) + ":" + props.getProperty(StringConstants.COMMANDER_PASSWORD)))); HttpPost httpPostRequest = new HttpPost("http://" + props.getProperty(StringConstants.COMMANDER_SERVER) + ":8000/rest/v1.0/jobs?request=runProcedure"); StringEntity input = new StringEntity(jo.toString()); input.setContentType("application/json"); httpPostRequest.setEntity(input); httpPostRequest.setHeader("Authorization", "Basic " + encoding); HttpResponse httpResponse = httpClient.execute(httpPostRequest); result = new JSONObject(EntityUtils.toString(httpResponse.getEntity())); return result.getString("jobId"); } finally { httpClient.getConnectionManager().shutdown(); } }
From source file:test.java.ecplugins.weblogic.TestUtils.java
/** * Wrapper around a HTTP GET to a REST service * //www. j ava2 s. c o m * @param url * @return JSONObject */ static JSONObject performHTTPGet(String url) throws Exception, JSONException { props = getProperties(); HttpClient httpClient = new DefaultHttpClient(); String encoding = new String( org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils .getBytesUtf8(props.getProperty(StringConstants.COMMANDER_USER) + ":" + props.getProperty(StringConstants.COMMANDER_PASSWORD)))); try { HttpGet httpGetRequest = new HttpGet(url); httpGetRequest.setHeader("Authorization", "Basic " + encoding); HttpResponse httpResponse = httpClient.execute(httpGetRequest); if (httpResponse.getStatusLine().getStatusCode() >= 400) { throw new RuntimeException("HTTP GET failed with " + httpResponse.getStatusLine().getStatusCode() + "-" + httpResponse.getStatusLine().getReasonPhrase()); } return new JSONObject(EntityUtils.toString(httpResponse.getEntity())); } finally { httpClient.getConnectionManager().shutdown(); } }