Example usage for org.json JSONObject has

List of usage examples for org.json JSONObject has

Introduction

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

Prototype

public boolean has(String key) 

Source Link

Document

Determine if the JSONObject contains a specific key.

Usage

From source file:com.ichi2.anki2.DeckOptions.java

private void addMissingValues() {
    try {//from  w  w w. j  a v  a2 s.com
        for (JSONObject o : mCol.getDecks().all()) {
            JSONObject conf = mCol.getDecks().confForDid(o.getLong("id"));
            if (!conf.has("replayq")) {
                conf.put("replayq", true);
                mCol.getDecks().save(conf);
            }
        }
    } catch (JSONException e1) {
        // nothing
    }
}

From source file:org.brickred.socialauth.provider.GooglePlusImpl.java

private Profile getProfile() throws Exception {
    String presp;//from  w  w  w  . j av a2  s  . c  o  m

    try {
        Response response = authenticationStrategy.executeFeed(PROFILE_URL);
        presp = response.getResponseBodyAsString(Constants.ENCODING);
    } catch (Exception e) {
        throw new SocialAuthException("Error while getting profile from " + PROFILE_URL, e);
    }
    try {
        LOG.debug("User Profile : " + presp);
        JSONObject resp = new JSONObject(presp);
        Profile p = new Profile();
        p.setValidatedId(resp.getString("id"));
        if (resp.has("name")) {
            p.setFullName(resp.getString("name"));
        }
        if (resp.has("given_name")) {
            p.setFirstName(resp.getString("given_name"));
        }
        if (resp.has("family_name")) {
            p.setLastName(resp.getString("family_name"));
        }
        if (resp.has("email")) {
            p.setEmail(resp.getString("email"));
        }
        if (resp.has("gender")) {
            p.setGender(resp.getString("gender"));
        }
        if (resp.has("picture")) {
            p.setProfileImageURL(resp.getString("picture"));
        }
        if (resp.has("id")) {
            p.setValidatedId(resp.getString("id"));
        }

        p.setProviderId(getProviderId());
        userProfile = p;
        return p;

    } catch (Exception ex) {
        throw new ServerDataException("Failed to parse the user profile json : " + presp, ex);
    }
}

From source file:ezy.boost.update.UpdateInfo.java

public static UpdateInfo parse(String s) throws JSONException {
    JSONObject o = new JSONObject(s);
    return parse(o.has("data") ? o.getJSONObject("data") : o);
}

From source file:org.vaadin.addons.locationtextfield.GoogleGeocoder.java

private LocationType getLocationType(JSONObject result) throws JSONException {
    if (!result.has("types"))
        return LocationType.UNKNOWN;
    JSONArray types = result.getJSONArray("types");
    for (int i = 0; i < types.length(); i++) {
        final String type = types.getString(i);
        if ("street_address".equals(type))
            return LocationType.STREET_ADDRESS;
        else if ("route".equals(type))
            return LocationType.ROUTE;
        else if ("intersection".equals(type))
            return LocationType.INTERSECTION;
        else if ("country".equals(type))
            return LocationType.COUNTRY;
        else if ("administrative_area_level_1".equals(type))
            return LocationType.ADMIN_LEVEL_1;
        else if ("administrative_area_level_2".equals(type))
            return LocationType.ADMIN_LEVEL_2;
        else if ("locality".equals(type))
            return LocationType.LOCALITY;
        else if ("neighborhood".equals(type))
            return LocationType.NEIGHBORHOOD;
        else if ("postal_code".equals(type))
            return LocationType.POSTAL_CODE;
        else if ("point_of_interest".equals(type))
            return LocationType.POI;
    }/*from   ww  w.j  a v  a2  s  . c  om*/
    return LocationType.UNKNOWN;
}

From source file:net.dv8tion.jda.core.handle.VoiceStateUpdateHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    final Long guildId = content.has("guild_id") ? content.getLong("guild_id") : null;
    if (guildId != null && api.getGuildLock().isLocked(guildId))
        return guildId;

    if (guildId != null)
        handleGuildVoiceState(content);/*from   w  w w  .  ja  va 2 s. co  m*/
    else
        handleCallVoiceState(content);
    return null;
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

/**
 * Inserts an object into the database and flags it to be sent by
 * the transport layer.// ww  w  .j a  v a2 s .c o m
 */
