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.markupartist.sthlmtraveling.provider.planner.Planner.java

public Trip2 addIntermediateStops(final Context context, Trip2 trip, JourneyQuery query) throws IOException {
    Uri u = Uri.parse(apiEndpoint2());/*from w  ww  .  j av  a2  s  . c om*/
    Uri.Builder b = u.buildUpon();
    b.appendEncodedPath("journey/v1/intermediate/");
    b.appendQueryParameter("ident", query.ident);
    b.appendQueryParameter("seqnr", query.seqnr);
    int references = 0;
    String reference = null;
    for (SubTrip st : trip.subTrips) {
        if ((!TextUtils.isEmpty(st.reference)) && st.intermediateStop.isEmpty()) {
            b.appendQueryParameter("reference", st.reference);
            references++;
            reference = st.reference;
        }
    }
    u = b.build();

    if (references == 0) {
        return trip;
    }

    HttpHelper httpHelper = HttpHelper.getInstance(context);
    HttpURLConnection connection = httpHelper.getConnection(u.toString());

    String rawContent;
    int statusCode = connection.getResponseCode();
    switch (statusCode) {
    case 200:
        rawContent = httpHelper.getBody(connection);
        try {
            JSONObject baseResponse = new JSONObject(rawContent);
            if (baseResponse.has("stops")) {
                if (baseResponse.isNull("stops")) {
                    Log.d(TAG, "stops was null, ignoring.");
                } else if (references == 1) {
                    JSONArray intermediateStopsJson = baseResponse.getJSONArray("stops");
                    for (SubTrip st : trip.subTrips) {
                        if (reference.equals(st.reference)) {
                            for (int i = 0; i < intermediateStopsJson.length(); i++) {
                                st.intermediateStop
                                        .add(IntermediateStop.fromJson(intermediateStopsJson.getJSONObject(i)));
                            }
                        }
                    }
                } else {
                    JSONObject intermediateStopsJson = baseResponse.getJSONObject("stops");
                    for (SubTrip st : trip.subTrips) {
                        if (intermediateStopsJson.has(st.reference)) {
                            JSONArray jsonArray = intermediateStopsJson.getJSONArray(st.reference);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                st.intermediateStop.add(IntermediateStop.fromJson(jsonArray.getJSONObject(i)));
                            }
                        }
                    }
                }

            } else {
                Log.w(TAG, "Invalid response when fetching intermediate stops.");
            }
        } catch (JSONException e) {
            Log.w(TAG, "Could not parse the reponse for intermediate stops.");
        }
        break;
    case 400: // Bad request
        rawContent = httpHelper.getErrorBody(connection);
        try {
            BadResponse br = BadResponse.fromJson(new JSONObject(rawContent));
            Log.e(TAG, "Invalid response for intermediate stops: " + br.toString());
        } catch (JSONException e) {
            Log.e(TAG, "Could not parse the reponse for intermediate stops.");
        }
    default:
        Log.e(TAG, "Status code not OK from intermediate stops API, was " + statusCode);
    }

    return trip;
}

From source file:com.markupartist.sthlmtraveling.provider.planner.Planner.java

