List of usage examples for org.json.simple JSONArray get
public E get(int index)
From source file:com.ge.research.semtk.load.utility.ImportSpecHandler.java
/** * Populate the texts with the correct instances based on the importspec. * @throws Exception //from w ww . j av a 2 s . co m */ private void setupTexts() throws Exception { // get the texts, if any JSONArray textsInfo = (JSONArray) this.importspec.get("texts"); if (textsInfo == null) { return; } for (int j = 0; j < textsInfo.size(); ++j) { JSONObject textJson = (JSONObject) textsInfo.get(j); String instanceID = (String) textJson.get("textId"); String textVal = (String) textJson.get("text"); this.textsAvailable.put(instanceID, textVal); } }
From source file:com.mp.gw2api.data.GW2APIAccount.java
@Override public void LoadFromJsonText(String text) { JSONParser parser = new JSONParser(); JSONObject json = null;/*from w ww .j a v a 2 s. c o m*/ JSONArray ja = null; JSONArray jb = null; try { //Parse json array json = (JSONObject) parser.parse(text); //Check for errors if (json.containsKey("text")) { errorText = (String) json.get("text"); return; } //Gather Account information id = (String) json.get("id"); name = (String) json.get("name"); world = (long) json.get("world"); ja = (JSONArray) json.get("guilds"); if (ja != null) if (ja.size() > 0) { guilds = new String[ja.size()]; for (int i = 0; i < ja.size(); i++) guilds[i] = (String) ja.get(i); } created = (String) json.get("created"); //access String accessStr = (String) json.get("access"); //For each AccessLevel String known. for (int i = 0; i < GW2Access.AccessStrings.length; i++) //If the accessStr read matches one known if (GW2Access.AccessStrings[i].equals(accessStr)) { //Fetch the enumeration related to that index access = AccessLevel.values()[i]; break;//break loop //If no values matched (error) } else if (i == GW2Access.AccessStrings.length - 1) access = AccessLevel.NONE; commander = (boolean) json.get("commander"); fractalLevel = (long) json.get("fractal_level"); dailyAP = (long) json.get("daily_ap"); monthlyAP = (long) json.get("monthly_ap"); wvwRank = (long) json.get("wvw_rank"); } catch (ParseException ex) { Logger.getLogger(com.mp.gw2api.lists.GW2APIMapList.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.ge.research.semtk.load.utility.ImportSpecHandler.java
/** * Return a pointer to every PropertyItem in ng that has a mapping in the import spec * @param ng//w w w .j av a 2s. c o m * @return */ public ArrayList<PropertyItem> getMappedPropItems(NodeGroup ng) { ArrayList<PropertyItem> ret = new ArrayList<PropertyItem>(); JSONArray nodes = (JSONArray) this.importspec.get("nodes"); // loop through the json nodes in the import spec for (int i = 0; i < nodes.size(); i++) { JSONObject nodeJson = (JSONObject) nodes.get(i); // get the related node from the NodeGroup String sparqlID = nodeJson.get("sparqlID").toString(); Node snode = ng.getNodeBySparqlID(sparqlID); // loop through Json node's properties JSONArray propsJArr = (JSONArray) nodeJson.get("props"); for (int j = 0; j < propsJArr.size(); j++) { JSONObject propJson = (JSONObject) propsJArr.get(j); String uriRelation = propJson.get("URIRelation").toString(); // if propertyJson has a mapping, return the PropertyItem JSONArray propMapJArr = (JSONArray) propJson.get("mapping"); if (propMapJArr != null && propMapJArr.size() > 0) { PropertyItem pItem = snode.getPropertyByURIRelation(uriRelation); ret.add(pItem); } } } return ret; }
From source file:net.emotivecloud.scheduler.drp4ost.DRP4OST.java
private boolean existsImage(String imageID) { boolean exists = false; //Get the Response Content in a String String images = oStackClient.getAllImages(); // Parsing the JSON response to get all the images JSONObject allImages = (JSONObject) JSONValue.parse(images); JSONArray jsonImages = (JSONArray) allImages.get("images"); for (int i = 0; i < jsonImages.size(); ++i) { JSONObject image = (JSONObject) jsonImages.get(i); String tmpImgID = image.get("name").toString(); if (tmpImgID.equals(imageID)) { exists = true;/* w ww .jav a 2 s . c o m*/ break; } } return exists; }
From source file:net.emotivecloud.scheduler.drp4ost.DRP4OST.java
private OVFWrapper[] getAllServersWrappers() { ArrayList<OVFWrapper> wrappers = new ArrayList<OVFWrapper>(); String servers = oStackClient.getAllServers(); JSONObject allServers = (JSONObject) JSONValue.parse(servers); JSONArray jsonServers = (JSONArray) allServers.get("servers"); for (int i = 0; i < jsonServers.size(); ++i) { JSONObject server = (JSONObject) jsonServers.get(i); OVFWrapper wTmp = this.parse(server.toString()); wrappers.add(wTmp);//from w w w.j a v a 2 s . c o m } OVFWrapper vms[] = wrappers.toArray(new OVFWrapper[wrappers.size()]); return vms; }
From source file:MemoryController.java
@RequestMapping("/memory") public @ResponseBody Memory memory( @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication, @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid, @RequestParam(value = "metricType", required = false, defaultValue = "") String name) throws FileNotFoundException, UnsupportedEncodingException, IOException { Properties props = new Properties(); FileInputStream fis = new FileInputStream("properties.xml"); //loading properites from properties file props.loadFromXML(fis);/* w w w .java 2 s .c om*/ String server_ip = props.getProperty("server_ip"); String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip JSONParser parser = new JSONParser(); HttpClient client = new HttpClient(); PutMethod putMethod = new PutMethod(ZABBIX_API_URL); putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this // create json object for apiinfo.version JSONObject jsonObj = new JSONObject(); jsonObj.put("jsonrpc", "2.0"); jsonObj.put("method", "item.get"); JSONObject params = new JSONObject(); params.put("output", "extend"); params.put("hostid", hostid); JSONObject search = new JSONObject(); search.put("key_", "memory"); params.put("search", search); params.put("sortfield", "name"); jsonObj.put("params", params); jsonObj.put("auth", authentication);// todo jsonObj.put("id", new Integer(1)); putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body PutMethod putMethod2 = new PutMethod(ZABBIX_API_URL); putMethod2.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this // create json object for apiinfo.version JSONObject jsonObj2 = new JSONObject(); jsonObj2.put("jsonrpc", "2.0"); jsonObj2.put("method", "item.get"); JSONObject params2 = new JSONObject(); params2.put("output", "extend"); params2.put("hostid", hostid); JSONObject search2 = new JSONObject(); search2.put("key_", "swap"); params2.put("search", search2); params2.put("sortfield", "name"); jsonObj2.put("params", params2); jsonObj2.put("auth", authentication);// todo jsonObj2.put("id", new Integer(1)); putMethod2.setRequestBody(jsonObj2.toString()); String loginResponse = ""; String loginResponse2 = ""; String memory = ""; String clock = ""; String metricType = ""; try { client.executeMethod(putMethod); // send to request to the zabbix api loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response Object obj = parser.parse(loginResponse); JSONObject obj2 = (JSONObject) obj; String jsonrpc = (String) obj2.get("jsonrpc"); JSONArray array = (JSONArray) obj2.get("result"); client.executeMethod(putMethod2); // send to request to the zabbix api loginResponse2 = putMethod2.getResponseBodyAsString(); // read the result of the response Object obj3 = parser.parse(loginResponse2); JSONObject obj4 = (JSONObject) obj3; String jsonrpc2 = (String) obj4.get("jsonrpc"); JSONArray array2 = (JSONArray) obj4.get("result"); for (int i = 0; i < array.size(); i++) { JSONObject tobj = (JSONObject) array.get(i); // lastValue = getLastValue(tobj); // lastClock = getLastClock(tobj); if (!tobj.get("hostid").equals(hostid)) continue; if (name.equals("totalMemory") && tobj.get("name").equals("Total memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Total Memeory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("cachedMemory") && tobj.get("name").equals("Cached memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Cached Memory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("freeMemory") && tobj.get("name").equals("Free memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Free Memory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("bufferedMemory") && tobj.get("name").equals("Buffers memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Buffered Memory"; return new Memory(hostid, metricType, memory, clock); } else if (name.equals("sharedMemory") && tobj.get("name").equals("Shared memory")) { memory = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "Shared Memory"; return new Memory(hostid, metricType, memory, clock); } else { continue; } } for (int i = 0; i < array2.size(); i++) { JSONObject tobj2 = (JSONObject) array2.get(i); if (!tobj2.get("hostid").equals(hostid)) continue; if (name.equals("freeSwap") && tobj2.get("name").equals("Free swap space")) { memory = (String) tobj2.get("lastvalue"); clock = (String) tobj2.get("lastclock"); metricType = "Free Swap Space"; return new Memory(hostid, metricType, memory, clock); } else { continue; } } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException pe) { System.out.println("Error"); } return new Memory( "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:"); }
From source file:com.acmeair.jmeter.functions.ExtrackBookingInfoFunction.java
private void processJSonString(SampleResult sample) { try {//from w ww . ja va2 s . com Object returnObject = new JSONParser().parse(sample.getResponseDataAsString()); JSONArray jsonArray; if (returnObject instanceof JSONArray) { jsonArray = (JSONArray) returnObject; } else { throw new RuntimeException("failed to parse booking information: " + returnObject.toString()); } int bookingNum = jsonArray.size(); context.setNUMBER_OF_BOOKINGS(bookingNum + ""); if (bookingNum > 2) { context.setNUMBER_TO_CANCEL(bookingNum - 2 + ""); } else { context.setNUMBER_TO_CANCEL("0"); } String[] bookingIds = new String[bookingNum]; for (int counter = 0; counter < bookingNum; counter++) { JSONObject booking = (JSONObject) jsonArray.get(counter);// .pkey.id; String bookingId; if (ExtractFlightsInfoFunction.pureIDs) { bookingId = (String) booking.get("_id"); } else { JSONObject bookingPkey = (JSONObject) booking.get("pkey"); bookingId = (String) bookingPkey.get("id"); } bookingIds[counter] = bookingId; } context.setBOOKING_IDs(bookingIds); BookingThreadLocal.set(context); } catch (ParseException e) { System.out.println("responseDataAsString = " + sample.getResponseDataAsString()); e.printStackTrace(); } catch (NullPointerException e) { System.out.println("NullPointerException in ExtrackBookingInfoFunction - ResponseData =" + sample.getResponseDataAsString()); e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.wcmc.Software.excel.ExportCMAPoints.java
@Override public void run() { Date now = new Date(); SimpleDateFormat date = new SimpleDateFormat("yyyy"); String year = date.format(now); JFileChooser saveAs = new JFileChooser(System.getProperty("user.home")); saveAs.setDialogTitle("Save Standings For The " + year + " Season"); saveAs.setFileFilter(new FileNameExtensionFilter("Excel 2003 (*.xls)", "xls")); if (saveAs.showSaveDialog(Client.window) == JFileChooser.APPROVE_OPTION) { File exportFile = null;/*w ww .jav a2s. c o m*/ if (!saveAs.getSelectedFile().toString().endsWith(".xls")) { exportFile = new File(saveAs.getSelectedFile().getAbsolutePath() + ".xls"); } else { exportFile = saveAs.getSelectedFile(); } try { WritableWorkbook excelFile = Workbook.createWorkbook(exportFile); System.out.println("Exporting Standings..."); int sheetNumber = 0; ArrayList<ClassItem> classes = Client.ms.rS.classes.getClasses(); Client.ms.trS.prgExport.setVisible(true); Client.ms.trS.prgExport.setPercent(0); Client.ms.trS.prgClass.setVisible(true); Client.ms.trS.prgClass.setPercent(0); Client.ms.trS.overall.setVisible(true); Client.ms.trS.classSpecific.setVisible(true); for (int i = 0; i < classes.size(); i++) { ClassItem c = classes.get(i); Client.ms.trS.classSpecific.setText("Class: " + c.getText()); WritableSheet classSheet = excelFile.createSheet(c.getText().toString(), sheetNumber); classSheet.mergeCells(1, 1, 13, 1); classSheet.addCell(new Label(1, 1, c.getText().toString() + " - Niagara Motorcycle Raceway - " + year + " Season", headerGrey)); classSheet.addCell(new Label(1, 3, "Plate #", headerBold)); classSheet.addCell(new Label(2, 3, "CMA", headerBold)); classSheet.addCell(new Label(3, 3, "First Name", headerBold)); classSheet.addCell(new Label(4, 3, "Last Name", headerBold)); classSheet.addCell(new Label(5, 3, "Total Points", headerBold)); Client.sc.send(CONST.GET_RACE_DATES + " " + year + CONST.seperator + c.getID()); String jsonData = null; while ((jsonData = Client.sc.getInfo()) == null) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } if (jsonData != null) { JSONParser parse = new JSONParser(); JSONObject jsonDates = (JSONObject) parse.parse(jsonData); if (jsonDates != null) { JSONArray jsonDatesArray = (JSONArray) jsonDates.get("dates"); JSONArray riderDataArray = (JSONArray) jsonDates.get("riders"); if (riderDataArray.size() == 0) { excelFile.removeSheet(sheetNumber); continue; } for (int d = 0; d < jsonDatesArray.size(); d++) { String dateString = (String) jsonDatesArray.get(d); classSheet.mergeCells(6 + (d * 2), 3, 6 + (d * 2) + 1, 3); DateFormat customDateFormat = new DateFormat("MMMM dd"); WritableCellFormat dateFormat = new WritableCellFormat(customDateFormat); dateFormat.setBorder(Border.ALL, BorderLineStyle.THICK); dateFormat.setAlignment(Alignment.CENTRE); dateFormat.setFont(arial10bold); SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-M-d"); Date eventDate = dateParser.parse(dateString); jxl.write.DateTime dateFormatCell = new jxl.write.DateTime(6 + (d * 2), 3, eventDate, dateFormat); classSheet.addCell(dateFormatCell); classSheet.addCell(new Label(6 + (d * 2), 5, "POS", dataCenter)); classSheet.addCell(new Label(6 + (d * 2) + 1, 5, "Points", dataCenter)); classSheet.setColumnView(6 + (d * 2), 10); classSheet.setColumnView(6 + (d * 2) + 1, 10); } classSheet.addCell(new Label(6 + jsonDatesArray.size() * 2, 3, "City", headerBold)); classSheet.addCell(new Label(7 + jsonDatesArray.size() * 2, 3, "Sponsors", headerBold)); classSheet.setColumnView(6 + jsonDatesArray.size() * 2, 25); classSheet.setColumnView(7 + jsonDatesArray.size() * 2, 75); for (int r = 0; r < riderDataArray.size(); r++) { JSONObject rider = (JSONObject) riderDataArray.get(r); JSONObject bike = (JSONObject) rider.get("bike"); if (bike != null) { classSheet.addCell(new Number(1, 6 + r, (long) bike.get("plate"), pointsBold)); } classSheet.addCell(new Label(2, 6 + r, (String) rider.get("license"), pointsBold)); classSheet .addCell(new Label(3, 6 + r, (String) rider.get("first_name"), dataCenter)); classSheet .addCell(new Label(4, 6 + r, (String) rider.get("last_name"), dataCenter)); classSheet .addCell(new Number(5, 6 + r, (long) rider.get("totalPoints"), pointsBold)); JSONArray events = (JSONArray) rider.get("events"); boolean hasEvent = false; for (int d = 0; d < jsonDatesArray.size(); d++) { hasEvent = false; for (int e = 0; e < events.size(); e++) { String dateString = (String) jsonDatesArray.get(d); JSONObject event = (JSONObject) events.get(e); if (event.get("date").equals(dateString)) { classSheet.addCell(new Number(6 + (d * 2), 6 + r, (long) event.get("position"), dataCenter)); classSheet.addCell(new Number(6 + (d * 2) + 1, 6 + r, (long) event.get("points"), dataCenter)); hasEvent = true; } } if (!hasEvent) { classSheet.addCell(new Label(6 + (d * 2), 6 + r, "", dataCenter)); classSheet.addCell(new Label(6 + (d * 2) + 1, 6 + r, "", dataCenter)); } } classSheet.addCell(new Label(6 + (jsonDatesArray.size() * 2), 6 + r, (String) rider.get("city"), dataCenter)); classSheet.addCell(new Label(7 + (jsonDatesArray.size() * 2), 6 + r, (String) rider.get("sponsors"), dataWrapped)); Client.ms.trS.prgClass .setPercent(((double) r / (double) riderDataArray.size()) * 100); } } } // Set Widths classSheet.setRowView(3, 300); classSheet.setColumnView(1, 10); classSheet.setColumnView(2, 10); classSheet.setColumnView(3, 18); classSheet.setColumnView(4, 18); classSheet.setColumnView(5, 15); sheetNumber++; Client.ms.trS.prgExport .setPercent(((double) i / (double) Client.ms.rS.classes.getClasses().size()) * 100); } excelFile.write(); excelFile.close(); WorkBook sortedWorkbook = new WorkBook(); try { sortedWorkbook.read(new FileInputStream(exportFile)); for (int i = 0; i < sheetNumber; i++) { sortedWorkbook.setSheet(i); sortedWorkbook.sort(6, 1, 60, 60, true, -5, 0, 0); } sortedWorkbook.setSheet(0); FileOutputStream out = new FileOutputStream(exportFile); sortedWorkbook.write(out); out.close(); } catch (Exception e) { e.printStackTrace(); } Client.ms.trS.prgExport.setVisible(false); Client.ms.trS.prgClass.setVisible(false); Client.ms.trS.overall.setVisible(false); Client.ms.trS.classSpecific.setVisible(false); } catch (IOException | WriteException | ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (java.text.ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
From source file:gov.usda.DataCatalogClient.Catalog.java
/** * Adds bureau name and bureau abbreviation to a dataset from a config file, normally * bureau_config_data.json. Called from addBureaNameToDataset which goes through * the entire catalog./* w w w . j a v a 2s . co m*/ * @param ds * @param bureauArray */ private void addBureauName(Dataset ds, JSONArray bureauArray) { Boolean found = false; List<String> bureauCodeList = ds.getBureauCodeList(); for (String bureauCode : bureauCodeList) { for (int i = 0; i < bureauArray.size(); i++) { JSONObject bureauObject = (JSONObject) bureauArray.get(i); if (bureauCode.equals(bureauObject.get("bureau_code"))) { ds.setBureauName((String) bureauObject.get("bureau_name")); ds.setBureauAbbreviation((String) bureauObject.get("bureau_abbreviation")); found = true; } } if (!found) { ds.setBureauName( "Name not found for bureau code: " + bureauCode + ", see bureau configuration file."); } found = false; } }
From source file:net.emotivecloud.scheduler.drp4ost.DRP4OST.java
@GET @Path("/resources") @Produces("application/xml") public ListStrings getNodes() { ListStrings list = new ListStrings(); ArrayList<String> hostsNames = new ArrayList<String>(); String hosts = oStackClient.getHosts(); JSONObject jsonHosts = (JSONObject) JSONValue.parse(hosts); JSONArray jsonHostsArray = (JSONArray) jsonHosts.get("hosts"); for (int i = 0; i < jsonHostsArray.size(); ++i) { JSONObject flavor = (JSONObject) jsonHostsArray.get(i); String hostName = flavor.get("host_name").toString(); hostsNames.add(hostName);//from w w w. ja va 2 s . c o m } list.addAll(hostsNames); // list.addAll(super.getNodes()); //GenericEntity<ListStrings> entity = new GenericEntity<ListStrings>(list) {}; //Response response = Response.ok(entity).build(); return list; }