List of usage examples for org.json.simple JSONArray size
public int size()
From source file:mini_mirc_client.Mini_mirc_client.java
public static void showMsg() { try {/*from w w w. ja v a 2 s.c om*/ synchronized (allMsg) { if (!allMsg.isEmpty() && allMsg.size() > 0) { for (int i = 0; i < allMsg.size(); i++) { JSONObject temp = (JSONObject) allMsg.get(i); JSONArray tempArr = (JSONArray) temp.get("msg"); for (int j = 0; j < tempArr.size(); j++) { temp = (JSONObject) tempArr.get(j); SimpleDateFormat formatDate = new SimpleDateFormat("yy-MM-dd HH:mm:ss"); Date sendDat = new Date(); sendDat.setTime((long) temp.get("timestamp")); System.out .println(">> [" + temp.get("channel").toString() + "] [" + temp.get("username") + "] " + temp.get("message") + " || " + formatDate.format(sendDat)); } } } allMsg.clear(); } } catch (Exception E) { E.printStackTrace(); } }
From source file:com.jts.rest.profileservice.utils.RestServiceHelper.java
/** * Returns the count of challenges for a given user * @param sessionId/*from w ww . j av a 2 s .c o m*/ * @param username * @return * @throws MalformedURLException * @throws IOException */ public static int getChallengeCountByUser(String sessionId, String username) throws MalformedURLException, IOException { JSONArray challenges = getChallenges(sessionId, username); return challenges.size(); }
From source file:com.emuneee.camerasyncmanager.util.GeocodeHelper.java
public static List<Camera> geocodeCameras(List<Camera> cameras, long sleep) throws Exception { List<Camera> geocoded = new ArrayList<Camera>(cameras.size()); int count = 1; // loop through and geocode each camera for (Camera camera : cameras) { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(sGeocodeUrl).append("?"); urlBuilder.append(sLatLng).append("="); urlBuilder.append(camera.getLatitude()).append(",").append(camera.getLongitude()); urlBuilder.append("&").append(sSensor); sLogger.debug("Geocode URL " + urlBuilder.toString()); try {/*from w ww. j ava2 s . c om*/ // retry String data = null; int retryCount = 0; while (data == null && retryCount < sRetryCount) { if (retryCount > 0) { sLogger.info("Retrying geocoding"); } data = HttpHelper.getStringDataFromUrl(urlBuilder.toString()); Thread.sleep(sleep); retryCount++; } if (data == null) { sLogger.warn("Unable to geocode the camera, no data returned " + camera); } else if (data != null && data.contains("OVER_QUERY_LIMIT")) { sLogger.warn("Unable to geocode the camera, query limit exceeded " + camera); throw new Exception("Unable to geocode the camera, query limit exceeded"); } else { JSONObject jsonObj = (JSONObject) new JSONParser().parse(data); JSONArray resultsArr = (JSONArray) jsonObj.get("results"); if (resultsArr.size() > 0) { for (int i = 0; i < resultsArr.size(); i++) { JSONObject result = (JSONObject) resultsArr.get(i); // loop through the address components JSONArray addressComponents = (JSONArray) result.get("address_components"); for (Object compObj : addressComponents) { JSONObject component = (JSONObject) compObj; String shortName = (String) component.get("short_name"); JSONArray types = (JSONArray) component.get("types"); // loop through the types for (Object typeObj : types) { String type = (String) typeObj; if (type.equalsIgnoreCase("administrative_area_level_3")) { camera.setArea(shortName); break; } else if (type.equalsIgnoreCase("locality")) { camera.setCity(shortName); break; } else if (type.equalsIgnoreCase("administrative_area_level_1")) { camera.setState(shortName); break; } else if (type.equalsIgnoreCase("country")) { camera.setCountry(shortName); break; } else if (type.equalsIgnoreCase("postal_code")) { camera.setZipCode(shortName); break; } } } if (camera.containsAllRequiredData()) { break; } else { sLogger.info( "Some required data is missing, moving to the next address component set"); } } } if (camera.containsAllRequiredData()) { geocoded.add(camera); sLogger.info("Camera " + count++ + " of " + cameras.size() + " geocoded"); sLogger.debug("Geocoded camera " + camera); sLogger.debug("Sleeping for " + sleep + " milliseconds"); } else { sLogger.warn( "Some required data is missing and geocoding results have been exhausted for camera: " + camera); } } } catch (InterruptedException e) { sLogger.error("Error geocoding address"); sLogger.error(e.getMessage()); } catch (ParseException e) { sLogger.error("Error geocoding address"); sLogger.error(e.getMessage()); } } return geocoded; }
From source file:OCRRestAPI.java
private static void PrintOCRResponse(String jsonResponse) throws ParseException, IOException { // Parse JSON data JSONParser parser = new JSONParser(); JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse); // Get available pages System.out.println("Available pages: " + jsonObj.get("AvailablePages")); // get an array from the JSON object JSONArray text = (JSONArray) jsonObj.get("OCRText"); // For zonal OCR: OCRText[z][p] z - zone, p - pages for (int i = 0; i < text.size(); i++) { System.out.println(" " + text.get(i)); }/*from w w w .j ava 2 s.co m*/ // Output file URL String outputFileUrl = (String) jsonObj.get("OutputFileUrl"); // If output file URL is specified if (outputFileUrl != null && !outputFileUrl.equals("")) { // Download output file DownloadConvertedFile(outputFileUrl); } }
From source file:me.fromgate.facechat.UpdateChecker.java
private static void updateLastVersion() { if (!enableUpdateChecker) return;/*from w w w .j a v a 2s .co m*/ URL url = null; try { url = new URL(projectApiUrl); } catch (Exception e) { log("Failed to create URL: " + projectApiUrl); return; } try { URLConnection conn = url.openConnection(); conn.addRequestProperty("X-API-Key", null); conn.addRequestProperty("User-Agent", projectName + " using UpdateChecker (by fromgate)"); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = reader.readLine(); JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() > 0) { JSONObject latest = (JSONObject) array.get(array.size() - 1); String plugin_name = (String) latest.get("name"); projectLastVersion = plugin_name.replace(projectName + " v", "").trim(); } } catch (Exception e) { log("Failed to check last version"); } }
From source file:com.example.prathik1.drfarm.OCRRestAPI.java
private static void PrintOCRResponse(String jsonResponse) throws ParseException, IOException { // Parse JSON data JSONParser parser = new JSONParser(); JSONObject jsonObj = (JSONObject) parser.parse(jsonResponse); // Get available pages System.out.println("Available pages: " + jsonObj.get("AvailablePages")); // get an array from the JSON object JSONArray text = (JSONArray) jsonObj.get("OCRText"); // For zonal OCR: OCRText[z][p] z - zone, p - pages for (int i = 0; i < text.size(); i++) { System.out.println(" " + text.get(i)); }/*from w w w .j a v a 2 s .c o m*/ // Output file URL String outputFileUrl = (String) jsonObj.get("OutputFileUrl"); // If output file URL is specified if (outputFileUrl != null && !outputFileUrl.equals("")) { // Download output file DownloadConvertedFile(outputFileUrl); } }
From source file:h.scratchpads.list.json.JSONReader.java
public static String[] getScratchpadsForHarvesting(HarvestingDataArchive archive, LogFile logFile) { String info;// ww w. jav a 2 s . c o m String[] scratchpadURLs = null; JSONArray arrayJSON = readJSON(HarvesterConfigData.CURRENT_Scratchpads_JSON_URL, logFile); if (arrayJSON != null) { List<String> urls = new ArrayList<String>(); info = "The list of current Scratchpads sites contains " + arrayJSON.size() + " URL(s)"; logFile.write(info); System.out.println(info); String field_website; String field_profile; String field_last_node_changed; String fieldLastNodeChangedFromArchive; boolean wasThereAnyChangeToHarvestingDataArchive = false; for (int i = 0; i < arrayJSON.size(); i++) { JSONObject jsonObject = (JSONObject) arrayJSON.get(i); field_website = (String) jsonObject.get("field_website"); if (field_website.startsWith("http")) { field_profile = (String) jsonObject.get("field_profile"); if ((field_profile.equalsIgnoreCase("scratchpad_2")) || (field_profile.equalsIgnoreCase("scratchpad_2_migrate"))) { field_last_node_changed = jsonObject.get("field_last_node_changed").toString(); fieldLastNodeChangedFromArchive = archive.getValue(field_website); if (!field_last_node_changed.equalsIgnoreCase(fieldLastNodeChangedFromArchive)) { archive.setValue(field_website, field_last_node_changed); wasThereAnyChangeToHarvestingDataArchive = true; urls.add(field_website); } } } } // if there was any change to HarvestingDataArchive then save it: if (wasThereAnyChangeToHarvestingDataArchive) { archive.saveHarvestingData(logFile); } scratchpadURLs = new String[urls.size()]; urls.toArray(scratchpadURLs); } return scratchpadURLs; }
From source file:info.usbo.skypetwitter.Run.java
private static void vk() throws ParseException { String url = "https://api.vk.com/method/wall.get?v=5.28&domain=Depersonilized&filter=owner&extended=1"; String line = ""; try {// w w w . java 2 s . c o m URL url2 = new URL(url); BufferedReader reader = new BufferedReader(new InputStreamReader(url2.openStream(), "UTF-8")); line = reader.readLine(); reader.close(); } catch (MalformedURLException e) { // ... } catch (IOException e) { // ... } JSONObject json = (JSONObject) new JSONParser().parse(line); json = (JSONObject) new JSONParser().parse(json.get("response").toString()); JSONArray jsona = (JSONArray) new JSONParser().parse(json.get("items").toString()); vk.clear(); for (int i = 0; i < jsona.size(); i++) { vk.add(new VK(jsona.get(i).toString())); } }
From source file:iracing.webapi.SpectatorSessionParser.java
static List<SpectatorSession> parse(String json) { JSONParser parser = new JSONParser(); List<SpectatorSession> output = null; try {/*from w ww . j a v a2 s . c o m*/ JSONArray rootArray = (JSONArray) parser.parse(json); output = new ArrayList<SpectatorSession>(); for (int i = 0; i < rootArray.size(); i++) { JSONObject r = (JSONObject) rootArray.get(i); SpectatorSession o = new SpectatorSession(); o.setSubSessionStatus(getString(r, "subses_status")); o.setSessionStatus(getString(r, "ses_status")); JSONObject b = (JSONObject) r.get("broadcast"); SpectatorSession.BroadcastInfo bi = new SpectatorSession.BroadcastInfo(); bi.setCanBroadcast((Boolean) b.get("canBroadcast")); bi.setSubSessionId(getLong(b, "subSessionId")); bi.setBroadcaster((Boolean) b.get("isBroadcaster")); bi.setMaximumUsers(getInt(b, "maxUsers")); bi.setAvailableSpectatorSlots(getInt(b, "availSpectatorSlots")); bi.setNumberOfDrivers(getInt(b, "numDrivers")); bi.setNumberOfDriverSlots(getInt(b, "numDriverSlots")); bi.setNumberOfSpectators(getInt(b, "numSpectators")); bi.setNumberOfBroadcasters(getInt(b, "numBroadcasters")); bi.setNumberOfSpectatorSlots(getInt(b, "numSpectatorSlots")); bi.setAvailableReservedBroadcasterSlots(getInt(b, "availReservedBCasterSlots")); bi.setCanWatch((Boolean) b.get("canWatch")); o.setBroadcastInfo(bi); o.setSubSessionId(getLong(r, "subsessionid")); o.setSessionId(getLong(r, "sessionid")); o.setSeriesId(getInt(r, "seriesid")); o.setTrackId(getInt(r, "trackid")); JSONObject h = (JSONObject) r.get("hosted"); if (h != null) { SpectatorSession.HostedInfo hi = new SpectatorSession.HostedInfo(); hi.setHeatFilterAmount(getInt(h, "heatFilterAmount")); hi.setPracticeLength(getInt(h, "practiceLength")); JSONArray a = (JSONArray) h.get("admins"); List<SpectatorSession.DriverInfo> driverList = new ArrayList<SpectatorSession.DriverInfo>(); for (int j = 0; j < a.size(); j++) { JSONObject ar = (JSONObject) a.get(j); if (ar != null) { SpectatorSession.DriverInfo di = new SpectatorSession.DriverInfo(); di.setCustomerId(getLong(ar, "custId")); di.setName(getString(ar, "displayName", true)); driverList.add(di); } } hi.setAdministrators(driverList); hi.setOrderId(getLong(h, "orderId")); hi.setMaximumIrating(getInt(h, "maxIR")); hi.setMinimumLicenseLevel(getInt(h, "minLicLevel")); hi.setRootPrivateSessionId(getLong(h, "rootPrivateSessionId")); hi.setDescription(getString(h, "desc", true)); hi.setFastTows(getInt(h, "fastTows")); hi.setQualifyingLength(getInt(h, "qualLength")); hi.setRaceLength(getInt(h, "raceLength")); hi.setRestrictResults((getInt(h, "restrictResults")) == 1); hi.setHardcoreLevelId(getInt(h, "hardcoreLevel")); hi.setId(getLong(h, "id")); hi.setMaximumLicenseLevel(getInt(h, "maxLicLevel")); hi.setQualifyingLaps(getInt(h, "qualLaps")); hi.setHostName(getString(h, "host", true)); // TODO: handle allowed clubs/leagues/teams hi.setRaceLaps(getInt(h, "raceLaps")); hi.setNumberOfServers(getInt(h, "numServers")); hi.setCustomerId(getLong(h, "custid")); // TODO: handle league info hi.setHeatGridType(getInt(h, "heatGridType")); hi.setExpires(new Date(getLong(h, "expires"))); hi.setHeatAddedDrivers(getInt(h, "heatAddedDrivers")); hi.setNumberOfServersFinished(getInt(h, "numServersFinished")); hi.setMultiClass((getInt(h, "multiClass")) == 1); hi.setRestrictViewing((getInt(h, "restrictViewing")) == 1); hi.setSessionName(getString(h, "sessionName", true)); List<Integer> carList = new ArrayList<Integer>(); JSONArray ca = (JSONArray) h.get("carIds"); for (int j = 0; j < ca.size(); j++) { carList.add(((Long) ca.get(j)).intValue()); } hi.setCars(carList); hi.setReason(getString(h, "reason", true)); hi.setTrackId(getInt(h, "trackId")); hi.setLaunchAt(new Date(getLong(h, "launchAt"))); hi.setMaximumDrivers(getInt(h, "maxDrivers")); hi.setSessionId(getLong(h, "sessionId")); hi.setHeatGridsId(getInt(h, "heatGridsId")); hi.setParentPrivateSessionId(getLong(h, "parentPrivateSessionId")); hi.setNightMode((getInt(h, "nightMode")) == 1); hi.setHeatSessionType(getInt(h, "heatSessionType")); hi.setHeatFilterType(getInt(h, "heatFilterType")); hi.setHeatFinal((getInt(h, "heatFinal")) == 1); hi.setCreated(new Date(getLong(h, "created"))); hi.setCautions((getInt(h, "cautions")) == 1); hi.setFixedSetup((getInt(h, "fixedSetup")) == 1); hi.setRestartType(getInt(h, "restartType")); hi.setTimeLimit(getInt(h, "timeLimit")); hi.setPasswordProtected((Boolean) h.get("pwdProtected")); hi.setFarmId(getInt(h, "farmId")); hi.setStatus(getInt(h, "status")); hi.setLoneQualifying((getInt(h, "loneQualify")) == 1); hi.setRollingStart((getInt(h, "rollingStarts")) == 1); hi.setNumberOfServersStarted(getInt(h, "numServersStarted")); JSONArray ff = (JSONArray) h.get("maxPercentFuelFills"); List<Integer> fuelList = new ArrayList<Integer>(); for (int j = 0; j < ff.size(); j++) { fuelList.add(((Long) ff.get(j)).intValue()); } // TODO: finish handling % fuel fills hi.setMinimumIrating(getInt(h, "minIR")); o.setHostedInfo(hi); } o.setStartTime(new Date(getLong(r, "start_time"))); o.setEventTypeId(getInt(r, "evttype")); o.setPrivateSessionId(getLong(r, "privatesessionid")); o.setSeasonId(getInt(r, "seasonid")); output.add(o); } } catch (ParseException ex) { Logger.getLogger(SpectatorSessionParser.class.getName()).log(Level.SEVERE, null, ex); } return output; }
From source file:mml.handler.scratch.ScratchVersion.java
/** * Convert a BSON object to a Scratch version internal format * @param json the bson object from the database * @return a ScratchVersion with layers/* w w w . j a v a 2 s. co m*/ */ public static ScratchVersion fromJSON(String json) { JSONObject jObj = (JSONObject) JSONValue.parse(json); boolean dirty = ((Boolean) jObj.get("dirty") != null) ? ((Boolean) jObj.get("dirty")) : false; Date saveTime = toDate((String) jObj.get(JSONKeys.TIME)); String longName = (String) jObj.get(JSONKeys.LONGNAME); ScratchVersion sv = new ScratchVersion((String) jObj.get(JSONKeys.VERSION1), longName, (String) jObj.get(JSONKeys.DOCID), (String) jObj.get(JSONKeys.DBASE), saveTime, dirty); JSONArray jArr = (JSONArray) jObj.get("layers"); if (jArr != null) { for (int i = 0; i < jArr.size(); i++) { JSONObject jLayer = (JSONObject) jArr.get(i); String layerName = (String) jLayer.get(JSONKeys.NAME); String body = (String) jLayer.get(JSONKeys.BODY); int layerNum = layerNumber(layerName); sv.addLayer(body.toCharArray(), layerNum); } } return sv; }