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.appdynamics.monitors.nginx.statsExtractor.UpstreamsStatsExtractor.java

private void collectMetrics(Map<String, String> upstreamsStats, String serverGroupName, JSONObject server) {

    String serverIp = server.getString("server");

    boolean backup = server.getBoolean("backup");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|backup", backup ? "1" : "0");

    long weight = server.getLong("weight");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|weight", String.valueOf(weight));

    // up?, down?, unavail?, or unhealthy?.
    String state = server.getString("state");
    int stateInt = -1;
    if ("up".equals(state)) {
        stateInt = 0;/*from  ww  w. j  a  v a 2 s . c  o m*/
    } else if ("down".equals(state)) {
        stateInt = 1;
    } else if ("unavail".equals(state)) {
        stateInt = 2;
    } else if ("unhealthy".equals(state)) {
        stateInt = 3;
    }
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|state", String.valueOf(stateInt));

    long active = server.getLong("active");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|active", String.valueOf(active));

    if (server.has("max_conns")) {
        long maxConns = server.getLong("max_conns");
        upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|max_conns",
                String.valueOf(maxConns));
    }

    long requests = server.getLong("requests");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|requests", String.valueOf(requests));

    JSONObject responses = server.getJSONObject("responses");
    long resp1xx = responses.getLong("1xx");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|responses|1xx",
            String.valueOf(resp1xx));

    long resp2xx = responses.getLong("2xx");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|responses|2xx",
            String.valueOf(resp2xx));

    long resp3xx = responses.getLong("3xx");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|responses|3xx",
            String.valueOf(resp3xx));

    long resp4xx = responses.getLong("4xx");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|responses|4xx",
            String.valueOf(resp4xx));

    long resp5xx = responses.getLong("5xx");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|responses|5xx",
            String.valueOf(resp5xx));

    long respTotal = responses.getLong("total");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|responses|total",
            String.valueOf(respTotal));

    long sent = server.getLong("sent");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|sent", String.valueOf(sent));

    long received = server.getLong("received");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|received", String.valueOf(received));

    long upstreamServerFails = server.getLong("fails");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|fails",
            String.valueOf(upstreamServerFails));

    long unavail = server.getLong("unavail");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|unavail", String.valueOf(unavail));

    JSONObject healthChecks = server.getJSONObject("health_checks");
    long checks = healthChecks.getLong("checks");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|health_checks|checks",
            String.valueOf(checks));

    long healthCheckFails = healthChecks.getLong("fails");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|health_checks|fails",
            String.valueOf(healthCheckFails));

    long unhealthy = healthChecks.getLong("unhealthy");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|health_checks|unhealthy",
            String.valueOf(unhealthy));

    if (server.has("last_passed")) {
        boolean lastPassed = healthChecks.getBoolean("last_passed");
        upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|health_checks|last_passed",
                String.valueOf(lastPassed ? 0 : 1));
    }

    long downtime = server.getLong("downtime");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|downtime", String.valueOf(downtime));

    long downstart = server.getLong("downstart");
    upstreamsStats.put("upstreams|" + serverGroupName + "|" + serverIp + "|downstart",
            String.valueOf(downstart));
}

From source file:com.namelessdev.mpdroid.cover.DiscogsCover.java

private static Collection<String> extractImageUrls(final String releaseJson) {
    final JSONObject jsonRootObject;
    final JSONArray jsonArray;
    String imageUrl;//  w w w.  j a v a2 s  .  c  o  m
    JSONObject jsonObject;
    final Collection<String> imageUrls = new ArrayList<>();

    try {
        jsonRootObject = new JSONObject(releaseJson);
        if (jsonRootObject.has("images")) {
            jsonArray = jsonRootObject.getJSONArray("images");
            for (int i = 0; i < jsonArray.length(); i++) {
                jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject.has("resource_url")) {
                    imageUrl = jsonObject.getString("resource_url");
                    imageUrls.add(imageUrl);
                }
            }
        }

    } catch (final Exception e) {
        if (CoverManager.DEBUG) {
            Log.e(TAG, "Failed to get release image URLs from Discogs.", e);
        }
    }
    return imageUrls;
}

From source file:com.namelessdev.mpdroid.cover.DiscogsCover.java

