List of usage examples for org.json JSONObject toString
public String toString()
From source file:tv.matchstick.demo.dashboard.DashBoardChannel.java
public final void join(FlintManager apiClient, String user) { try {// ww w .j a v a2 s . c o m Log.d(TAG, "join: " + user); JSONObject payload = new JSONObject(); payload.put(KEY_COMMAND, KEY_JOIN); payload.put(KEY_USER, user); sendMessage(apiClient, payload.toString()); } catch (JSONException e) { Log.e(TAG, "Cannot create object to show file", e); } }
From source file:tv.matchstick.demo.dashboard.DashBoardChannel.java
/** * Sends a command to leave the current game. *///from w w w .j a v a2 s.c o m public final void leave(FlintManager apiClient, String user) { try { Log.d(TAG, "leave"); JSONObject payload = new JSONObject(); payload.put(KEY_COMMAND, KEY_LEAVE); payload.put(KEY_USER, user); sendMessage(apiClient, payload.toString()); } catch (JSONException e) { Log.e(TAG, "Cannot create object to leave", e); } }
From source file:com.plant42.log4j.layouts.JSONLayout.java
/** * format a given LoggingEvent to a string, in this case JSONified string * @param loggingEvent// ww w . j a v a 2 s . com * @return String representation of LoggingEvent */ @Override public String format(LoggingEvent loggingEvent) { JSONObject root = new JSONObject(); try { //== write basic fields writeBasic(root, loggingEvent); //== write throwable fields writeThrowable(root, loggingEvent); } catch (JSONException e) { e.printStackTrace(); } return root.toString(); }
From source file:com.Upwork.api.OAuthClient.java
/** * Send signed POST OAuth request/* www . j a v a 2 s .co m*/ * * @param url Relative URL * @param type Type of HTTP request (HTTP method) * @param params Hash of parameters * @throws JSONException If JSON object is invalid or request was abnormal * @return {@link JSONObject} JSON Object that contains data from response * */ private JSONObject sendPostRequest(String url, Integer type, HashMap<String, String> params) throws JSONException { String fullUrl = getFullUrl(url); HttpPost request = new HttpPost(fullUrl); switch (type) { case METHOD_PUT: case METHOD_DELETE: // assign overload value String oValue; if (type == METHOD_PUT) { oValue = "put"; } else { oValue = "delete"; } params.put(OVERLOAD_PARAM, oValue); case METHOD_POST: break; default: throw new RuntimeException("Wrong http method requested"); } // doing post request using json to avoid issue with urlencoded symbols JSONObject json = new JSONObject(); for (Map.Entry<String, String> entry : params.entrySet()) { json.put(entry.getKey(), entry.getValue()); } request.setHeader("Content-Type", "application/json"); try { request.setEntity(new StringEntity(json.toString())); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // sign request try { mOAuthConsumer.sign(request); } catch (OAuthException e) { e.printStackTrace(); } return UpworkRestClient.getJSONObject(request, type, params); }
From source file:com.google.testing.testify.risk.frontend.server.task.UploadDataTask.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) { String user = req.getParameter("user"); String jsonString = req.getParameter("json"); try {//from w w w . j a v a 2s.c o m // TODO(jimr): add impersonation of user in string user. JSONObject json = new JSONObject(jsonString); JSONObject item; if (json.has("bug")) { item = json.getJSONObject("bug"); Bug bug = new Bug(); bug.setParentProjectId(item.getLong("projectId")); bug.setExternalId(item.getLong("bugId")); bug.setTitle(item.getString("title")); bug.setPath(item.getString("path")); bug.setSeverity(item.getLong("severity")); bug.setPriority(item.getLong("priority")); bug.setBugGroups(Sets.newHashSet(StringUtil.csvToList(item.getString("groups")))); bug.setBugUrl(item.getString("url")); bug.setState(item.getString("status")); bug.setStateDate(item.getLong("statusDate")); dataService.addBug(bug); } else if (json.has("test")) { item = json.getJSONObject("test"); TestCase test = new TestCase(); test.setParentProjectId(item.getLong("projectId")); test.setExternalId(item.getLong("testId")); test.setTitle(item.getString("title")); test.setTags(Sets.newHashSet(StringUtil.csvToList(item.getString("tags")))); test.setTestCaseUrl(item.getString("url")); test.setState(item.getString("result")); test.setStateDate(item.getLong("resultDate")); dataService.addTestCase(test); } else if (json.has("checkin")) { item = json.getJSONObject("checkin"); Checkin checkin = new Checkin(); checkin.setParentProjectId(item.getLong("projectId")); checkin.setExternalId(item.getLong("checkinId")); checkin.setSummary(item.getString("summary")); checkin.setDirectoriesTouched(Sets.newHashSet(StringUtil.csvToList(item.getString("directories")))); checkin.setChangeUrl(item.getString("url")); checkin.setState(item.getString("state")); checkin.setStateDate(item.getLong("stateDate")); dataService.addCheckin(checkin); } else { LOG.severe("No applicable data found for json: " + json.toString()); } } catch (JSONException e) { // We don't issue a 500 or similar response code here to prevent retries, which would have // no different a result. LOG.severe("Couldn't parse input JSON: " + jsonString); return; } }
From source file:org.pixmob.freemobile.netstat.SyncService.java
private void run(Intent intent, final SQLiteDatabase db) throws Exception { final long now = dateAtMidnight(System.currentTimeMillis()); Log.i(TAG, "Initializing statistics before uploading"); final LongSparseArray<DailyStat> stats = new LongSparseArray<DailyStat>(15); final Set<Long> uploadedStats = new HashSet<Long>(15); final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS; // Get pending uploads. Cursor c = db.query("daily_stat", new String[] { "stat_timestamp", "orange", "free_mobile", "sync" }, "stat_timestamp>=? AND stat_timestamp<?", new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null); try {/*from w ww . j a v a 2 s . c om*/ while (c.moveToNext()) { final long d = c.getLong(0); final int sync = c.getInt(3); if (SYNC_UPLOADED == sync) { uploadedStats.add(d); } else if (SYNC_PENDING == sync) { final DailyStat s = new DailyStat(); s.orange = c.getInt(1); s.freeMobile = c.getInt(2); stats.put(d, s); } } } finally { c.close(); } // Compute missing uploads. final ContentValues cv = new ContentValues(); db.beginTransaction(); try { for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) { if (stats.get(d) == null && !uploadedStats.contains(d)) { final DailyStat s = computeDailyStat(d); cv.put("stat_timestamp", d); cv.put("orange", s.orange); cv.put("free_mobile", s.freeMobile); cv.put("sync", SYNC_PENDING); db.insertOrThrow("daily_stat", null, cv); stats.put(d, s); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } // Delete old statistics. if (DEBUG) { Log.d(TAG, "Cleaning up upload database"); } db.delete("daily_stat", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) }); // Check if there are any statistics to upload. final int statsLen = stats.size(); if (statsLen == 0) { Log.i(TAG, "Nothing to upload"); return; } // Check if the remote server is up. final HttpClient client = createHttpClient(); try { client.head(createServerUrl(null)).execute(); } catch (HttpClientException e) { Log.w(TAG, "Remote server is not available: cannot upload statistics", e); return; } // Upload statistics. Log.i(TAG, "Uploading statistics"); final JSONObject json = new JSONObject(); final String deviceId = getDeviceId(); final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false); for (int i = 0; i < statsLen; ++i) { final long d = stats.keyAt(i); final DailyStat s = stats.get(d); try { json.put("timeOnOrange", s.orange); json.put("timeOnFreeMobile", s.freeMobile); } catch (JSONException e) { final IOException ioe = new IOException("Failed to prepare statistics upload"); ioe.initCause(e); throw ioe; } final String url = createServerUrl( "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d)); if (DEBUG) { Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url); } final byte[] rawJson = json.toString().getBytes("UTF-8"); try { client.post(url).content(rawJson, "application/json") .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND) .to(new HttpResponseHandler() { @Override public void onResponse(HttpResponse response) throws Exception { final int sc = response.getStatusCode(); if (HttpURLConnection.HTTP_NOT_FOUND == sc) { // Check if the device has just been // registered. if (deviceWasRegistered) { throw new IOException("Failed to upload statistics"); } else { // Got 404: the device does not exist. // We need to register this device. registerDevice(deviceId); // Restart this service. startService(new Intent(getApplicationContext(), SyncService.class) .putExtra(EXTRA_DEVICE_REG, true)); } } else if (HttpURLConnection.HTTP_OK == sc) { // Update upload database. cv.clear(); cv.put("sync", SYNC_UPLOADED); db.update("daily_stat", cv, "stat_timestamp=?", new String[] { String.valueOf(d) }); if (DEBUG) { Log.d(TAG, "Upload done for " + DateUtils.formatDate(d)); } } } }).execute(); } catch (HttpClientException e) { final IOException ioe = new IOException("Failed to send request with statistics"); ioe.initCause(e); throw ioe; } } }
From source file:org.pixmob.freemobile.netstat.SyncService.java
private void registerDevice(String deviceId) throws IOException { final JSONObject json = new JSONObject(); try {/*from w ww . j a v a 2 s .co m*/ json.put("brand", Build.BRAND); json.put("model", Build.MODEL); } catch (JSONException e) { final IOException ioe = new IOException("Failed to prepare device registration request"); ioe.initCause(e); throw ioe; } final byte[] rawJson = json.toString().getBytes("UTF-8"); Log.i(TAG, "Registering device"); final String url = createServerUrl("/device/" + deviceId); final HttpClient client = createHttpClient(); try { client.put(url).expect(HttpURLConnection.HTTP_CREATED).content(rawJson, "application/json").execute(); } catch (HttpClientException e) { final IOException ioe = new IOException("Failed to register device " + deviceId); ioe.initCause(e); throw ioe; } }
From source file:com.example.hbranciforte.trafficclient.DataTraffic.java
public void lunchResume(View view) throws JSONException, IOException { if (validate_form()) { JSONObject payment = getPaymentInfo(); JSONObject zone = getZoneInfo(); JSONObject device = getDeviceinfo(); JSONObject car = getCarInfo();/* w w w .j a v a2s . c om*/ JSONObject parking = new JSONObject(); EditText parkingCoins = (EditText) findViewById(R.id.fichas); parking.put("parking_units", Integer.valueOf(parkingCoins.getText().toString())); parking.put("zone", zone); parking.put("device", device); parking.put("car", car); parking.put("payment", payment); DefaultHttpClient httpclient = new DefaultHttpClient(); //HttpPost httppostreq = new HttpPost("http://10.0.2.2:3000/parkings"); HttpPost httppostreq = new HttpPost("http://45.55.79.197/parkings"); StringEntity se = new StringEntity(parking.toString()); httppostreq.setHeader("Content-type", "application/json"); httppostreq.setEntity(se); HttpResponse httpresponse = httpclient.execute(httppostreq); if (httpresponse.getStatusLine().getStatusCode() == 200) { Intent intent = new Intent(this, Resume.class); String responseString = new BasicResponseHandler().handleResponse(httpresponse); intent.putExtra("response", responseString); intent.putExtra("data", parking.toString()); startActivity(intent); } } }
From source file:eu.smartfp7.linkeddatamanager.interfaces.StructuredSearch.java
/** * Finding locations within a geo-spatial rectangle identified by the exact geographical coordinates of its lower-left corner and its upper-right corner * @param lat1: Between 0 and 90 degrees. Positive (North) o negative (South) * @param long1: Between 0 and 180 degrees. Positive (East) o negative (West) * @param lat2: Between 0 and 90 degrees. Positive (North) o negative (South) * @param long2: Between 0 and 180 degrees. Positive (East) o negative (West) * @param dataset: The dataset in which perform the search. By default Factforge * @return A JSON file format with the found venues * @throws IOException//from ww w. j av a 2s. c o m */ @GET @Path("locRec") @Produces({ MediaType.APPLICATION_JSON }) public Response sLocRec(@QueryParam("lat1") float lat1, @QueryParam("long1") float long1, @QueryParam("lat2") float lat2, @QueryParam("long2") float long2, @QueryParam("dataset") @DefaultValue("factforge") String dataset) throws IOException { logger.info("Invoking search Location by coordinates, rectangule"); logger.info("Dataset: " + dataset); logger.info("Lat1: " + lat1); logger.info("Long1: " + long1); logger.info("Lat2: " + lat2); logger.info("Long2: " + long2); InputStream in = null; Mapping m = new MappingManager().getMapping(dataset); SimpleQueryBuilder builder = new SimpleQueryBuilder(m); builder.setCriteria("", "", "", lat1, long1, lat2, long2, -1); String query = builder.printQuery(); SPARQLtoJSON queryer = new SPARQLtoJSON(m.getEndpoint(), m); try { JSONObject res = queryer.executeSPARQL(query); in = new ByteArrayInputStream(res.toString().getBytes()); } catch (Exception e) { e.printStackTrace(); return Response.serverError().build(); } logger.info("Invoked search Location by coordinates, rectangule"); return Response.ok(in).build(); }
From source file:eu.smartfp7.linkeddatamanager.interfaces.StructuredSearch.java
/** * Finding locations located within a geo-spatial circle identified by the geo-graphical coordinates (a pair of latitude and longitude) of its centre and its radius * @param lat1: The latitude coordinate indicating the centre. Between 0 and 90 degrees. Positive (North) o negative (South) * @param long1: The longitude coordinate indicating the centre. Between 0 and 180 degrees. Positive (East) o negative (West) * @param radius: The radio from the centre * @param dataset: The dataset in which perform the search. By default Factforge * @return A JSON file format with the found venues * @throws IOException /* ww w . j a v a2 s . co m*/ */ @GET @Path("locCirc") @Produces({ MediaType.APPLICATION_JSON }) public Response sLocCirc(@QueryParam("lat1") float lat1, @QueryParam("long1") float long1, @QueryParam("radius") float radius, @QueryParam("dataset") @DefaultValue("factforge") String dataset) throws IOException { logger.info("Invoking search Locations by coordinates, circule"); logger.info("Dataset: " + dataset); logger.info("Lat1: " + lat1); logger.info("Long1: " + long1); logger.info("Radius: " + radius); InputStream in = null; Mapping m = new MappingManager().getMapping(dataset); SimpleQueryBuilder builder = new SimpleQueryBuilder(m); builder.setCriteria("", "", "", lat1, long1, -91, -81, radius); String query = builder.printQuery(); SPARQLtoJSON queryer = new SPARQLtoJSON(m.getEndpoint(), m); try { JSONObject res = queryer.executeSPARQL(query); in = new ByteArrayInputStream(res.toString().getBytes()); } catch (Exception e) { e.printStackTrace(); return Response.serverError().build(); } logger.info("Invoked search locations by coordinates, circule"); return Response.ok(in).build(); }