List of usage examples for org.json.simple JSONArray size
public int size()
From source file:amulet.resourceprofiler.JSONResourceReader.java
/** * Parse the input JSON file for energy data collected during our * evaluation of the amulet hardware. JSON data content will be * loaded into Plain Old Java Objects (POJOs) for easy handling * in later parts of the AFT. // ww w. j a va2s. c om * * @param filename The JSON file with energy data. */ public void read(String filename) { this.filename = filename; JSONParser parser = new JSONParser(); try { // Top-level JSON object. JSONObject jsonRootObj = (JSONObject) parser.parse(new FileReader(this.filename)); // System.out.println("DEBUG:: jsonRootObj="+jsonRootObj); // Extract Device Information. JSONObject jsonDeviceInfo = (JSONObject) jsonRootObj.get("device_information"); deviceInformation.jsonDeviceInfo = jsonDeviceInfo; deviceInformation.deviceName = (String) jsonDeviceInfo.get("device_name"); deviceInformation.batterySize = (Long) jsonDeviceInfo.get("battery_size"); deviceInformation.batterySizeUnits = (String) jsonDeviceInfo.get("battery_size_units"); deviceInformation.memTypeVolatile = (String) jsonDeviceInfo.get("volatile_mem_type"); deviceInformation.memSizeVolatile = (Long) jsonDeviceInfo.get("volatile_mem_size_bytes"); deviceInformation.memTypeNonVolatile = (String) jsonDeviceInfo.get("non_volatile_mem_type"); deviceInformation.memSizeNonVolatile = (Long) jsonDeviceInfo.get("non_volatile_mem_size_bytes"); deviceInformation.memTypeSecondary = (String) jsonDeviceInfo.get("secondary_storage_type"); deviceInformation.memSizeSecondary = (Double) jsonDeviceInfo.get("secondary_storage_size_bytes"); deviceInformation.avgNumInstructionsPerLoC = (Double) jsonDeviceInfo.get("instructions_per_loc"); deviceInformation.avgBasicInstructionPower = (Double) jsonDeviceInfo.get("basic_instruction_power"); deviceInformation.avgBasicInstructionTime = (Double) jsonDeviceInfo.get("basic_instruction_time"); deviceInformation.avgBasicInstructionUnit = (String) jsonDeviceInfo.get("basic_loc_time_unit"); // Extract Steady-State Information. JSONObject jsonSteadyStateInfo = (JSONObject) jsonRootObj.get("steady_state_info"); steadyStateInformation.jsonSteadyStateInfo = jsonSteadyStateInfo; steadyStateInformation.radioBoardSleepPower = (Double) jsonSteadyStateInfo .get("radio_board_sleep_power"); steadyStateInformation.appBoardSleepPower = (Double) jsonSteadyStateInfo.get("app_board_sleep_power"); steadyStateInformation.displayIdlePower = (Double) jsonSteadyStateInfo.get("display_idle_power"); steadyStateInformation.sensorAccelerometer = (Double) jsonSteadyStateInfo.get("sensor_accelerometer"); steadyStateInformation.sensorHeartRate = (Double) jsonSteadyStateInfo.get("sensor_heartrate"); // Array of "parameters". JSONArray paramArray = (JSONArray) jsonRootObj.get("api_calls"); apiInfo = paramArray; for (int i = 0; i < paramArray.size(); i++) { JSONObject jsonObj = (JSONObject) paramArray.get(i); /* * Build POJO based on energy parameter element from JSON data file. * * NOTE: Extend this section of code to parse more parameters * as needed. Also, see: `JSONEnergyParam` below. */ EnergyParam param = new EnergyParam(); param.name = jsonObj.get("resource_name").toString(); param.type = jsonObj.get("resource_type").toString(); param.avgPower = (Double) jsonObj.get("avg_power"); param.avgTime = (Double) jsonObj.get("time"); param.timeUnit = jsonObj.get("time_unit").toString(); // Add the param to the collection of params read in. addEnergyParam(param); } // DEBUG OUTPUT BLOCK ///////////////////////////////////// if (debugEnabled) { System.out.println(this.toString()); } /////////////////////////////////////////////////////////// } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } }
From source file:eu.hansolo.accs.RestClient.java
private JSONObject getSpecificObject(final URIBuilder BUILDER) { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { HttpGet get = new HttpGet(BUILDER.build()); CloseableHttpResponse response = httpClient.execute(get); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != 200) { //throw new RuntimeException("Failed: HTTP error code: " + statusCode); return new JSONObject(); }/*w ww.jav a 2 s. c om*/ String output = getFromResponse(response); JSONArray jsonArray = (JSONArray) JSONValue.parse(output); JSONObject jsonObject = jsonArray.size() > 0 ? (JSONObject) jsonArray.get(0) : new JSONObject(); return jsonObject; } catch (URISyntaxException | IOException e) { return new JSONObject(); } }
From source file:CPUController.java
@RequestMapping("/cpu") public @ResponseBody CPU cpu( @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 . j ava 2 s. com*/ 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_", "cpu"); 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 String loginResponse = ""; String cpu = ""; 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"); // System.out.println(array); for (int i = 0; i < array.size(); i++) { JSONObject tobj = (JSONObject) array.get(i); String key = (String) tobj.get("key_"); if (!tobj.get("hostid").equals(hostid)) continue; if (name.equals("idle") && key.contains("idle")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "cpu idle time"; } else if (name.equals("iowait") && key.contains("iowait")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "cpu iowait time"; } else if (name.equals("nice") && key.contains("nice")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "cpu nice time"; } else if (name.equals("system") && key.contains("system")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "cpu system time"; } else if (name.equals("user") && key.contains("user")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "cpu user time"; } else if (name.equals("load") && key.contains("load")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "processor load"; } else if (name.equals("usage") && key.contains("usage")) { cpu = (String) tobj.get("lastvalue"); clock = (String) tobj.get("lastclock"); metricType = "system cpu usage average"; } } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException pe) { System.out.println("Error"); } if (cpu.equals("")) { return new CPU( "Error: Please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:"); } return new CPU(hostid, metricType, cpu, clock); }
From source file:com.googlecode.fascinator.portal.process.HomeInstitutionNotifier.java
@Override public boolean process(String id, String inputKey, String outputKey, String stage, String configFilePath, HashMap<String, Object> dataMap) throws Exception { Indexer indexer = (Indexer) dataMap.get("indexer"); HashSet<String> failedOids = (HashSet<String>) dataMap.get(outputKey); if (failedOids == null) { failedOids = new HashSet<String>(); }/*from w ww . jav a 2s . c o m*/ Collection<String> oids = (Collection<String>) dataMap.get(inputKey); // load up the list of institutions... JsonSimple config = new JsonSimple(new File(configFilePath)); HashMap<String, JsonObject> homes = new HashMap<String, JsonObject>(); for (Object homeObj : config.getArray("institutions")) { JsonObject home = (JsonObject) homeObj; homes.put((String) home.get("name"), home); } File sysFile = JsonSimpleConfig.getSystemFile(); Storage storage = PluginManager.getStorage("file-system"); storage.init(sysFile); ByteArrayOutputStream out; String targetPayload = "arms.xml"; String targetProperty = "dataprovider:organization"; for (String oid : oids) { log.debug("Processing oid:" + oid); out = null; // get the solr doc SearchRequest searchRequest = new SearchRequest("id:" + oid); ByteArrayOutputStream result = new ByteArrayOutputStream(); indexer.search(searchRequest, result); SolrResult resultObject = new SolrResult(result.toString()); List<SolrDoc> results = resultObject.getResults(); SolrDoc solrDoc = results.get(0); // get the target property String targetProp = solrDoc.getString("", targetProperty); if (targetProp == null) { JSONArray array = solrDoc.getArray(targetProperty); if (array.size() > 0) { targetProp = (String) array.get(0); } } log.debug("Target property value: " + targetProp); if (targetProp != null && targetProp.length() > 0) { String channel = (String) homes.get(targetProp).get("channel"); if (channel != null) { log.debug("Using channel:" + channel); if (channel.endsWith("email")) { sendEmail(dataMap, failedOids, config, storage, out, targetPayload, oid, solrDoc, channel); } else { log.debug("Sending message through the queue..."); // defaults to queue MessageqNotifierService notifierService = ApplicationContextProvider.getApplicationContext() .getBean(channel + "_service", MessageqNotifierService.class); out = extractPayload(storage, out, targetPayload, oid); if (out != null) { notifierService.sendMessage(out.toString("UTF-8")); } else { log.error("Payload not found: " + targetPayload + ", for oid:" + oid); } } } else { log.debug("Channel configuration not found, ignoring."); } } else { log.debug("Target property has no value, ignoring."); } } return true; }
From source file:de.thejeterlp.bukkit.updater.Updater.java
/** * Index://ww w .j a va 2 s . c o m * 0: downloadUrl * 1: name * 2: releaseType * * @return */ protected String[] read() { debug("Method: read()"); try { URLConnection conn = url.openConnection(); conn.setConnectTimeout(5000); conn.setDoOutput(true); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = reader.readLine(); JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) return null; Map<?, ?> map = (Map) array.get(array.size() - 1); String downloadUrl = (String) map.get("downloadUrl"); String name = (String) map.get("name"); String releaseType = (String) map.get("releaseType"); return new String[] { downloadUrl, name, releaseType }; } catch (Exception e) { main.getLogger().severe("Error on trying to check remote versions. Error: " + e); return null; } }
From source file:net.bashtech.geobot.JSONUtil.java
public static List<String> getEmotes() { List<String> emotes = new LinkedList<String>(); try {/* ww w. j a va2 s . co m*/ JSONParser parser = new JSONParser(); Object obj = parser.parse(BotManager.getRemoteContent("http://direct.twitchemotes.com/global.json")); JSONObject jsonObject = (JSONObject) obj; for (Object o : jsonObject.keySet()) { String name = (String) o; if (name.length() > 0) emotes.add(name); } Object obj1 = parser.parse(BotManager.getRemoteContent("https://api.betterttv.net/emotes")); JSONObject jsonObject1 = (JSONObject) obj1; JSONArray emotesObj = (JSONArray) jsonObject1.get("emotes"); for (int i = 0; i < emotesObj.size(); i++) { JSONObject emoteObject = (JSONObject) emotesObj.get(i); String emoteStr = (String) emoteObject.get("regex"); emotes.add(emoteStr); } emotes.add(":)"); emotes.add(":o"); emotes.add(":("); emotes.add(";)"); emotes.add(":/"); emotes.add(";p"); emotes.add(">("); emotes.add("B)"); emotes.add("O_o"); emotes.add("O_O"); emotes.add("R)"); emotes.add(":D"); emotes.add(":z"); emotes.add("D:"); emotes.add(":p"); emotes.add(":P"); } catch (Exception ex) { ex.printStackTrace(); } finally { return emotes; } }
From source file:ActualizadorLocal.Clientes.ClienteNodos.java
public void procesarDatos(String datos) throws SQLException { //Preprocesamos los datos, para darle un nombre al array: datos = "{\"nodos\":" + datos + "}"; JSONParser parser = new JSONParser(); try {//from w w w. j ava 2 s.co m JSONObject obj = (JSONObject) parser.parse(datos); JSONArray lista = (JSONArray) obj.get("nodos"); for (int i = 0; i < lista.size(); i++) { long a0 = (long) ((JSONObject) lista.get(i)).get("idNodo"); String a1 = (String) ((JSONObject) lista.get(i)).get("nombre"); double a2 = (double) ((JSONObject) lista.get(i)).get("latitud"); double a3 = (double) ((JSONObject) lista.get(i)).get("longitud"); nodos.add(a0); //Tenemos que calcular el polgono para la visualizacin de los datos mediante GOOGLE FUSION TABLES: double lat = Math.toRadians(new Double(a2)); double lon = Math.toRadians(new Double(a3)); double radio = 50.0 / 6378137.0; String cadena_poligono = "<Polygon><outerBoundaryIs><LinearRing><coordinates>"; for (int j = 0; j <= 360; j = j + 15) { double r = Math.toRadians(j); double lat_rad = Math .asin(Math.sin(lat) * Math.cos(radio) + Math.cos(lat) * Math.sin(radio) * Math.cos(r)); double lon_rad = Math.atan2(Math.sin(r) * Math.sin(radio) * Math.cos(lat), Math.cos(radio) - Math.sin(lat) * Math.sin(lat_rad)); double lon_rad_f = ((lon + lon_rad + Math.PI) % (2 * Math.PI)) - Math.PI; cadena_poligono = cadena_poligono + Math.toDegrees(lon_rad_f) + "," + Math.toDegrees(lat_rad) + ",0.0 "; } cadena_poligono = cadena_poligono + "</coordinates></LinearRing></outerBoundaryIs></Polygon>"; this.InsertarDatos("\"" + (String) Long.toString(a0) + "\",\"" + a1 + "\",\"" + Double.toString(a2) + "\",\"" + Double.toString(a3) + "\",\"" + cadena_poligono + "\""); } } catch (Exception e) { System.err.println(e.getMessage()); } syncDB(); }
From source file:de.matzefratze123.heavyspleef.util.Updater.java
public void query() { URL url;// w w w.ja v a2 s. co m try { url = new URL(API_HOST + API_QUERY + PROJECT_ID); } catch (MalformedURLException e) { e.printStackTrace(); return; } try { URLConnection conn = url.openConnection(); conn.setConnectTimeout(6000); conn.addRequestProperty("User-Agent", "HeavySpleef-Updater (by matzefratze123)"); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String query = reader.readLine(); JSONArray array = (JSONArray) JSONValue.parse(query); String version = null; if (array.size() > 0) { // Get the newest file's details JSONObject latest = (JSONObject) array.get(array.size() - 1); fileTitle = (String) latest.get(API_TITLE_VALUE); fileName = (String) latest.get(API_NAME_VALUE); downloadUrl = (String) latest.get(API_LINK_VALUE); String[] parts = fileTitle.split(" v"); if (parts.length >= 2) { version = parts[1]; } checkVersions(version); done = true; } } catch (IOException e) { Logger.severe("Failed querying the curseforge api: " + e.getMessage()); e.printStackTrace(); } }
From source file:com.nubits.nubot.pricefeeds.ExchangeratelabPriceFeed.java
@Override public LastPrice getLastPrice(CurrencyPair pair) { long now = System.currentTimeMillis(); long diff = now - lastRequest; if (diff >= refreshMinTime) { String url = getUrl(pair); String htmlString;//w w w. j a va 2 s . c o m try { htmlString = Utils.getHTML(url, true); } catch (IOException ex) { LOG.severe(ex.toString()); return new LastPrice(true, name, pair.getOrderCurrency(), null); } JSONParser parser = new JSONParser(); try { JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString)); JSONArray array = (JSONArray) httpAnswerJson.get("rates"); String lookingfor = pair.getOrderCurrency().getCode().toUpperCase(); boolean found = false; double rate = -1; for (int i = 0; i < array.size(); i++) { JSONObject temp = (JSONObject) array.get(i); String tempCurrency = (String) temp.get("to"); if (tempCurrency.equalsIgnoreCase(lookingfor)) { found = true; rate = Utils.getDouble((Double) temp.get("rate")); rate = Utils.round(1 / rate, 8); } } lastRequest = System.currentTimeMillis(); if (found) { lastPrice = new LastPrice(false, name, pair.getOrderCurrency(), new Amount(rate, pair.getPaymentCurrency())); return lastPrice; } else { LOG.warning("Cannot find currency " + lookingfor + " on feed " + name); return new LastPrice(true, name, pair.getOrderCurrency(), null); } } catch (Exception ex) { LOG.severe(ex.toString()); lastRequest = System.currentTimeMillis(); return new LastPrice(true, name, pair.getOrderCurrency(), null); } } else { LOG.fine("Wait " + (refreshMinTime - (System.currentTimeMillis() - lastRequest)) + " ms " + "before making a new request. Now returning the last saved price\n\n"); return lastPrice; } }
From source file:com.nubits.nubot.pricefeeds.feedservices.ExchangeratelabPriceFeed.java
@Override public LastPrice getLastPrice(CurrencyPair pair) { long now = System.currentTimeMillis(); long diff = now - lastRequest; if (diff >= refreshMinTime) { String url = getUrl(pair); String htmlString;//from w w w.ja v a2 s . com try { htmlString = Utils.getHTML(url, true); } catch (IOException ex) { LOG.error(ex.toString()); return new LastPrice(true, name, pair.getOrderCurrency(), null); } JSONParser parser = new JSONParser(); try { JSONObject httpAnswerJson = (JSONObject) (parser.parse(htmlString)); JSONArray array = (JSONArray) httpAnswerJson.get("rates"); String lookingfor = pair.getOrderCurrency().getCode().toUpperCase(); boolean found = false; double rate = -1; for (int i = 0; i < array.size(); i++) { JSONObject temp = (JSONObject) array.get(i); String tempCurrency = (String) temp.get("to"); if (tempCurrency.equalsIgnoreCase(lookingfor)) { found = true; rate = Utils.getDouble((Double) temp.get("rate")); rate = Utils.round(1 / rate, 8); } } lastRequest = System.currentTimeMillis(); if (found) { lastPrice = new LastPrice(false, name, pair.getOrderCurrency(), new Amount(rate, pair.getPaymentCurrency())); return lastPrice; } else { LOG.warn("Cannot find currency " + lookingfor + " on feed " + name); return new LastPrice(true, name, pair.getOrderCurrency(), null); } } catch (Exception ex) { LOG.error(ex.toString()); lastRequest = System.currentTimeMillis(); return new LastPrice(true, name, pair.getOrderCurrency(), null); } } else { LOG.warn("Wait " + (refreshMinTime - (System.currentTimeMillis() - lastRequest)) + " ms " + "before making a new request. Now returning the last saved price\n\n"); return lastPrice; } }