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:org.wso2.carbon.ml.integration.common.utils.MLHttpClient.java

/**
 * Get the ID of an analysis from the name
 * /*  w  w w  .  j ava 2s .  c o m*/
 * @param analysisName  Name of the analysis
 * @return              ID of the analysis
 * @throws              MLHttpClientException 
 */
public int getAnalysisId(int projectId, String analysisName) throws MLHttpClientException {
    CloseableHttpResponse response;
    try {
        response = doHttpGet("/api/projects/" + projectId + "/analyses/" + analysisName);
        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 analysis: " + analysisName, e);
    }
}

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

/**
 * Get a ID of the first version-set of a dataset
 * /*from  www  .  jav a2s .c om*/
 * @param datasetId ID of the dataset
 * @return          ID of the first versionset of the dataset
 * @throws          ClientProtocolException
 * @throws          MLHttpClientException 
 */
public int getAVersionSetIdOfDataset(int datasetId) throws MLHttpClientException {
    CloseableHttpResponse response;
    try {
        response = doHttpGet("/api/datasets/" + datasetId + "/versions");
        // Get the Id of the first dataset
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));
        JSONArray responseJson = new JSONArray(bufferedReader.readLine());
        JSONObject datsetVersionJson = (JSONObject) responseJson.get(0);
        return datsetVersionJson.getInt("id");
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to get a version set ID of dataset: " + datasetId, e);
    }
}

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

/**
 * Get the ID of the version set with the given version and of a given dataset
 * /* w ww  . ja v a  2 s.c o m*/
 * @param datasetId ID of the dataset
 * @return          ID of the first versionset of the dataset
 * @throws          ClientProtocolException
 * @throws          MLHttpClientException 
 */
public int getVersionSetIdOfDataset(int datasetId, String version) throws MLHttpClientException {
    CloseableHttpResponse response;
    try {
        response = doHttpGet("/api/datasets/" + datasetId + "/versions/" + version);
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent()));
        String line = bufferedReader.readLine();
        JSONObject responseJson = new JSONObject(line);
        bufferedReader.close();
        response.close();
        return responseJson.getInt("id");
    } catch (Exception e) {
        throw new MLHttpClientException("Failed to get a version set ID of dataset: " + datasetId, e);
    }
}

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

/**
 * Get the model ID using the name of the model
 * //  w w  w  .  ja va  2  s . co m
 * @param modelName Name of the model
 * @return          ID of the model
 * @throws          MLHttpClientException 
 */
public int getModelId(String modelName) throws MLHttpClientException {
    CloseableHttpResponse response;
    try {
        response = doHttpGet("/api/models/" + modelName);
        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 a version set ID of model: " + modelName, e);
    }
}

From source file:org.melato.bus.otp.OTPParser.java

static OTP.Error parseError(JSONObject json) throws JSONException {
    json = getObject(json, "error");
    if (json == null) {
        return null;
    }/*from   w w w.  j av a 2  s  .  com*/
    OTP.Error error = new OTP.Error();
    error.id = json.getInt("id");
    error.msg = json.getString("msg");
    return error;
}

From source file:com.android.launcher4.compat.PackageInstallerCompatV16.java

private static PackageInstallInfo infoFromJson(String packageName, String json) {
    PackageInstallInfo info = new PackageInstallInfo(packageName);
    try {//from w w w  . j  a  va  2  s .c o  m
        JSONObject object = (JSONObject) new JSONTokener(json).nextValue();
        info.state = object.getInt(KEY_STATE);
        info.progress = object.getInt(KEY_PROGRESS);
    } catch (JSONException e) {
        Log.e(TAG, "failed to deserialize app state update", e);
    }
    return info;
}

From source file:com.chainsaw.clearweather.BackgroundFetch.java

@Override
protected WeatherData doInBackground(String... params) {
    publishProgress(10);/*from w w  w. j a  v a2 s. c  om*/

    HttpURLConnection con = null;
    InputStream is = null;

    if (!isNetworkAvailable()) {
        fetchStatus = NO_NETWORK;
    }

    if (isNetworkAvailable()) {

        try {
            con = (HttpURLConnection) (new URL(params[0])).openConnection();
            con.setRequestMethod("GET");
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setConnectTimeout(SERVER_TIMEOUT);
            con.connect();
            buffer = new StringBuffer();
            is = con.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = null;
            while ((line = br.readLine()) != null)
                buffer.append(line);
            is.close();
            con.disconnect();
        } catch (Throwable t) {
            fetchStatus = SERVER_ERROR;
            t.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (Throwable t) {
                fetchStatus = SERVER_ERROR;
                t.printStackTrace();
            }
            try {
                con.disconnect();
            } catch (Throwable t) {
                fetchStatus = SERVER_ERROR;
                t.printStackTrace();
            }
        }

        try {
            weatherData = (buffer.toString() == null) ? new JSONObject() : new JSONObject(buffer.toString());
            fetchStatus = DONE;
        } catch (Throwable e) {
            fetchStatus = NO_DATA;
            e.printStackTrace();
        }

        is = null;
        con = null;

        try {
            if ((fetchStatus == DONE) && (weatherData != null)) {
                WeatherData.newDataStatus = DONE;
                JSONObject mainObj = weatherData.getJSONObject("main");
                JSONArray weatherObj = weatherData.getJSONArray("weather");
                returnData = new WeatherData(true, (int) (Math.round(mainObj.getDouble("temp") - 273.15)),
                        ((int) (Math.round(mainObj.getInt("humidity")))), weatherData.getString("name"),
                        ((JSONObject) weatherObj.get(0)).getString("description"));
            }
        } catch (Throwable e) {
            fetchStatus = NO_DATA;
            e.printStackTrace();
        }
    }
    switch (fetchStatus) {
    case NO_DATA:
        WeatherData.newDataStatus = NO_DATA;
        break;
    case SERVER_ERROR:
        WeatherData.newDataStatus = SERVER_ERROR;
        break;
    case NO_NETWORK:
        WeatherData.newDataStatus = NO_NETWORK;
        break;
    }
    if (returnData == null)
        WeatherData.newDataStatus = NO_DATA;

    return returnData;

}

