Example usage for org.json JSONArray getJSONObject

List of usage examples for org.json JSONArray getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(int index) throws JSONException 

Source Link

Document

Get the JSONObject associated with an index.

Usage

From source file:org.wso2.carbon.connector.integration.test.pivotaltracker.PivotaltrackerConnectorIntegrationTest.java

/**
 * Positive test case for createLabelForStory method with mandatory parameters.
 * //from  ww  w.j av  a2 s . co m
 * @throws JSONException
 * @throws IOException
 */
@Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateProjectWithMandatoryParameters",
        "testCreateStoryWithMandatoryParameters" }, description = "pivotaltracker {createLabelForStory} integration test with mandatory parameters.")
public void testCreateLabelForStoryWithMandatoryParameters() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:createLabelForStory");
    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_createLabelForStory_mandatory.json");
    final String labelId = esbRestResponse.getBody().getString("id");

    final String apiEndpoint = apiEndpointUrl + "/projects/" + connectorProperties.getProperty("projectId")
            + "/stories/" + connectorProperties.getProperty("storyId") + "/labels";
    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndpoint, "GET", apiRequestHeadersMap);
    JSONArray apiOutputArray = new JSONArray(apiRestResponse.getBody().getString("output"));
    JSONObject lableObj = null;
    for (int i = 0; i < apiOutputArray.length(); i++) {
        lableObj = apiOutputArray.getJSONObject(i);
        if (labelId.equals(lableObj.getString("id"))) {
            break;
        }
    }
    Assert.assertEquals(connectorProperties.getProperty("labelName"), lableObj.getString("name"));

}

From source file:org.wso2.carbon.connector.integration.test.pivotaltracker.PivotaltrackerConnectorIntegrationTest.java

/**
 * Positive test case for listStories method with mandatory parameters.
 * /*  w  w w. j a  va  2 s  .c  o m*/
 * @throws IOException
 * @throws JSONException
 */
@Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateProjectWithMandatoryParameters",
        "testCreateStoryWithOptionalParameters" }, description = "pivotaltracker {listStories} integration test with mandatory parameters.")
public void testListStoriesWithMandatoryParameters() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:listStories");

    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_listStories_mandatory.json");
    JSONArray esbUserStoryArray = new JSONArray(esbRestResponse.getBody().getString("output"));

    String apiEndPoint = apiEndpointUrl + "/projects/" + connectorProperties.getProperty("projectId")
            + "/stories";

    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);
    JSONArray apiUserStoryArray = new JSONArray(apiRestResponse.getBody().getString("output"));

    Assert.assertEquals(esbUserStoryArray.length(), apiUserStoryArray.length());
    Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("id"),
            apiUserStoryArray.getJSONObject(0).getString("id"));
    Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("name"),
            apiUserStoryArray.getJSONObject(0).getString("name"));
    Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("created_at"),
            apiUserStoryArray.getJSONObject(0).getString("created_at"));
    Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("updated_at"),
            apiUserStoryArray.getJSONObject(0).getString("updated_at"));
}

From source file:org.wso2.carbon.connector.integration.test.pivotaltracker.PivotaltrackerConnectorIntegrationTest.java

/**
 * Positive test case for listStories method with optional parameters.
 * //ww w. ja  v  a2s.  c o  m
 * @throws IOException
 * @throws JSONException
 */
@Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateProjectWithMandatoryParameters",
        "testCreateStoryWithOptionalParameters" }, description = "pivotaltracker {listStories} integration test with optional parameters.")
