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.lmpessoa.sonarview.core.Server.java

public List<Issue> getIssues(String projectId) throws MalformedURLException, IOException {
    int pageIndex = 1;
    int total = Integer.MAX_VALUE;
    List<Issue> result = new ArrayList<>();
    while (result.size() < total) {
        JSONObject response = readIssuesFromServer(projectId, pageIndex);
        if (total == Integer.MAX_VALUE) {
            total = response.getInt("total");
        }/*from   ww  w  .j av a2 s  .  c  o  m*/
        JSONArray issues = response.getJSONArray("issues");
        for (int i = 0; i < issues.length(); ++i) {
            result.add(new Issue(issues.getJSONObject(i)));
        }
        pageIndex += 1;
    }
    return result;
}

From source file:ch.ethz.inf.vs.android.g54.a4.util.SnapshotCache.java

private static List<WifiReading> jsonToReadings(JSONArray json) {
    List<WifiReading> readings = new ArrayList<WifiReading>(json.length());
    for (int i = 0; i < json.length(); i++) {
        try {/*from w w  w  . j a v  a2 s .  com*/
            JSONObject ap = json.getJSONObject(i);
            String mac = ap.getString("mac");
            String ssid = ap.getString("ssid");
            int signal = ap.getInt("signal");
            readings.add(new WifiReading(mac, ssid, signal));
        } catch (JSONException e) {
            return null;
        }
    }
    return readings;
}

From source file:com.flurry.samples.tumblrsharing.Photo.java

/**
 * Deserializes JSON into Photo objects/*from  w w w.j  a  v a2 s.  com*/
 *
 * @param photoArray     JSONArray for photo list
 */
public static List<Photo> fromJson(JSONArray photoArray) {
    List<Photo> photoList = new ArrayList<Photo>();
    JSONObject photoObject = null;
    try {
        // Deserialize json into object fields
        for (int i = 0; i < photoArray.length(); i++) {
            Photo p = new Photo();
            photoObject = photoArray.getJSONObject(i);

            p.owner = photoObject.getString("owner");
            p.photoId = photoObject.getString("id");
            p.secret = photoObject.getString("secret");
            p.server = photoObject.getInt("server");
            p.farm = photoObject.getInt("farm");
            p.title = photoObject.getString("title");
            p.photoUrl = "https://farm" + p.farm + ".staticflickr.com/" + p.server + "/" + p.photoId + "_"
                    + p.secret + "_c.jpg";
            p.photoUrl = p.photoUrl.replace(" ", "");

            photoList.add(p);
        }

    } catch (JSONException e) {
        AnalyticsHelper.logError(LOG_TAG, "Deserialize Photo Feed JSONArray Error.", e);
        return null;
    }
    // Return new object
    return photoList;
}

From source file:org.eclipse.orion.server.cf.handlers.v1.AppsHandlerV1.java

private IStatus getApps(Target target) throws Exception {
    String appsUrl = target.getSpace().getCFJSON().getJSONObject("entity").getString("apps_url");
    //      appsUrl = appsUrl.replaceAll("apps", "summary");
    URI appsURI = URIUtil.toURI(target.getUrl()).resolve(appsUrl);

    GetMethod getAppsMethod = new GetMethod(appsURI.toString());
    HttpUtil.configureHttpMethod(getAppsMethod, target);
    getAppsMethod.setQueryString("inline-relations-depth=2"); //$NON-NLS-1$

    ServerStatus getAppsStatus = HttpUtil.executeMethod(getAppsMethod);
    if (!getAppsStatus.isOK())
        return getAppsStatus;

    /* extract available apps */
    JSONObject appsJSON = getAppsStatus.getJsonData();

    if (appsJSON.getInt(CFProtocolConstants.V2_KEY_TOTAL_RESULTS) < 1) {
        return new ServerStatus(IStatus.OK, HttpServletResponse.SC_OK, null, null);
    }//from w  w  w.jav  a  2  s. c  om

    JSONObject result = new JSONObject();
    JSONArray resources = appsJSON.getJSONArray(CFProtocolConstants.V2_KEY_RESOURCES);
    for (int k = 0; k < resources.length(); ++k) {
        JSONObject appJSON = resources.getJSONObject(k);
        App2 app = new App2();
        app.setCFJSON(appJSON);
        result.append("Apps", app.toJSON());
    }

    return new ServerStatus(Status.OK_STATUS, HttpServletResponse.SC_OK, result);
}

From source file:com.parking.billing.Security.java

