List of usage examples for org.json.simple JSONArray get
public E get(int index)
From source file:com.apifest.doclet.integration.tests.DocletTest.java
@Test public void check_what_doclet_will_generate_correct_stream_request_parameters() throws Exception { // GIVEN//from w w w. j a v a 2 s . com String parserFilePath = "./all-mappings-docs.json"; Map<String, RequestParamDocumentation> correctNameToTypeMap = new HashMap<String, RequestParamDocumentation>(); addRequestParamToMap("ids", "string", "** user ids goes here **", true, correctNameToTypeMap); addRequestParamToMap("fields", "list", "** The keys from result json can be added as filter**", false, correctNameToTypeMap); addRequestParamToMap("since", "integer", "** since is optional parameter**", false, correctNameToTypeMap); addRequestParamToMap("until", "integer", "** until is optional parameter**", false, correctNameToTypeMap); // WHEN runDoclet(); // THEN JSONParser parser = new JSONParser(); FileReader fileReader = null; try { fileReader = new FileReader(parserFilePath); JSONObject json = (JSONObject) parser.parse(fileReader); JSONArray arr = (JSONArray) json.get("endpoints"); JSONObject obj = (JSONObject) arr.get(0); JSONArray reqParam = (JSONArray) obj.get("requestParams"); for (int i = 0; i < reqParam.size(); i++) { JSONObject currentParam = (JSONObject) reqParam.get(i); String currentName = (String) currentParam.get("name"); RequestParamDocumentation correctCurrentParam = correctNameToTypeMap.get(currentName); Assert.assertEquals((String) currentParam.get("type"), correctCurrentParam.getType()); Assert.assertEquals((String) currentParam.get("name"), correctCurrentParam.getName()); Assert.assertEquals((String) currentParam.get("description"), correctCurrentParam.getDescription()); Assert.assertEquals(currentParam.get("required"), correctCurrentParam.isRequired()); } } finally { if (fileReader != null) { fileReader.close(); } deleteJsonFile(parserFilePath); } }
From source file:com.dagobert_engine.portfolio.service.MtGoxPortfolioService.java
/** * Get permissions for api key/* www . ja v a 2 s .com*/ * * @param forceRefresh * @return */ public MtGoxPermission[] getApiPermissions() { ArrayList<MtGoxPermission> perms = new ArrayList<>(); JSONArray array = (JSONArray) getData().get("Rights"); for (int i = 0; i < array.size(); i++) { perms.add(MtGoxPermission.fromString((String) array.get(i))); } return perms.toArray(new MtGoxPermission[perms.size()]); }
From source file:com.apifest.doclet.integration.tests.DocletTest.java
@Test public void check_what_doclet_will_generate_correct_stream_result_parameters() throws Exception { // GIVEN// w w w .ja va 2 s. co m String parserFilePath = "./all-mappings-docs.json"; Map<String, ResultParamDocumentation> resNameToTypeMap = new HashMap<String, ResultParamDocumentation>(); addResultParamToMap("tw_id", "integer", "The ** tw_id ** description", true, resNameToTypeMap); addResultParamToMap("in_reply_to_screen_name", "string", "The ** in_reply_to_screen_name ** description", true, resNameToTypeMap); addResultParamToMap("request_handle", "string", "The ** request_handle ** description", true, resNameToTypeMap); addResultParamToMap("in_reply_to_status_id", "string", "The ** in_reply_to_status_id ** description", true, resNameToTypeMap); addResultParamToMap("channel", "string", "The ** channel ** description", true, resNameToTypeMap); // WHEN runDoclet(); // THEN JSONParser parser = new JSONParser(); FileReader fileReader = null; try { fileReader = new FileReader(parserFilePath); JSONObject json = (JSONObject) parser.parse(fileReader); JSONArray arr = (JSONArray) json.get("endpoints"); JSONObject obj = (JSONObject) arr.get(0); JSONArray resParam = (JSONArray) obj.get("resultParams"); for (int i = 0; i < resParam.size(); i++) { JSONObject currentParam = (JSONObject) resParam.get(i); String currentName = (String) currentParam.get("name"); ResultParamDocumentation correctCurrentParam = resNameToTypeMap.get(currentName); Assert.assertEquals((String) currentParam.get("type"), correctCurrentParam.getType()); Assert.assertEquals((String) currentParam.get("name"), correctCurrentParam.getName()); Assert.assertEquals((String) currentParam.get("description"), correctCurrentParam.getDescription()); Assert.assertEquals(currentParam.get("required"), correctCurrentParam.isRequired()); } } finally { if (fileReader != null) { fileReader.close(); } deleteJsonFile(parserFilePath); } }
From source file:API.JSONPractice.java
private void getMatch() throws Exception { Integer[] apIds = { 1026, 1052, 1056, 1058, 3001, 3003, 3020, 3023, 3025, 3027, 3040, 3041, 3050, 3057, 3060, 3089, 3092, 3098, 3100, 3108, 3113, 3115, 3116, 3124, 3135, 3136, 3145, 3146, 3151, 3152, 3157, 3165, 3174, 3191, 3285, 3303, 3504, 3708, 3716, 3720, 3724 }; List<Integer> apIdsList = Arrays.asList(apIds); Files.walk(Paths.get("C:\\AP_ITEMS\\")).forEach(filePath -> { if (Files.isRegularFile(filePath)) { try (FileReader fileReader = new FileReader(filePath.toString())) { File file = new File(filePath.toString()); String fileName = file.getName(); String region = fileName.replace(".json", "").toLowerCase(); JSONParser jsonParser = new JSONParser(); JSONArray matchId = (JSONArray) jsonParser.parse(fileReader); for (int i = 0; i < jsonFileSize; i++) { url = "https://" + region + ".api.pvp.net/api/lol/" + region + "/v2.2/match/" + matchId.get(i) + "?api_key=" + api_key; System.out.println(url); File jsonFile = new File("C:\\Riot_API\\" + region + "\\" + matchId.get(i) + ".json"); if (!jsonFile.exists()) { FileWriter fileWriter = new FileWriter(jsonFile); BufferedWriter bw = new BufferedWriter(fileWriter); URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); do { // optional default is GET con.setRequestMethod("GET"); int responseCode = con.getResponseCode(); System.out.println("\nSending 'GET' request to URL : " + url); System.out.println("Response Code : " + responseCode); if (responseCode == 500 || responseCode == 503) { tryAgain = true; } else { tryAgain = false; }/* w ww .j a va 2s .co m*/ } while (tryAgain); StringBuffer response = new StringBuffer(); try (BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } // do try in.close(); } catch (IOException e) { e.printStackTrace(); } JSONObject jsonObject = new JSONObject(response.toString()); for (int n = 0; n < numberOfParticipants; n++) { JSONObject stats = jsonObject.getJSONArray("participants").getJSONObject(n) .getJSONObject("stats"); JSONObject object = new JSONObject(); JSONArray arr = new JSONArray(); // String test = jsonObject.getJSONArray("participants").getJSONObject(i).getJSONObject("timeline").getString("lane"); for (int count = 0; count < itemSlots; count++) { if (stats.getInt("item" + count) != 0) { arr.add(stats.getInt("item" + count)); itemList.add(stats.getInt("item" + count)); } } object.put("participant" + (n + 1), arr); bw.write(object.toString()); } bw.flush(); bw.close(); } /* for (int itemId : itemList) { if (apIdsList.contains(itemId)) { fullApList.add(itemId); } } */ // Sleep count came from request limit of 500 request per 10 minute. // Therefore, 1.2 sec per request is allowed. Thread.sleep(1200); } NumberFormat defaultFormat = NumberFormat.getPercentInstance(); defaultFormat.setMinimumFractionDigits(1); /* for (int value : apIdsList) { double occurrences = Collections.frequency(fullApList, value); System.out.println(defaultFormat.format(occurrences / itemList.size())); } */ } catch (Exception e) { e.printStackTrace(); } } }); // } catch (FileNotFoundException | IOException | ParseException e) }
From source file:com.apifest.doclet.integration.tests.DocletTest.java
@Test public void when_doclet_run_outputs_tags() throws ParseException, IOException { // GIVEN/*from w w w .ja va 2s. c o m*/ String parserFilePath = "./all-mappings-docs.json"; // WHEN runDoclet(); // THEN JSONParser parser = new JSONParser(); FileReader fileReader = null; try { fileReader = new FileReader(parserFilePath); JSONObject json = (JSONObject) parser.parse(fileReader); String version = (String) json.get("version"); JSONArray arr = (JSONArray) json.get("endpoints"); JSONObject obj = (JSONObject) arr.get(1); JSONObject obj1 = (JSONObject) arr.get(0); Assert.assertEquals(version, "v1"); Assert.assertEquals(obj.get("group"), "Twitter Followers"); Assert.assertEquals(obj.get("scope"), "twitter_followers"); Assert.assertEquals(obj.get("method"), "GET"); Assert.assertEquals(obj.get("endpoint"), "/v1/twitter/followers/metrics"); Assert.assertEquals(obj.get("description"), null); Assert.assertEquals(obj.get("summary"), null); Assert.assertEquals(obj.get("paramsDescription"), null); Assert.assertEquals(obj.get("resultsDescription"), null); Assert.assertEquals(obj1.get("group"), "Twitter Followers"); Assert.assertEquals(obj1.get("scope"), "twitter_followers"); Assert.assertEquals(obj1.get("method"), "GET"); Assert.assertEquals(obj1.get("endpoint"), "/v1/twitter/followers/stream"); Assert.assertNotEquals(obj1.get("description"), null); Assert.assertNotEquals(obj1.get("summary"), null); Assert.assertEquals(obj1.get("paramsDescription"), "** Parameter description is going here!**"); Assert.assertEquals(obj1.get("resultsDescription"), "** Result description is the best! **"); } finally { if (fileReader != null) { fileReader.close(); } deleteJsonFile(parserFilePath); } }
From source file:com.capitalone.dashboard.datafactory.jira.JiraDataFactoryImplTest.java
/** * Test method for//from www. j a va 2s .com * {@link com.capitalone.dashboard.datafactory.jira.JiraDataFactoryImpl#getPagingQueryResponse()} * . */ @Ignore @Test public void testGetPagingQueryResponse() { logger.debug("RUNNING TEST FOR PAGING QUERY RESPONSE"); jiraDataFactory = new JiraDataFactoryImpl(1, properties.getProperty("jira.credentials"), properties.getProperty("jira.base.url"), properties.getProperty("jira.query.endpoint")); jiraDataFactory.buildBasicQuery(query); jiraDataFactory.buildPagingQuery(0); try { JSONArray rs = jiraDataFactory.getPagingQueryResponse(); /* * Testing actual JSON for values */ JSONArray dataMainArry = new JSONArray(); JSONObject dataMainObj = new JSONObject(); dataMainArry = (JSONArray) rs.get(0); dataMainObj = (JSONObject) dataMainArry.get(0); logger.info("Paging query response: " + dataMainObj.get("fields").toString()); // fields assertTrue("No valid Number was found", dataMainObj.get("fields").toString().length() >= 1); } catch (NullPointerException npe) { fail("There was a problem with an object used to connect to Jira during the test:\n" + npe.getMessage() + " caused by: " + npe.getCause()); } catch (ArrayIndexOutOfBoundsException aioobe) { fail("The object returned from Jira had no JSONObjects in it during the test; try increasing the scope of your test case query and try again.\n" + aioobe.getMessage() + " caused by: " + aioobe.getCause()); } catch (IndexOutOfBoundsException ioobe) { logger.info("JSON artifact may be empty - re-running test to prove this out..."); JSONArray rs = jiraDataFactory.getPagingQueryResponse(); /* * Testing actual JSON for values */ String strRs = new String(); strRs = rs.toString(); logger.info("Paging query response: " + strRs); assertEquals("There was nothing returned from Jira that is consistent with a valid response.", "[[]]", strRs); } catch (Exception e) { fail("There was an unexpected problem while connecting to Jira during the test:\n" + e.getMessage() + " caused by: " + e.getCause()); } }
From source file:test.portlet.service.impl.MolgenisAPIRequestLocalServiceImpl.java
/** * // ww w . ja va2s . c o m * @param token * @return */ private String readData(String biobankid) { //String url = "https://molgenis21.target.rug.nl/api/v2/test?aggs=x==Diseases;distinct==ParticipantID&q=BiobankID=q=\"http%3A%2F%2Fcatalogue.rd-connect.eu%2Fweb%2F71542\""; //String url = "https://molgenis21.target.rug.nl/api/v2/test?aggs=x==Diseases;distinct==ParticipantID"; String url = "https://molgenis21.target.rug.nl/api/v2/rdconnect_Sample?aggs=x==Disease;distinct==ParticipantID&q=BiobankID==" + biobankid; System.out.println(url); try { // Construct Table Columns String cols = "{key: 'Disease Name',sortable: true},"; cols += "{key: 'Number of Patients, Donors',sortable: true},"; cols += "{key: 'Gene',sortable: true},"; cols += "{key: 'ORPHA Code',sortable: true},"; cols += "{key: 'ICD 10',sortable: true},"; cols += "{key: 'OMIM',sortable: true},"; cols += "{key: 'Synonym(s)',sortable: true}"; // Create request HttpClient clinet = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(url); get.addHeader("x-molgenis-token", token_); HttpResponse response = clinet.execute(get); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = reader.readLine()) != null) { if (line.contains("{\"errors\":[{\"message\":\"No COUNT permission on entity test\"}]}")) { // Login Error: return "ERROR:LoginPermission."; } else { String data = ""; // Parse our JSON response JSONParser jsonparser = new JSONParser(); JSONObject baseobject = (JSONObject) jsonparser.parse(line); // getting the aggregated table JSONObject aggregates = (JSONObject) baseobject.get("aggs"); JSONArray xlabelarray = (JSONArray) aggregates.get("xLabels"); JSONArray matrixarray = (JSONArray) aggregates.get("matrix"); for (int rows = 0; rows < xlabelarray.size(); rows++) { JSONObject xlabel = (JSONObject) xlabelarray.get(rows); JSONArray count = (JSONArray) matrixarray.get(rows); if (!data.equals("")) { data += ","; } data += "{'Disease Name':'" + (String) xlabel.get("Label") + "',"; data += "'Number of Patients, Donors':'" + count.get(0) + "',"; data += "'ORPHA Code':'" + (String) xlabel.get("IRI") + "'}"; } String returnstring = "AUI().use('aui-datatable','aui-datatype','datatable-sort',function(Y) {var remoteData = [" + data + "];var nestedCols = [" + cols + "];var dataTable = new Y.DataTable({columns: nestedCols,data: remoteData}).render('#diseasematrix');dataTable.get('boundingBox').unselectable();});"; return returnstring; } } } catch (ParseException e) { System.out.println("ERROR: readData(String token)"); System.out.println(e); } catch (IOException e) { System.out.println("ERROR: readData(String token)"); System.out.println(e); } return ""; }
From source file:eu.seaclouds.platform.discoverer.crawler.CloudTypes.java
private void supports(String keyName, JSONObject feat, Offering offering) { if (feat.containsKey(keyName) == false) return;/* w ww. j a v a 2 s . c o m*/ JSONArray dbs = (JSONArray) feat.get(keyName); for (int i = 0; i < dbs.size(); i++) { String cloudHarmonySupportName = (String) dbs.get(i); String seaCloudsSupportName = externaltoSCTag.get(cloudHarmonySupportName); if (seaCloudsSupportName != null) offering.addProperty(seaCloudsSupportName + "_support", "true"); } }
From source file:io.personium.test.jersey.cell.ctl.AccountTest.java
/** * ????. Account=>?=>. Role=>?=>. AccountRole??=>?=>. ??=>Role=>Account. * @throws TokenParseException TokenParseException * @throws TokenRootCrtException TokenRootCrtException * @throws TokenDsigException TokenDsigException *//* w ww . j a v a 2 s .c o m*/ @Test public final void crud() throws TokenParseException, TokenDsigException, TokenRootCrtException { String testAccountName = "test_account"; String testAccountPass = "password"; String accUrl = this.createAccount(testAccountName, testAccountPass); log.debug(accUrl); String testRoleName = "testRole"; String roleUrl = this.createRole(testRoleName); log.debug(roleUrl); // ???C Http.request("link-account-role.txt") .with("token", AbstractCase.MASTER_TOKEN_NAME) .with("cellPath", cellName) .with("username", testAccountName) .with("roleUrl", roleUrl) .returns() .statusCode(HttpStatus.SC_NO_CONTENT); // DcRequest req = DcRequest.post(UrlUtils.accountLinks(cellName, testAccountName)); // req.header(HttpHeaders.AUTHORIZATION, MASTER_TOKEN).addJsonBody("uri", roleUrl); // DcResponse res = request(req); // assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); // ????R(?) // TODO ?????? log.debug("koooooooo"); PersoniumRequest req = PersoniumRequest.get(UrlUtils.accountLinks(cellName, testAccountName)) .header(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN).header(HttpHeaders.ACCEPT, "application/json"); PersoniumResponse res = request(req); assertEquals(HttpStatus.SC_OK, res.getStatusCode()); JSONObject linkJson = res.bodyAsJson(); JSONArray linksResults = getResultsFromEntitysResponse(linkJson); JSONObject linkJson2 = (JSONObject) linksResults.get(0); assertEquals(roleUrl, linkJson2.get("uri")); // ????U // TODO UPDATE?????? // BOX? String boxName = "testbox"; String boxSchema = "https://example.com/hogecell/"; createBox2(boxName, boxSchema); // ?? // grant_type=password&username={username}&password={password} req = PersoniumRequest.post(UrlUtils.auth(cellName)); String authBody = String.format("grant_type=password&username=%s&password=%s", testAccountName, testAccountPass); req.header(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded").addStringBody(authBody); res = request(req); assertEquals(HttpStatus.SC_OK, res.getStatusCode()); JSONObject token = res.bodyAsJson(); assertNotNull(token); // ?? req = PersoniumRequest.post(UrlUtils.auth(cellName)); authBody = String.format("grant_type=password&username=%s&password=%s&p_target=%s", testAccountName, testAccountPass, "https://example.com/testcell"); req.header(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded").addStringBody(authBody); res = request(req); assertEquals(HttpStatus.SC_OK, res.getStatusCode()); token = res.bodyAsJson(); assertNotNull(token); String accessToken = null; accessToken = (String) token.get("access_token"); assertNotNull(accessToken); TransCellAccessToken tcat = TransCellAccessToken.parse(accessToken); String url = UrlUtils.cellRoot(cellName); assertEquals(testRoleName, tcat.getRoles().get(0).getName()); assertEquals(url + "__role/__/" + testRoleName, tcat.getRoles().get(0).schemeCreateUrl(url)); assertEquals(url, tcat.getIssuer()); assertEquals(url + "#" + testAccountName, tcat.getSubject()); // ????D String roleId = roleUrl.substring(roleUrl.indexOf("'") + 1); roleId = roleId.substring(0, roleId.indexOf("'")); req = PersoniumRequest.delete(UrlUtils.accountLink(cellName, testAccountName, roleId)) .header(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN); res = request(req); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); // Role?D req = PersoniumRequest.delete(roleUrl) .header(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN) .header(HttpHeaders.IF_MATCH, "*"); res = request(req); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); // Account?D req = PersoniumRequest.delete(accUrl) .header(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN) .header(HttpHeaders.IF_MATCH, "*"); res = request(req); assertEquals(HttpStatus.SC_NO_CONTENT, res.getStatusCode()); }
From source file:de.tobiyas.racesandclasses.chat.channels.container.ChannelSaveContainer.java
/** * Generates the List of Participants from the value saved in the DB. * // w w w . j ava 2 s . co m * @return */ public List<String> generateParitipants() { try { List<String> participants = new LinkedList<String>(); JSONArray tempObject = (JSONArray) new JSONParser().parse(this.participants); //early out for error in reading. if (tempObject == null || tempObject.size() == 0) return participants; for (int i = 0; i < tempObject.size(); i++) { participants.add(tempObject.get(i).toString()); } return participants; } catch (ParseException e) { e.printStackTrace(); return new LinkedList<String>(); } }