private static List<String> extractReleaseIds(final String releaseIdJson) {
    final JSONObject jsonRootObject;
    final JSONArray jsonArray;
    String releaseId;/*from  www.  j  a  va2  s .c  o  m*/
    JSONObject jsonObject;
    final List<String> releaseIds = new ArrayList<>();

    try {
        jsonRootObject = new JSONObject(releaseIdJson);
        if (jsonRootObject.has("results")) {
            jsonArray = jsonRootObject.getJSONArray("results");
            for (int i = 0; i < jsonArray.length(); i++) {
                jsonObject = jsonArray.getJSONObject(i);
                if (jsonObject.has("id")) {
                    releaseId = jsonObject.getString("id");
                    releaseIds.add(releaseId);
                }
            }
        }

    } catch (final Exception e) {
        if (CoverManager.DEBUG) {
            Log.e(TAG, "Failed to get release Ids from Discogs.", e);
        }
    }
    return releaseIds;
}

From source file:org.alfresco.integrations.google.docs.webscripts.SaveContent.java

private Map<String, Serializable> parseContent(final WebScriptRequest req) {
    final Map<String, Serializable> result = new HashMap<String, Serializable>();
    Content content = req.getContent();//from w w w.  j  a v  a 2s  .  c o  m
    String jsonStr = null;
    JSONObject json = null;

    try {
        if (content == null || content.getSize() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        jsonStr = content.getContent();

        if (jsonStr == null || jsonStr.trim().length() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }
        log.debug("Parsed JSON: " + jsonStr);

        json = new JSONObject(jsonStr);

        if (!json.has(JSON_KEY_NODEREF)) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                    "Key " + JSON_KEY_NODEREF + " is missing from JSON: " + jsonStr);
        } else {
            NodeRef nodeRef = new NodeRef(json.getString(JSON_KEY_NODEREF));
            result.put(JSON_KEY_NODEREF, nodeRef);

            if (json.has(JSON_KEY_OVERRIDE)) {
                result.put(JSON_KEY_OVERRIDE, json.getBoolean(JSON_KEY_OVERRIDE));
            } else {
                result.put(JSON_KEY_OVERRIDE, false);
            }

            if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)) {
                result.put(JSON_KEY_MAJORVERSION,
                        json.getBoolean(JSON_KEY_MAJORVERSION) ? VersionType.MAJOR : VersionType.MINOR);
                result.put(JSON_KEY_DESCRIPTION, json.getString(JSON_KEY_DESCRIPTION));
            }

            if (json.has(JSON_KEY_REMOVEFROMDRIVE)) {
                result.put(JSON_KEY_REMOVEFROMDRIVE, json.getBoolean(JSON_KEY_REMOVEFROMDRIVE));
            }
        }
    } catch (final IOException ioe) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage(), ioe);
    } catch (final JSONException je) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON: " + jsonStr);
    } catch (final WebScriptException wse) {
        throw wse; // Ensure WebScriptExceptions get rethrown verbatim
    } catch (final Exception e) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON '" + jsonStr + "'.", e);
    }

    return result;
}

From source file:robots.ScrapBot.java