public void testListStoriesWithOptionalParameters() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:listStories");

    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_listStories_optional.json");
    JSONArray esbUserStoryArray = new JSONArray(esbRestResponse.getBody().getString("output"));

    URLEncoder encoder = new URLEncoder();
    final String state = encoder.encode("accepted");

    String apiEndPoint = apiEndpointUrl + "/projects/" + connectorProperties.getProperty("projectId")
            + "/stories?offset=0&limit=10&created_before=" + connectorProperties.getProperty("createdBefore")
            + "&created_after=" + connectorProperties.getProperty("createdAfter") + "&with_state=" + state;

    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);
    JSONArray apiUserStoryArray = new JSONArray(apiRestResponse.getBody().getString("output"));

    Assert.assertEquals(esbUserStoryArray.length(), apiUserStoryArray.length());
    Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("id"),
            apiUserStoryArray.getJSONObject(0).getString("id"));
    Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("name"),
            apiUserStoryArray.getJSONObject(0).getString("name"));
    Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("created_at"),
            apiUserStoryArray.getJSONObject(0).getString("created_at"));
    Assert.assertEquals(esbUserStoryArray.getJSONObject(0).getString("updated_at"),
            apiUserStoryArray.getJSONObject(0).getString("updated_at"));

}

From source file:org.softcatala.corrector.LanguageToolParsing.java

public Suggestion[] GetSuggestions(String jsonText) {
    ArrayList<Suggestion> suggestions = new ArrayList<Suggestion>();

    try {//from w ww  .  jav a  2  s . c om

        JSONObject json = new JSONObject(jsonText);
        JSONArray matches = json.getJSONArray("matches");

        for (int i = 0; i < matches.length(); i++) {

            JSONObject match = matches.getJSONObject(i);

            JSONArray replacements = match.getJSONArray("replacements");
            JSONObject rule = match.getJSONObject("rule");
            String ruleId = rule.getString("id");

            // Since we process fragments we need to skip the upper case
            // suggestion
            if (ruleId.equals("UPPERCASE_SENTENCE_START") == true)
                continue;

            Suggestion suggestion = new Suggestion();

            if (replacements.length() == 0) {
                String message = match.getString("message");
                String msgText = String.format("(%s)", message);
                suggestion.Text = new String[] { msgText };
            } else {
                ArrayList<String> list = new ArrayList<String>();
                for (int r = 0; r < replacements.length(); r++) {
                    JSONObject replacement = replacements.getJSONObject(r);
                    String value = replacement.getString("value");
                    list.add(value);
                }
                suggestion.Text = list.toArray(new String[list.size()]);
            }

            suggestion.Position = match.getInt("offset");
            suggestion.Length = match.getInt("length");
            suggestions.add(suggestion);

            Log.d(TAG, "Request result: " + suggestion.Position + " Len:" + suggestion.Length);
        }

    } catch (Exception e) {
        Log.e(TAG, "GetSuggestions", e);
    }

    return suggestions.toArray(new Suggestion[0]);
}

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

public ItemFlipCard(JSONArray json) throws JSONException {
    super(ItemType.FlipCard, json);

    JSONObject item = json.getJSONObject(2);
    JSONObject flipCard = item.getJSONObject("flipCard");

    if (flipCard.getString("flipCardType").equals("JARVIS"))
        mVirusType = FlipCardType.Jarvis;
    else if (flipCard.getString("flipCardType").equals("ADA"))
        mVirusType = FlipCardType.Ada;/*from w ww  . j  av  a2s  . co m*/
    else
        System.out.println("unknown virus type");
}

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

/**
 * Query the Wiktionary API to pick a random dictionary word. Will try
 * multiple times to find a valid word before giving up.
 *
 * @return Random dictionary word, or null if no valid word was found.
 * @throws ApiException If any connection or server error occurs.
 * @throws ParseException If there are problems parsing the response.
 *///  w w w .  jav  a2  s  . co  m
public static String getRandomWord() throws ApiException, ParseException {
    // Keep trying a few times until we find a valid word
    int tries = 0;
    while (tries++ < RANDOM_TRIES) {
        // Query the API for a random word
        String content = getUrlContent(WIKTIONARY_RANDOM);
        try {
            // Drill into the JSON response to find the returned word
            JSONObject response = new JSONObject(content);
            JSONObject query = response.getJSONObject("query");
            JSONArray random = query.getJSONArray("random");
            JSONObject word = random.getJSONObject(0);
            String foundWord = word.getString("title");

            // If we found an actual word, and it wasn't rejected by our invalid
            // filter, then accept and return it.
            if (foundWord != null && !sInvalidWord.matcher(foundWord).find()) {
                return foundWord;
            }
        } catch (JSONException e) {
            throw new ParseException("Problem parsing API response", e);
        }
    }

    // No valid word found in number of tries, so return null
    return null;
}