/**
 * Verifies that the data was signed with the given signature, and returns
 * the list of verified purchases. The data is in JSON format and contains
 * a nonce (number used once) that we generated and that was signed
 * (as part of the whole data string) with a private key. The data also
 * contains the {@link PurchaseState} and product ID of the purchase.
 * In the general case, there can be an array of purchase transactions
 * because there may be delays in processing the purchase on the backend
 * and then several purchases can be batched together.
 * @param signedData the signed JSON string (signed, not encrypted)
 * @param signature the signature for the data, signed with the private key
 */// w  w w  .j  a  va 2  s.  c om
public static ArrayList<VerifiedPurchase> verifyPurchase(String signedData, String signature) {
    if (signedData == null) {
        Log.e(TAG, "data is null");
        return null;
    }
    if (BillingConstants.DEBUG) {
        Log.i(TAG, "signedData: " + signedData);
    }

    boolean verified = false;

    if (!TextUtils.isEmpty(signature)) {
        /**
         * Compute your public key (that you got from the Android Market publisher site).
         *
         * Instead of just storing the entire literal string here embedded in the
         * program,  construct the key at runtime from pieces or
         * use bit manipulation (for example, XOR with some other string) to hide
         * the actual key.  The key itself is not secret information, but we don't
         * want to make it easy for an adversary to replace the public key with one
         * of their own and then fake messages from the server.
         *
         * Generally, encryption keys / passwords should only be kept in memory
         * long enough to perform the operation they need to perform.
         */
        //Chintan's Key
        String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuRIrk/6nAPzZo5HKe261/ZMfoe63mtY5QUlc0A0/77RTicrS9Nk1VjtVniRpHmjasQOGsQrBpBGJUYp0ixsjJpgfjLv7OvpF8Hp/ucth2T/Bm7kl/odRDT3urAp3snvqZEzfOg1wtDU7DAnDW1zNSqVNCVczXRnNrEmGxEjamKkTTQwz37ui7AhjKXCXAJY4n5ANj1oymnjGN5FHfzcMb07wR/ucz39ZX+Raf6qBsbnYkmuDH6pJ/4ZI9+vjbgWzXCx07DefQW4dtNMQZlVlKgKnJUkafePUYJVIO4sRgeWL1e5b8dbIYMO7gB9oopyfVhZifi+pDGr5+YAxi6D3PwIDAQAB";
        //Mandar's Key:
        //String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj7zgTswMi1ePyAK7rCnCOkpmviHZzoSn2cxtyQ5ZQRFifNGkKq3Gli3VbeIeeJR8GHzlfOPUSgtMrd17WtGJoo29rsw6UuXov+imQutGKZglcM/cIrlIdZCsse3dGYyDcKFhEHrC/nPdwlYxgIGBaZKAcbbhitkdgYaVHQvGFTagCytxDq9NDJAY7exSKKm2HimfjlcBZjhHeImZ+cRCPux+9uoBQ4mTRYjrXfcpi/OPKTKsq2AHXf/y60qsZJlgGl3tBgRQo6lOEr7UbbHKESTKvOQ4t3J1wjNz8Z3+T0PZHb5JkeTsdAE7cG7jmz2HmMxfdXcT5mBTTDei6DPDGwIDAQAB";
        PublicKey key = Security.generatePublicKey(base64EncodedPublicKey);
        verified = Security.verify(key, signedData, signature);
        if (!verified) {
            Log.w(TAG, "signature does not match data.");
            return null;
        }
    }

    JSONObject jObject;
    JSONArray jTransactionsArray = null;
    int numTransactions = 0;
    long nonce = 0L;
    try {
        jObject = new JSONObject(signedData);

        // The nonce might be null if the user backed out of the buy page.
        nonce = jObject.optLong("nonce");
        jTransactionsArray = jObject.optJSONArray("orders");
        if (jTransactionsArray != null) {
            numTransactions = jTransactionsArray.length();
        }
    } catch (JSONException e) {
        return null;
    }

    if (!Security.isNonceKnown(nonce)) {
        Log.w(TAG, "Nonce not found: " + nonce);
        return null;
    }

    ArrayList<VerifiedPurchase> purchases = new ArrayList<VerifiedPurchase>();
    try {
        for (int i = 0; i < numTransactions; i++) {
            JSONObject jElement = jTransactionsArray.getJSONObject(i);
            int response = jElement.getInt("purchaseState");
            PurchaseState purchaseState = PurchaseState.valueOf(response);
            String productId = jElement.getString("productId");
            String packageName = jElement.getString("packageName");
            long purchaseTime = jElement.getLong("purchaseTime");
            String orderId = jElement.optString("orderId", "");
            String notifyId = null;
            if (jElement.has("notificationId")) {
                notifyId = jElement.getString("notificationId");
            }
            String developerPayload = jElement.optString("developerPayload", null);

            // If the purchase state is PURCHASED, then we require a
            // verified nonce.

            /**
             *   mandarm - We are ok with no signature for our test code! 
             */
            //TODO - Take care for signed purchases.

            if (purchaseState == PurchaseState.PURCHASED && !verified) {
                continue;
            }

            purchases.add(new VerifiedPurchase(purchaseState, notifyId, productId, orderId, purchaseTime,
                    developerPayload));
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSON exception: ", e);
        return null;
    }
    removeNonce(nonce);
    return purchases;
}

From source file:com.prey.json.actions.Report.java

public void get(Context ctx, List<ActionResult> lista, JSONObject parameters) {

    long lastReportStartDate = new Date().getTime();
    PreyLogger.d("____lastReportStartDate:" + lastReportStartDate);
    PreyConfig.getPreyConfig(ctx).setLastReportStartDate(lastReportStartDate);
    PreyConfig.getPreyConfig(ctx).setMissing(true);
    int interval = 0;
    try {/*from  w w w . j a  va  2 s  . c  o m*/
        PreyLogger.d("interval:" + parameters.getString("interval"));
        interval = parameters.getInt("interval");
    } catch (Exception e) {
        interval = 0;
    }
    String exclude = "";
    try {
        PreyLogger.d("exclude:" + parameters.getString("exclude"));
        exclude = parameters.getString("exclude");
    } catch (Exception e) {

    }
    PreyConfig.getPreyConfig(ctx).setIntervalReport("" + interval);
    PreyConfig.getPreyConfig(ctx).setExcludeReport(exclude);
    ReportScheduled.getInstance(ctx).run(interval);
}

From source file:com.clearcenter.mobile_demo.mdStatusActivity.java

public List<JSONObject> sortedSamplesList(String data) {
    SortedMap<String, JSONObject> map = new TreeMap<String, JSONObject>();

    try {/*from w  w w .  ja v a 2s. c  o m*/
        int version = 0;
        JSONObject json_data = new JSONObject(data);
        if (json_data.has("version"))
            version = json_data.getInt("version");
        if (version < 1 && json_data.has("time")) {
            String key = json_data.getString("time");
            map.put(key, json_data);
        } else if (version >= 1 && json_data.has("samples") && !json_data.isNull("samples")) {
            json_data = json_data.getJSONObject("samples");
            Iterator i = json_data.keys();
            while (i.hasNext()) {
                String key = i.next().toString();
                JSONObject sample = json_data.getJSONObject(key);
                sample.put("time", key);
                map.put(key, sample);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSONException", e);
    }

    return new LinkedList<JSONObject>(map.values());
}

From source file:asynctasks.AddTicketDataAsync.java

@Override
protected void onPostExecute(JSONObject json) {
    pDialog.cancel();/*www.  j  av a  2 s .  com*/
    int success;
    try {
        success = json.getInt("success");
        if (success == 1) {

            NewTicket frag = (NewTicket) fm.findFragmentByTag("New Ticket");
            frag.dismiss();

        } else {
            Toast.makeText(context, "ERROR IN SUBMISSION", Toast.LENGTH_SHORT).show();
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.poguico.palmabici.parsers.Parser.java

public static ArrayList<Station> parseNetworkJSON(String data) {
    ArrayList<Station> stations = new ArrayList<Station>();
    JSONArray jsonArray;//www  .  j  ava2s  .c  o m
    JSONObject jsonObject;
    Long lngAcum = 0L, latAcum = 0L;
    int id;

    try {
        jsonArray = new JSONArray(data);

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

            lngAcum += jsonObject.getLong("lng");
            latAcum += jsonObject.getLong("lat");

            id = jsonObject.getInt("id");
            stations.add(new Station(id, jsonObject.getString("name"), jsonObject.getDouble("lng") / 1e6,
                    jsonObject.getDouble("lat") / 1e6, jsonObject.getInt("free"), jsonObject.getInt("bikes"),
                    false, NetworkStationAlarm.hasAlarm(id)));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return stations;
}

From source file:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * Get the ID of the project from the name
 * /*from   w  w  w . j  a v  a 2 s  .  c o  m*/
 * @param projectName   Name of the project
 * @return              ID of the project
 * @throws              MLHttpClientException 
 */
public int getProjectId(String projectName) throws MLHttpClientException {
    CloseableHttpResponse response;
    try {
        response = doHttpGet("/api/projects/" + projectName);
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));
        JSONObject responseJson = new JSONObject(bufferedReader.readLine());
        bufferedReader.close();
        response.close();
        return responseJson.getInt("id");
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to get ID of project: " + projectName, e);
    }
}