public void scrapWeapons(boolean verbose, boolean pretend) throws Exception {
    // TODO: Pretty sure I'll need to ensure that it's scrapping scrappable weapons.  eg. pull out genuines, etc.
    getSchema();/*w  w w  .j a  v  a  2  s  .com*/
    getBackpack();

    final Point smeltWeapons = pointProvider.getPoint(PointPlace.smeltWeapons);

    outputter.output("Scrapping Weapons...");
    leftClick(smeltWeapons.x, smeltWeapons.y);

    // Populate the array with all items and the information we care about.
    int bitmask = 0xFFFF;
    for (int i = 0; i < backpackItems.length(); i++) {
        JSONObject item = backpackItems.getJSONObject(i);
        int inventoryValue = backpackItems.getJSONObject(i).getInt("inventory");
        Weapon currentItem = new Weapon();
        currentItem.setDefindex(item.getInt("defindex"));
        currentItem.setInventorySlot(inventoryValue & bitmask);
        items.add(currentItem);
    }

    // Fill in remaining information and remove non-weapons
    ArrayList<Weapon> newList = new ArrayList<Weapon>();
    for (Weapon item : items) {
        for (int i = 0; i < schemaItems.length(); i++) {
            JSONObject schemaItem = schemaItems.getJSONObject(i);
            if (item.getDefindex().equals(schemaItem.getInt("defindex")) && item.getInventorySlot() > 0) {
                if (schemaItem.has("craft_material_type")) {
                    if (schemaItem.getString("craft_material_type").equals("weapon")) {
                        item.setName(schemaItem.getString("item_name"));
                        JSONArray classesJson = schemaItem.getJSONObject("used_by_classes")
                                .getJSONArray("class");
                        ArrayList<TF2Class> classes = new ArrayList<TF2Class>();
                        for (int j = 0; j < classesJson.length(); j++) {
                            String tf2Class = classesJson.getString(j);
                            TF2Class currentClass = TF2Class.SCOUT;
                            if (tf2Class.equals("Scout"))
                                currentClass = TF2Class.SCOUT;
                            else if (tf2Class.equals("Soldier"))
                                currentClass = TF2Class.SOLIDER;
                            else if (tf2Class.equals("Pyro"))
                                currentClass = TF2Class.PYRO;
                            else if (tf2Class.equals("Demoman"))
                                currentClass = TF2Class.DEMOMAN;
                            else if (tf2Class.equals("Heavy"))
                                currentClass = TF2Class.HEAVY;
                            else if (tf2Class.equals("Engineer"))
                                currentClass = TF2Class.ENGINEER;
                            else if (tf2Class.equals("Medic"))
                                currentClass = TF2Class.MEDIC;
                            else if (tf2Class.equals("Sniper"))
                                currentClass = TF2Class.SNIPER;
                            else if (tf2Class.equals("Spy"))
                                currentClass = TF2Class.SPY;
                            classes.add(currentClass);
                        }
                        item.setClasses(classes);
                        newList.add(item);
                    }
                }
            }
        }
    }
    items = newList;

    // Now, compare and determine two items to scrap
    ArrayList<Weapon> itemsToIgnore = new ArrayList<Weapon>();
    for (Weapon item : items) {
        // If the item is still there, it hasn't been used in crafting OR it hasn't been iterated to yet.
        if (!itemsToIgnore.contains(item)) {
            Weapon match = null;
            for (Weapon hopefulMatch : items) {
                if (!hopefulMatch.equals(item) && !itemsToIgnore.contains(hopefulMatch)) {
                    for (TF2Class tf2Class : item.getClasses()) {
                        for (TF2Class hopefulClass : hopefulMatch.getClasses()) {
                            if (tf2Class.equals(hopefulClass)) {
                                // These two weapons are compatible.  Scrap 'em!
                                match = hopefulMatch;
                                break;
                            }
                        }
                        if (match != null)
                            break;
                    }
                }
                if (match != null)
                    break;
            }
            // Come out here
            if (match != null) {
                // Scrap
                if (verbose)
                    outputter.output("Scrapping a " + item.getName() + " and a " + match.getName() + ".");
                if (!pretend) {
                    scrapWeapons(item, match);
                    Point mouseLoc = MouseInfo.getPointerInfo().getLocation();
                    Point ok2 = pointProvider.getPoint(PointPlace.ok2);
                    if (mouseLoc.getX() != ok2.x || mouseLoc.getY() != ok2.getY())
                        break;
                }
                itemsToIgnore.add(match);
            }
            itemsToIgnore.add(item);
        }
    }
    outputter.output("Weapons Scrapped.");
}

From source file:edu.rit.csh.androidwebnews.DisplayThreadsActivity.java

@Override
public void update(String jsonString) {
    if (jsonString.startsWith("Error:")) { // error in the Async Task
        connectionDialog.setMessage(jsonString);
        if (!connectionDialog.isShowing()) {
            connectionDialog.show();//w w w.jav a2 s.  c o  m
        }
    } else {
        try {
            JSONObject obj = new JSONObject(jsonString);
            if (obj.has("error")) {
                if (!dialog.isShowing()) {
                    dialog.show();
                }
            } else if (obj.has("posts_older")) {
                if (hc.getThreadsFromString(jsonString).size() == 0) {
                    //hitBottom = true;
                    ((DisplayThreadsFragment) getSupportFragmentManager()
                            .findFragmentById(R.id.threadsfragment)).addThreads(new ArrayList<PostThread>());
                } else if (!requestedAdditionalThreads) {
                    ArrayList<PostThread> threads = hc.getThreadsFromString(jsonString);
                    lastFetchedThreads.clear();
                    lastFetchedThreads = (ArrayList<PostThread>) threads.clone();
                    ((DisplayThreadsFragment) getSupportFragmentManager()
                            .findFragmentById(R.id.threadsfragment)).update(threads);
                } else {
                    ArrayList<PostThread> newThreads = hc.getThreadsFromString(jsonString);
                    for (PostThread thread : newThreads)
                        lastFetchedThreads.add(thread);
                    ((DisplayThreadsFragment) getSupportFragmentManager()
                            .findFragmentById(R.id.threadsfragment)).addThreads(newThreads);
                    requestedAdditionalThreads = false;
                }
            } else if (obj.has("unread_counts")) { // unread count
                int unread = hc.getUnreadCountFromString(jsonString)[0];
                int groupUnread = 0;
                for (Newsgroup group : hc
                        .getNewsGroupFromString(sharedPref.getString("newsgroups_json_string", ""))) {
                    groupUnread += group.unreadCount;
                }
                if (unread != groupUnread) {
                    hc.getNewsGroups();
                } else {
                    newsgroupListMenu.update(
                            hc.getNewsGroupFromString(sharedPref.getString("newsgroups_json_string", "")));
                }
            } else { // newsgroups
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putString("newsgroups_json_string", jsonString);
                editor.commit();
                newsgroupListMenu.update(hc.getNewsGroupFromString(jsonString));
            }
        } catch (JSONException ignored) {
        }
    }
}

