Example usage for org.json JSONObject getInt

List of usage examples for org.json JSONObject getInt

Introduction

In this page you can find the example usage for org.json JSONObject getInt.

Prototype

public int getInt(String key) throws JSONException 

Source Link

Document

Get the int value associated with a key.

Usage

From source file:com.aujur.ebookreader.sync.PageTurnerWebProgressService.java

@Override
public List<BookProgress> getProgress(String fileName) throws AccessException {

    String userId = this.config.getSynchronizationEmail();
    String accessKey = this.config.getSynchronizationAccessKey();

    if ("".equals(userId) || "".equals(fileName)) {
        LOG.debug("Empty username or filename. Aborting sync. (" + userId + " / " + fileName + ")");
        return null;
    }//w  w w. j ava 2  s  .  c  o  m

    String key = computeKey(fileName);

    LOG.debug("Doing progress query for key: " + key);

    HttpGet get = new HttpGet(getSyncServerURL() + key + "?accessKey=" + URLEncoder.encode(accessKey));
    get.setHeader("User-Agent", config.getUserAgent());

    try {
        HttpResponse response = client.execute(get);

        int statusCode = response.getStatusLine().getStatusCode();
        LOG.debug("Got status " + statusCode + " from server.");

        if (statusCode == HTTP_FORBIDDEN) {
            throw new AccessException(EntityUtils.toString(response.getEntity()));
        }

        if (statusCode == HTTP_NOT_FOUND) {
            return new ArrayList<BookProgress>();
        }

        if (statusCode != HTTP_SUCCESS) {
            return null;
        }

        String responseString = EntityUtils.toString(response.getEntity());

        JSONArray jsonArray = new JSONArray(responseString);

        List<BookProgress> result = new ArrayList<BookProgress>();

        for (int i = 0; i < jsonArray.length(); i++) {

            JSONObject json = jsonArray.getJSONObject(i);

            int index = json.getInt("bookIndex");
            int progress = json.getInt("progress");
            int percentage = json.getInt("percentage");

            Date timeStamp = dateFormat.parse(json.getString("storedOn"));

            String deviceName = json.getString("deviceName");

            result.add(new BookProgress(fileName, index, progress, percentage, timeStamp, deviceName));
        }

        return result;

    } catch (IOException e) {
        LOG.error("Got error while querying server", e);
        return null;
    } catch (JSONException json) {
        LOG.error("Error reading response", json);
        return null;
    } catch (ParseException p) {
        LOG.error("Invalid date", p);
        return null;
    }

}

From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java