From source file:org.eclipse.orion.server.tests.servlets.git.GitBlameTest.java

@Test
public void testBlameMultiCommit() throws IOException, SAXException, JSONException, CoreException {

    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

    for (IPath clonePath : clonePaths) {
        //clone a repo
        JSONObject clone = clone(clonePath);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        //get project/folder metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject folder = new JSONObject(response.getText());
        JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        //create file test.txtx
        JSONObject testTxt = getChild(folder, "test.txt");
        modifyFile(testTxt, "line one \n line two \n line 3 \n line 4");

        //commit the file
        addFile(testTxt);//from w w  w. j  a  v a2s  . c om
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "initial commit", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // get the blame uri for this file
        JSONObject testTxtGitSection = testTxt.getJSONObject(GitConstants.KEY_GIT);
        String blameUri = testTxtGitSection.getString(GitConstants.KEY_BLAME);

        // blame the file
        request = getGetGitBlameRequest(blameUri);
        response = webConversation.getResource(request);

        // testing
        JSONObject blameObject = new JSONObject(response.getText());

        // non blame info tests
        JSONArray blame = blameObject.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        assertNotNull(blameObject.get(ProtocolConstants.KEY_CHILDREN));
        assertEquals(blame.length(), 1);
        blameObject = blame.getJSONObject(0);
        assertNotNull(blameObject.get(GitConstants.KEY_AUTHOR_EMAIL));
        assertNotNull(blameObject.get(GitConstants.KEY_AUTHOR_NAME));
        assertNotNull(blameObject.get(GitConstants.KEY_AUTHOR_IMAGE));
        assertNotNull(blameObject.get(GitConstants.KEY_COMMITTER_EMAIL));
        assertNotNull(blameObject.get(GitConstants.KEY_COMMITTER_NAME));
        assertNotNull(blameObject.get(GitConstants.KEY_COMMIT_MESSAGE));
        assertNotNull(blameObject.get(GitConstants.KEY_COMMIT_TIME));
        assertNotNull(blameObject.get(GitConstants.KEY_COMMIT));
        assertNotNull(blameObject.get(ProtocolConstants.KEY_NAME));
        JSONArray children = blameObject.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        JSONObject child = children.getJSONObject(0);
        assertEquals(children.length(), 1);
        assertEquals(child.get(GitConstants.KEY_START_RANGE), 1);
        assertEquals(child.get(GitConstants.KEY_END_RANGE), 4);

        //save commit info to test
        String commitLocation1 = blameObject.getString(GitConstants.KEY_COMMIT);
        int commitTime1 = blameObject.getInt(GitConstants.KEY_COMMIT_TIME);
        String commitId1 = blameObject.getString(ProtocolConstants.KEY_NAME);

        // modify the file
        modifyFile(testTxt, "LINE ONE \n LINE TWO \n LINE THREE \n LINE FOUR \n LINE FIVE");
        addFile(testTxt);

        //commit the new changes
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "initial commit", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // get blame uri
        testTxtGitSection = testTxt.getJSONObject(GitConstants.KEY_GIT);
        blameUri = testTxtGitSection.getString(GitConstants.KEY_BLAME);

        // blame file
        request = getGetGitBlameRequest(blameUri);
        response = webConversation.getResource(request);

        // test
        blameObject = new JSONObject(response.getText());

        // non blame info tests
        assertEquals(blameObject.length(), 4);
        assertEquals(blameObject.getString(ProtocolConstants.KEY_TYPE), "Blame");
        assertEquals(blameObject.getString(ProtocolConstants.KEY_LOCATION), blameUri);

        blame = blameObject.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        assertNotNull(blameObject.get(ProtocolConstants.KEY_CHILDREN));

        // test first commit
        assertEquals(blame.length(), 1);
        blameObject = blame.getJSONObject(0);

        //test second commit
        blameObject = blame.getJSONObject(0);

        assertNotNull(blameObject.get(GitConstants.KEY_AUTHOR_EMAIL));
        assertNotNull(blameObject.get(GitConstants.KEY_AUTHOR_NAME));
        assertNotNull(blameObject.get(GitConstants.KEY_AUTHOR_IMAGE));
        assertNotNull(blameObject.get(GitConstants.KEY_COMMITTER_EMAIL));
        assertNotNull(blameObject.get(GitConstants.KEY_COMMITTER_NAME));
        assertNotNull(blameObject.get(GitConstants.KEY_COMMIT_MESSAGE));
        assertNotNull(blameObject.get(GitConstants.KEY_COMMIT_TIME));
        assertNotNull(blameObject.get(GitConstants.KEY_COMMIT));
        assertNotNull(blameObject.get(ProtocolConstants.KEY_NAME));
        children = blameObject.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        child = children.getJSONObject(0);
        assertEquals(children.length(), 1);
        assertEquals(child.get(GitConstants.KEY_START_RANGE), 1);
        assertEquals(child.get(GitConstants.KEY_END_RANGE), 5);

        String commitLocation2 = blameObject.getString(GitConstants.KEY_COMMIT);
        int commitTime2 = blameObject.getInt(GitConstants.KEY_COMMIT_TIME);
        String commitId2 = blameObject.getString(ProtocolConstants.KEY_NAME);

        // test that there are not duplicates of the same commit
        assertNotSame(commitId1, commitId2);
        assertNotSame(commitLocation1, commitLocation2);
        assertNotSame(commitTime1, commitTime2);

    }
}

