List of usage examples for org.json JSONArray length
public int length()
From source file:com.phelps.liteweibo.model.weibo.CommentList.java
public static CommentList parse(String jsonString) { if (TextUtils.isEmpty(jsonString)) { return null; }//from ww w .j a 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 {/*from w w w .j a v a2s.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.wso2.carbon.connector.integration.test.pivotaltracker.PivotaltrackerConnectorIntegrationTest.java
/** * Positive test case for listProjects method with mandatory parameters. * // w w w . j a v a2 s.c o m * @throws JSONException * @throws IOException */ @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateProjectWithMandatoryParameters", "testCreateProjectWithOptionalParameters" }, description = "pivotaltracker {listProjects} integration test with mandatory parameters.") public void testListProjectsWithMandatoryParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:listProjects"); RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_listProjects_mandatory.json"); JSONArray esbOutputArray = new JSONArray(esbRestResponse.getBody().getString("output")); final String apiEndpoint = apiEndpointUrl + "/projects"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndpoint, "GET", apiRequestHeadersMap); JSONArray apiOutputArray = new JSONArray(apiRestResponse.getBody().getString("output")); Assert.assertEquals(esbOutputArray.length(), apiOutputArray.length()); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("id"), apiOutputArray.getJSONObject(0).getString("id")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("name"), apiOutputArray.getJSONObject(0).getString("name")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("account_id"), apiOutputArray.getJSONObject(0).getString("account_id")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("kind"), apiOutputArray.getJSONObject(0).getString("kind")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("week_start_day"), apiOutputArray.getJSONObject(0).getString("week_start_day")); }
From source file:org.wso2.carbon.connector.integration.test.pivotaltracker.PivotaltrackerConnectorIntegrationTest.java
/** * Positive test case for listProjects method with optional parameters. * // w ww . j a va 2s . c om * @throws JSONException * @throws IOException */ @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateProjectWithMandatoryParameters", "testCreateProjectWithOptionalParameters" }, description = "pivotaltracker {listProjects} integration test with mandatory parameters.") public void testListProjectsWithOptionalParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:listProjects"); RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_listProjects_optional.json"); JSONArray esbOutputArray = new JSONArray(esbRestResponse.getBody().getString("output")); final String apiEndpoint = apiEndpointUrl + "/projects"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndpoint, "GET", apiRequestHeadersMap); JSONArray apiOutputArray = new JSONArray(apiRestResponse.getBody().getString("output")); Assert.assertNotEquals(esbOutputArray.length(), apiOutputArray.length()); Assert.assertEquals(esbRestResponse.getHttpStatusCode(), 200); Assert.assertEquals(apiRestResponse.getHttpStatusCode(), 200); }
From source file:org.wso2.carbon.connector.integration.test.pivotaltracker.PivotaltrackerConnectorIntegrationTest.java
/** * Positive test case for getProjectLabels method with mandatory parameters. * /*from w w w . java 2s . c o m*/ * @throws JSONException * @throws IOException */ @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateLabelForProjectWithMandatoryParameters" }, description = "pivotaltracker {getProjectLabels} integration test with mandatory parameters.") public void testGetProjectLabelsWithMandatoryParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:getProjectLabels"); RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_getProjectLabels_mandatory.json"); JSONArray esbOutputArray = new JSONArray(esbRestResponse.getBody().getString("output")); final String apiEndpoint = apiEndpointUrl + "/projects/" + connectorProperties.getProperty("projectId") + "/labels"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndpoint, "GET", apiRequestHeadersMap); JSONArray apiOutputArray = new JSONArray(apiRestResponse.getBody().getString("output")); Assert.assertEquals(esbOutputArray.length(), apiOutputArray.length()); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("id"), apiOutputArray.getJSONObject(0).getString("id")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("name"), apiOutputArray.getJSONObject(0).getString("name")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("project_id"), apiOutputArray.getJSONObject(0).getString("project_id")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("kind"), apiOutputArray.getJSONObject(0).getString("kind")); Assert.assertEquals(esbOutputArray.getJSONObject(0).getString("created_at"), apiOutputArray.getJSONObject(0).getString("created_at")); }
From source file:org.wso2.carbon.connector.integration.test.pivotaltracker.PivotaltrackerConnectorIntegrationTest.java
/** * Positive test case for createLabelForStory method with mandatory parameters. * /*w w w . j av a 2s. c o m*/ * @throws JSONException * @throws IOException */ @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateProjectWithMandatoryParameters", "testCreateStoryWithMandatoryParameters" }, description = "pivotaltracker {createLabelForStory} integration test with mandatory parameters.") public void testCreateLabelForStoryWithMandatoryParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:createLabelForStory"); RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_createLabelForStory_mandatory.json"); final String labelId = esbRestResponse.getBody().getString("id"); final String apiEndpoint = apiEndpointUrl + "/projects/" + connectorProperties.getProperty("projectId") + "/stories/" + connectorProperties.getProperty("storyId") + "/labels"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndpoint, "GET", apiRequestHeadersMap); JSONArray apiOutputArray = new JSONArray(apiRestResponse.getBody().getString("output")); JSONObject lableObj = null; for (int i = 0; i < apiOutputArray.length(); i++) { lableObj = apiOutputArray.getJSONObject(i); if (labelId.equals(lableObj.getString("id"))) { break; } } Assert.assertEquals(connectorProperties.getProperty("labelName"), lableObj.getString("name")); }
From source file:org.wso2.carbon.connector.integration.test.pivotaltracker.PivotaltrackerConnectorIntegrationTest.java
/** * Positive test case for listStories method with mandatory parameters. * /*www . j a v a2s .c o m*/ * @throws IOException * @throws JSONException */ @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateProjectWithMandatoryParameters", "testCreateStoryWithOptionalParameters" }, description = "pivotaltracker {listStories} integration test with mandatory parameters.") public void testListStoriesWithMandatoryParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:listStories"); RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_listStories_mandatory.json"); JSONArray esbUserStoryArray = new JSONArray(esbRestResponse.getBody().getString("output")); String apiEndPoint = apiEndpointUrl + "/projects/" + connectorProperties.getProperty("projectId") + "/stories"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap); JSONArray apiUserStoryArray = new JSONArray(apiRestResponse.getBody().getString("output")); Assert.assertEquals(esbUserStoryArray.length(), apiUserStoryArray.length()); Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("id"), apiUserStoryArray.getJSONObject(0).getString("id")); Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("name"), apiUserStoryArray.getJSONObject(0).getString("name")); Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("created_at"), apiUserStoryArray.getJSONObject(0).getString("created_at")); Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("updated_at"), apiUserStoryArray.getJSONObject(0).getString("updated_at")); }
From source file:org.wso2.carbon.connector.integration.test.pivotaltracker.PivotaltrackerConnectorIntegrationTest.java
/** * Positive test case for listStories method with optional parameters. * /*from ww w. j av a 2 s . co m*/ * @throws IOException * @throws JSONException */ @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateProjectWithMandatoryParameters", "testCreateStoryWithOptionalParameters" }, description = "pivotaltracker {listStories} integration test with optional parameters.") public void testListStoriesWithOptionalParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:listStories"); RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_listStories_optional.json"); JSONArray esbUserStoryArray = new JSONArray(esbRestResponse.getBody().getString("output")); URLEncoder encoder = new URLEncoder(); final String state = encoder.encode("accepted"); String apiEndPoint = apiEndpointUrl + "/projects/" + connectorProperties.getProperty("projectId") + "/stories?offset=0&limit=10&created_before=" + connectorProperties.getProperty("createdBefore") + "&created_after=" + connectorProperties.getProperty("createdAfter") + "&with_state=" + state; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap); JSONArray apiUserStoryArray = new JSONArray(apiRestResponse.getBody().getString("output")); Assert.assertEquals(esbUserStoryArray.length(), apiUserStoryArray.length()); Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("id"), apiUserStoryArray.getJSONObject(0).getString("id")); Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("name"), apiUserStoryArray.getJSONObject(0).getString("name")); Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("created_at"), apiUserStoryArray.getJSONObject(0).getString("created_at")); Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("updated_at"), apiUserStoryArray.getJSONObject(0).getString("updated_at")); }
From source file:org.softcatala.corrector.LanguageToolParsing.java
public Suggestion[] GetSuggestions(String jsonText) { ArrayList<Suggestion> suggestions = new ArrayList<Suggestion>(); try {// w ww. jav 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:org.brickred.socialauth.provider.FourSquareImpl.java
/** * Gets the list of contacts of the user. * // w ww . ja va2 s . 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; }