List of usage examples for org.json JSONArray toString
public String toString()
From source file:com.imos.sample.pi.ControlGpioExample.java
public void pythonTemperatureSensor() { try {/*from w w w.j a v a 2 s . c o 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(ControlGpioExample.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.dbg4j.core.DebugUtils.java
/** * Converts <code>DebugData</code> collection into json array string * @param debugDatas//from www . j a v a 2 s . c o m * @return */ public static String toJsonArray(Collection<DebugData> debugDatas) { JSONArray jsonArray = new JSONArray(); for (DebugData dd : debugDatas) { try { jsonArray.put(new JSONObject(dd.toString())); } catch (JSONException ignored) { } } return jsonArray.toString(); }
From source file:com.liferay.mobile.android.http.HttpUtil.java
public static JSONArray post(Session session, JSONArray commands) throws Exception { String url = getURL(session, "/invoke"); Request request = new Request(session.getAuthentication(), Method.POST, session.getHeaders(), url, commands.toString(), session.getConnectionTimeout(), session.getCallback()); Response response = client.send(request); if (response == null) { return null; } else {/*from www .j av a 2 s . c om*/ return new JSONArray(response.getBody()); } }
From source file:Servlet.ListaFashionista.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods./*from www . java2 s .co m*/ * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { FashionistaDAO fashiondao = new FashionistaDAO(); if (request.getParameterValues("nome") == null) { List<Fashionista> fashionistas = fashiondao.listFashionista(); request.getSession(true).setAttribute("fashionistas", fashionistas); response.sendRedirect("listaTotal.jsp"); } else { List<Fashionista> fashionistas = fashiondao .listFashionistaByName(request.getParameterValues("nome")[0].toString()); response.setContentType("application/json"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); JSONArray jsonArray = new JSONArray(); for (Fashionista fashionista : fashionistas) { JSONObject json = new JSONObject(); json.put("nome", fashionista.getNome()); jsonArray.put(json); } out.print(jsonArray.toString()); } }
From source file:com.di.bi.nextgen.installattribution.searchcountrycode.SearchCountryCode.java
public static org.json.JSONArray ReadJson() throws FileNotFoundException, IOException, ParseException { JSONParser parser = new JSONParser(); File configFile = new File("test.json"); String fileConfigurationContent = readFile(configFile.getPath()); org.json.JSONArray jsonObj = new org.json.JSONArray(fileConfigurationContent); System.out.println("------------------------" + jsonObj.toString()); Map<String, Object> map = new HashMap(); return jsonObj; }
From source file:com.pimp.companionforband.fragments.cloud.ActivitiesFragment.java
@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); activitiesLV = (ListView) view.findViewById(R.id.activities_listview); statusTV = (TextView) view.findViewById(R.id.status_textview); stringArrayList = new ArrayList<>(); stringArrayAdapter = new ArrayAdapter<>(getContext(), R.layout.activities_list_item, R.id.list_item_textView, stringArrayList); activitiesLV.setAdapter(stringArrayAdapter); RequestQueue queue = Volley.newRequestQueue(getContext()); JsonObjectRequest activitiesRequest = new JsonObjectRequest(Request.Method.GET, CloudConstants.BASE_URL + CloudConstants.Activities_URL, null, new Response.Listener<JSONObject>() { @Override/* w ww .ja v a 2 s . c om*/ public void onResponse(JSONObject response) { statusTV.setText("CSV file can be found in CompanionForBand/Activities\n"); Iterator<String> stringIterator = response.keys(); while (stringIterator.hasNext()) { try { String key = stringIterator.next(); JSONArray jsonArray = response.getJSONArray(key); String path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "CompanionForBand" + File.separator + "Activities"; File file = new File(path); file.mkdirs(); JsonFlattener parser = new JsonFlattener(); CSVWriter writer = new CSVWriter(); try { List<LinkedHashMap<String, String>> flatJson = parser .parseJson(jsonArray.toString()); writer.writeAsCSV(flatJson, path + File.separator + key + ".csv"); } catch (Exception e) { Log.e("ActivitiesParseJson", e.toString()); } for (int i = 0; i < jsonArray.length(); i++) { JSONObject activity = jsonArray.getJSONObject(i); Iterator<String> iterator = activity.keys(); String str = ""; while (iterator.hasNext()) { key = iterator.next(); str = str + UIUtils.splitCamelCase(key) + " : " + activity.get(key).toString() + "\n"; } stringArrayAdapter.add(str); } } catch (Exception e) { Log.e("Activities", e.toString()); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show(); } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + MainActivity.sharedPreferences.getString("access_token", "hi")); return headers; } }; queue.add(activitiesRequest); }
From source file:com.google.android.apps.paco.FeedbackActivity.java
private WebViewClient createWebViewClientThatHandlesFileLinksForCharts(final Feedback feedback) { WebViewClient webViewClient = new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { Uri uri = Uri.parse(url);/*from w ww . j a v a 2s . c o m*/ if (uri.getScheme().startsWith("http")) { return true; // throw away http requests - we don't want 3rd party javascript sending url requests due to security issues. } String inputIdStr = uri.getQueryParameter("inputId"); if (inputIdStr == null) { return true; } long inputId = Long.parseLong(inputIdStr); JSONArray results = new JSONArray(); for (Event event : experiment.getEvents()) { JSONArray eventJson = new JSONArray(); DateTime responseTime = event.getResponseTime(); if (responseTime == null) { continue; // missed signal; } eventJson.put(responseTime.getMillis()); // in this case we are looking for one input from the responses that we are charting. for (Output response : event.getResponses()) { if (response.getInputServerId() == inputId) { Input inputById = experiment.getInputById(inputId); if (!inputById.isInvisible() && inputById.isNumeric()) { eventJson.put(response.getDisplayOfAnswer(inputById)); results.put(eventJson); continue; } } } } env.put("data", results.toString()); env.put("inputId", inputIdStr); view.loadUrl(stripQuery(url)); return true; } }; return webViewClient; }
From source file:com.google.android.apps.paco.FeedbackActivity.java
private static String convertEventsToJsonString(final Feedback feedback, final Experiment experiment, List<Event> events) { // TODO use jackson instead. But preserve these synthesized values for backward compatibility. final JSONArray experimentData = new JSONArray(); for (Event event : events) { try {//www . j a v a2s .c o m JSONObject eventObject = new JSONObject(); boolean missed = event.getResponseTime() == null; eventObject.put("isMissedSignal", missed); if (!missed) { eventObject.put("responseTime", event.getResponseTime().getMillis()); } boolean selfReport = event.getScheduledTime() == null; eventObject.put("isSelfReport", selfReport); if (!selfReport) { eventObject.put("scheduleTime", event.getScheduledTime().getMillis()); } JSONArray responses = new JSONArray(); for (Output response : event.getResponses()) { JSONObject responseJson = new JSONObject(); Input input = experiment.getInputById(response.getInputServerId()); if (input == null) { // just create the event based on all of the values in the datum responseJson.put("name", response.getName()); responseJson.put("isMultiselect", false); responseJson.put("prompt", feedback.getTextOfInputForOutput(experiment, response)); responseJson.put("answer", response.getAnswer()); // deprecate answerOrder for answerRaw responseJson.put("answerOrder", response.getAnswer()); responseJson.put("answerRaw", response.getAnswer()); responses.put(responseJson); } else { responseJson.put("inputId", input.getServerId()); responseJson.put("name", input.getName()); responseJson.put("responseType", input.getResponseType()); responseJson.put("isMultiselect", input.isMultiselect()); responseJson.put("prompt", feedback.getTextOfInputForOutput(experiment, response)); responseJson.put("answer", response.getDisplayOfAnswer(input)); // deprecate answerOrder for answerRaw responseJson.put("answerOrder", response.getAnswer()); responseJson.put("answerRaw", response.getAnswer()); responses.put(responseJson); } } eventObject.put("responses", responses); if (responses.length() > 0) { experimentData.put(eventObject); } } catch (JSONException jse) { // skip this event and do the next event. } } String experimentDataAsJson = experimentData.toString(); return experimentDataAsJson; }
From source file:com.novartis.opensource.yada.test.ServiceTest.java
/** * Validation method for external REST result * //from w w w . j av a 2 s. c o m * @param result the query result * @return {@code true} if result complies with expected output spec * @throws YADAExecutionException when the test fails */ public boolean validateThirdPartyJSONResult(String result) throws YADAExecutionException { try { JSONArray res = new JSONArray(result); logJSONResult(res); } catch (JSONException e) { try { JSONObject res = new JSONObject(result); if (res.has("Exception")) throw new YADAExecutionException(res.toString()); logJSONResult(res); } catch (JSONException e1) { throw new YADAExecutionException(); } } return true; }
From source file:com.flowzr.budget.holo.export.flowzr.FlowzrSyncEngine.java
public static <T extends Object> void pushUpdate(String tableName, Class<T> clazz) throws ClientProtocolException, IOException, JSONException, Exception { SQLiteDatabase db2 = dba.db();//from ww w.j av a2s . c o m Cursor cursorCursor; String sql; long total; sql = "select count(*) from " + tableName + " where updated_on<=0 or remote_key is null or (updated_on > " + last_sync_ts; if (!tableName.equals(DatabaseHelper.BUDGET_TABLE)) { sql = sql + " and updated_on<" + startTimestamp + ")"; } else { sql = sql + ")"; } cursorCursor = db.rawQuery(sql, null); cursorCursor.moveToFirst(); total = cursorCursor.getLong(0); sql = "select * from " + tableName + " where updated_on<=0 or remote_key is null or (updated_on > " + last_sync_ts; if (!tableName.equals(DatabaseHelper.BUDGET_TABLE)) { sql = sql + " and updated_on<" + startTimestamp + ")"; } else { sql = sql + ")"; } if (tableName.equals(DatabaseHelper.TRANSACTION_TABLE)) { sql += " order by parent_id asc,_id asc"; } else if (tableName.equals(DatabaseHelper.BUDGET_TABLE)) { sql += " order by parent_budget_id asc"; } else if (!tableName.equals("currency_exchange_rate")) { sql += " order by _id asc"; } cursorCursor = db2.rawQuery(sql, null); JSONArray resultSet = new JSONArray(); int i = 0; if (cursorCursor.moveToFirst() && isCanceled != true) { Log.i("flowzr", "pushing " + tableName); do { if (i % 10 == 0) { //notifyUser(context.getString(R.string.flowzr_sync_sending) + " " + tableName, (int)(Math.round(i*100/total))); } resultSet.put(cursorToDict(tableName, cursorCursor)); i++; if (i % MAX_PUSH_SIZE == 0) { String resp = makeRequest(tableName, resultSet.toString()); resultSet = new JSONArray(); if (resp.equals(FLOWZR_MSG_NET_ERROR)) { isCanceled = true; } if (isCanceled) { return; } } } while (cursorCursor.moveToNext()); } cursorCursor.close(); if (i % MAX_PUSH_SIZE != 0) { String resp = makeRequest(tableName, resultSet.toString()); if (resp.equals(FLOWZR_MSG_NET_ERROR)) { isCanceled = true; Log.e("flowzr", resp); } if (isCanceled) { Log.i("flowzr", "sync canceled!"); return; } } }