From source file:com.commonsware.android.vidtry.URLHistory.java

void load(String rawJSON) throws JSONException {
    JSONObject json = new JSONObject(rawJSON);

    for (Iterator i = json.keys(); i.hasNext();) {
        String key = i.next().toString();
        HistoryItem h = new HistoryItem(key, json.getInt(key));

        spareCopy.add(h);//w ww .j a  v  a2 s.  c  om
        add(h);
    }
}

From source file:org.marietjedroid.connect.MarietjeClientChannel.java

public void handleMessage(String token, JSONObject data) throws JSONException {

    System.out.println("processing" + data.toString());
    if (data.getString("type").equals("media_part")) {
        synchronized (tracksRetrieved) {
            JSONObject ding = data.getJSONObject("part");

            @SuppressWarnings("unchecked")
            Iterator<String> it = ding.keys();
            while (it.hasNext())
                tempPartialMedia.add(ding.getJSONArray((it.next().toString())));
            if (this.partialMediaSize == tempPartialMedia.size()) {
                this.partialMedia = tempPartialMedia.toArray(new JSONArray[0]);
                this.tempPartialMedia.clear();
                this.partialMediaSize = -1;
                tracksRetrieved.release();
            }/* w  ww .j  ava  2 s . co m*/

        }
    } else if (data.getString("type").equals("media")) {
        synchronized (tracksRetrieved) {
            this.partialMediaSize = data.getInt("count");
            if (this.partialMediaSize == tempPartialMedia.size()) {
                this.partialMedia = tempPartialMedia.toArray(new JSONArray[0]);
                this.tempPartialMedia.clear();
                this.partialMediaSize = 0;
                tracksRetrieved.release();
            }
        }
    } else if (data.getString("type").equals("welcome"))
        return;
    else if (data.getString("type").equals("playing")) {
        this.nowPlaying = data.getJSONObject("playing");
        playingRetrieved.release();
    } else if (data.getString("type").equals("requests")) {
        this.requests = data.getJSONArray("requests");
        this.requestsRetrieved.release();

    } else if (data.getString("type").equals("error_login")) {
        synchronized (loginAttempt) {
            this.loginError = new MarietjeException(data.getString("message"));
            this.loginAttempt.release();
        }
    } else if (data.getString("type").equals("login_token")) {
        synchronized (this.loginToken) {
            this.loginToken = data.getString("login_token");
            this.loginAttempt.release();
        }
    } else if (data.getString("type").equals("logged_in")) {
        synchronized (loginAttempt) {
            this.accessKey = data.getString("accessKey");
            loginAttempt.release();
        }
    } else if (data.getString("type").equals("error_request")) {
        this.requestError = data.getString("message");
        this.requestsRetrieved.release();
    } else if (data.getString("type").equals("query_media_results")) {
        if (data.getInt("token") != server.queryToken) {
            return; // wrong result set
        }
        synchronized (this.queryResults) {
            this.queryResults.clear();
            JSONArray results = data.getJSONArray("results");
            for (int i = 0; results.opt(i) != null; i++) {
                JSONObject m = results.getJSONObject(i);
                this.queryResults.add(new MarietjeTrack(m));
            }
            this.queryResultsRetrieved.release();
        }

    }

    this.setChanged();
    this.notifyObservers(data.getString("type"));
}