List of usage examples for org.json.simple JSONArray get
public E get(int index)
From source file:com.lifetime.util.TimeOffUtil.java
protected static List<RepliconTimeOff> createTimeOffList(String response) throws ParseException { JSONParser parser = new JSONParser(); JSONObject jsonObject = (JSONObject) parser.parse(response); JSONObject d = (JSONObject) jsonObject.get("d"); JSONArray rows = (JSONArray) d.get("rows"); List<RepliconTimeOff> list = new ArrayList<RepliconTimeOff>(); for (Object row : rows) { JSONArray cells = (JSONArray) ((JSONObject) row).get("cells"); JSONObject owner = (JSONObject) cells.get(0); String employeeName = (String) owner.get("textValue"); JSONObject department = (JSONObject) cells.get(1); String departmentName = (String) department.get("textValue"); JSONObject ptoType = (JSONObject) cells.get(2); String ptoTypeName = (String) ptoType.get("textValue"); SimpleDateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy"); JSONObject startDateJson = (JSONObject) cells.get(3); String startDateString = (String) startDateJson.get("textValue"); Date startDate = null;//from w w w . j av a 2 s. c om try { startDate = dateFormat.parse(startDateString); } catch (java.text.ParseException e) { e.printStackTrace(); } JSONObject endDateJson = (JSONObject) cells.get(3); String endDateString = (String) endDateJson.get("textValue"); Date endDate = null; try { endDate = dateFormat.parse(endDateString); } catch (java.text.ParseException e) { e.printStackTrace(); } JSONObject approvedJson = (JSONObject) cells.get(5); String approvedString = (String) approvedJson.get("textValue"); boolean approved = approvedString.equals("Approved") ? true : false; RepliconTimeOff repliconTimeOff = new RepliconTimeOffImpl(employeeName, departmentName, startDate, endDate, ptoTypeName, approved); list.add(repliconTimeOff); } return list; }
From source file:iracing.webapi.HostedSessionResultSummaryParser.java
static long parse(String json, ItemHandler handler) { JSONParser parser = new JSONParser(); // System.err.println(json); long output = 0; if (!"{}".equals(json)) { try {/*from ww w . j a va2s. com*/ JSONObject root = (JSONObject) parser.parse(json); output = getLong(root, "rowcount"); JSONArray rootArray = (JSONArray) root.get("rows"); for (int i = 0; i < rootArray.size(); i++) { JSONObject r = (JSONObject) rootArray.get(i); HostedSessionResultSummary summary = new HostedSessionResultSummary(); summary.setWasPrivate((getInt(r, "private")) == 1); summary.setDriverSearchedBestLapTime(getLong(r, "bestlaptime")); summary.setDriverSearchedStartingPosition(getInt(r, "startingposition")); summary.setDriverSearchedClassStartingPosition(getInt(r, "classstartingposition")); summary.setDriverSearchedFinishingPosition(getInt(r, "finishingposition")); summary.setDriverSearchedClassFinishingPosition(getInt(r, "classfinishingposition")); summary.setDriverSearchedCarClassId(getInt(r, "carclassid")); summary.setDriverSearchedIncidents(getInt(r, "incidents")); summary.setPracticeLength(getInt(r, "practicelength")); summary.setQualifyingLaps(getInt(r, "qualifylaps")); summary.setQualifyingLength(getInt(r, "qualifylength")); summary.setRaceLaps(getInt(r, "racelaps")); summary.setRaceLength(getInt(r, "racelength")); summary.setStartTime(new Date(getLong(r, "start_time"))); summary.setMinimumLicenseLevel(getInt(r, "minliclevel")); summary.setMaximumLicenseLevel(getInt(r, "maxliclevel")); summary.setMinimumIrating(getInt(r, "minir")); summary.setMaximumIrating(getInt(r, "maxir")); summary.setPrivateSessionId(getLong(r, "privatesessionid")); IracingCustomer host = new IracingCustomer(); host.setId(getLong(r, "host_custid")); host.setName(getString(r, "host_displayname", true)); summary.setHost(host); summary.setHostLicenseLevel(getInt(r, "host_licenselevel")); summary.setSessionName(getString(r, "sessionname", true)); summary.setTrackId(getInt(r, "trackid")); summary.setTrackName(getString(r, "track_name", true)); IracingCustomer winner = new IracingCustomer(); winner.setId(getLong(r, "winner_custid")); winner.setName(getString(r, "winner_displayname", true)); summary.setWinner(winner); summary.setWinnerLicenseLevel(getInt(r, "winner_licenselevel")); summary.setSessionId(getLong(r, "sessionid")); summary.setSubSessionId(getLong(r, "subsessionid")); summary.setSubSessionFinishedAt(new Date(getLong(r, "subsessionfinishedat"))); summary.setRaceFinishedAt(new Date(getLong(r, "racefinishedat"))); summary.setLoneQualifying((getInt(r, "lonequalify")) == 1); summary.setHardcoreLevelId(getInt(r, "hardcorelevel")); summary.setNightMode((getInt(r, "nightmode")) == 1); summary.setRestarts(getInt(r, "restarts")); summary.setFullCourseCautions((getInt(r, "fullcoursecautions")) == 1); summary.setRollingStarts((getInt(r, "rollingstarts")) == 1); summary.setMultiClass((getInt(r, "multiclass")) == 1); summary.setFixedSetup((getInt(r, "fixed_setup")) == 1); summary.setNumberOfFastTows(getInt(r, "numfasttows")); String s = getString(r, "carids", true); String[] sa = s.split(","); List<Integer> carIds = new ArrayList<Integer>(); for (String carId : sa) { carIds.add(Integer.parseInt(carId)); } summary.setCars(carIds); s = getString(r, "max_pct_fuel_fills", true); if (!"".equals(s)) { sa = s.split(","); List<Integer> maxFuelFills = new ArrayList<Integer>(); for (String mff : sa) { maxFuelFills.add(Integer.parseInt(mff)); } summary.setMaximumPercentageFuelFills(maxFuelFills); } summary.setMaximumDrivers(getInt(r, "maxdrivers")); summary.setCreated(new Date(getLong(r, "created"))); summary.setSessionFastestLap(getLong(r, "sessionfastlap")); summary.setCategoryId(getInt(r, "catid")); handler.onHostedSessionResultSummaryParsed(summary); } } catch (ParseException ex) { Logger.getLogger(HostedSessionResultSummaryParser.class.getName()).log(Level.SEVERE, null, ex); } } return output; }
From source file:kltn.geocoding.Geocoding.java
private static Geometry getBoundary(String s) throws MalformedURLException, IOException, org.json.simple.parser.ParseException { String link = "https://maps.googleapis.com/maps/api/geocode/json?&key=AIzaSyALCgmmer3Cht-mFQiaJC9yoWdSqvfdAiM"; link = link + "&address=" + URLEncoder.encode(s); URL url = new URL(link); HttpsURLConnection httpsCon = (HttpsURLConnection) url.openConnection(); InputStream is = httpsCon.getInputStream(); StringWriter writer = new StringWriter(); IOUtils.copy(is, writer, "UTF-8"); String jsonString = writer.toString(); JSONParser parse = new JSONParser(); Object obj = parse.parse(jsonString); JSONObject jsonObject = (JSONObject) obj; System.out.println(s);//from ww w . j a va 2s . c o m System.out.println(jsonObject.toJSONString()); JSONArray resultArr = (JSONArray) jsonObject.get("results"); Object resultObject = parse.parse(resultArr.get(0).toString()); JSONObject resultJsonObject = (JSONObject) resultObject; Object geoObject = parse.parse(resultJsonObject.get("geometry").toString()); JSONObject geoJsonObject = (JSONObject) geoObject; if (!geoJsonObject.containsKey("bounds")) { return null; } Object boundObject = parse.parse(geoJsonObject.get("bounds").toString()); JSONObject boundJsonObject = (JSONObject) boundObject; // System.out.println(boundJsonObject.toJSONString()); Object southwest = parse.parse(boundJsonObject.get("southwest").toString()); JSONObject southwestJson = (JSONObject) southwest; String southwestLat = southwestJson.get("lat").toString(); String southwestLong = southwestJson.get("lng").toString(); Object northeast = parse.parse(boundJsonObject.get("northeast").toString()); JSONObject northeastJson = (JSONObject) northeast; String northeastLat = northeastJson.get("lat").toString(); String northeastLong = northeastJson.get("lng").toString(); String polygon = "POLYGON((" + southwestLong.trim() + " " + northeastLat.trim() + "," + northeastLong.trim() + " " + northeastLat.trim() + "," + northeastLong.trim() + " " + southwestLat.trim() + "," + southwestLong.trim() + " " + southwestLat.trim() + "," + southwestLong.trim() + " " + northeastLat.trim() + "))"; Geometry geo = wktToGeometry(polygon); return geo; }
From source file:kjscompiler.Program.java
private static void run() throws ParseException, IOException, NullPointerException { Settings settings = new Settings(settingsPath); System.out.println("Searching for " + settings.getPattern() + " in " + settings.getBaseDir()); JSONArray Base = settings.getBaseDir(); List<String> files = new ArrayList<String>(); for (int i = 0; i < Base.size(); i++) { files.addAll(FileScanner.run((String) Base.get(i), settings.getPattern(), settings.getProjectPath())); }//from w ww .j a va 2 s . c om System.out.println("Found " + files.size() + " files"); List<FileInfo> fiPrimaries = new ArrayList<FileInfo>(); List<String> pExternals = new ArrayList<String>(); Hashtable<String, Integer> fiHtPrimaries = new Hashtable<String, Integer>(); for (String fullpath : files) { FileInfo fi = new FileInfo(fullpath); if (!fi.getIsIgnore()) { if (fi.getIsExternal()) { pExternals.add(fi.getFilename()); } else { fiPrimaries.add(fi); } } } System.out.println("Primaries: " + fiPrimaries.size() + " files"); System.out.println("Externals: " + pExternals.size() + " files"); OrderDeps od = new OrderDeps(fiPrimaries); List<FileInfo> ordered = od.getOrderedFiles(); List<String> oErrors = od.getErrors(); for (int i = 0, length = oErrors.size(); i < length; i++) { String err = oErrors.get(i); System.out.println("Order Error #" + (i + 1) + ": " + err); } System.out.println("Primaries ordered"); List<String> pPrimaries = new ArrayList<String>(); for (int i = 0, length = ordered.size(); i < length; i++) { pPrimaries.add(ordered.get(i).getFilename()); } String compilationLevel = settings.getLevel(); GoogleClosureCompiler compiler = new GoogleClosureCompiler(pPrimaries, settings.getOutput(), compilationLevel, pExternals); compiler.setWrapper(settings.getWrapper()); compiler.setWarningLevel(WarningLevel.VERBOSE); compiler.run(); System.out.println("Compiled file: " + settings.getOutput()); JSError[] errors = compiler.getErrors(); for (int i = 0, length = errors.length; i < length; i++) { JSError err = errors[i]; System.out.println("Error #" + (i + 1) + ": " + err.description + " in " + err.sourceName + " (" + err.lineNumber + ")"); } if (errors.length == 0) { JSError[] warnings = compiler.getWarnings(); for (int i = 0, length = warnings.length; i < length; i++) { JSError warn = errors[i]; System.out.println("Warning #" + (i + 1) + ": " + warn.description + " in " + warn.sourceName + " (" + warn.lineNumber + ")"); } } System.out.println("\n\n Thank you for using kJScompiler!\n Who said JavaScript can't be compiled?\n"); System.exit(0); }
From source file:mini_mirc_client.Mini_mirc_client.java
public static void showMsg() { try {/* w ww .j a 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.healthcit.analytics.utils.ExcelExportUtils.java
@SuppressWarnings("unchecked") public static void streamVisualizationDataAsExcelFormat(OutputStream out, JSONObject data) { // Get the array of columns JSONArray jsonColumnArray = (JSONArray) data.get(COLUMNS_JSON_KEY); String[] excelColumnArray = new String[jsonColumnArray.size()]; for (int index = 0; index < excelColumnArray.length; ++index) { excelColumnArray[index] = (String) ((JSONObject) jsonColumnArray.get(index)).get(LABEL_JSON_KEY); }/*from w w w. j a v a 2 s . c o m*/ // Get the array of rows JSONArray jsonRowArray = (JSONArray) data.get(ROWS_JSON_KEY); JSONArray excelRowArray = new JSONArray(); Iterator<JSONObject> jsonRowIterator = jsonRowArray.iterator(); while (jsonRowIterator.hasNext()) { JSONArray rowCell = (JSONArray) jsonRowIterator.next().get(ROWCELL_JSON_KEY); JSONObject excelRowObj = new JSONObject(); for (int index = 0; index < rowCell.size(); ++index) { excelRowObj.put(excelColumnArray[index], ((JSONObject) rowCell.get(index)).get(ROWCELLVALUE_JSON_KEY)); } excelRowArray.add(excelRowObj); } // build the Excel outputstream Json2Excel.build(out, excelRowArray.toJSONString(), excelColumnArray); }
From source file:me.fromgate.facechat.UpdateChecker.java
private static void updateLastVersion() { if (!enableUpdateChecker) return;/*from w ww . ja va2 s. c o 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 ww. j av a 2 s . c om*/ // 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:Controller.MainClass.java
public static String getLocationFromAPi(String CityName) throws ParseException { String[] list;/*from ww w . ja va 2 s . c o m*/ list = CityName.replaceAll("[^a-zA-Z]", "").toLowerCase().split("\\s+"); CityName = list[0]; String Address = ""; String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + CityName + "&sensor=false"; try { String genreJson = IOUtils.toString(new URL(url)); JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson); JSONArray genreArray = (JSONArray) genreJsonObject.get("results"); if (genreArray.size() == 0) { return ""; } else { JSONObject firstGenre = (JSONObject) genreArray.get(0); String City = firstGenre.get("formatted_address").toString(); JSONObject obj = (JSONObject) firstGenre.get("geometry"); JSONObject loc = (JSONObject) obj.get("location"); String lat = loc.get("lat").toString(); String lng = loc.get("lng").toString(); Address = (String) (lat + "/" + lng + "/" + City); } } catch (IOException e) { e.printStackTrace(); } return Address; }
From source file:Models.Geographic.Repository.RepositoryGoogle.java
/** * //w w w .j a v a2 s . c om * @param latitude * @param longitude * @return */ public static HashMap reverse(double latitude, double longitude) { HashMap a = new HashMap(); try { //URL url=new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng=" + String.valueOf(latitude) + "," + String.valueOf(longitude)); URL url = new URL(Configuration.getParameter("geocoding_google_url_send_json") + "latlng=" + String.valueOf(latitude) + "," + String.valueOf(longitude)); URL file_url = new URL( url.getProtocol() + "://" + url.getHost() + signRequest(url.getPath(), url.getQuery())); //BufferedReader lector=new BufferedReader(new InputStreamReader(url.openStream())); BufferedReader lector = new BufferedReader(new InputStreamReader(file_url.openStream())); String textJson = "", tempJs; while ((tempJs = lector.readLine()) != null) textJson += tempJs; if (textJson == null) throw new Exception("Don't found item"); JSONObject google = ((JSONObject) JSONValue.parse(textJson)); a.put("status", google.get("status").toString()); if (a.get("status").toString().equals("OK")) { JSONArray results = (JSONArray) google.get("results"); JSONArray address_components = (JSONArray) ((JSONObject) results.get(2)).get("address_components"); for (int i = 0; i < address_components.size(); i++) { JSONObject items = (JSONObject) address_components.get(i); //if(((JSONObject)types.get(0)).get("").toString().equals("country")) if (items.get("types").toString().contains("country")) { a.put("country", items.get("long_name").toString()); a.put("iso", items.get("short_name").toString()); break; } } } } catch (Exception ex) { a = null; System.out.println("Error Google Geocoding: " + ex); } return a; }