List of usage examples for org.json JSONObject put
public JSONObject put(String key, Object value) throws JSONException
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 {// www .j a v a2 s . co m 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 {//www . j a va2 s.c o 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 a 2s .c o m 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:com.example.hbranciforte.trafficclient.DataTraffic.java
private JSONObject getPaymentInfo() { JSONObject payment = new JSONObject(); EditText paymentField1 = (EditText) findViewById(R.id.payment_field1); EditText licenseSec = (EditText) findViewById(R.id.payment_security); TextView valor = (TextView) findViewById(R.id.valor); try {/* ww w . j a v a 2 s. c o m*/ payment.put("type", "test_method"); payment.put("data", "{\"data\",\"".concat(paymentField1.getText().toString()).concat("\",\"security\":\"") .concat(licenseSec.getText().toString().concat("\",\"price\":") .concat(Float.toString(price)).concat("}"))); payment.put("price", price); return payment; } catch (JSONException e) { Log.e("json error", e.getMessage()); } return payment; }
From source file:com.example.hbranciforte.trafficclient.DataTraffic.java
private JSONObject getZoneInfo() { JSONObject zone = new JSONObject(); try {//from ww w . j a v a 2 s. c o m zone.put("name", zone_info.get("name")); zone.put("number", zone_info.get("number")); } catch (JSONException e) { Log.e("JSON ERROR", e.getMessage()); } return zone; }
From source file:com.example.hbranciforte.trafficclient.DataTraffic.java
private JSONObject getDeviceinfo() { JSONObject device = new JSONObject(); try {// w w w . ja v a 2 s . c om TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); String token = telephonyManager.getDeviceId().toString(); device.put("notification_token", token); device.put("user_agent", System.getProperty("http.agent").toString()); } catch (JSONException e) { Log.e("Json error", e.getMessage()); } return device; }
From source file:com.example.hbranciforte.trafficclient.DataTraffic.java
private JSONObject getCarInfo() { JSONObject car = new JSONObject(); EditText licenseLetters = (EditText) findViewById(R.id.license_letters); EditText licenseNumbers = (EditText) findViewById(R.id.license_numbers); try {//from w w w . ja va2s. co m car.put("license_plate", licenseLetters.getText().toString().toUpperCase().concat(licenseNumbers.getText().toString())); } catch (JSONException e) { Log.e("JSON error", e.getMessage()); } return car; }
From source file:com.amazonaws.sns.samples.tools.SampleMessageGenerator.java
public static String getSampleAndroidMessage() { JSONObject androidMessageMap = new JSONObject(); JSONObject notification = new JSONObject(); //Map<String, Object> androidMessageMap = new HashMap<String, Object>(); try {//from w ww .j av a 2 s . co m //androidMessageMap.put("collapse_key", "Welcome"); notification.put("title", "AWS SNS Notification"); notification.put("body", "This is to test the AWS SNS server."); androidMessageMap.put("notification", notification); androidMessageMap.put("data", new JSONObject()); //androidMessageMap.put("delay_while_idle", true); //androidMessageMap.put("time_to_live", 125); //androidMessageMap.put("dry_run", false); } catch (Exception e) { e.printStackTrace(); } return jsonify(androidMessageMap); }
From source file:it.unicaradio.android.tasks.DownloadCaptchaAsyncTask.java
/** * {@inheritDoc}/*from ww w . ja v a2 s . c o m*/ */ @Override protected Response<String> doInBackground(Void... params) { try { JSONObject request = new JSONObject(); request.put("method", "getCaptcha"); byte[] postData = request.toString().getBytes(); Response<String> response = new Response<String>(); byte[] resultBytes = NetworkUtils.httpPost(WEB_SERVICE, postData, "application/json"); String resultString = new String(resultBytes); Log.d(TAG, "Got CAPTCHA answer: " + resultString); JSONObject resultJSON = new JSONObject(resultString); response.setResult(resultJSON.getString("result")); return response; } catch (ClientProtocolException e) { Log.e(TAG, e.getMessage(), e); return new Response<String>(Error.INTERNAL_GENERIC_ERROR); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); return new Response<String>(Error.INTERNAL_DOWNLOAD_ERROR); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return new Response<String>(Error.INTERNAL_GENERIC_ERROR); } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); return new Response<String>(Error.INTERNAL_GENERIC_ERROR); } }