List of usage examples for org.json.simple JSONArray get
public E get(int index)
From source file:com.rylinaux.plugman.util.BukGetUtil.java
/** * Check if the installed plugin version is up-to-date with the DBO version. * * @param pluginName the plugin name./* w w w .ja va 2 s.co m*/ * @return the reflective UpdateResult. */ public static UpdateResult checkUpToDate(String pluginName) { String pluginSlug = BukGetUtil.getPluginSlug(pluginName); if (pluginSlug == null || pluginSlug.isEmpty()) { return new UpdateResult(UpdateResult.ResultType.INVALID_PLUGIN); } JSONObject json = BukGetUtil.getPluginData(pluginSlug); JSONArray versions = (JSONArray) json.get("versions"); if (versions.size() == 0) { return new UpdateResult(UpdateResult.ResultType.INVALID_PLUGIN); } JSONObject latest = (JSONObject) versions.get(0); String currentVersion = PluginUtil.getPluginVersion(pluginName); String latestVersion = (String) latest.get("version"); if (currentVersion == null) { return new UpdateResult(UpdateResult.ResultType.NOT_INSTALLED, currentVersion, latestVersion); } else if (currentVersion.equalsIgnoreCase(latestVersion)) { return new UpdateResult(UpdateResult.ResultType.UP_TO_DATE, currentVersion, latestVersion); } else { return new UpdateResult(UpdateResult.ResultType.OUT_OF_DATE, currentVersion, latestVersion); } }
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 {//from w w w. ja v a2 s .c om 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:br.ufrgs.ufrgsmapas.network.LocationParser.java
public static void parseBuildings(SparseArray<BuildingVo> mTempBuilding) { // Read JSON File Connection con = HttpConnection.connect(URL); con.method(Connection.Method.POST).ignoreContentType(true); Connection.Response resp; try {// w w w.j a v a 2s . co m resp = con.execute(); } catch (IOException e) { if (DebugUtils.DEBUG) Log.e(TAG, "Error fetching positions: " + e); return; } String jsonDoc = resp.body(); // Parse JSON to find each element JSONObject jsonStartObject = (JSONObject) JSONValue.parse(jsonDoc); // Get the array with objects representing each building JSONArray jsonBuildings = (JSONArray) jsonStartObject.get("features"); int buildingsListSize = ((List) jsonBuildings).size(); // Iterate through buildings for (int i = 0; i < buildingsListSize; i++) { // Get buildingVo object JSONObject jsonBuilding = (JSONObject) jsonBuildings.get(i); // Get buildingVo id int id = ((Number) jsonBuilding.get("id")).intValue(); // Get coordinates array JSONObject jsonGeometry = (JSONObject) jsonBuilding.get("geometry"); JSONArray jsonCoordinates = (JSONArray) ((JSONArray) ((JSONArray) jsonGeometry.get("coordinates")) .get(0)).get(0); // Get latitudes and longitudes List coordList = jsonCoordinates; int coordListSize = coordList.size(); double[] latitude = new double[coordListSize]; double[] longitude = new double[coordListSize]; for (int j = 0; j < coordListSize; j++) { latitude[j] = (double) ((List) coordList.get(j)).get(1); longitude[j] = (double) ((List) coordList.get(j)).get(0); } // Create buildingVo object and add to list - store only the center of the position double[] center = centroid(latitude, longitude); BuildingVo buildingVo = new BuildingVo(id, center[0], center[1]); mTempBuilding.append(id, buildingVo); } }
From source file:net.itransformers.toplogyviewer.gui.neo4j.Neo4jLoader.java
public static String getLatestNetwork() { String HighestNetworkID = null; String query = "start network=node:node_auto_index(name='network') return network"; String params = ""; String output = executeCypherQuery(query, params); JSONObject json = null;/*from ww w .jav a 2 s. c om*/ try { json = (JSONObject) new JSONParser().parse(output); } catch (ParseException e) { e.printStackTrace(); } JSONArray jsonData = (JSONArray) json.get("data"); JSONArray array = (JSONArray) jsonData.get(jsonData.size() - 1); JSONObject object1 = (JSONObject) array.get(array.size() - 1); String delims = "[/]"; //Get the latest element of the URL e.g the node ID. String[] tokens = object1.get("self").toString().split(delims); HighestNetworkID = tokens[tokens.length - 1]; return HighestNetworkID; }
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. ja va 2 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: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 {/*w w w .j a v a 2s.co m*/ // 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: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//from w w w .j a v a 2s. 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; }
From source file:com.jilk.ros.rosbridge.implementation.JSON.java
private static Object convertJSONArrayToArray(JSONArray ja, Class c, Registry<Class> r) { Object result = Array.newInstance(c, ja.size()); for (int i = 0; i < ja.size(); i++) { Object lookup = ja.get(i); Object value = null;//from w w w .j a v a 2s. c o m if (lookup != null) { if (lookup.getClass().equals(JSONObject.class)) value = convertJSONObjectToMessage((JSONObject) lookup, c, r); else if (lookup.getClass().equals(JSONArray.class)) // this is not actually allowed in ROS value = convertJSONArrayToArray((JSONArray) lookup, c.getComponentType(), r); else value = convertJSONPrimitiveToPrimitive(lookup, c); Array.set(result, i, value); } } return result; }
From source file:com.worldline.easycukes.commons.helpers.JSONHelper.java
/** * Returns the value of a given property from a particular * {@link JSONObject}/*from w w w . j a va2s . c o m*/ * * @param jsonObject the {@link JSONObject} to be used for extracting values * @param property the property you'd like to get from the specified * {@link JSONObject} * @return the value of the specified property if it's found, or null if it * cannot be found */ public static String getValue(@NonNull final JSONObject jsonObject, @NonNull final String property) { if (jsonObject != null) if (jsonObject.get(property) != null) return jsonObject.get(property).toString(); final int index = property.indexOf("."); if (index > 0) { final Object object = getProperty(jsonObject, property.substring(0, index)); if (object != null) { if (object instanceof JSONObject) return getValue((JSONObject) object, property.substring(index + 1)); if (object instanceof JSONArray) { final JSONArray jsonArray = (JSONArray) object; if (jsonArray.size() > 0) return getValue((JSONObject) jsonArray.get(0), property.substring(index + 1)); } } } return null; }
From source file:freebase.api.FreebaseAPIMusic.java
private static List<Recording> encodeJSON(JSONArray results) { List<Recording> recordings = new ArrayList<>(); for (Object recordingObj : results) { JSONObject recordingJObj = (JSONObject) recordingObj; Recording recording = new Recording(getId((String) recordingJObj.get("mid"), recording_map), (String) recordingJObj.get("mid"), (String) recordingJObj.get("name")); JSONArray recorded_by_arr = (JSONArray) recordingJObj.get("recorded_by"); JSONObject recorded_by = (JSONObject) recorded_by_arr.get(0); //Directedby directedby = new Directedby(); //directedby.setId(directedbyIDs.next()); Artist artist = new Artist(getId((String) recorded_by.get("mid"), artist_map), (String) recorded_by.get("mid"), (String) recorded_by.get("name")); recording.setArtist(artist);/* ww w. jav a 2 s . c o m*/ //directedby.setDirector(artist); //recording.setDirectedBy(directedby); recordings.add(recording); } return recordings; }