From source file:org.brickred.socialauth.provider.FourSquareImpl.java

/**
 * Gets the list of contacts of the user.
 * //  ww w . j  av a  2s  .  c  om
 * @return List of contact objects representing Contacts. Only name and
 *         profile URL will be available
 */

@Override
public List<Contact> getContactList() throws Exception {
    LOG.info("Fetching contacts from " + CONTACTS_URL);

    Response serviceResponse;
    try {
        serviceResponse = authenticationStrategy.executeFeed(CONTACTS_URL);
    } catch (Exception e) {
        throw new SocialAuthException("Error while getting contacts from " + CONTACTS_URL, e);
    }
    if (serviceResponse.getStatus() != 200) {
        throw new SocialAuthException("Error while getting contacts from " + CONTACTS_URL + "Status : "
                + serviceResponse.getStatus());
    }
    String respStr;
    try {
        respStr = serviceResponse.getResponseBodyAsString(Constants.ENCODING);
    } catch (Exception exc) {
        throw new SocialAuthException("Failed to read response from  " + CONTACTS_URL, exc);
    }
    LOG.debug("User Contacts list in JSON " + respStr);
    JSONObject resp = new JSONObject(respStr);
    List<Contact> plist = new ArrayList<Contact>();
    JSONArray items = new JSONArray();
    if (resp.has("response")) {
        JSONObject robj = resp.getJSONObject("response");
        if (robj.has("friends")) {
            JSONObject fobj = robj.getJSONObject("friends");
            if (fobj.has("items")) {
                items = fobj.getJSONArray("items");
            }
        } else {
            throw new SocialAuthException("Failed to parse the user profile json : " + respStr);
        }
    } else {
        throw new SocialAuthException("Failed to parse the user profile json : " + respStr);
    }
    LOG.debug("Contacts Found : " + items.length());
    for (int i = 0; i < items.length(); i++) {
        JSONObject obj = items.getJSONObject(i);
        Contact c = new Contact();
        if (obj.has("firstName")) {
            c.setFirstName(obj.getString("firstName"));
        }
        if (obj.has("lastName")) {
            c.setLastName(obj.getString("lastName"));
        }
        if (obj.has("id")) {
            c.setProfileUrl(VIEW_PROFILE_URL + obj.getString("id"));
            c.setId(obj.getString("id"));
        }
        plist.add(c);
    }

    return plist;
}

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

