List of usage examples for org.json JSONArray getJSONObject
public JSONObject getJSONObject(int index) throws JSONException
From source file:org.wso2.carbon.connector.integration.test.canvas.CanvasConnectorIntegrationTest.java
/** * Positive test case for listDiscussionTopics method with optional parameters. *//*from ww w.j av a 2 s. c om*/ @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateDiscussionTopicWithOptionalParameters" }, description = "Canvas {listDiscussionTopics} integration test with optional parameters.") public void testListDiscussionTopicsWithOptionalParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:listDiscussionTopics"); RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_listDiscussionTopics_optional.json"); String apiEndPoint = connectorProperties.getProperty("apiUrl") + "/api/v1/courses/" + connectorProperties.getProperty("courseId") + "/discussion_topics?order_by=position&scope=unlocked"; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap); JSONArray esbResponseArray = new JSONArray(esbRestResponse.getBody().getString("output")); JSONArray apiResponseArray = new JSONArray(apiRestResponse.getBody().getString("output")); Assert.assertEquals(apiResponseArray.length(), esbResponseArray.length()); if (apiResponseArray.length() > 0) { JSONObject esbFirstResult = esbResponseArray.getJSONObject(0); JSONObject apiFirstResult = apiResponseArray.getJSONObject(0); Assert.assertEquals(apiFirstResult.getString("id"), esbFirstResult.getString("id")); Assert.assertEquals(apiFirstResult.getString("title"), esbFirstResult.getString("title")); Assert.assertEquals(apiFirstResult.getString("message"), esbFirstResult.getString("message")); } }
From source file:org.wso2.carbon.connector.integration.test.canvas.CanvasConnectorIntegrationTest.java
/** * Test createEntry method with Mandatory Parameters. *///from w ww .ja va 2s . c o m @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateDiscussionTopicWithOptionalParameters" }, description = "Canvas {createEntry} integration test with Mandatory parameters.") public void testCreateEntryWithMandatoryParameters() throws IOException, JSONException { headersMap.put("Action", "urn:createEntry"); final String requestString = proxyUrl + "?courseId=" + connectorProperties.getProperty("courseId") + "&topicId=" + connectorProperties.getProperty("topicId") + "&apiUrl=" + connectorProperties.getProperty("apiUrl") + "&accessToken=" + connectorProperties.getProperty("accessToken"); MultipartFormdataProcessor multipartProcessor = new MultipartFormdataProcessor(requestString, headersMap); File file = new File(pathToResourcesDirectory + connectorProperties.getProperty("attachmentFileName")); multipartProcessor.addFileToRequest("attachment", file, URLConnection.guessContentTypeFromName(file.getName())); multipartProcessor.addFormDataToRequest("message", connectorProperties.getProperty("entryMessage")); RestResponse<JSONObject> esbRestResponse = multipartProcessor.processForJsonResponse(); String entryId = esbRestResponse.getBody().getString("id"); String userId = esbRestResponse.getBody().getString("user_id"); connectorProperties.put("entryId", entryId); final String apiUrl = connectorProperties.getProperty("apiUrl") + "/api/v1/courses/" + connectorProperties.getProperty("courseId") + "/discussion_topics/" + connectorProperties.getProperty("topicId") + "/entry_list?ids[]=" + entryId; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); JSONArray apiResponseArray = new JSONArray(apiRestResponse.getBody().getString("output")); JSONObject apiFirstElement = apiResponseArray.getJSONObject(0); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Assert.assertEquals(apiFirstElement.getString("created_at").split("T")[0], sdf.format(new Date())); Assert.assertEquals(apiFirstElement.getString("user_id"), userId); }
From source file:org.wso2.carbon.connector.integration.test.canvas.CanvasConnectorIntegrationTest.java
/** * Test createEntry method with Optional Parameters. *///ww w . j av a 2s . c om @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateDiscussionTopicWithOptionalParameters" }, description = "Canvas {createEntry} integration test with optional parameters.") public void testCreateEntryWithOptionalParameters() throws IOException, JSONException { headersMap.put("Action", "urn:createEntry"); final String requestString = proxyUrl + "?courseId=" + connectorProperties.getProperty("courseId") + "&topicId=" + connectorProperties.getProperty("topicId") + "&apiUrl=" + connectorProperties.getProperty("apiUrl") + "&accessToken=" + connectorProperties.getProperty("accessToken"); MultipartFormdataProcessor multipartProcessor = new MultipartFormdataProcessor(requestString, headersMap); File file = new File(pathToResourcesDirectory + connectorProperties.getProperty("attachmentFileName")); multipartProcessor.addFileToRequest("attachment", file, URLConnection.guessContentTypeFromName(file.getName())); multipartProcessor.addFormDataToRequest("message", connectorProperties.getProperty("entryMessage")); RestResponse<JSONObject> esbRestResponse = multipartProcessor.processForJsonResponse(); String entryId = esbRestResponse.getBody().getString("id"); final String apiUrl = connectorProperties.getProperty("apiUrl") + "/api/v1/courses/" + connectorProperties.getProperty("courseId") + "/discussion_topics/" + connectorProperties.getProperty("topicId") + "/entry_list?ids[]=" + entryId; RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiUrl, "GET", apiRequestHeadersMap); JSONArray apiResponseArray = new JSONArray(apiRestResponse.getBody().getString("output")); JSONObject apiFirstElement = apiResponseArray.getJSONObject(0); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Assert.assertEquals(connectorProperties.getProperty("entryMessage"), apiFirstElement.getString("message")); Assert.assertEquals(connectorProperties.getProperty("attachmentFileName"), apiFirstElement.getJSONObject("attachment").getString("filename")); Assert.assertEquals(apiFirstElement.getString("created_at").split("T")[0], sdf.format(new Date())); }
From source file:org.wso2.carbon.connector.integration.test.canvas.CanvasConnectorIntegrationTest.java
/** * Test deleteEntry method with Mandatory Parameters. *///from ww w . j a v a2 s . c om @Test(groups = { "wso2.esb" }, dependsOnMethods = { "testListEntriesWithNegativeCase", "testUpdateEntryWithOptionalParameters" }, description = "canvas {deleteEntry} integration test with mandatory parameters.", priority = 2) public void testDeleteEntryWithMandatoryParameters() throws IOException, JSONException { esbRequestHeadersMap.put("Action", "urn:deleteEntry"); String apiEndPoint = connectorProperties.getProperty("apiUrl") + "/api/v1/courses/" + connectorProperties.getProperty("courseId") + "/discussion_topics/" + connectorProperties.getProperty("topicId") + "/entry_list?ids[]=" + connectorProperties.getProperty("entryId"); RestResponse<JSONObject> apiRestResponseBefore = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap); JSONArray apiResponseArrayBefore = new JSONArray(apiRestResponseBefore.getBody().getString("output")); sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap, "esb_deleteEntry_mandatory.json"); RestResponse<JSONObject> apiRestResponseAfter = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap); JSONArray apiResponseArrayAfter = new JSONArray(apiRestResponseAfter.getBody().getString("output")); // Deleted key is not there in the response before the entry was deleted. Assert.assertEquals(apiResponseArrayBefore.getJSONObject(0).has("deleted"), false); // Deleted key is there with value 'true' in the response after the entry was deleted. Assert.assertEquals(apiResponseArrayAfter.getJSONObject(0).getBoolean("deleted"), true); }
From source file:com.mifos.mifosxdroid.dialogfragments.loanchargedialog.LoanChargeDialogFragment.java
@Override public void showAllChargesV3(ResponseBody result) { /* Activity is null - Fragment has been detached; no need to do anything. */ if (getActivity() == null) return;//from ww w .ja va2s .c om Log.d(LOG_TAG, ""); final List<Charges> charges = new ArrayList<>(); // you can use this array to populate your spinner final ArrayList<String> chargesNames = new ArrayList<String>(); //Try to get response body BufferedReader reader = null; StringBuilder sb = new StringBuilder(); try { reader = new BufferedReader(new InputStreamReader(result.byteStream())); String line; while ((line = reader.readLine()) != null) { sb.append(line); } JSONObject obj = new JSONObject(sb.toString()); if (obj.has("chargeOptions")) { JSONArray chargesTypes = obj.getJSONArray("chargeOptions"); for (int i = 0; i < chargesTypes.length(); i++) { JSONObject chargesObject = chargesTypes.getJSONObject(i); Charges charge = new Charges(); charge.setId(chargesObject.optInt("id")); charge.setName(chargesObject.optString("name")); charges.add(charge); chargesNames.add(chargesObject.optString("name")); chargeNameIdHashMap.put(charge.getName(), charge.getId()); } } String stringResult = sb.toString(); } catch (Exception e) { Log.e(LOG_TAG, "", e); } final ArrayAdapter<String> chargesAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, chargesNames); chargesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sp_charge_name.setAdapter(chargesAdapter); sp_charge_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { Id = chargeNameIdHashMap.get(chargesNames.get(i)); Log.d("chargesoptionss" + chargesNames.get(i), String.valueOf(Id)); if (Id != -1) { } else { Toast.makeText(getActivity(), getString(R.string.error_select_charge), Toast.LENGTH_SHORT) .show(); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); }
From source file:net.dv8tion.jda.core.handle.GuildEmojisUpdateHandler.java
@Override protected Long handleInternally(JSONObject content) { final long guildId = content.getLong("guild_id"); if (api.getGuildLock().isLocked(guildId)) return guildId; GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId); if (guild == null) { api.getEventCache().cache(EventCache.Type.GUILD, guildId, () -> handle(responseNumber, allContent)); return null; }/* w w w .j a va 2 s.c o m*/ JSONArray array = content.getJSONArray("emojis"); TLongObjectMap<Emote> emoteMap = guild.getEmoteMap(); List<Emote> oldEmotes = new ArrayList<>(emoteMap.valueCollection()); //snapshot of emote cache List<Emote> newEmotes = new ArrayList<>(); for (int i = 0; i < array.length(); i++) { JSONObject current = array.getJSONObject(i); final long emoteId = current.getLong("id"); EmoteImpl emote = (EmoteImpl) emoteMap.get(emoteId); EmoteImpl oldEmote = null; if (emote == null) { emote = new EmoteImpl(emoteId, guild); newEmotes.add(emote); } else { // emote is in our cache which is why we don't want to remove it in cleanup later oldEmotes.remove(emote); oldEmote = emote.clone(); } emote.setName(current.getString("name")).setManaged(current.getBoolean("managed")); //update roles JSONArray roles = current.getJSONArray("roles"); Set<Role> newRoles = emote.getRoleSet(); Set<Role> oldRoles = new HashSet<>(newRoles); //snapshot of cached roles for (int j = 0; j < roles.length(); j++) { Role role = guild.getRoleById(roles.getString(j)); newRoles.add(role); oldRoles.remove(role); } //cleanup old cached roles that were not found in the JSONArray for (Role r : oldRoles) { // newRoles directly writes to the set contained in the emote newRoles.remove(r); } // finally, update the emote emoteMap.put(emote.getIdLong(), emote); // check for updated fields and fire events handleReplace(oldEmote, emote); } //cleanup old emotes that don't exist anymore for (Emote e : oldEmotes) { emoteMap.remove(e.getIdLong()); api.getEventManager().handle(new EmoteRemovedEvent(api, responseNumber, e)); } for (Emote e : newEmotes) { api.getEventManager().handle(new EmoteAddedEvent(api, responseNumber, e)); } return null; }
From source file:org.everit.json.schema.TestSuiteTest.java
@Parameters(name = "{2}") public static List<Object[]> params() { List<Object[]> rval = new ArrayList<>(); Reflections refs = new Reflections("org.everit.json.schema.draft4", new ResourcesScanner()); Set<String> paths = refs.getResources(Pattern.compile(".*\\.json")); for (String path : paths) { if (path.indexOf("/optional/") > -1 || path.indexOf("/remotes/") > -1) { continue; }//from www.j a v a2 s. c o m String fileName = path.substring(path.lastIndexOf('/') + 1); JSONArray arr = loadTests(TestSuiteTest.class.getResourceAsStream("/" + path)); for (int i = 0; i < arr.length(); ++i) { JSONObject schemaTest = arr.getJSONObject(i); JSONArray testcaseInputs = schemaTest.getJSONArray("tests"); for (int j = 0; j < testcaseInputs.length(); ++j) { JSONObject input = testcaseInputs.getJSONObject(j); Object[] params = new Object[5]; params[0] = "[" + fileName + "]/" + schemaTest.getString("description"); params[1] = schemaTest.get("schema"); params[2] = "[" + fileName + "]/" + input.getString("description"); params[3] = input.get("data"); params[4] = input.getBoolean("valid"); rval.add(params); } } } return rval; }
From source file:net.cellcloud.talk.HttpSpeaker.java
private void requestHeartbeat() { // URL/*w w w . j a v a 2 s . c o m*/ StringBuilder url = new StringBuilder("http://"); url.append(this.address.getHostString()).append(":").append(this.address.getPort()); url.append(URI_HEARTBEAT); // ?? try { ContentResponse response = this.client.newRequest(url.toString()).method(HttpMethod.GET) .header(HttpHeader.COOKIE, this.cookie).send(); if (response.getStatus() == HttpResponse.SC_OK) { // this.hbFailedCounts = 0; JSONObject responseData = this.readContent(response.getContent()); if (responseData.has(HttpHeartbeatHandler.Primitives)) { // ? JSONArray primitives = responseData.getJSONArray(HttpHeartbeatHandler.Primitives); for (int i = 0, size = primitives.length(); i < size; ++i) { JSONObject primJSON = primitives.getJSONObject(i); // ?? this.doDialogue(primJSON); } } } else { // ++this.hbFailedCounts; Logger.w(HttpSpeaker.class, "Heartbeat failed"); } } catch (InterruptedException | TimeoutException | ExecutionException e) { // ++this.hbFailedCounts; } catch (JSONException e) { Logger.log(getClass(), e, LogLevel.ERROR); } // hbMaxFailed ? if (this.hbFailedCounts >= this.hbMaxFailed) { this.hangUp(); } }
From source file:org.loklak.android.client.SearchClient.java
public static Timeline search(final String protocolhostportstub, final String query, final Timeline.Order order, final String source, final int count, final int timezoneOffset, final long timeout) throws IOException { Timeline tl = new Timeline(order); String urlstring = ""; try {//from w ww . ja v a 2 s.co m urlstring = protocolhostportstub + "/api/search.json?q=" + URLEncoder.encode(query.replace(' ', '+'), "UTF-8") + "&timezoneOffset=" + timezoneOffset + "&maximumRecords=" + count + "&source=" + (source == null ? "all" : source) + "&minified=true&timeout=" + timeout; JSONObject json = JsonIO.loadJson(urlstring); if (json == null || json.length() == 0) return tl; JSONArray statuses = json.getJSONArray("statuses"); if (statuses != null) { for (int i = 0; i < statuses.length(); i++) { JSONObject tweet = statuses.getJSONObject(i); JSONObject user = tweet.getJSONObject("user"); if (user == null) continue; tweet.remove("user"); UserEntry u = new UserEntry(user); MessageEntry t = new MessageEntry(tweet); tl.add(t, u); } } if (json.has("search_metadata")) { JSONObject metadata = json.getJSONObject("search_metadata"); if (metadata.has("hits")) { tl.setHits((Integer) metadata.get("hits")); } if (metadata.has("scraperInfo")) { String scraperInfo = (String) metadata.get("scraperInfo"); tl.setScraperInfo(scraperInfo); } } } catch (Throwable e) { Log.e("SeachClient", e.getMessage(), e); } //System.out.println(parser.text()); return tl; }
From source file:conroller.UserController.java
public static ArrayList<UserModel> userDetailsTable() throws IOException, JSONException { String userName, fullName, email, address, gender, telNo, password, typeOfUser; ArrayList<UserModel> arrayList = new ArrayList<>(); phpConnection.setConnection(//from www .jav a 2s . c o m "http://itmahaweliauthority.net23.net/MahaweliAuthority/userPHPfiles/UserGetView.php"); JSONObject jSONObject = new JSONObject(phpConnection.readData()); JSONArray array = jSONObject.getJSONArray("server_response"); for (int i = 0; i < array.length(); i++) { JSONObject details = array.getJSONObject(i); try { userName = String.valueOf(details.getString("userName")); } catch (Exception e) { userName = null; } try { fullName = String.valueOf(details.getString("fullName")); } catch (Exception e) { fullName = null; } try { email = String.valueOf(details.getString("email")); } catch (Exception e) { email = null; } try { address = String.valueOf(details.getString("address")); } catch (Exception e) { address = null; } try { gender = String.valueOf(details.getString("gender")); } catch (Exception e) { gender = null; } try { telNo = String.valueOf(details.getString("telNo")); } catch (Exception e) { telNo = null; } try { password = String.valueOf(details.getString("password")); } catch (Exception e) { password = null; } try { typeOfUser = String.valueOf(details.getString("typeOfUser")); } catch (Exception e) { typeOfUser = null; } UserModel data = new UserModel(userName, fullName, email, address, gender, telNo, password, typeOfUser); arrayList.add(data); } return arrayList; }