private Response doJourneyQuery(final Context context, JourneyQuery query, int scrollDirection)
        throws IOException, BadResponse {

    Uri u = Uri.parse(apiEndpoint2());//from  w w  w  .j av a  2s  .c om
    Uri.Builder b = u.buildUpon();
    b.appendEncodedPath("v1/journey/");
    if (scrollDirection > -1) {
        b.appendQueryParameter("dir", String.valueOf(scrollDirection));
        b.appendQueryParameter("ident", query.ident);
        b.appendQueryParameter("seq", query.seqnr);
    } else {
        if (query.origin.hasLocation()) {
            b.appendQueryParameter("origin", query.origin.name);
            b.appendQueryParameter("origin_latitude", String.valueOf(query.origin.latitude / 1E6));
            b.appendQueryParameter("origin_longitude", String.valueOf(query.origin.longitude / 1E6));
        } else {
            b.appendQueryParameter("origin", String.valueOf(query.origin.getNameOrId()));
        }
        if (query.destination.hasLocation()) {
            b.appendQueryParameter("destination", query.destination.name);
            b.appendQueryParameter("destination_latitude", String.valueOf(query.destination.latitude / 1E6));
            b.appendQueryParameter("destination_longitude", String.valueOf(query.destination.longitude / 1E6));
        } else {
            b.appendQueryParameter("destination", String.valueOf(query.destination.getNameOrId()));
        }
        for (String transportMode : query.transportModes) {
            b.appendQueryParameter("transport", transportMode);
        }
        if (query.time != null) {
            b.appendQueryParameter("date", query.time.format("%d.%m.%Y"));
            b.appendQueryParameter("time", query.time.format("%H:%M"));
        }
        if (!query.isTimeDeparture) {
            b.appendQueryParameter("arrival", "1");
        }
        if (query.hasVia()) {
            b.appendQueryParameter("via", query.via.name);
        }
        if (query.alternativeStops) {
            b.appendQueryParameter("alternative", "1");
        }
    }

    // Include intermediate stops.
    //b.appendQueryParameter("intermediate_stops", "1");

    u = b.build();

    HttpHelper httpHelper = HttpHelper.getInstance(context);
    HttpURLConnection connection = httpHelper.getConnection(u.toString());

    Response r = null;
    String rawContent;
    int statusCode = connection.getResponseCode();
    switch (statusCode) {
    case 200:
        rawContent = httpHelper.getBody(connection);
        try {
            JSONObject baseResponse = new JSONObject(rawContent);
            if (baseResponse.has("journey")) {
                r = Response.fromJson(baseResponse.getJSONObject("journey"));
            } else {
                Log.w(TAG, "Invalid response");
            }
        } catch (JSONException e) {
            Log.d(TAG, "Could not parse the reponse...");
            throw new IOException("Could not parse the response.");
        }
        break;
    case 400:
        rawContent = httpHelper.getErrorBody(connection);
        BadResponse br;
        try {
            br = BadResponse.fromJson(new JSONObject(rawContent));
        } catch (JSONException e) {
            Log.d(TAG, "Could not parse the reponse...");
            throw new IOException("Could not parse the response.");
        }
        throw br;
    default:
        Log.d(TAG, "Status code not OK from API, was " + statusCode);
        throw new IOException("A remote server error occurred when getting deviations.");
    }

    return r;
}

From source file:org.openqa.selenium.safari.SafariDriverCommandExecutor.java

@Override
public synchronized Response execute(Command command) {
    if (!server.isRunning() && DriverCommand.QUIT.equals(command.getName())) {
        Response itsOkToQuitMultipleTimes = new Response();
        itsOkToQuitMultipleTimes.setStatus(ErrorCodes.SUCCESS);
        return itsOkToQuitMultipleTimes;
    }/* w  w w  .j  av  a 2s. c o  m*/

    checkState(connection != null, "Executor has not been started yet");

    // On quit(), the SafariDriver's browser extension simply returns a stub success
    // response, so we can short-circuit the process and just return that here.
    // The SafarIDriver's browser extension doesn't do anything on qu
    // There's no need to wait for a response when quitting.
    if (DriverCommand.QUIT.equals(command.getName())) {
        Response response = new Response(command.getSessionId());
        response.setStatus(ErrorCodes.SUCCESS);
        response.setState(ErrorCodes.SUCCESS_STRING);
        return response;
    }

    try {
        SafariCommand safariCommand = new SafariCommand(command);
        String rawJsonCommand = new BeanToJsonConverter().convert(serialize(safariCommand));
        ListenableFuture<String> futureResponse = connection.send(rawJsonCommand);

        JSONObject jsonResponse = new JSONObject(futureResponse.get());
        Response response = new JsonToBeanConverter().convert(Response.class,
                jsonResponse.getJSONObject("response").toString());
        if (response.getStatus() == ErrorCodes.SUCCESS) {
            checkArgument(safariCommand.getId().equals(jsonResponse.getString("id")),
                    "Response ID<%s> does not match command ID<%s>", jsonResponse.getString("id"),
                    safariCommand.getId());
        }

        return response;
    } catch (JSONException e) {
        throw new JsonException(e);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new WebDriverException(e);
    } catch (ExecutionException e) {
        throw Throwables.propagate(e.getCause());
    }
}