From source file:com.parse.loginsample.layoutoverride.SampleProfileActivity.java

private void updateViewsWithProfileInfo() {
    ParseUser currentUser = ParseUser.getCurrentUser();
    if (currentUser.has("profile")) {
        JSONObject userProfile = currentUser.getJSONObject("profile");
        try {//from   ww  w . j  a  va 2  s .  c om

            if (userProfile.has("facebookId")) {
                userProfilePictureView.setProfileId("10153999845374167");
            } else {
                // Show the default, blank user profile picture
                userProfilePictureView.setProfileId(null);
            }

            if (userProfile.has("name")) {
                //nameTextView.setText(userProfile.getString("name"));
            } else {
                //nameTextView.setText("");
            }

        } catch (Exception e) {
            //Log.d(IntegratingFacebookTutorialApplication.TAG, "Error parsing saved user data.");
        }
    }
}

From source file:de.kp.ames.office.xml.ImpressBuilder.java

private IPage buildOverviewPage(OdfDrawPage officePage, JSONObject jPage) throws Exception {

    // provide new impress page
    BriefingOneText textPage = new BriefingOneText(impressFile, officePage);

    //********************** header *************************************

    // set title and optionally a subtitle
    textPage.setTitle(jPage.getString(J_HEADER_TITLE));
    if (jPage.has(J_HEADER_SUBTITLE))
        textPage.setSubTitle(jPage.getString(J_HEADER_SUBTITLE));

    //********************** content ************************************

    textPage.setOutline(jPage.getString(J_CONTENT_OVERVIEW));

    return textPage;

}

From source file:de.kp.ames.office.xml.ImpressBuilder.java

private IPage buildOutlinePage(OdfDrawPage officePage, JSONObject jPage) throws Exception {

    // provide new impress page
    BriefingOneText textPage = new BriefingOneText(impressFile, officePage);

    //********************** header *************************************

    // set title and optionally a subtitle
    textPage.setTitle(jPage.getString(J_HEADER_TITLE));
    if (jPage.has(J_HEADER_SUBTITLE))
        textPage.setSubTitle(jPage.getString(J_HEADER_SUBTITLE));

    //********************** content ************************************

    // the outline of this presentation page is computed from the
    // titles of all other pages

    if (outline != null)
        textPage.setOutline(outline);/*from www.ja  v  a 2s  .c o m*/

    return textPage;

}

From source file:de.kp.ames.office.xml.ImpressBuilder.java

/**
 * Build an Impress diagram page; the respective images
 * are determines via a callback mechanism
 * /*ww w.  j  a v  a  2  s  .  c om*/
 * @param officePage
 * @param jPage
 * @return
 * @throws Exception
 */
private IPage buildDiagramPage(OdfDrawPage officePage, JSONObject jPage) throws Exception {

    /* 
     * Build new diagram page
     */
    BriefingDiagram diagramPage = new BriefingDiagram(impressFile, officePage);

    /* 
     * Set title and optionally a subtitle
     */
    diagramPage.setTitle(jPage.getString(J_HEADER_TITLE));
    if (jPage.has(J_HEADER_SUBTITLE))
        diagramPage.setSubTitle(jPage.getString(J_HEADER_SUBTITLE));

    /*
     * Set content
     */

    if (jPage.has(J_CONTENT_ISSUE_IMAGE)) {

        /*
         * Retrieve image identified by a unique identifier
         * from image list provided by the callback mechanism
         */
        String uid = jPage.getString(J_CONTENT_ISSUE_IMAGE);
        if ((images != null) && images.containsKey(uid)) {

            OOImageUtil picture = new OOImageUtil(uid, images.get(uid));
            diagramPage.addImage(officePage, picture);
        }

    }

    return diagramPage;

}