List of usage examples for org.json.simple JSONArray get
public E get(int index)
From source file:de.fhg.fokus.odp.portal.datasets.searchresults.BrowseDataSetsSearchResults.java
/** * This method adds the screenname of all users, which commented this * dataset, to a String array and returns this array. * //from ww w .j a v a 2s. co m * @param comments * the {@link JSONArray} * @return array filled with screennames of commenters */ private String[] getCommentersScreennames(JSONArray comments) { String[] commentersNames = new String[comments.size()]; for (int i = 0; i < comments.size(); i++) { String userId = (String) ((JSONObject) comments.get(i)).get("userId"); try { commentersNames[i] = UserLocalServiceUtil.getUserById(Long.parseLong(userId)).getScreenName(); } catch (NumberFormatException e) { LOGGER.error(e.getLocalizedMessage(), e); } catch (PortalException e) { LOGGER.error(e.getLocalizedMessage(), e); } catch (SystemException e) { LOGGER.error(e.getLocalizedMessage(), e); } } return commentersNames; }
From source file:com.apifest.doclet.integration.tests.DocletTest.java
@Test public void check_what_doclet_will_generate_correct_endpoints_order() throws Exception { // GIVEN/*from w ww. j a va 2s. co 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); JSONArray arr = (JSONArray) json.get("endpoints"); JSONObject obj = (JSONObject) arr.get(0); JSONObject obj1 = (JSONObject) arr.get(1); Assert.assertEquals(obj.get("endpoint"), "/v1/twitter/followers/stream"); Assert.assertEquals(obj1.get("endpoint"), "/v1/twitter/followers/metrics"); } finally { if (fileReader != null) { fileReader.close(); } deleteJsonFile(parserFilePath); } }
From source file:com.nubits.nubot.utils.FrozenBalancesManager.java
private void parseFrozenBalancesFile() { JSONParser parser = new JSONParser(); String FrozenBalancesManagerString = FilesystemUtils.readFromFile(this.pathToFrozenBalancesFiles); try {//from w ww .j a va2 s .c o m JSONObject frozenBalancesJSON = (JSONObject) (parser.parse(FrozenBalancesManagerString)); double quantity = Double.parseDouble((String) frozenBalancesJSON.get("frozen-quantity-total")); Amount frozenAmount = new Amount(quantity, toFreezeCurrency); setInitialFrozenAmount(frozenAmount, false); JSONArray historyArr = (JSONArray) frozenBalancesJSON.get("history"); for (int i = 0; i < historyArr.size(); i++) { JSONObject tempHistoryRow = (JSONObject) historyArr.get(i); DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH); Date timestamp = df.parse((String) tempHistoryRow.get("timestamp")); double frozeQuantity = Double.parseDouble((String) tempHistoryRow.get("froze-quantity")); String currencyCode = (String) tempHistoryRow.get("currency-code"); history.add(new HistoryRow(timestamp, frozeQuantity, currencyCode)); } } catch (ParseException | NumberFormatException | java.text.ParseException e) { LOG.error("Error while parsing the frozen balances file (" + pathToFrozenBalancesFiles + ")\n" + e.toString()); } }
From source file:com.apifest.doclet.integration.tests.DocletTest.java
@Test public void check_what_doclet_will_generate_correct_metric_exceptions() throws Exception { // GIVEN// ww w. java2 s.c o m String parserFilePath = "./all-mappings-docs.json"; Map<String, ExceptionDocumentation> exsNameToDescriptionMap = new HashMap<String, ExceptionDocumentation>(); addException("invalid_parameter", "Please add valid parameter", 400, "The parameter is invalid", exsNameToDescriptionMap); // 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(1); JSONArray exsParam = (JSONArray) obj.get("exceptions"); for (int i = 0; i < exsParam.size(); i++) { JSONObject currentParam = (JSONObject) exsParam.get(i); String currentName = (String) currentParam.get("name"); ExceptionDocumentation correctCurrentParam = exsNameToDescriptionMap.get(currentName); Assert.assertEquals((String) currentParam.get("name"), correctCurrentParam.getName()); Assert.assertEquals((String) currentParam.get("condition"), correctCurrentParam.getCondition()); Assert.assertEquals((String) currentParam.get("description"), correctCurrentParam.getDescription()); Assert.assertEquals(currentParam.get("code"), new Long(correctCurrentParam.getCode())); } } finally { if (fileReader != null) { fileReader.close(); } deleteJsonFile(parserFilePath); } }
From source file:com.apifest.doclet.integration.tests.DocletTest.java
@Test public void check_what_doclet_will_generate_correct_stream_exceptions() throws Exception { // GIVEN/* ww w .j ava 2 s . c o m*/ String parserFilePath = "./all-mappings-docs.json"; Map<String, ExceptionDocumentation> exsNameToDescriptionMap = new HashMap<String, ExceptionDocumentation>(); addException("invalid_since_until", "Since/until parameter must be within the last 30 days", 400, "The period is invalid", exsNameToDescriptionMap); // 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 exsParam = (JSONArray) obj.get("exceptions"); for (int i = 0; i < exsParam.size(); i++) { JSONObject currentParam = (JSONObject) exsParam.get(i); String currentName = (String) currentParam.get("name"); ExceptionDocumentation correctCurrentParam = exsNameToDescriptionMap.get(currentName); Assert.assertEquals((String) currentParam.get("name"), correctCurrentParam.getName()); Assert.assertEquals((String) currentParam.get("condition"), correctCurrentParam.getCondition()); Assert.assertEquals((String) currentParam.get("description"), correctCurrentParam.getDescription()); Assert.assertEquals(currentParam.get("code"), new Long(correctCurrentParam.getCode())); } } finally { if (fileReader != null) { fileReader.close(); } deleteJsonFile(parserFilePath); } }
From source file:com.capitalone.dashboard.datafactory.jira.JiraDataFactoryImplTest.java
/** * Test method for// w w w . jav a 2s .c o m * {@link com.capitalone.dashboard.datafactory.jira.JiraDataFactoryImpl#getQueryResponse(java.lang.String)} * . */ @Ignore @Test public void testGetQueryResponse() { logger.debug("RUNNING TEST FOR BASIC QUERY RESPONSE"); jiraDataFactory = new JiraDataFactoryImpl(properties.getProperty("jira.credentials"), properties.getProperty("jira.base.url"), properties.getProperty("jira.query.endpoint")); jiraDataFactory.buildBasicQuery(query); try { JSONArray rs = jiraDataFactory.getQueryResponse(); /* * 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("Basic 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.getQueryResponse(); /* * Testing actual JSON for values */ String strRs = new String(); strRs = rs.toString(); logger.info("Basic 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:com.gmail.bleedobsidian.itemcase.Updater.java
/** * Query ServerMods API for project variables. * * @return If successful or not./*from w w w . java 2s. co m*/ */ private boolean query() { try { final URLConnection con = this.url.openConnection(); con.setConnectTimeout(5000); con.setReadTimeout(5000); if (this.apiKey != null) { con.addRequestProperty("X-API-Key", this.apiKey); } con.addRequestProperty("User-Agent", this.plugin.getName() + " Updater"); con.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { this.result = UpdateResult.ERROR_ID; return false; } this.versionName = (String) ((JSONObject) array.get(array.size() - 1)).get("name"); this.versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get("downloadUrl"); this.versionType = (String) ((JSONObject) array.get(array.size() - 1)).get("releaseType"); this.versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get("gameVersion"); return true; } catch (IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { this.result = UpdateResult.ERROR_APIKEY; } else { this.result = UpdateResult.ERROR_SERVER; } return false; } }
From source file:com.facebook.tsdb.tsdash.server.PlotEndpoint.java
@Override @SuppressWarnings("unchecked") public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); try {/*from www. ja v a2s . co m*/ // decode parameters String jsonParams = request.getParameter("params"); if (jsonParams == null) { throw new Exception("Parameters not specified"); } JSONObject jsonParamsObj = (JSONObject) JSONValue.parse(jsonParams); long tsFrom = (Long) jsonParamsObj.get("tsFrom"); long tsTo = (Long) jsonParamsObj.get("tsTo"); long width = (Long) jsonParamsObj.get("width"); long height = (Long) jsonParamsObj.get("height"); boolean surface = (Boolean) jsonParamsObj.get("surface"); boolean palette = false; if (jsonParams.contains("palette")) { palette = (Boolean) jsonParamsObj.get("palette"); } JSONArray metricsArray = (JSONArray) jsonParamsObj.get("metrics"); if (metricsArray.size() == 0) { throw new Exception("No metrics to fetch"); } MetricQuery[] metricQueries = new MetricQuery[metricsArray.size()]; for (int i = 0; i < metricsArray.size(); i++) { metricQueries[i] = MetricQuery.fromJSONObject((JSONObject) metricsArray.get(i)); } TsdbDataProvider dataProvider = TsdbDataProviderFactory.get(); long ts = System.currentTimeMillis(); Metric[] metrics = new Metric[metricQueries.length]; for (int i = 0; i < metrics.length; i++) { MetricQuery q = metricQueries[i]; metrics[i] = dataProvider.fetchMetric(q.name, tsFrom, tsTo, q.tags, q.orders); metrics[i] = metrics[i].dissolveTags(q.getDissolveList(), q.aggregator); if (q.rate) { metrics[i].computeRate(); } } long loadTime = System.currentTimeMillis() - ts; // check to see if we have data boolean hasData = false; for (Metric metric : metrics) { if (metric.hasData()) { hasData = true; break; } } if (!hasData) { throw new Exception("No data"); } JSONObject responseObj = new JSONObject(); JSONArray encodedMetrics = new JSONArray(); for (Metric metric : metrics) { encodedMetrics.add(metric.toJSONObject()); } // plot just the first metric for now GnuplotProcess gnuplot = GnuplotProcess.create(surface); GnuplotOptions options = new GnuplotOptions(surface); options.enablePalette(palette); options.setDimensions((int) width, (int) height).setTimeRange(tsFrom, tsTo); String plotFilename = gnuplot.plot(metrics, options); gnuplot.close(); responseObj.put("metrics", encodedMetrics); responseObj.put("loadtime", loadTime); responseObj.put("ploturl", generatePlotURL(plotFilename)); out.println(responseObj.toJSONString()); long renderTime = System.currentTimeMillis() - ts - loadTime; logger.info("[Plot] time frame: " + (tsTo - tsFrom) + "s, " + "load time: " + loadTime + "ms, " + "render time: " + renderTime + "ms"); } catch (Throwable e) { out.println(getErrorResponse(e)); } out.close(); }
From source file:com.capitalone.dashboard.client.team.TeamDataClientImpl.java
/** * Updates the MongoDB with a JSONArray received from the source system * back-end with story-based data./*w ww . jav a2 s. co m*/ * * @param tmpMongoDetailArray * A JSON response in JSONArray format from the source system * @param featureCollector * @return * @return */ protected void updateMongoInfo(JSONArray tmpMongoDetailArray) { try { JSONObject dataMainObj = new JSONObject(); for (int i = 0; i < tmpMongoDetailArray.size(); i++) { if (dataMainObj != null) { dataMainObj.clear(); } dataMainObj = (JSONObject) tmpMongoDetailArray.get(i); ScopeOwnerCollectorItem team = new ScopeOwnerCollectorItem(); /* * Checks to see if the available asset state is not active from * the V1 Response and removes it if it exists and not active: */ if (!TOOLS.sanitizeResponse((String) dataMainObj.get("AssetState")).equalsIgnoreCase("Active")) { this.removeInactiveScopeOwnerByTeamId(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid"))); } else { boolean deleted = this .removeExistingEntity(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid"))); // Id if (deleted) { team.setId(this.getOldTeamId()); team.setEnabled(this.isOldTeamEnabledState()); } // collectorId team.setCollectorId(featureCollectorRepository.findByName(Constants.VERSIONONE).getId()); // teamId team.setTeamId(TOOLS.sanitizeResponse((String) dataMainObj.get("_oid"))); // name team.setName(TOOLS.sanitizeResponse((String) dataMainObj.get("Name"))); // changeDate; team.setChangeDate( TOOLS.toCanonicalDate(TOOLS.sanitizeResponse((String) dataMainObj.get("ChangeDate")))); // assetState team.setAssetState(TOOLS.sanitizeResponse((String) dataMainObj.get("AssetState"))); // isDeleted; team.setIsDeleted(TOOLS.sanitizeResponse((String) dataMainObj.get("IsDeleted"))); try { teamRepo.save(team); } catch (Exception e) { LOGGER.error( "Unexpected error caused when attempting to save data\nCaused by: " + e.getCause(), e); } } } } catch (Exception e) { LOGGER.error("FAILED: " + e.getMessage() + ", " + e.getClass(), e); } }
From source file:com.apifest.doclet.integration.tests.DocletTest.java
@Test public void check_what_doclet_will_generate_correct_metrics_request_parameters() throws Exception { // GIVEN//from w w w . j a v a 2 s.co m 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); // 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(1); 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()); // System.out.println(currentParam.get("name")); // System.out.println(correctCurrentParam.getName()); } } finally { if (fileReader != null) { fileReader.close(); } deleteJsonFile(parserFilePath); } }