long addToFeed(String appId, String feedName, ContentValues values) {
    try {
        JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
        String type = values.getAsString(DbObject.TYPE);

        long nextSeqId = getFeedMaxSequenceId(Contact.MY_ID, feedName) + 1;
        long timestamp = new Date().getTime();
        json.put(DbObjects.TYPE, type);
        json.put(DbObjects.FEED_NAME, feedName);
        json.put(DbObjects.SEQUENCE_ID, nextSeqId);
        json.put(DbObjects.TIMESTAMP, timestamp);
        json.put(DbObjects.APP_ID, appId);

        // Explicit column referencing avoids database errors.
        ContentValues cv = new ContentValues();
        cv.put(DbObject._ID, getNextId());
        cv.put(DbObject.APP_ID, appId);
        cv.put(DbObject.FEED_NAME, feedName);
        cv.put(DbObject.CONTACT_ID, Contact.MY_ID);
        cv.put(DbObject.TYPE, type);
        cv.put(DbObject.SEQUENCE_ID, nextSeqId);
        cv.put(DbObject.JSON, json.toString());
        cv.put(DbObject.TIMESTAMP, timestamp);
        cv.put(DbObject.LAST_MODIFIED_TIMESTAMP, new Date().getTime());

        if (values.containsKey(DbObject.RAW)) {
            cv.put(DbObject.RAW, values.getAsByteArray(DbObject.RAW));
        }
        if (values.containsKey(DbObject.KEY_INT)) {
            cv.put(DbObject.KEY_INT, values.getAsInteger(DbObject.KEY_INT));
        }
        if (json.has(DbObject.CHILD_FEED_NAME)) {
            cv.put(DbObject.CHILD_FEED_NAME, json.optString(DbObject.CHILD_FEED_NAME));
        }
        if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT)
            throw new RuntimeException("Messasge size is too large for sending");
        Long objId = getWritableDatabase().insertOrThrow(DbObject.TABLE, null, cv);

        if (json.has(DbObjects.TARGET_HASH)) {
            long hashA = json.optLong(DbObjects.TARGET_HASH);
            long idA = objIdForHash(hashA);
            String relation;
            if (json.has(DbObjects.TARGET_RELATION)) {
                relation = json.optString(DbObjects.TARGET_RELATION);
            } else {
                relation = DbRelation.RELATION_PARENT;
            }
            if (idA == -1) {
                Log.e(TAG, "No objId found for hash " + hashA);
            } else {
                addObjRelation(idA, objId, relation);
            }
        }

        Uri objUri = DbObject.uriForObj(objId);
        mContext.getContentResolver().registerContentObserver(objUri, false,
                new ModificationObserver(mContext, objId));
        return objId;
    } catch (Exception e) {
        // TODO, too spammy
        //e.printStackTrace(System.err);
        return -1;
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

long addObjectByJson(long contactId, JSONObject json, long hash, byte[] raw, Integer intKey) {
    try {// ww w.  j a v a2s  .  c  om
        long objId = getNextId();
        long seqId = json.optLong(DbObjects.SEQUENCE_ID);
        long timestamp = json.getLong(DbObjects.TIMESTAMP);
        String feedName = json.getString(DbObjects.FEED_NAME);
        String type = json.getString(DbObjects.TYPE);
        String appId = json.getString(DbObjects.APP_ID);
        ContentValues cv = new ContentValues();
        cv.put(DbObject._ID, objId);
        cv.put(DbObject.APP_ID, appId);
        cv.put(DbObject.FEED_NAME, feedName);
        cv.put(DbObject.CONTACT_ID, contactId);
        cv.put(DbObject.TYPE, type);
        cv.put(DbObject.SEQUENCE_ID, seqId);
        cv.put(DbObject.JSON, json.toString());
        cv.put(DbObject.TIMESTAMP, timestamp);
        cv.put(DbObject.HASH, hash);
        cv.put(DbObject.SENT, 1);

        cv.put(DbObject.LAST_MODIFIED_TIMESTAMP, new Date().getTime());
        if (raw != null) {
            cv.put(DbObject.RAW, raw);
        }
        if (intKey != null) {
            cv.put(DbObject.KEY_INT, intKey);
        }

        // TODO: Deprecated!!
        if (json.has(DbObject.CHILD_FEED_NAME)) {
            cv.put(DbObject.CHILD_FEED_NAME, json.optString(DbObject.CHILD_FEED_NAME));
        }
        if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT)
            throw new RuntimeException("Messasge size is too large for sending");
        long newObjId = getWritableDatabase().insertOrThrow(DbObject.TABLE, null, cv);

        String notifyName = feedName;
        if (json.has(DbObjects.TARGET_HASH)) {
            long hashA = json.optLong(DbObjects.TARGET_HASH);
            long idA = objIdForHash(hashA);
            notifyName = feedName + ":" + hashA;
            String relation;
            if (json.has(DbObjects.TARGET_RELATION)) {
                relation = json.optString(DbObjects.TARGET_RELATION);
            } else {
                relation = DbRelation.RELATION_PARENT;
            }
            if (idA == -1) {
                Log.e(TAG, "No objId found for hash " + hashA);
            } else {
                addObjRelation(idA, newObjId, relation);
            }
        }

        ContentResolver resolver = mContext.getContentResolver();
        DungBeetleContentProvider.notifyDependencies(this, resolver, notifyName);
        updateObjModification(App.instance().getMusubi().objForId(newObjId));
        return objId;
    } catch (Exception e) {
        if (DBG)
            Log.e(TAG, "Error adding object by json.", e);
        return -1;
    }
}

