List of usage examples for org.json JSONObject put
public JSONObject put(String key, Object value) throws JSONException
From source file:fr.cobaltians.cobalt.fragments.CobaltFlipperFragment.java
private void swipe(final int direction) { mHandler.post(new Runnable() { @Override/*from w ww . j av a2 s . c o m*/ public void run() { JSONObject jsonObj = new JSONObject(); try { jsonObj.put(Cobalt.kJSType, Cobalt.JSTypeEvent); if (direction == GESTURE_SWIPE_LEFT) { jsonObj.put(Cobalt.kJSEvent, JSEventSwipeLeft); if (Cobalt.DEBUG) Log.i(Cobalt.TAG, TAG + " - swipe: next"); } else if (direction == GESTURE_SWIPE_RIGHT) { jsonObj.put(Cobalt.kJSEvent, JSEventSwipeRight); if (Cobalt.DEBUG) Log.i(Cobalt.TAG, TAG + " - swipe: previous"); } sendMessage(jsonObj); } catch (JSONException exception) { exception.printStackTrace(); } } }); }
From source file:org.ohmage.request.user.UserStatsReadRequest.java
/** * Responds to the user's request.// ww w.ja va 2 s . c o m */ @Override public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { JSONObject jsonResult = new JSONObject(); if (!isFailed()) { try { jsonResult.put(JSON_KEY_HOURS_SINCE_LAST_SURVEY_UPLOAD, hoursSinceLastSurveyUpload); jsonResult.put(JSON_KEY_HOURS_SINCE_LAST_MOBILITY_UPLOAD, ((hoursSinceLastMobilityUpload == null) ? DEFAULT_VALUE_IF_NO_MOBILITY_UPLOADS : hoursSinceLastMobilityUpload)); jsonResult.put(JSON_KEY_PAST_DAY_SUCCESSFUL_SURVEY_LOCATION_UPDATES_PERCENTAGE, pastDaySuccessfulSurveyLocationUpdatesPercentage); jsonResult.put(JSON_KEY_PAST_DAY_SUCCESSFUL_MOBILITY_LOCATION_UPDATES_PERCENTAGE, ((pastDatSuccessfulMobilityLocationUpdatesPercentage == null) ? DEFAULT_VALUE_IF_NO_MOBILITY_UPLOADS_IN_LAST_DAY : pastDatSuccessfulMobilityLocationUpdatesPercentage)); } catch (JSONException e) { LOGGER.error("There was an error creating the JSONArray result object.", e); setFailed(); } } super.respond(httpRequest, httpResponse, JSON_KEY_RESULT, jsonResult); }
From source file:at.alladin.rmbt.qos.QoSUtil.java
/** * /*from w w w . j ava 2s . c om*/ * @param settings * @param conn * @param answer * @param lang * @param errorList * @throws SQLException * @throws JSONException * @throws HstoreParseException * @throws IllegalAccessException * @throws IllegalArgumentException */ public static void evaluate(final ResourceBundle settings, final Connection conn, final TestUuid uuid, final JSONObject answer, String lang, final ErrorList errorList) throws SQLException, HstoreParseException, JSONException, IllegalArgumentException, IllegalAccessException { // Load Language Files for Client final List<String> langs = Arrays.asList(settings.getString("RMBT_SUPPORTED_LANGUAGES").split(",\\s*")); if (langs.contains(lang)) { errorList.setLanguage(lang); } else { lang = settings.getString("RMBT_DEFAULT_LANGUAGE"); } if (conn != null) { final Client client = new Client(conn); final Test test = new Test(conn); boolean necessaryDataAvailable = false; if (uuid != null && uuid.getType() != null && uuid.getUuid() != null) { switch (uuid.getType()) { case OPEN_TEST_UUID: if (test.getTestByOpenTestUuid(UUID.fromString(uuid.getUuid())) > 0 && client.getClientByUid(test.getField("client_id").intValue())) { necessaryDataAvailable = true; } break; case TEST_UUID: if (test.getTestByUuid(UUID.fromString(uuid.getUuid())) > 0 && client.getClientByUid(test.getField("client_id").intValue())) { necessaryDataAvailable = true; } break; } } final long timeStampFullEval = System.currentTimeMillis(); if (necessaryDataAvailable) { final Locale locale = new Locale(lang); final ResultOptions resultOptions = new ResultOptions(locale); final JSONArray resultList = new JSONArray(); QoSTestResultDao resultDao = new QoSTestResultDao(conn); List<QoSTestResult> testResultList = resultDao.getByTestUid(test.getUid()); if (testResultList == null || testResultList.isEmpty()) { throw new UnsupportedOperationException("test " + test + " has no result list"); } //map that contains all test types and their result descriptions determined by the test result <-> test objectives comparison Map<TestType, TreeSet<ResultDesc>> resultKeys = new HashMap<>(); //test description set: Set<String> testDescSet = new TreeSet<>(); //test summary set: Set<String> testSummarySet = new TreeSet<>(); //Staring timestamp for evaluation time measurement final long timeStampEval = System.currentTimeMillis(); //iterate through all result entries for (final QoSTestResult testResult : testResultList) { //reset test counters testResult.setFailureCounter(0); testResult.setSuccessCounter(0); //get the correct class of the result; TestType testType = null; try { testType = TestType.valueOf(testResult.getTestType().toUpperCase(Locale.US)); } catch (IllegalArgumentException e) { final String errorMessage = "WARNING: QoS TestType '" + testResult.getTestType().toUpperCase(Locale.US) + "' not supported by ControlServer. Test with UID: " + testResult.getUid() + " skipped."; System.out.println(errorMessage); errorList.addErrorString(errorMessage); testType = null; } if (testType == null) { continue; } Class<? extends AbstractResult<?>> clazz = testType.getClazz(); //parse hstore data final JSONObject resultJson = new JSONObject(testResult.getResults()); AbstractResult<?> result = QoSUtil.HSTORE_PARSER.fromJSON(resultJson, clazz); result.setResultJson(resultJson); if (result != null) { //add each test description key to the testDescSet (to fetch it later from the db) if (testResult.getTestDescription() != null) { testDescSet.add(testResult.getTestDescription()); } if (testResult.getTestSummary() != null) { testSummarySet.add(testResult.getTestSummary()); } testResult.setResult(result); } //compare test results compareTestResults(testResult, result, resultKeys, testType, resultOptions); //resultList.put(testResult.toJson()); //save all test results after the success and failure counters have been set //resultDao.updateCounter(testResult); } //ending timestamp for evaluation time measurement final long timeStampEvalEnd = System.currentTimeMillis(); //------------------------------------------------------------- //fetch all result strings from the db QoSTestDescDao descDao = new QoSTestDescDao(conn, locale); //FIRST: get all test descriptions Set<String> testDescToFetchSet = testDescSet; testDescToFetchSet.addAll(testSummarySet); Map<String, String> testDescMap = descDao.getAllByKeyToMap(testDescToFetchSet); for (QoSTestResult testResult : testResultList) { //and set the test results + put each one to the result list json array String preParsedDesc = testDescMap.get(testResult.getTestDescription()); if (preParsedDesc != null) { String description = String.valueOf( TestScriptInterpreter.interprete(testDescMap.get(testResult.getTestDescription()), QoSUtil.HSTORE_PARSER, testResult.getResult(), true, resultOptions)); testResult.setTestDescription(description); } //do the same for the test summary: String preParsedSummary = testDescMap.get(testResult.getTestSummary()); if (preParsedSummary != null) { String description = String.valueOf( TestScriptInterpreter.interprete(testDescMap.get(testResult.getTestSummary()), QoSUtil.HSTORE_PARSER, testResult.getResult(), true, resultOptions)); testResult.setTestSummary(description); } resultList.put(testResult.toJson(uuid.getType())); } //finally put results to json answer.put("testresultdetail", resultList); JSONArray resultDescArray = new JSONArray(); //SECOND: fetch all test result descriptions for (TestType testType : resultKeys.keySet()) { TreeSet<ResultDesc> descSet = resultKeys.get(testType); //fetch results to same object descDao.loadToTestDesc(descSet); //another tree set for duplicate entries: //TODO: there must be a better solution //(the issue is: compareTo() method returns differnt values depending on the .value attribute (if it's set or not)) TreeSet<ResultDesc> descSetNew = new TreeSet<>(); //add fetched results to json for (ResultDesc desc : descSet) { if (!descSetNew.contains(desc)) { descSetNew.add(desc); } else { for (ResultDesc d : descSetNew) { if (d.compareTo(desc) == 0) { d.getTestResultUidList().addAll(desc.getTestResultUidList()); } } } } for (ResultDesc desc : descSetNew) { if (desc.getValue() != null) { resultDescArray.put(desc.toJson()); } } } //System.out.println(resultDescArray); //put result descriptions to json answer.put("testresultdetail_desc", resultDescArray); QoSTestTypeDescDao testTypeDao = new QoSTestTypeDescDao(conn, locale); JSONArray testTypeDescArray = new JSONArray(); for (QoSTestTypeDesc desc : testTypeDao.getAll()) { final JSONObject testTypeDesc = desc.toJson(); if (testTypeDesc != null) { testTypeDescArray.put(testTypeDesc); } } //put result descriptions to json answer.put("testresultdetail_testdesc", testTypeDescArray); JSONObject evalTimes = new JSONObject(); evalTimes.put("eval", (timeStampEvalEnd - timeStampEval)); evalTimes.put("full", (System.currentTimeMillis() - timeStampFullEval)); answer.put("eval_times", evalTimes); //System.out.println(answer); } else errorList.addError("ERROR_REQUEST_TEST_RESULT_DETAIL_NO_UUID"); } else errorList.addError("ERROR_DB_CONNECTION"); }
From source file:org.entando.entando.plugins.jptrello.aps.system.services.trello.TrelloConfig.java
public String toXml() throws Throwable { JSONObject json = new JSONObject(); json.put(CONFIG_ORGANIZATION, _organization); json.put(CONFIG_KEY, _apiKey);//from w ww . j av a2 s . c o m json.put(CONFIG_SECRET, _apiSecret); json.put(CONFIG_TOKEN, _token); return XML.toString(json, CONFIG_ROOT); }
From source file:com.sfalma.trace.Sfalma.java
public static String createJSON(String app_package, String version, String phoneModel, String android_version, String stackTrace, String wifi_status, String mob_net_status, String gps_status, Date occuredAt) throws Exception { JSONObject json = new JSONObject(); JSONObject request_json = new JSONObject(); JSONObject exception_json = new JSONObject(); JSONObject application_json = new JSONObject(); JSONObject client_json = new JSONObject(); request_json.put("remote_ip", ""); json.put("request", request_json); // stackTrace contains many info we need to extract BufferedReader reader = new BufferedReader(new StringReader(stackTrace)); if (occuredAt == null) exception_json.put("occured_at", reader.readLine()); else/*from ww w .jav a 2 s . c o m*/ exception_json.put("occured_at", occuredAt); exception_json.put("message", reader.readLine()); //get message String exception_class = reader.readLine(); exception_json.put("where", exception_class.substring(exception_class.lastIndexOf("(") + 1, exception_class.lastIndexOf(")"))); exception_json.put("klass", getClass(stackTrace)); exception_json.put("backtrace", stackTrace); json.put("exception", exception_json); reader.close(); application_json.put("phone", phoneModel); application_json.put("appver", version); application_json.put("appname", app_package); application_json.put("osver", android_version); //os_ver application_json.put("wifi_on", wifi_status); application_json.put("mobile_net_on", mob_net_status); application_json.put("gps_on", gps_status); json.put("application_environment", application_json); client_json.put("version", "sfalma-version-0.6"); client_json.put("name", "sfalma-android"); json.put("client", client_json); return json.toString(); }
From source file:edu.asu.bscs.ihattend.jsonrpcapp.JsonRPCCalculator.java
public Double calculate(Double op1, Double op2, String operation) { try {// w w w . j a va 2 s. c o m JSONObject jsonObject = new JSONObject(); jsonObject.put("jsonrpc", "2.0"); jsonObject.put("id", ++id); jsonObject.put("method", operation); String params = String.format(",\"params\":[%.2f,%.2f]", op1, op2); String almost = jsonObject.toString(); String begin = almost.substring(0, almost.length() - 1); String end = almost.substring(almost.length() - 1); String call = begin + params + end; Log.d(TAG, "call: " + call); String responseString = server.call(call); Log.d(TAG, "response: " + responseString); JSONObject response = new JSONObject(responseString); Double result = response.optDouble("result"); Log.d(TAG, "result: " + result); return result; } catch (Exception e) { e.printStackTrace(); } // should really throw an exception... return 0.0; }
From source file:com.cdd.bao.importer.KeywordMapping.java
public void save() throws IOException { JSONObject json = new JSONObject(); JSONArray listID = new JSONArray(), listText = new JSONArray(), listProp = new JSONArray(); JSONArray listVal = new JSONArray(), listLit = new JSONArray(), listRef = new JSONArray(), listAsrt = new JSONArray(); for (Identifier id : identifiers) { JSONObject obj = new JSONObject(); obj.put("regex", id.regex); obj.put("prefix", id.prefix); listID.put(obj);//from www. j a v a2 s . c o m } for (TextBlock txt : textBlocks) { JSONObject obj = new JSONObject(); obj.put("regex", txt.regex); obj.put("title", txt.title); listText.put(obj); } for (Property prop : properties) { JSONObject obj = new JSONObject(); obj.put("regex", prop.regex); obj.put("propURI", prop.propURI); obj.put("groupNest", prop.groupNest); listProp.put(obj); } for (Value val : values) { JSONObject obj = new JSONObject(); obj.put("regex", val.regex); obj.put("valueRegex", val.valueRegex); obj.put("valueURI", val.valueURI); obj.put("propURI", val.propURI); obj.put("groupNest", val.groupNest); listVal.put(obj); } for (Literal lit : literals) { JSONObject obj = new JSONObject(); obj.put("regex", lit.regex); obj.put("valueRegex", lit.valueRegex); obj.put("propURI", lit.propURI); obj.put("groupNest", lit.groupNest); listLit.put(obj); } for (Reference ref : references) { JSONObject obj = new JSONObject(); obj.put("regex", ref.regex); obj.put("valueRegex", ref.valueRegex); obj.put("prefix", ref.prefix); obj.put("propURI", ref.propURI); obj.put("groupNest", ref.groupNest); listRef.put(obj); } for (Assertion asrt : assertions) { JSONObject obj = new JSONObject(); obj.put("propURI", asrt.propURI); obj.put("groupNest", asrt.groupNest); obj.put("valueURI", asrt.valueURI); listAsrt.put(obj); } json.put("identifiers", listID); json.put("textBlocks", listText); json.put("properties", listProp); json.put("values", listVal); json.put("literals", listLit); json.put("references", listRef); json.put("assertions", listAsrt); Writer wtr = new FileWriter(file); wtr.write(json.toString(2)); wtr.close(); }
From source file:com.cdd.bao.importer.KeywordMapping.java
public JSONObject createAssay(JSONObject keydata, Schema schema, Map<Schema.Assignment, SchemaTree> treeCache) throws JSONException, IOException { String uniqueID = null;//from w w w .j ava2 s . c o m List<String> linesTitle = new ArrayList<>(), linesBlock = new ArrayList<>(); List<String> linesSkipped = new ArrayList<>(), linesProcessed = new ArrayList<>(); Set<String> gotAnnot = new HashSet<>(), gotLiteral = new HashSet<>(); JSONArray jsonAnnot = new JSONArray(); final String SEP = "::"; // assertions: these always supply a term for (Assertion asrt : assertions) { JSONObject obj = new JSONObject(); obj.put("propURI", ModelSchema.expandPrefix(asrt.propURI)); obj.put("groupNest", new JSONArray(expandPrefixes(asrt.groupNest))); obj.put("valueURI", ModelSchema.expandPrefix(asrt.valueURI)); jsonAnnot.put(obj); String hash = asrt.propURI + SEP + asrt.valueURI + SEP + (asrt.groupNest == null ? "" : String.join(SEP, asrt.groupNest)); gotAnnot.add(hash); } // go through the columns one at a time for (String key : keydata.keySet()) { String data = keydata.getString(key); Identifier id = findIdentifier(key); if (id != null) { if (uniqueID == null) uniqueID = id.prefix + data; continue; } TextBlock tblk = findTextBlock(key); if (tblk != null) { if (Util.isBlank(tblk.title)) linesTitle.add(data); else linesBlock.add(tblk.title + ": " + data); } Value val = findValue(key, data); if (val != null) { if (Util.isBlank(val.valueURI)) { linesSkipped.add(key + ": " + data); } else { String hash = val.propURI + SEP + val.valueURI + SEP + (val.groupNest == null ? "" : String.join(SEP, val.groupNest)); if (gotAnnot.contains(hash)) continue; JSONObject obj = new JSONObject(); obj.put("propURI", ModelSchema.expandPrefix(val.propURI)); obj.put("groupNest", new JSONArray(expandPrefixes(val.groupNest))); obj.put("valueURI", ModelSchema.expandPrefix(val.valueURI)); jsonAnnot.put(obj); gotAnnot.add(hash); linesProcessed.add(key + ": " + data); } continue; } Literal lit = findLiteral(key, data); if (lit != null) { String hash = lit.propURI + SEP + (lit.groupNest == null ? "" : String.join(SEP, lit.groupNest)) + SEP + data; if (gotLiteral.contains(hash)) continue; JSONObject obj = new JSONObject(); obj.put("propURI", ModelSchema.expandPrefix(lit.propURI)); obj.put("groupNest", new JSONArray(expandPrefixes(lit.groupNest))); obj.put("valueLabel", data); jsonAnnot.put(obj); gotLiteral.add(hash); linesProcessed.add(key + ": " + data); continue; } Reference ref = findReference(key, data); if (ref != null) { Pattern ptn = Pattern.compile(ref.valueRegex); Matcher m = ptn.matcher(data); if (!m.matches() || m.groupCount() < 1) throw new IOException( "Pattern /" + ref.valueRegex + "/ did not match '" + data + "' to produce a group."); JSONObject obj = new JSONObject(); obj.put("propURI", ModelSchema.expandPrefix(ref.propURI)); obj.put("groupNest", new JSONArray(expandPrefixes(ref.groupNest))); obj.put("valueLabel", ref.prefix + m.group(1)); jsonAnnot.put(obj); linesProcessed.add(key + ": " + data); continue; } // probably shouldn't get this far, but just in case linesSkipped.add(key + ": " + data); } // annotation collapsing: sometimes there's a branch sequence that should exclude parent nodes for (int n = 0; n < jsonAnnot.length(); n++) { JSONObject obj = jsonAnnot.getJSONObject(n); String propURI = obj.getString("propURI"), valueURI = obj.optString("valueURI"); if (valueURI == null) continue; String[] groupNest = obj.getJSONArray("groupNest").toStringArray(); Schema.Assignment[] assnList = schema.findAssignmentByProperty(ModelSchema.expandPrefix(propURI), groupNest); if (assnList.length == 0) continue; SchemaTree tree = treeCache.get(assnList[0]); if (tree == null) continue; Set<String> exclusion = new HashSet<>(); for (SchemaTree.Node node = tree.getNode(valueURI); node != null; node = node.parent) exclusion.add(node.uri); if (exclusion.size() == 0) continue; for (int i = jsonAnnot.length() - 1; i >= 0; i--) if (i != n) { obj = jsonAnnot.getJSONObject(i); if (!obj.has("valueURI")) continue; if (!propURI.equals(obj.getString("propURI"))) continue; if (!Objects.deepEquals(groupNest, obj.getJSONArray("groupNest").toStringArray())) continue; if (!exclusion.contains(obj.getString("valueURI"))) continue; jsonAnnot.remove(i); } } /*String text = ""; if (linesBlock.size() > 0) text += String.join("\n", linesBlock) + "\n\n"; if (linesSkipped.size() > 0) text += "SKIPPED:\n" + String.join("\n", linesSkipped) + "\n\n"; text += "PROCESSED:\n" + String.join("\n", linesProcessed);*/ List<String> sections = new ArrayList<>(); if (linesTitle.size() > 0) sections.add(String.join(" / ", linesTitle)); if (linesBlock.size() > 0) sections.add(String.join("\n", linesBlock)); sections.add("#### IMPORTED ####"); if (linesSkipped.size() > 0) sections.add("SKIPPED:\n" + String.join("\n", linesSkipped)); if (linesProcessed.size() > 0) sections.add("PROCESSED:\n" + String.join("\n", linesProcessed)); String text = String.join("\n\n", sections); JSONObject assay = new JSONObject(); assay.put("uniqueID", uniqueID); assay.put("text", text); assay.put("schemaURI", schema.getSchemaPrefix()); assay.put("annotations", jsonAnnot); return assay; }
From source file:actuatorapp.ActuatorApp.java
public ActuatorApp() throws IOException, JSONException { //Takes a sting with a relay name "RELAYLO1-10FAD.relay1" //Actuator a = new Actuator("RELAYLO1-12854.relay1"); //Starts the virtualhub that is needed to connect to the actuators Process process = new ProcessBuilder("src\\actuatorapp\\VirtualHub.exe").start(); //{"yocto_addr":"10FAD","payload":{"value":true},"type":"control"} api = new Socket("10.42.72.25", 8082); OutputStreamWriter osw = new OutputStreamWriter(api.getOutputStream(), StandardCharsets.UTF_8); InputStreamReader isr = new InputStreamReader(api.getInputStream(), StandardCharsets.UTF_8); //Sends JSON authentication to CommandAPI JSONObject secret = new JSONObject(); secret.put("type", "authenticate"); secret.put("secret", "testpass"); osw.write(secret.toString() + "\r\n"); osw.flush();//from www . ja v a 2s.c om System.out.println("sent"); //Waits and recieves JSON authentication response BufferedReader br = new BufferedReader(isr); JSONObject response = new JSONObject(br.readLine()); System.out.println(response.toString()); if (!response.getBoolean("success")) { System.err.println("Invalid API secret"); System.exit(1); } try { while (true) { //JSON object will contain message from the server JSONObject type = getCommand(br); //Forward the command to be processed (will find out which actuators to turn on/off) commandFromApi(type); } } catch (Exception e) { System.out.println("Error listening to api"); } }
From source file:com.liferay.mobile.android.v62.announcementsentry.AnnouncementsEntryService.java
public JSONObject addEntry(long plid, long classNameId, long classPK, String title, String content, String url, String type, int displayDateMonth, int displayDateDay, int displayDateYear, int displayDateHour, int displayDateMinute, int expirationDateMonth, int expirationDateDay, int expirationDateYear, int expirationDateHour, int expirationDateMinute, int priority, boolean alert) throws Exception { JSONObject _command = new JSONObject(); try {//from w ww.ja va 2s.c o m JSONObject _params = new JSONObject(); _params.put("plid", plid); _params.put("classNameId", classNameId); _params.put("classPK", classPK); _params.put("title", checkNull(title)); _params.put("content", checkNull(content)); _params.put("url", checkNull(url)); _params.put("type", checkNull(type)); _params.put("displayDateMonth", displayDateMonth); _params.put("displayDateDay", displayDateDay); _params.put("displayDateYear", displayDateYear); _params.put("displayDateHour", displayDateHour); _params.put("displayDateMinute", displayDateMinute); _params.put("expirationDateMonth", expirationDateMonth); _params.put("expirationDateDay", expirationDateDay); _params.put("expirationDateYear", expirationDateYear); _params.put("expirationDateHour", expirationDateHour); _params.put("expirationDateMinute", expirationDateMinute); _params.put("priority", priority); _params.put("alert", alert); _command.put("/announcementsentry/add-entry", _params); } catch (JSONException _je) { throw new Exception(_je); } JSONArray _result = session.invoke(_command); if (_result == null) { return null; } return _result.getJSONObject(0); }