Example usage for org.json JSONObject getJSONObject

List of usage examples for org.json JSONObject getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(String key) throws JSONException 

Source Link

Document

Get the JSONObject value associated with a key.

Usage

From source file:com.att.voice.AttDigitalLife.java

public String getAttribute(Map<String, String> authMap, String deviceGUID, String attribute) {
    try {//w  w  w . jav  a 2 s  . co  m
        URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(DIGITAL_LIFE_PATH)
                .setPath("/penguin/api/" + authMap.get("id") + "/devices/" + deviceGUID + "/" + attribute);

        URI uri = builder.build();
        HttpGet httpget = new HttpGet(uri);
        httpget.setHeader("Authtoken", authMap.get("Authtoken"));
        httpget.setHeader("Requesttoken", authMap.get("Requesttoken"));
        httpget.setHeader("Appkey", authMap.get("Appkey"));

        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpclient.execute(httpget, responseHandler);

        String json = responseBody.trim();
        JSONObject content = new JSONObject(json);
        return content.getJSONObject("content").getString("value");
    } catch (URISyntaxException | IOException | JSONException ex) {
        System.err.println(ex.getMessage());
        return null;
    }
}

From source file:com.appdynamics.monitors.nginx.statsExtractor.UpstreamsStatsExtractor.java

@Override
public Map<String, String> extractStats(JSONObject respJson) {

    JSONObject upstreams = respJson.getJSONObject("upstreams");

    int version = respJson.getInt("version");

    Map<String, String> upstreamsStats = new HashMap<String, String>();
    if (version == 6) {
        upstreamsStats = getUpstreamsStatsV6(upstreams);
    } else if (version == 5) {
        upstreamsStats = getUpstreamsStatsV5(upstreams);
    }/*w w  w  . j a v  a 2  s  . c  o m*/
    return upstreamsStats;
}

From source file:com.appdynamics.monitors.nginx.statsExtractor.UpstreamsStatsExtractor.java

private Map<String, String> getUpstreamsStatsV6(JSONObject upstreams) {
    Map<String, String> upstreamsStats = new HashMap<String, String>();
    Set<String> serverGroupNames = upstreams.keySet();

    for (String serverGroupName : serverGroupNames) {
        JSONObject jsonObject = upstreams.getJSONObject(serverGroupName);

        Set<String> keys = jsonObject.keySet();
        for (String key : keys) {
            Object element = jsonObject.get(key);

            if (element instanceof JSONArray) {
                JSONArray serverGroups = (JSONArray) element;

                for (int i = 0; i < serverGroups.length(); i++) {
                    JSONObject server = serverGroups.getJSONObject(i);
                    collectMetrics(upstreamsStats, serverGroupName, server);
                }//from  w  ww .ja  v  a  2 s .  com
            }
        }
    }
    return upstreamsStats;
}

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;// w ww . j av  a  2 s .co 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:in.neoandroid.neoupdate.neoUpdate.java

