List of usage examples for org.json JSONArray put
public JSONArray put(Object value)
From source file:com.imos.sample.pi.MotionSensor.java
public void pythonTemperatureSensor() { try {//from w w w. j a v a 2s . co m String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 11 4"; int count = 0; JSONArray array = new JSONArray(); int dayOfMonth = 0; cal.setTime(new Date()); dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); while (true) { Process p = Runtime.getRuntime().exec(cmd); p.waitFor(); StringBuilder output = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = reader.readLine()) != null) { output.append(line); } String result = output.toString(), tempStr; double temp, humid; if (!result.trim().isEmpty()) { tempStr = result.substring(result.indexOf("Humid")); result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1); temp = Double.parseDouble(result); result = tempStr; result = result.substring(result.indexOf("=") + 1, result.indexOf("%")); humid = Double.parseDouble(result); JSONObject data = new JSONObject(); data.put("temp", temp); data.put("humid", humid); data.put("time", new Date().getTime()); array.put(data); } Thread.sleep(60000); count++; if (count == 60) { Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, null, ""); cal.setTime(new Date()); StringBuilder builder = new StringBuilder(); builder.append(cal.get(Calendar.DAY_OF_MONTH)); builder.append("-"); builder.append(cal.get(Calendar.MONTH)); builder.append("-"); builder.append(cal.get(Calendar.YEAR)); builder.append("-"); builder.append(cal.get(Calendar.HOUR_OF_DAY)); builder.append("_"); builder.append(cal.get(Calendar.MINUTE)); try (BufferedWriter writer = new BufferedWriter( new FileWriter(builder.toString() + "_data.json"))) { writer.append(array.toString()); } catch (IOException ex) { } System.out.println(builder.toString()); count = 0; array = new JSONArray(); if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) { builder = new StringBuilder(); builder.append(cal.get(Calendar.DAY_OF_MONTH)); builder.append("-"); builder.append(cal.get(Calendar.MONTH)); builder.append("-"); builder.append(cal.get(Calendar.YEAR)); String dirName = builder.toString(); File newDir = new File("src/main/resources/" + dirName); newDir.mkdir(); File files = new File("src/main/resources/"); for (File file : files.listFiles()) { if (file.getName().endsWith(".json")) { file.renameTo(new File("src/main/resources/" + dirName + file.getName())); file.delete(); } } dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); } } } } catch (IOException | InterruptedException ex) { Logger.getLogger(MotionSensor.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.jennifer.ui.chart.widget.LegendWidget.java
private JSONArray getLegendIcon(JSONObject brushObject) { JSONArray arr = new JSONArray(); JSONArray data = JSONUtil.clone(brushObject.getJSONArray("target")); if (key != null && key.length() > 0) { data = chart.data();//from ww w .j a va2 s. com } int count = data.length(); for (int i = 0; i < count; i++) { String text = ""; if (key != null && key.length() > 0) { text = chart.series(key).optString("text", data.getJSONObject(i).getString(key)); } else { String target = data.getString(i); text = chart.series(target).optString("text", target); } double rectWidth = (fontWidth - 4) * text.length(); double width = Math.min(rectWidth, fontHeight); double height = width; Transform group = root.group(new JSONObject().put("class", "legend icon")); Transform rect = group.rect(new JSONObject().put("x", 0).put("y", 0).put("width", width) .put("height", height).put("fill", chart.color(i, brushObject.optJSONArray("colors")))); group.text(new JSONObject().put("x", width + 4).put("y", fontHeight - 3) // 3 is top, bottom font margin .put("font-family", chart.theme("fontFamily")).put("font-size", chart.theme("legendFontSize")) .put("fill", chart.theme("legendFontColor")).put("text-anchor", "start")).textNode(text); arr.put(new JSONObject().put("width", width + 4 + rectWidth + (i == count - 1 ? 0 : 10)) .put("height", height + 4).put("icon", group) ); } return arr; }
From source file:pt.webdetails.cpf.persistence.PersistenceEngine.java
public JSONObject query(String query, Map<String, Object> params) throws JSONException { JSONObject json = new JSONObject(); try {/*from w ww .j a va2 s . c o m*/ json.put("result", Boolean.TRUE); List<ODocument> result = executeQuery(query, params); if (result != null) { JSONArray arr = new JSONArray(); for (ODocument resDoc : result) { arr.put(new JSONObject(resDoc.toJSON())); } json.put("object", arr); } } catch (ODatabaseException ode) { json.put("result", Boolean.FALSE); json.put("errorMessage", "DatabaseException: Review query"); logger.error(getExceptionDescription(ode)); } return json; }
From source file:org.LexGrid.lexevs.metabrowser.helper.ChildPagingJsonConverter.java
/** * Builds the children./*w w w . j av a2s.c o m*/ * * @param focusNode the focus node * @param page the page * @param levels the levels * * @return the jSON array */ private JSONArray buildChildren(MetaTreeNode focusNode, int page, int levels) { int children = 0; JSONArray childrenArray = new JSONArray(); ChildIterator itr = focusNode.getChildren(); List<String> childrenCuis = new ArrayList<String>(); while (itr.hasNext() && children < (MAX_CHILDREN * page) && levels > 0) { MetaTreeNode child = itr.next(); childrenCuis.add(child.getCui()); JSONObject obj = buildNode(child); try { obj.put("CHILDREN_NODES", buildChildrenNodes(child, levels - 1)); } catch (JSONException e) { throw new RuntimeException(e); } childrenArray.put(obj); children++; } if (children >= MAX_CHILDREN) { childrenArray.put(buildMoreChildrenNode(focusNode.getCui(), focusNode.getSab(), childrenCuis)); } return childrenArray; }
From source file:org.LexGrid.lexevs.metabrowser.helper.ChildPagingJsonConverter.java
/** * Walk tree from root./* w w w . j a va2 s .c om*/ * * @param node the node * * @return the jSON object */ private JSONObject walkTreeFromRoot(MetaTreeNode node, boolean isRoot) { int childLimit; if (isRoot) { childLimit = Integer.MAX_VALUE; } else { childLimit = MAX_CHILDREN; } JSONObject nodeObject = new JSONObject(); try { nodeObject = buildNode(node); JSONArray childrenArray = new JSONArray(); if (node.getPathToRootChilden() != null) { List<String> childrenCuis = new ArrayList<String>(); int children = 0; for (MetaTreeNode child : node.getPathToRootChilden()) { children++; childrenCuis.add(child.getCui()); childrenArray.put(walkTreeFromRoot(child, false)); } ChildIterator itr = node.getChildren(); if (itr != null) { while (itr.hasNext() && children < childLimit) { MetaTreeNode child = itr.next(); if (!knownChildrenContainsCode(node.getPathToRootChilden(), child.getCui())) { childrenArray.put(walkTreeFromRoot(child, false)); childrenCuis.add(child.getCui()); children++; } } } if (children >= childLimit) { childrenArray.put(buildMoreChildrenNode(node.getCui(), node.getSab(), childrenCuis)); } } nodeObject.put(CHILDREN_NODES, childrenArray); } catch (JSONException e) { throw new RuntimeException(e); } return nodeObject; }
From source file:com.adintellig.UDFJson.java
private Object extract_json_withkey(Object json, String path) throws JSONException { if (json.getClass() == org.json.JSONArray.class) { JSONArray jsonArray = new JSONArray(); for (int i = 0; i < ((JSONArray) json).length(); i++) { Object josn_elem = ((JSONArray) json).get(i); try { Object json_obj = ((JSONObject) josn_elem).get(path); if (json_obj.getClass() == org.json.JSONArray.class) { for (int j = 0; j < ((JSONArray) json_obj).length(); j++) { jsonArray.put(((JSONArray) json_obj).get(j)); }/*from w w w.j av a 2 s . co m*/ } else { jsonArray.put(json_obj); } } catch (Exception e) { continue; } } return (jsonArray.length() == 0) ? null : jsonArray; } else { return ((JSONObject) json).get(path); } }
From source file:ch.ethz.inf.vs.android.g54.a4.util.SnapshotCache.java
private static JSONArray readingsToJson(List<WifiReading> readings) throws JSONException { JSONArray rs = new JSONArray(); for (WifiReading reading : readings) { JSONObject ap = new JSONObject(); ap.put("mac", reading.mac); ap.put("ssid", reading.ssid); ap.put("signal", reading.signal); rs.put(ap); }/* ww w .j av a 2 s . c o m*/ return rs; }
From source file:com.google.testing.web.screenshotter.Screenshotter.java
private JSONObject getRequestBodyJson() throws JSONException { JSONObject params = new JSONObject(); if (element.isPresent()) { params.put("Element", webElementToJSON(element.get())); }/*from ww w . j ava2 s .c o m*/ if (!excluding.isEmpty()) { JSONArray ex = new JSONArray(); for (WebElement el : excluding) { ex.put(webElementToJSON(el)); } params.put("Exclude", ex); } return params; }
From source file:com.chaosinmotion.securechat.server.json.ReturnResult.java
/** * Convert to string. If this is successful the return looks like: * { "success": true, "data": ... }// w w w .j a va 2 s .co m * If an error, this looks like: * { "success": false, "error": number, "message": "msg", "exception": [...] } */ public String toString() { JSONObject obj = new JSONObject(); obj.put("success", success); if (success) { /* * Generate the success return. */ JSONObject data = returnData(); if (data != null) { obj.put("data", data); } } else { /* * Generate the error return */ obj.put("error", errorCode); obj.put("message", errorMessage); if (exception != null) { JSONArray array = new JSONArray(); for (String str : exception) { array.put(str); } obj.put("exception", array); } } return obj.toString(4); // formatted string. }
From source file:org.apache.giraph.graph.BspServiceWorker.java
/** * Marshal the aggregator values of to a JSONArray that will later be * aggregated by master. Reset the 'use' of aggregators in the next * superstep/*from w ww. j av a2 s . c o m*/ * * @param superstep Superstep to marshall on * @return JSON array of the aggreagtor values */ private JSONArray marshalAggregatorValues(long superstep) { JSONArray aggregatorArray = new JSONArray(); if ((superstep == INPUT_SUPERSTEP) || (aggregatorInUse.size() == 0)) { return aggregatorArray; } for (String name : aggregatorInUse) { try { Aggregator<Writable> aggregator = getAggregatorMap().get(name); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); DataOutput output = new DataOutputStream(outputStream); aggregator.getAggregatedValue().write(output); JSONObject aggregatorObj = new JSONObject(); aggregatorObj.put(AGGREGATOR_NAME_KEY, name); aggregatorObj.put(AGGREGATOR_CLASS_NAME_KEY, aggregator.getClass().getName()); aggregatorObj.put(AGGREGATOR_VALUE_KEY, Base64.encodeBytes(outputStream.toByteArray())); aggregatorArray.put(aggregatorObj); if (LOG.isInfoEnabled()) { LOG.info("marshalAggregatorValues: " + "Found aggregatorObj " + aggregatorObj + ", value (" + aggregator.getAggregatedValue() + ")"); } } catch (JSONException e) { throw new IllegalStateException("Failed to marshall aggregator " + "with JSONException " + name, e); } catch (IOException e) { throw new IllegalStateException("Failed to marshall aggregator " + "with IOException " + name, e); } } if (LOG.isInfoEnabled()) { LOG.info("marshalAggregatorValues: Finished assembling " + "aggregator values in JSONArray - " + aggregatorArray); } aggregatorInUse.clear(); return aggregatorArray; }