List of usage examples for org.json.simple JSONArray size
public int size()
From source file:org.apache.storm.scheduler.utils.ArtifactoryConfigLoader.java
private String loadMostRecentArtifact(String location, String host, Integer port) { // Is this a directory or is it a file? JSONObject json = getArtifactMetadata(location, host, port); if (json == null) { LOG.error("got null metadata"); return null; }/*from w w w. j a va 2 s .c o m*/ String downloadURI = (String) json.get("downloadUri"); // This means we are pointing at a file. if (downloadURI != null) { // Then get it and return the file as string. String returnValue = doGet(null, location, host, port); saveInArtifactoryCache(returnValue); return returnValue; } // This should mean that we were pointed at a directory. // Find the most recent child and load that. JSONArray msg = (JSONArray) json.get("children"); if (msg == null || msg.size() == 0) { LOG.error("Expected directory children not present"); return null; } JSONObject newest = (JSONObject) Collections.max(msg, new DirEntryCompare()); if (newest == null) { LOG.error("Failed to find most recent artifact uri in {}", location); return null; } String uri = (String) newest.get("uri"); if (uri == null) { LOG.error("Expected directory uri not present"); return null; } String returnValue = doGet(null, location + uri, host, port); saveInArtifactoryCache(returnValue); return returnValue; }
From source file:com.skelril.ShivtrAuth.AuthenticationCore.java
@Override public synchronized void run() { JSONArray characters = getFrom("characters.json"); log.info("Testing the connection to " + websiteURL + "..."); if (characters != null) { log.info("Connection test successful."); if (characters.size() > 0) { updateWhiteList(characters); } else {//from ww w . j a v a2 s .c o m log.warning("No characters could be downloaded!"); log.info("Your website could be under maintenance or contain no characters."); } } else { log.warning("Connection test failed!"); } if (this.characters.size() == 0) { log.info("Attempting to load offline files..."); loadBackupWhiteList(); } log.info(this.characters.size() + " characters have been loaded."); }
From source file:com.telefonica.iot.tidoop.apiext.backends.ckan.CKANBackend.java
/** * Gets the resource identifiers/names within a given package id/name. * @param pkgId//from w ww . ja v a 2s. com * @return The resource identifiers/names within the given package id/name */ public List<String> getResources(String pkgId) { logger.debug("Getting the resources within " + pkgId + " + package"); List<String> resIds = new ArrayList<String>(); try { String url = "http" + (ssl ? "s" : "") + "://" + ckanHost + ":" + ckanPort + "/api/3/action/package_show?id=" + pkgId; CKANResponse resp = doCKANRequest("GET", url, ""); JSONObject result = (JSONObject) resp.getJsonObject().get("result"); JSONArray resources = (JSONArray) result.get("resources"); if (resources == null || resources.size() == 0) { logger.debug("No resources got from package " + pkgId); return resIds; } // if for (Object res : resources) { JSONObject resource = (JSONObject) res; resIds.add((String) resource.get("id")); } // for return resIds; } catch (Exception e) { logger.debug("An exception occured, returning partial resource list. Details=" + e.getMessage()); return resIds; } // try catch }
From source file:com.telefonica.iot.tidoop.apiext.backends.ckan.CKANBackend.java
/** * Gets the total number of records within a given resource. * @param resId Resource identifier/*from w ww . ja v a 2 s. c o m*/ * @return The total number of records within the given resource */ public int getNumRecords(String resId) { logger.debug("Getting the number of records within " + resId); try { int numRecords = 0; int i = 0; while (true) { String url = "http" + (ssl ? "s" : "") + "://" + ckanHost + ":" + ckanPort + "/api/3/action/datastore_search?limit=" + splitsLength + "&offset=" + (i * splitsLength) + "&resource_id=" + resId; CKANResponse resp = doCKANRequest("GET", url, ""); JSONObject result = (JSONObject) resp.getJsonObject().get("result"); JSONArray records = (JSONArray) result.get("records"); if (records == null || records.size() == 0) { logger.debug("No records got from resource " + resId); break; } // if numRecords += records.size(); i++; } // while return numRecords; } catch (Exception e) { logger.debug("An exception occured, returning 0 records. Details=" + e.getMessage()); return 0; } // try catch }
From source file:com.orthancserver.DicomDecoder.java
private String[] GetSlices(OrthancConnection c, JSONArray instances) throws IOException { String[] result;/*from www. ja va 2s. c om*/ result = SortSlicesBy3D(c, instances); if (result != null && result.length == instances.size()) { return result; } result = SortSlicesByNumber(c, instances); if (result != null && result.length == instances.size()) { return result; } throw new IOException("Not a 3D image"); }
From source file:test.portlet.service.impl.MolgenisAPIRequestLocalServiceImpl.java
/** * /*from ww w. j a v a 2s . com*/ * @param token * @return */ private String readData(String biobankid) { //String url = "https://molgenis21.target.rug.nl/api/v2/test?aggs=x==Diseases;distinct==ParticipantID&q=BiobankID=q=\"http%3A%2F%2Fcatalogue.rd-connect.eu%2Fweb%2F71542\""; //String url = "https://molgenis21.target.rug.nl/api/v2/test?aggs=x==Diseases;distinct==ParticipantID"; String url = "https://molgenis21.target.rug.nl/api/v2/rdconnect_Sample?aggs=x==Disease;distinct==ParticipantID&q=BiobankID==" + biobankid; System.out.println(url); try { // Construct Table Columns String cols = "{key: 'Disease Name',sortable: true},"; cols += "{key: 'Number of Patients, Donors',sortable: true},"; cols += "{key: 'Gene',sortable: true},"; cols += "{key: 'ORPHA Code',sortable: true},"; cols += "{key: 'ICD 10',sortable: true},"; cols += "{key: 'OMIM',sortable: true},"; cols += "{key: 'Synonym(s)',sortable: true}"; // Create request HttpClient clinet = HttpClientBuilder.create().build(); HttpGet get = new HttpGet(url); get.addHeader("x-molgenis-token", token_); HttpResponse response = clinet.execute(get); BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String line = ""; while ((line = reader.readLine()) != null) { if (line.contains("{\"errors\":[{\"message\":\"No COUNT permission on entity test\"}]}")) { // Login Error: return "ERROR:LoginPermission."; } else { String data = ""; // Parse our JSON response JSONParser jsonparser = new JSONParser(); JSONObject baseobject = (JSONObject) jsonparser.parse(line); // getting the aggregated table JSONObject aggregates = (JSONObject) baseobject.get("aggs"); JSONArray xlabelarray = (JSONArray) aggregates.get("xLabels"); JSONArray matrixarray = (JSONArray) aggregates.get("matrix"); for (int rows = 0; rows < xlabelarray.size(); rows++) { JSONObject xlabel = (JSONObject) xlabelarray.get(rows); JSONArray count = (JSONArray) matrixarray.get(rows); if (!data.equals("")) { data += ","; } data += "{'Disease Name':'" + (String) xlabel.get("Label") + "',"; data += "'Number of Patients, Donors':'" + count.get(0) + "',"; data += "'ORPHA Code':'" + (String) xlabel.get("IRI") + "'}"; } String returnstring = "AUI().use('aui-datatable','aui-datatype','datatable-sort',function(Y) {var remoteData = [" + data + "];var nestedCols = [" + cols + "];var dataTable = new Y.DataTable({columns: nestedCols,data: remoteData}).render('#diseasematrix');dataTable.get('boundingBox').unselectable();});"; return returnstring; } } } catch (ParseException e) { System.out.println("ERROR: readData(String token)"); System.out.println(e); } catch (IOException e) { System.out.println("ERROR: readData(String token)"); System.out.println(e); } return ""; }
From source file:com.dagobert_engine.portfolio.service.MtGoxPortfolioService.java
/** * Get permissions for api key//w w w . ja va 2s .c o m * * @param forceRefresh * @return */ public MtGoxPermission[] getApiPermissions() { ArrayList<MtGoxPermission> perms = new ArrayList<>(); JSONArray array = (JSONArray) getData().get("Rights"); for (int i = 0; i < array.size(); i++) { perms.add(MtGoxPermission.fromString((String) array.get(i))); } return perms.toArray(new MtGoxPermission[perms.size()]); }
From source file:jGPIO.DTO.java
public String createFileContents() { StringBuilder fileContents = new StringBuilder().append("/*\n") .append("* Copyright (C) 2012 Texas Instruments Incorporated - http://www.ti.com/\n").append("*\n") .append("* This program is free software; you can redistribute it and/or modify\n") .append("* it under the terms of the GNU General Public License version 2 as\n") .append("* published by the Free Software Foundation.\n") .append("* Or something like that, I don't really care too much\n") .append("* Created automagically by jgpio, created by Doug Edey\n") .append("* github.com/dougedey\n").append("*/\n").append("/dts-v1/;\n").append("/plugin/;\n"); // work out the values to be put into the file fileContents.append("/ {\n").append("\tcompatible = \"ti,beaglebone\", \"ti,beaglebone-black\";\n") .append("\tpart-number = \"BB-JGPIO\";\n").append("\tversion = \"00A0\";\n") .append("\n\texclusive-use=\n"); // iterate the list of known GPIOs and add them for (int i = 0; i < gpios.size(); i++) { JSONObject gpioDetails = (JSONObject) gpios.get(i); String exclusive = (String) gpioDetails.get("key"); if (i == (gpios.size() - 1)) { // are we at the end of the list // (there has to be an easier way // using an iterator fileContents.append("\t\t\"" + exclusive + "\";\n"); } else {//from w w w . j a v a 2 s. c om fileContents.append("\t\t\"" + exclusive + "\",\n"); } } fileContents.append("\t\tfragment@0 {\n").append("\t\t\ttarget = <&am33xx_pinmux>;\n") .append("\t\t\t__overlay__ {\n").append("\t\t\t\tjgpio_pins: pinmux_jgpio_pins {\n") .append("\t\t\t\tpinctrl-single,pins = <\n"); // iterate the list of known GPIOs and add them for (Object o : gpios) { JSONObject gpioDetails = (JSONObject) o; String exclusive = (String) gpioDetails.get("key"); String muxRegOffset = (String) gpioDetails.get("muxRegOffset"); Integer mode = (Integer) gpioDetails.get("UserMode"); String userSelectedPin = (String) gpioDetails.get("UserSelectedPin"); // we only need this for digital IO, analog inputs can be activated // using the BB-ADC file int pinmux = 0x00; if (mode == DTO.INPUT) { pinmux = 0x30; } if (mode == DTO.OUTPUT) { pinmux = 0x00; } JSONArray options = (JSONArray) gpioDetails.get("options"); for (int i = 0; i < options.size(); i++) { String option = (String) options.get(i); if (option.equalsIgnoreCase(userSelectedPin)) { pinmux += i; } } fileContents.append("\t\t\t\t\t" + muxRegOffset + " 0x" + Integer.toHexString(pinmux) + " /* " + exclusive + "*/\n"); } fileContents.append("\t\t\t\t>;\n").append("\t\t\t};\n").append("\t\t};\n").append("\t};\n\n"); // Start the fragment to initialize it all fileContents.append("\tfragment@1 {\n").append("\t\ttarget = <&ocp>;\n").append("\t\t__overlay__ {\n") .append("\t\t\tstatus = \"okay\";\n").append("\t\t\tpinctrl-names=\"default\";\n") .append("\t\t\tpinctrl-0 = <&jgpio_pins>;\n").append("\t\t};\n").append("\t};\n").append("};\n"); return fileContents.toString(); }
From source file:com.skelril.ShivtrAuth.AuthenticationCore.java
public synchronized JSONArray getFrom(String subAddress) { JSONArray objective = new JSONArray(); HttpURLConnection connection = null; BufferedReader reader = null; try {// ww w . j a v a 2 s. co m JSONParser parser = new JSONParser(); for (int i = 1; true; i++) { try { // Establish the connection URL url = new URL(websiteURL + subAddress + "?page=" + i); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(1500); connection.setReadTimeout(1500); // Check response codes return if invalid if (connection.getResponseCode() < 200 || connection.getResponseCode() >= 300) return null; // Begin to read results reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder builder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { builder.append(line); } // Parse Data JSONObject o = (JSONObject) parser.parse(builder.toString()); JSONArray ao = (JSONArray) o.get("characters"); if (ao.isEmpty()) break; Collections.addAll(objective, (JSONObject[]) ao.toArray(new JSONObject[ao.size()])); } catch (ParseException e) { break; } finally { if (connection != null) connection.disconnect(); if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } } } catch (IOException e) { return null; } return objective; }
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;//from w w w . j a va2 s . 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(); } } }