From source file:com.hichinaschool.flashcards.libanki.sync.Syncer.java

public void mergeChanges(JSONObject lchg, JSONObject rchg) {
    try {/*from   w  ww  . java  2s.  c o  m*/
        // then the other objects
        mergeModels(rchg.getJSONArray("models"));
        mergeDecks(rchg.getJSONArray("decks"));
        mergeTags(rchg.getJSONArray("tags"));
        if (rchg.has("conf")) {
            mergeConf(rchg.getJSONObject("conf"));
        }
        // this was left out of earlier betas
        if (rchg.has("crt")) {
            mCol.setCrt(rchg.getLong("crt"));
        }
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    prepareToChunk();
}

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

@Test
public void testLog() throws Exception {
    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);

        // modify
        JSONObject testTxt = getChild(folder, "test.txt");
        modifyFile(testTxt, "first change");
        addFile(testTxt);/*from  ww  w  . j a  va2s .co m*/

        // commit1
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit1", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // modify again
        modifyFile(testTxt, "second change");
        addFile(testTxt);

        // commit2
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit2", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // get the full log
        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(3, commitsArray.length());

        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        commit = commitsArray.getJSONObject(1);
        assertEquals("commit1", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        commit = commitsArray.getJSONObject(2);
        assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        String initialGitCommitName = commit.getString(ProtocolConstants.KEY_NAME);
        String initialGitCommitURI = gitHeadUri.replaceAll(Constants.HEAD, initialGitCommitName);

        //get log for given page size
        commitsArray = log(gitHeadUri, 1, 1, false, true);
        assertEquals(1, commitsArray.length());

        commit = commitsArray.getJSONObject(0);
        assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        //get log for second page
        commitsArray = log(gitHeadUri, 2, 1, true, true);
        assertEquals(1, commitsArray.length());

        commit = commitsArray.getJSONObject(0);
        assertEquals("commit1", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        // prepare a scoped log location
        request = getPostForScopedLogRequest(initialGitCommitURI, Constants.HEAD);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        String newGitCommitUri = response.getHeaderField(ProtocolConstants.KEY_LOCATION);
        assertEquals(newGitCommitUri,
                new JSONObject(response.getText()).getString(ProtocolConstants.KEY_LOCATION));

        // get a scoped log
        commitsArray = log(newGitCommitUri);
        assertEquals(2, commitsArray.length());

        commit = commitsArray.getJSONObject(0);
        assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));

        commit = commitsArray.getJSONObject(1);
        assertEquals("commit1", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
    }
}

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

@Test
public void testLogOrionServerLinked() throws Exception {
    File orionServer = new File("").getAbsoluteFile().getParentFile(/*org.eclipse.orion.server.tests*/)
            .getParentFile(/*tests*/);
    Assume.assumeTrue(new File(orionServer, Constants.DOT_GIT).exists());

    URI workspaceLocation = createWorkspace(getMethodName());
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(),
            orionServer.toURI().toString());
    String location = project.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

    // get project/folder metadata
    WebRequest request = getGetRequest(location);
    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);

    // reading first 50 commits should be enough to start a task
    JSONArray commitsArray = log(gitHeadUri, 1, 50, false, true);
    assertEquals(50, commitsArray.length());
}

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

@Test
public void testLogRemoteBranch() throws Exception {
    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 gitRemoteUri = gitSection.getString(GitConstants.KEY_REMOTE);
        JSONObject originMasterDetails = getRemoteBranch(gitRemoteUri, 1, 0, Constants.MASTER);
        String originMasterCommitUri = originMasterDetails.getString(GitConstants.KEY_COMMIT);

        JSONArray commitsArray = log(originMasterCommitUri);
        assertEquals(1, commitsArray.length());
    }/*from w  w w  .jav a2  s.c om*/
}

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