@Test
public void testCherryPick() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);

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

        // 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());

        String folderLocation = folder.getString(ProtocolConstants.KEY_LOCATION);
        JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        JSONObject testTxt = getChild(folder, "test.txt");
        modifyFile(testTxt, "first line\nsec. line\nthird line\n");

        addFile(testTxt);/*  www  .j a  va  2s  .  co m*/

        commitFile(testTxt, "lines in test.txt", false);

        // create new file
        String fileName = "new.txt";
        request = getPostFilesRequest(folderLocation + "/", getNewFileJSON(fileName).toString(), fileName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        // add all
        request = GitAddTest.getPutGitIndexRequest(gitIndexUri);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

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

        // modify
        modifyFile(testTxt, "first line\nsec. line\nthird line\nfourth line\n");

        // add
        addFile(testTxt);

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

        // modify
        modifyFile(testTxt, "first line\nsecond line\nthird line\nfourth line\n");

        // add
        addFile(testTxt);

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

        // remember starting point and commit to cherry-pick
        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(5, commitsArray.length());
        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("fixed test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        String toCherryPick = commit.getString(ProtocolConstants.KEY_NAME);
        commit = commitsArray.getJSONObject(3);
        assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        String startingPoint = commit.getString(ProtocolConstants.KEY_NAME);

        // branch
        response = branch(branchesLocation, "side", startingPoint);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
        response = checkoutBranch(cloneLocation, "side");
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // modify
        modifyFile(testTxt, "first line\nsec. line\nthird line\nfeature++\n");

        // add
        addFile(testTxt);

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

        // CHERRY-PICK
        JSONObject cherryPick = cherryPick(gitHeadUri, toCherryPick);
        CherryPickStatus mergeResult = CherryPickStatus.valueOf(cherryPick.getString(GitConstants.KEY_RESULT));
        assertEquals(CherryPickStatus.OK, mergeResult);
        assertTrue(cherryPick.getBoolean(GitConstants.KEY_HEAD_UPDATED));

        // try again, should be OK, but nothing changed
        cherryPick = cherryPick(gitHeadUri, toCherryPick);
        mergeResult = CherryPickStatus.valueOf(cherryPick.getString(GitConstants.KEY_RESULT));
        assertEquals(CherryPickStatus.OK, mergeResult);
        assertFalse(cherryPick.getBoolean(GitConstants.KEY_HEAD_UPDATED));

        // 'new.txt' should be not there
        JSONObject newTxt = getChild(folder, "new.txt");
        assertNull(newTxt);

        // check cherry-pick result in the file
        request = getGetRequest(testTxt.getString(ProtocolConstants.KEY_LOCATION));
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        assertEquals("first line\nsecond line\nthird line\nfeature++\n", response.getText());

        // check log
        commitsArray = log(gitHeadUri);
        assertEquals(4, commitsArray.length());
        commit = commitsArray.getJSONObject(0);
        assertEquals("fixed test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        commit = commitsArray.getJSONObject(1);
        assertEquals("enhanced test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        commit = commitsArray.getJSONObject(2);
        assertEquals("lines in test.txt", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        commit = commitsArray.getJSONObject(3);
        assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
    }
}

From source file:com.andybotting.tramhunter.objects.FavouriteList.java

/**
 * Get the favourite items/*from  ww  w .ja  va  2 s. com*/
 * @return 
 */
public ArrayList<Favourite> getFavouriteItems() {

    ArrayList<Favourite> favourites = new ArrayList<Favourite>();
    JSONArray favouriteJSONArray = null;
    TramHunterDB db = new TramHunterDB();

    // Fetch JSON favourite stops string from preferences
    String favouriteString = mPreferenceHelper.getStarredStopsString();
    if (LOGV)
        Log.i(TAG, "Parsing favourite string: " + favouriteString);

    // Check to see if we even have any favourites
    if (favouriteString.length() > 1) {

        // Convert any old favourites - if not a JSON Array
        if (!favouriteString.contains("["))
            favouriteString = convertOldFavourites(favouriteString);

        try {
            favouriteJSONArray = new JSONArray(favouriteString);

            for (int i = 0; i < favouriteJSONArray.length(); i++) {

                JSONObject favouriteJSONObject = favouriteJSONArray.getJSONObject(i);

                int tramTrackerID = favouriteJSONObject.optInt("stop");
                int routeID = favouriteJSONObject.optInt("route", -1);
                String name = favouriteJSONObject.optString("name", null);

                Stop stop = db.getStop(tramTrackerID);
                Route route = null;

                if (routeID != -1)
                    route = db.getRoute(routeID);

                favourites.add(new Favourite(stop, route, name));
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    db.close();
    return favourites;
}

From source file:com.sonoport.freesound.response.mapping.PagingResponseMapper.java

@Override
public List<I> map(final JSONObject source) {
    final List<I> items = new LinkedList<>();
    final JSONArray resultsArray = extractFieldValue(source, "results", JSONArray.class);

    if (resultsArray != null) {
        for (int i = 0; i < resultsArray.length(); i++) {
            if (!resultsArray.isNull(i)) {
                final JSONObject jsonObject = resultsArray.getJSONObject(i);
                if ((jsonObject != null)) {
                    final I item = itemMapper.map(jsonObject);
                    items.add(item);//  ww w.  j  a  v  a2 s  .c o  m
                }
            }
        }
    }

    return items;
}