public Object[] sync(Connection con) {
    mSyncMsg = "";
    // if the deck has any pending changes, flush them first and bump mod time
    mCol.save();//from   w w  w .j  a v  a 2s . co m
    // step 1: login & metadata
    HttpResponse ret = mServer.meta();
    if (ret == null) {
        return null;
    }
    int returntype = ret.getStatusLine().getStatusCode();
    if (returntype == 403) {
        return new Object[] { "badAuth" };
    } else if (returntype != 200) {
        return new Object[] { "error", returntype, ret.getStatusLine().getReasonPhrase() };
    }
    try {
        mCol.getDb().getDatabase().beginTransaction();
        try {
            // Log.i(AnkiDroidApp.TAG, "Sync: getting meta data from server");
            JSONObject rMeta = new JSONObject(mServer.stream2String(ret.getEntity().getContent()));
            long rscm = rMeta.getLong("scm");
            int rts = rMeta.getInt("ts");
            mRMod = rMeta.getLong("mod");
            mMaxUsn = rMeta.getInt("usn");
            mMediaUsn = rMeta.getInt("musn");
            mSyncMsg = rMeta.getString("msg");
            // skip uname, AnkiDroid already stores and shows it
            if (!rMeta.getBoolean("cont")) {
                // Don't add syncMsg; it can be fetched by UI code using the accessor
                return new Object[] { "serverAbort" };
            } else {
                // don't abort, but ui should show messages after sync finishes
                // and require confirmation if it's non-empty
            }
            // Log.i(AnkiDroidApp.TAG, "Sync: building local meta data");
            JSONObject lMeta = meta();
            mLMod = lMeta.getLong("mod");
            mMinUsn = lMeta.getInt("usn");
            long lscm = lMeta.getLong("scm");
            int lts = lMeta.getInt("ts");

            long diff = Math.abs(rts - lts);
            if (diff > 300) {
                return new Object[] { "clockOff", diff };
            }
            if (mLMod == mRMod) {
                // Log.i(AnkiDroidApp.TAG, "Sync: no changes - returning");
                return new Object[] { "noChanges" };
            } else if (lscm != rscm) {
                // Log.i(AnkiDroidApp.TAG, "Sync: full sync necessary - returning");
                return new Object[] { "fullSync" };
            }
            mLNewer = mLMod > mRMod;
            // step 2: deletions
            publishProgress(con, R.string.sync_deletions_message);

            // Log.i(AnkiDroidApp.TAG, "Sync: collection removed data");
            JSONObject lrem = removed();
            JSONObject o = new JSONObject();
            o.put("minUsn", mMinUsn);
            o.put("lnewer", mLNewer);
            o.put("graves", lrem);

            // Log.i(AnkiDroidApp.TAG, "Sync: sending and receiving removed data");
            JSONObject rrem = mServer.start(o);
            if (rrem == null) {
                // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                return null;
            }
            if (rrem.has("errorType")) {
                // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                return new Object[] { "error", rrem.get("errorType"), rrem.get("errorReason") };
            }

            // Log.i(AnkiDroidApp.TAG, "Sync: applying removed data");
            remove(rrem);
            // ... and small objects
            publishProgress(con, R.string.sync_small_objects_message);

            // Log.i(AnkiDroidApp.TAG, "Sync: collection small changes");
            JSONObject lchg = changes();
            JSONObject sch = new JSONObject();
            sch.put("changes", lchg);

            // Log.i(AnkiDroidApp.TAG, "Sync: sending and receiving small changes");
            JSONObject rchg = mServer.applyChanges(sch);
            if (rchg == null) {
                // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                return null;
            }
            if (rchg.has("errorType")) {
                // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                return new Object[] { "error", rchg.get("errorType"), rchg.get("errorReason") };
            }

            // Log.i(AnkiDroidApp.TAG, "Sync: merging small changes");
            mergeChanges(lchg, rchg);
            // step 3: stream large tables from server
            publishProgress(con, R.string.sync_download_chunk);
            while (true) {
                // Log.i(AnkiDroidApp.TAG, "Sync: downloading chunked data");
                JSONObject chunk = mServer.chunk();
                if (chunk == null) {
                    // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                    return null;
                }
                if (chunk.has("errorType")) {
                    // Log.i(AnkiDroidApp.TAG, "Sync: error - returning");
                    return new Object[] { "error", chunk.get("errorType"), chunk.get("errorReason") };
                }
                // Log.i(AnkiDroidApp.TAG, "Sync: applying chunked data");
                applyChunk(chunk);
                if (chunk.getBoolean("done")) {
                    break;
                }
            }
            // step 4: stream to server
            publishProgress(con, R.string.sync_upload_chunk);
            while (true) {
                // Log.i(AnkiDroidApp.TAG, "Sync: collecting chunked data");
                JSONObject chunk = chunk();
                JSONObject sech = new JSONObject();
                sech.put("chunk", chunk);
                // Log.i(AnkiDroidApp.TAG, "Sync: sending chunked data");
                mServer.applyChunk(sech);
                if (chunk.getBoolean("done")) {
                    break;
                }
            }
            // step 5: sanity check during beta testing
            JSONObject c = sanityCheck();
            JSONObject sanity = mServer.sanityCheck2(c);
            if (sanity == null || !sanity.optString("status", "bad").equals("ok")) {
                return new Object[] { "sanityCheckError", null };
            }
            // finalize
            publishProgress(con, R.string.sync_finish_message);
            // Log.i(AnkiDroidApp.TAG, "Sync: sending finish command");
            long mod = mServer.finish();
            if (mod == 0) {
                return new Object[] { "finishError" };
            }
            // Log.i(AnkiDroidApp.TAG, "Sync: finishing");
            finish(mod);

            publishProgress(con, R.string.sync_writing_db);
            mCol.getDb().getDatabase().setTransactionSuccessful();
        } finally {
            mCol.getDb().getDatabase().endTransaction();
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        throw new RuntimeException(e);
    } catch (OutOfMemoryError e) {
        AnkiDroidApp.saveExceptionReportFile(e, "Syncer-sync");
        return new Object[] { "OutOfMemoryError" };
    } catch (IOException e) {
        AnkiDroidApp.saveExceptionReportFile(e, "Syncer-sync");
        return new Object[] { "IOException" };
    }
    return new Object[] { "success" };
}

From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java

public JSONObject sanityCheck() {
    JSONObject result = new JSONObject();
    try {/*from w ww.  j ava  2s.c o  m*/
        if (mCol.getDb().queryScalar("SELECT count() FROM cards WHERE nid NOT IN (SELECT id FROM notes)",
                false) != 0) {
            Log.e(AnkiDroidApp.TAG, "Sync - SanityCheck: there are cards without mother notes");
            result.put("client", "missing notes");
            return result;
        }
        if (mCol.getDb().queryScalar(
                "SELECT count() FROM notes WHERE id NOT IN (SELECT DISTINCT nid FROM cards)", false) != 0) {
            Log.e(AnkiDroidApp.TAG, "Sync - SanityCheck: there are notes without cards");
            result.put("client", "missing cards");
            return result;
        }
        if (mCol.getDb().queryScalar("SELECT count() FROM cards WHERE usn = -1", false) != 0) {
            Log.e(AnkiDroidApp.TAG, "Sync - SanityCheck: there are unsynced cards");
            result.put("client", "cards had usn = -1");
            return result;
        }
        if (mCol.getDb().queryScalar("SELECT count() FROM notes WHERE usn = -1", false) != 0) {
            Log.e(AnkiDroidApp.TAG, "Sync - SanityCheck: there are unsynced notes");
            result.put("client", "notes had usn = -1");
            return result;
        }
        if (mCol.getDb().queryScalar("SELECT count() FROM revlog WHERE usn = -1", false) != 0) {
            Log.e(AnkiDroidApp.TAG, "Sync - SanityCheck: there are unsynced revlogs");
            result.put("client", "revlog had usn = -1");
            return result;
        }
        if (mCol.getDb().queryScalar("SELECT count() FROM graves WHERE usn = -1", false) != 0) {
            Log.e(AnkiDroidApp.TAG, "Sync - SanityCheck: there are unsynced graves");
            result.put("client", "graves had usn = -1");
            return result;
        }
        for (JSONObject g : mCol.getDecks().all()) {
            if (g.getInt("usn") == -1) {
                Log.e(AnkiDroidApp.TAG, "Sync - SanityCheck: unsynced deck: " + g.getString("name"));
                result.put("client", "deck had usn = -1");
                return result;
            }
        }
        for (Integer usn : mCol.getTags().allItems().values()) {
            if (usn == -1) {
                Log.e(AnkiDroidApp.TAG, "Sync - SanityCheck: there are unsynced tags");
                result.put("client", "tag had usn = -1");
                return result;
            }
        }
        boolean found = false;
        for (JSONObject m : mCol.getModels().all()) {
            if (mCol.getServer()) {
                // the web upgrade was mistakenly setting usn
                if (m.getInt("usn") < 0) {
                    m.put("usn", 0);
                    found = true;
                }
            } else {
                if (m.getInt("usn") == -1) {
                    Log.e(AnkiDroidApp.TAG, "Sync - SanityCheck: unsynced model: " + m.getString("name"));
                    result.put("client", "model had usn = -1");
                    return result;
                }
            }
        }
        if (found) {
            mCol.getModels().save();
        }
        mCol.getSched().reset();
        // check for missing parent decks
        mCol.getSched().deckDueList();
        // return summary of deck
        JSONArray ja = new JSONArray();
        JSONArray sa = new JSONArray();
        for (int c : mCol.getSched().counts()) {
            sa.put(c);
        }
        ja.put(sa);
        ja.put(mCol.getDb().queryScalar("SELECT count() FROM cards"));
        ja.put(mCol.getDb().queryScalar("SELECT count() FROM notes"));
        ja.put(mCol.getDb().queryScalar("SELECT count() FROM revlog"));
        ja.put(mCol.getDb().queryScalar("SELECT count() FROM graves"));
        ja.put(mCol.getModels().all().size());
        ja.put(mCol.getDecks().all().size());
        ja.put(mCol.getDecks().allConf().size());
        result.put("client", ja);
        return result;
    } catch (JSONException e) {
        Log.e(AnkiDroidApp.TAG, "Syncer.sanityCheck(): ", e);
        throw new RuntimeException(e);
    }
}

From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java

/**
 * Models ********************************************************************
 *//*from   www . j a v a  2 s  .  co m*/

private JSONArray getModels() {
    JSONArray result = new JSONArray();
    try {
        if (mCol.getServer()) {
            for (JSONObject m : mCol.getModels().all()) {
                if (m.getInt("usn") >= mMinUsn) {
                    result.put(m);
                }
            }
        } else {
            for (JSONObject m : mCol.getModels().all()) {
                if (m.getInt("usn") == -1) {
                    m.put("usn", mMaxUsn);
                    result.put(m);
                }
            }
            mCol.getModels().save();
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java

/**
 * Decks ********************************************************************
 *//*from  w ww  .j  ava 2s.  co  m*/

private JSONArray getDecks() {
    JSONArray result = new JSONArray();
    try {
        if (mCol.getServer()) {
            JSONArray decks = new JSONArray();
            for (JSONObject g : mCol.getDecks().all()) {
                if (g.getInt("usn") >= mMinUsn) {
                    decks.put(g);
                }
            }
            JSONArray dconfs = new JSONArray();
            for (JSONObject g : mCol.getDecks().allConf()) {
                if (g.getInt("usn") >= mMinUsn) {
                    dconfs.put(g);
                }
            }
            result.put(decks);
            result.put(dconfs);
        } else {
            JSONArray decks = new JSONArray();
            for (JSONObject g : mCol.getDecks().all()) {
                if (g.getInt("usn") == -1) {
                    g.put("usn", mMaxUsn);
                    decks.put(g);
                }
            }
            JSONArray dconfs = new JSONArray();
            for (JSONObject g : mCol.getDecks().allConf()) {
                if (g.getInt("usn") == -1) {
                    g.put("usn", mMaxUsn);
                    dconfs.put(g);
                }
            }
            mCol.getDecks().save();
            result.put(decks);
            result.put(dconfs);
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:my.madet.uniteninfo.OpenVPN.java

public void sendResponseDataToMyVPN(final String purchaseData, final String dataSignature) {

    new HttpHandler() {
        @Override/*from ww  w . j  a  va  2s.  c o m*/
        public HttpUriRequest getHttpRequestMethod() {
            HttpPost httppost = new HttpPost("https://apps.madet.my/myvpn/googlebilling/");
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("purchaseData", purchaseData));
            nameValuePairs.add(new BasicNameValuePair("purchaseDataSignature", dataSignature));
            try {
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return httppost;
        }

        @Override
        public void onResponse(String result) {
            Log.d("HttpHandler", "result: " + result);
            try {
                JSONObject jObject = new JSONObject(result);

                if (jObject.getInt("code") == InAppPurchase.MYVPN_RESPONSE_BILLING_OK) {
                    // success linked

                    manageSubscriptionButton.setVisibility(View.VISIBLE);
                    subscribeButton.setVisibility(View.GONE);

                    SharedPreferences.Editor editor = sharedPref.edit();
                    editor.putString("myvpn_user_name", jObject.getString("user_name"));
                    editor.commit();

                } else if (jObject.getInt("code") == InAppPurchase.MYVPN_RESPONSE_BILLING_SIGNATURE_ERROR) {
                    Toast.makeText(getActivity(), "Purchase Signature error!", Toast.LENGTH_LONG).show();
                } else if (jObject.getInt("code") == InAppPurchase.MYVPN_RESPONSE_BILLING_USER_NOT_FOUND) {
                    Toast.makeText(getActivity(), "Please register MyVPN account and link the account",
                            Toast.LENGTH_LONG).show();
                    linkAccountTextView.setVisibility(View.VISIBLE);
                    linkAccountUserNameEditText.setVisibility(View.VISIBLE);
                    linkAccountPasswordEditText.setVisibility(View.VISIBLE);
                    linkAccountConnectButton.setVisibility(View.VISIBLE);
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void preRequest() {
            // TODO Auto-generated method stub
        }

    }.execute();
}

From source file:io.selendroid.server.CreateSessionHandlerTest.java

@Test
public void assertNewTestSessionCreationAndGetCapabilties() throws Exception {
    HttpResponse sessionResponse = executeCreateSessionRequest();
    JSONObject json = parseJsonResponse(sessionResponse);
    String sessionId = json.getString("sessionId");

    // Get capabilities of session
    HttpResponse getCapaResp = executeRequest("http://" + host + ":" + port + "/wd/hub/session/" + sessionId,
            HttpMethod.GET);//  w  ww  .  j  av a  2 s.  co  m
    SelendroidAssert.assertResponseIsOk(getCapaResp);
    JSONObject capa = parseJsonResponse(getCapaResp);
    Assert.assertEquals(sessionId, capa.getString("sessionId"));
    Assert.assertEquals(0, capa.getInt("status"));

    Assert.assertEquals("selendroid", capa.getJSONObject("value").getString(Capabilities.NAME));
}

From source file:es.ucm.look.data.remote.restful.RestMethod.java

/**
 * To know the 'number' of last id inserted in the Server
 * /*from  w w  w  .j  a v a  2s  .co m*/
 * @return
 */
public static int getLastId() {

    int result = -1;

    String query = URLEncoder.encode("SELECT e FROM Main e ORDER BY e.id DESC");

    String params = "?max=1&query=" + query;

    HttpClient httpclient = new DefaultHttpClient();

    // Prepare a request object
    HttpGet httpget = new HttpGet(ConfigNet.getInstance().getURL("mains/" + params));

    // Accept Text/plain
    httpget.addHeader("accept", "application/json");

    // Execute the request
    HttpResponse response;
    try {
        response = httpclient.execute(httpget);

        // Get the response entity
        HttpEntity entity = response.getEntity();

        // If response entity is not null
        if (entity != null) {

            // get entity contents and convert it to string
            InputStream instream = entity.getContent();
            String resultResponse = convertStreamToString(instream);

            // construct a JSON object with result
            try {
                // extract field id of the json
                JSONObject json = new JSONObject(resultResponse);
                JSONObject mainEntity = json.getJSONObject("main");
                result = mainEntity.getInt("id");

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // Closing the input stream will trigger connection release
            instream.close();
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Return the result
    return result;
}

From source file:com.domuslink.api.DomusHandler.java

public void getAliasState(Alias theAlias) throws Exception {
    JSONObject theResponse = null;

    if ((this.hostPath != null || this.hostPath.length() != 0) && !theAlias.isScene()
            && !theAlias.isMultiAlias()) {
        ApiHandler.prepareUserAgent(this.c, authPass, hostPath);
        try {//  ww w.jav  a 2 s.  co m
            theResponse = ApiHandler.getPageContent(this, "aliasstate", theAlias.getLabel());
        } catch (Exception e) {
            Log.e(TAG, "Error getting alias state page content at " + this.hostPath, e);
            throw e;
        }

        try {
            if (theResponse.getInt("state") == -1 && theResponse.getInt("level") == -1) {
                Log.e(TAG, "domus.Link reports heyu is not running");
                throw new HeyuException();
            }
            theAlias.setState(theResponse.getInt("state"));
            theAlias.setDimLevel(theResponse.getInt("level"));
        } catch (Exception e) {
            Log.e(TAG, "Error getting alias state value from JSONObject", e);
            throw e;
        }
    } else {
        theAlias.setState(0);
        theAlias.setDimLevel(0);
    }
}

From source file:views.online.Panel_RejoindrePartieMulti.java

/**
 * Permet de mettre a jour la liste des serveurs avec une rponse JSON
 * //from   ww  w. j av a  2s  .c om
 * @param resultatJSON le rsultat du serveur d'enregistrement
 */
private void mettreAJourListeDepuisJSON(String resultatJSON) {
    try {
        // Analyse de la rponse du serveur d'enregistrement
        JSONObject jsonResultat = new JSONObject(resultatJSON);

        // on vide la liste des serveurs
        serveurs.clear();

        if (jsonResultat.getInt("status") == CodeRegisterment.OK) {
            // slection des serveurs de jeu
            JSONArray jsonArray = jsonResultat.getJSONArray("parties");

            // ajout des serveurs de jeu
            int i = 0;
            for (; i < jsonArray.length(); i++) {
                JSONObject serveur = jsonArray.getJSONObject(i);

                ajouterServeur(serveur.getString("nomPartie"), serveur.getString("adresseIp"),
                        serveur.getInt("numeroPort"), serveur.getString("mode"),
                        serveur.getString("nomTerrain"), serveur.getInt("capacite"),
                        serveur.getInt("placesRestantes"));

            }

            if (i > 0)
                tbServeurs.setRowSelectionInterval(0, 0);

            lblEtat.setForeground(LookInterface.COULEUR_SUCCES);
            lblEtat.setText(Language.getTexte(Language.ID_TXT_CON_SRV_CENTRAL_ETABLIE));
        } else {
            lblEtat.setForeground(LookInterface.COULEUR_SUCCES);
            lblEtat.setText(Language.getTexte(Language.ID_TXT_CON_SRV_CENTRAL_ETABLIE) + " ["
                    + Language.getTexte(Language.ID_TXT_AUCUN_SRV_DISPONIBLE) + "]");
        }
    } catch (JSONException e1) {
        lblEtat.setForeground(LookInterface.COULEUR_ERREUR);
        lblEtat.setText("Format de rponse du serveur incorrect!");
    }
}