@Test
public void testLogWithTag() throws Exception {
    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 metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());

        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(1, commitsArray.length());

        String commitUri = commitsArray.getJSONObject(0).getString(ProtocolConstants.KEY_LOCATION);
        JSONObject updatedCommit = tag(commitUri, "tag");
        JSONArray tagsArray = updatedCommit.getJSONArray(GitConstants.KEY_TAGS);
        assertEquals(1, tagsArray.length());
        assertEquals(Constants.R_TAGS + "tag", tagsArray.getJSONObject(0).get(ProtocolConstants.KEY_FULL_NAME));

        commitsArray = log(gitHeadUri);/*from  ww w .j  a va 2s.c  o m*/
        assertEquals(1, commitsArray.length());

        tagsArray = commitsArray.getJSONObject(0).getJSONArray(GitConstants.KEY_TAGS);
        assertEquals(1, tagsArray.length());
        assertEquals(Constants.R_TAGS + "tag", tagsArray.getJSONObject(0).get(ProtocolConstants.KEY_FULL_NAME));
    }
}

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

@Test
public void testLogWithBranch() throws Exception {
    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);
        String branchesLocation = clone.getString(GitConstants.KEY_BRANCH);

        // get project metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());

        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitCommitUri = gitSection.getString(GitConstants.KEY_COMMIT);

        JSONArray commitsArray = log(gitCommitUri);
        assertEquals(1, commitsArray.length());

        branch(branchesLocation, "branch");

        commitsArray = log(gitCommitUri);
        assertEquals(1, commitsArray.length());

        JSONArray branchesArray = commitsArray.getJSONObject(0).getJSONArray(GitConstants.KEY_BRANCHES);
        assertEquals(3, branchesArray.length());
        assertEquals(Constants.R_HEADS + "branch",
                branchesArray.getJSONObject(0).get(ProtocolConstants.KEY_FULL_NAME));
        assertEquals(Constants.R_HEADS + Constants.MASTER,
                branchesArray.getJSONObject(1).get(ProtocolConstants.KEY_FULL_NAME));
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER,
                branchesArray.getJSONObject(2).get(ProtocolConstants.KEY_FULL_NAME));
    }/*from   w  w w  .  jav a 2  s  .  c o m*/
}

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

@Test
public void testLogWithParents() throws Exception {
    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 metadata
        WebRequest request = getGetRequest(cloneContentLocation);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project = new JSONObject(response.getText());

        JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        // modify
        JSONObject testTxt = getChild(project, "test.txt");
        modifyFile(testTxt, "first change");
        addFile(testTxt);/* w w w  . j ava2  s .  com*/

        // commit1
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit1", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // modify again
        modifyFile(testTxt, "second change");
        addFile(testTxt);

        // commit2
        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "commit2", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // get the full log
        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(3, commitsArray.length());

        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("commit2", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        assertEquals(1, commit.getJSONArray(ProtocolConstants.KEY_PARENTS).length());
        String parent = commit.getJSONArray(ProtocolConstants.KEY_PARENTS).getJSONObject(0)
                .getString(ProtocolConstants.KEY_NAME);

        commit = commitsArray.getJSONObject(1);
        assertEquals("commit1", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        assertEquals(parent, commit.get(ProtocolConstants.KEY_NAME));
        assertEquals(1, commit.getJSONArray(ProtocolConstants.KEY_PARENTS).length());
        parent = commit.getJSONArray(ProtocolConstants.KEY_PARENTS).getJSONObject(0)
                .getString(ProtocolConstants.KEY_NAME);

        commit = commitsArray.getJSONObject(2);
        assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        assertEquals(parent, commit.get(ProtocolConstants.KEY_NAME));
        assertEquals(0, commit.getJSONArray(ProtocolConstants.KEY_PARENTS).length());
    }
}