private Boolean parseMetafile(JSONObject metafile) {
    double version;
    boolean forceVersion;
    boolean allowed = false;
    try {//from   ww  w.ja  va  2  s  .com
        version = metafile.getDouble("version");
        forceVersion = metafile.getBoolean("forceVersion");
        JSONObject appDetails = metafile.getJSONObject("app");
        JSONArray assets = metafile.getJSONArray("assets");
        JSONArray devices = metafile.getJSONArray("allowedDevices");

        int nAssets = assets.length();
        String packageName = appDetails.getString("packageName");
        int versionCode = appDetails.getInt("versionCode");
        String apkPath = appDetails.getString("APK");
        boolean offlineSupport = appDetails.getBoolean("offlineSupport");

        if (enableDebug) {
            Log.d(TAG, "Version: " + version + ":" + neoUpdateVersion);
            Log.d(TAG, "Package Name: " + packageName + ":" + packageInfo.packageName);
            Log.d(TAG, "APK Path: " + apkPath);
        }

        // Check if it is being updated using offline storage
        if (!offlineSupport && fromOfflineStorage) {
            Log.e(TAG, "Updating from offline storage is disabled for this app?");
            return false;
        }

        db.clearDevicesList();
        for (int i = 0; i < devices.length(); i++) {
            String device = devices.getString(i);
            if (device.length() > 0 && deviceID.compareToIgnoreCase(device) == 0)
                allowed = true;
            db.insertDevice(device);
            if (enableDebug)
                Log.d(TAG, "Device Allowed: " + device);
        }

        // DeviceID or signature error
        if (!allowed)
            return false;

        apkUpdatePath = null;
        if (version > neoUpdateVersion && forceVersion) {
            Log.e(TAG, "neoUpdate seems to be of older version! Required: " + version + " Current: "
                    + neoUpdateVersion);
            return false;
        }

        if (packageInfo.packageName.compareTo(packageName) != 0) {
            Log.e(TAG, "PackageNames don't seem to match - url for some other app? Provided: " + packageName);
            return false;
        }

        if (packageInfo.versionCode < versionCode) {
            // APK Update Required - Lets first do that
            apkUpdatePath = new NewAsset();
            apkUpdatePath.path = apkPath;
            apkUpdatePath.md5 = appDetails.getString("md5");
            return true;
        }

        // Parse the assets
        for (int i = 0; i < nAssets; i++) {
            JSONObject obj = assets.getJSONObject(i);
            NewAsset asset = new NewAsset();
            asset.path = obj.getString("path");
            asset.md5 = obj.getString("md5");

            // Ignore already downloaded files
            if (db.updateAndGetStatus(asset.path, asset.md5) == neoUpdateDB.UPDATE_STATUS.UPDATE_COMPLETE)
                continue;
            filesToDownload.add(asset);
            if (enableDebug) {
                Log.d(TAG, "Enqueued: " + asset.path + " With MD5: " + asset.md5);
            }
        }
        totalFilesToDownload = filesToDownload.size();
    } catch (Exception e) {
        if (enableDebug)
            e.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.uiautomation.ios.wkrdp.internal.WebKitRemoteDebugProtocol.java

public synchronized JSONObject sendWebkitCommand(JSONObject command, int pageId) {
    String sender = generateSenderString(pageId);
    try {//from w  ww.j  a v  a2 s  . c o  m
        commandId++;
        command.put("id", commandId);

        long start = System.currentTimeMillis();

        String xml = plist.JSONCommand(command);
        Map<String, String> var = ImmutableMap.of("$WIRConnectionIdentifierKey", connectionId, "$bundleId",
                bundleId, "$WIRSenderKey", sender, "$WIRPageIdentifierKey", "" + pageId);
        for (String key : var.keySet()) {
            xml = xml.replace(key, var.get(key));
        }
        sendMessage(xml);
        JSONObject response = handler.getResponse(command.getInt("id"));
        JSONObject error = response.optJSONObject("error");
        if (error != null) {
            throw new RemoteExceptionException(error, command);
        } else if (response.optBoolean("wasThrown", false)) {
            throw new WebDriverException("remote JS exception " + response.toString(2));
        } else {
            log.fine(System.currentTimeMillis() + "\t\t" + (System.currentTimeMillis() - start) + "ms\t"
                    + command.getString("method") + " " + command);
            JSONObject res = response.getJSONObject("result");
            if (res == null) {
                System.err.println("GOT a null result from " + response.toString(2));
            }
            return res;
        }
    } catch (JSONException e) {
        throw new WebDriverException(e);
    }
}

From source file:com.bw.hawksword.wiktionary.SimpleWikiHelper.java

/**
 * Read and return the content for a specific Wiktionary page. This makes a
 * lightweight API call, and trims out just the page content returned.
 * Because this call blocks until results are available, it should not be
 * run from a UI thread.//from w w w .  j a v  a2  s.  c  om
 *
 * @param title The exact title of the Wiktionary page requested.
 * @param expandTemplates If true, expand any wiki templates found.
 * @return Exact content of page.
 * @throws ApiException If any connection or server error occurs.
 * @throws ParseException If there are problems parsing the response.
 */
public static String getPageContent(String title, boolean expandTemplates) throws ApiException, ParseException {
    // Encode page title and expand templates if requested
    String encodedTitle = Uri.encode(title);
    String expandClause = expandTemplates ? WIKTIONARY_EXPAND_TEMPLATES : "";

    // Query the API for content
    String content = getUrlContent(String.format(WIKTIONARY_PAGE, encodedTitle, expandClause));
    try {
        // Drill into the JSON response to find the content body
        JSONObject response = new JSONObject(content);
        JSONObject query = response.getJSONObject("query");
        JSONObject pages = query.getJSONObject("pages");
        JSONObject page = pages.getJSONObject((String) pages.keys().next());
        JSONArray revisions = page.getJSONArray("revisions");
        JSONObject revision = revisions.getJSONObject(0);
        return revision.getString("*");
    } catch (JSONException e) {
        throw new ParseException("Problem parsing API response", e);
    }
}

From source file:JSON.JasonJSON.java

public static void main(String[] args) throws Exception {

    URL Url = new URL("http://api.wunderground.com/api/22b4347c464f868e/conditions/q/Colorado/COS.json");
    //This next URL is still being played with. Some of the formatting is hard to figure out, but Wunderground 
    //writes a perfectly formatted JSON file that is easy to read with Java.
    // URL Url = new URL("https://api.darksky.net/forecast/08959bb1e2c7eae0f3d1fafb5d538032/38.886,-104.7201");

    try {// ww w  .  ja  v  a  2s .c o m

        HttpURLConnection urlCon = (HttpURLConnection) Url.openConnection();

        //          This part will read the data returned thru HTTP and load it into memory
        //          I have this code left over from my CIT260 project.
        InputStream stream = urlCon.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        StringBuilder result = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            result.append(line);
        }

        // The next lines read certain parts of the JSON data and print it out on the screen
        //Creates the JSONObject object and loads the JSON file from the URLConnection
        //Into a StringWriter object. I am printing this out in raw format just so I can see it doing something

        JSONObject json = new JSONObject(result.toString());

        JSONObject coloradoInfo = (JSONObject) json.get("current_observation");

        StringWriter out = new StringWriter();
        json.write(out);
        String jsonTxt = json.toString();
        System.out.print(jsonTxt);

        List<String> list = new ArrayList<>();
        JSONArray array = json.getJSONArray(jsonTxt);
        System.out.print(jsonTxt);

        // for (int i =0;i<array.length();i++){
        //list.add(array.getJSONObject(i).getString("current_observation"));
        //}

        String wunderGround = "Data downloaded from: " +

                coloradoInfo.getJSONObject("image").getString("title") + "\nLink\t\t: "
                + coloradoInfo.getJSONObject("image").getString("link") + "\nCity\t\t: "
                + coloradoInfo.getJSONObject("display_location").getString("city") + "\nState\t\t: "
                + coloradoInfo.getJSONObject("display_location").getString("state_name") + "\nTime\t\t: "
                + coloradoInfo.get("observation_time_rfc822") + "\nTemperature\t\t: "
                + coloradoInfo.get("temperature_string") + "\nWindchill\t\t: "
                + coloradoInfo.get("windchill_string") + "\nRelative Humidity\t: "
                + coloradoInfo.get("relative_humidity") + "\nWind\t\t\t: " + coloradoInfo.get("wind_string")
                + "\nWind Direction\t\t: " + coloradoInfo.get("wind_dir") + "\nBarometer Pressure\t\t: "
                + coloradoInfo.get("pressure_in");

        System.out.println("\nColorado Springs Weather:");
        System.out.println("____________________________________");
        System.out.println(wunderGround);

    } catch (IOException e) {
        System.out.println("***ERROR*******************ERROR********************. " + "\nURL: " + Url.toString()
                + "\nERROR: " + e.toString());
    }

}

From source file:com.norman0406.slimgress.API.Item.ItemModShield.java

public ItemModShield(JSONArray json) throws JSONException {
    super(ItemBase.ItemType.ModShield, json);

    JSONObject item = json.getJSONObject(2);
    JSONObject modResource = item.getJSONObject("modResource");
    JSONObject stats = modResource.getJSONObject("stats");
    mMitigation = Integer.parseInt(stats.getString("MITIGATION"));
}