From source file:eu.trentorise.smartcampus.ac.network.RemoteConnector.java

/**
 * @param string/*ww w.j a v  a 2  s .com*/
 * @param refresh
 * @param clientId
 * @param clientSecret
 * @throws AACException 
 */
public static TokenData refreshToken(String service, String refresh, String clientId, String clientSecret)
        throws AACException {
    HttpResponse resp = null;
    HttpEntity entity = null;
    Log.i(TAG, "refreshing token: " + refresh);
    String url = service + PATH_TOKEN + "?grant_type=refresh_token&refresh_token=" + refresh + "&client_id="
            + clientId + "&client_secret=" + clientSecret;
    HttpPost post = new HttpPost(url);
    post.setEntity(entity);
    post.setHeader("Accept", "application/json");
    try {
        resp = getHttpClient().execute(post);
        String response = EntityUtils.toString(resp.getEntity());
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            TokenData data = TokenData.valueOf(response);
            Log.v(TAG, "Successful authentication");
            return data;
        }
        Log.e(TAG, "Error validating " + resp.getStatusLine());
        try {
            JSONObject error = new JSONObject(response);
            if (error != null && error.has("error")) {
                throw new AACException(HttpStatus.SC_UNAUTHORIZED,
                        "OAuth error " + error.optString("error_description"));
            }
        } catch (JSONException e) {
            Log.w(TAG, "Unknown response message:" + resp.getStatusLine());
        }
        throw new AACException("Error validating " + resp.getStatusLine());

        //        } catch (Exception e) {
        //            Log.e(TAG, "Exception when getting authtoken", e);
        //            if (resp != null) {
        //               throw new AACException(resp.getStatusLine().getStatusCode(), ""+e.getMessage());
        //            } else {
        //               throw new AACException(e);
        //            }
    } catch (ClientProtocolException e) {
        if (resp != null) {
            throw new AACException(resp.getStatusLine().getStatusCode(), "" + e.getMessage());
        } else {
            throw new AACException(e);
        }
    } catch (IOException e) {
        if (resp != null) {
            throw new AACException(resp.getStatusLine().getStatusCode(), "" + e.getMessage());
        } else {
            throw new AACException(e);
        }
    } finally {
        Log.v(TAG, "refresh token completing");
    }
}

From source file:com.kevinquan.android.utils.JSONUtils.java

/**
 * Retrieve a JSON Array object stored at the provided key from the provided JSON object
 * @param obj The JSON object to retrieve from
 * @param key The key to retrieve//from  ww  w  .  j  ava 2 s . c  o m
 * @return the JSON Array object stored in the key, or null if the key doesn't exist
 */
public static JSONArray safeGetArray(JSONObject obj, String key) {
    if (obj == null || TextUtils.isEmpty(key))
        return null;
    if (obj.has(key)) {
        try {
            return obj.getJSONArray(key);
        } catch (JSONException e) {
            Log.w(TAG, "Could not get JSONArray from key " + key, e);
        }
    }
    return null;
}

From source file:com.kevinquan.android.utils.JSONUtils.java

/**
 * Retrieve a JSON array stored at the provided key from the provided JSON object
 * @param obj The JSON object to retrieve from
 * @param key The key to retrieve/* w ww  .j  ava2s  .c om*/
 * @return the array stored in the key, or null if the key doesn't exist
 */
public static JSONArray safeGetArrayFromObject(JSONObject obj, String key) {
    if (obj == null || TextUtils.isEmpty(key))
        return null;
    if (obj.has(key)) {
        try {
            return obj.getJSONArray(key);
        } catch (JSONException e) {
            Log.w(TAG, "Could not get Array from JSONArray from key " + key, e);
        }
    }
    return null;
}