Example usage for org.json JSONArray length

List of usage examples for org.json JSONArray length

Introduction

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

Prototype

public int length() 

Source Link

Document

Get the number of elements in the JSONArray, included nulls.

Usage

From source file:ch.lom.clemens.android.bibliography.data.JSONWebConnector.java

public String[] getCollectionDocIDs(MCollection col, int page) {
    if (!isConnected()) {
        StartActivity.singleton.doAuthentication(StartActivity.MENDELEY_RETRIEVE_COLLECTION);
        return null;
    }//from  w  ww .j  ava2 s  .  c  om

    String[] ids = null;
    try {
        String strResponse;
        if (col.m_coltype == MCollection.AUTHORED) {
            strResponse = connect("http://www.mendeley.com/oapi/library/documents/authored/?page=" + page
                    + "&consumer_key=" + m_consumerkey);
        } else if (col.m_coltype == MCollection.LIBRARY) {
            strResponse = connect(
                    "http://www.mendeley.com/oapi/library/?page=" + page + "&consumer_key=" + m_consumerkey);
        } else {
            strResponse = connect("http://www.mendeley.com/oapi/library/collections/" + col.id + "/?page="
                    + page + "&consumer_key=" + m_consumerkey);
        }

        Log.i("MendeleyComm", "Collection: " + col.id + "\n" + strResponse);

        JSONObject colData = new JSONObject(strResponse);

        JSONArray documents = colData.getJSONArray("document_ids");
        ids = new String[documents.length()];
        for (int i = 0; i < documents.length(); i++) {
            ids[i] = documents.getString(i);
        }

        // make sure we get all pages
        int totalpages = colData.getInt("total_pages");
        if (page + 1 < totalpages) {
            String[] adddocs = getCollectionDocIDs(col, page + 1);

            String[] alldocs = new String[ids.length + adddocs.length];
            for (int i = 0; i < ids.length; i++)
                alldocs[i] = ids[i];
            for (int i = 0; i < adddocs.length; i++)
                alldocs[ids.length + i] = adddocs[i];
            ids = alldocs;
        }

    } catch (Exception e) {
        Log.e("MendeleyConnector", "Got a " + e.getClass().getName() + ": " + e.getMessage());
    }

    return ids;
}

From source file:ch.lom.clemens.android.bibliography.data.JSONWebConnector.java

public MGroup[] getGroups(MendeleyConnector con) {

    if (!isConnected()) {
        StartActivity.singleton.doAuthentication(StartActivity.MENDELEY_RETRIEVE_COLLECTIONS);
        return null;
    }//  w ww.  ja v a  2  s  . c o  m

    MGroup[] groups = null;

    try {
        String strResponse = connect(
                "http://www.mendeley.com/oapi/library/groups?consumer_key=" + m_consumerkey);

        Log.i("MendeleyComm", strResponse);

        JSONArray items = new JSONArray(strResponse);

        groups = new MGroup[items.length()];

        for (int i = 0; i < items.length(); i++) {
            JSONObject collection = items.getJSONObject(i);

            groups[i] = new MGroup(con);

            groups[i].id = collection.getString("id");
            groups[i].name = collection.getString("name");
            groups[i].type = collection.getString("type");
            groups[i].size = collection.getInt("size");
        }
    } catch (Exception e) {
        Log.e("MendeleyConnector", "Got exception when parsing online group data");
        Log.e("MendeleyConnector", e.getClass().getSimpleName() + ": " + e.getMessage());
    }
    return groups;
}

From source file:ch.lom.clemens.android.bibliography.data.JSONWebConnector.java

public String[] getGroupDocuments(MGroup group, int page) {
    if (!isConnected()) {
        StartActivity.singleton.doAuthentication(StartActivity.MENDELEY_RETRIEVE_COLLECTION);
        return null;
    }//from  w ww .  j a va 2  s .c om

    String[] ids = null;
    try {
        String strResponse = connect("http://www.mendeley.com/oapi/library/groups/" + group.id + "/?page="
                + page + "&consumer_key=" + m_consumerkey);

        Log.i("MendeleyComm", "Collection: " + group.id + "\n" + strResponse);

        JSONObject colData = new JSONObject(strResponse);

        JSONArray documents = colData.getJSONArray("document_ids");
        ids = new String[documents.length()];
        for (int i = 0; i < documents.length(); i++) {
            ids[i] = documents.getString(i);
        }

        // make sure we get all pages
        int totalpages = colData.getInt("total_pages");
        if (page + 1 < totalpages) {
            String[] adddocs = getGroupDocuments(group, page + 1);

            String[] alldocs = new String[ids.length + adddocs.length];
            for (int i = 0; i < ids.length; i++)
                alldocs[i] = ids[i];
            for (int i = 0; i < adddocs.length; i++)
                alldocs[ids.length + i] = adddocs[i];
            ids = alldocs;
        }

    } catch (Exception e) {
        Log.e("MendeleyConnector", "Got a " + e.getClass().getName() + ": " + e.getMessage());
    }

    return ids;
}

From source file:ch.lom.clemens.android.bibliography.data.JSONWebConnector.java

private MDocument parseDocumentResult(MDocument mdoc, String strResponse) throws JSONException {

    JSONObject doc = new JSONObject(strResponse);

    try {// w ww  .j  ava 2  s .c  o m
        mdoc.title = doc.getString("title");
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document title");
    }
    try {
        mdoc.year = doc.getString("year");
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document year");
    }
    try {
        mdoc.notes = doc.getString("notes");
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document notes");
    }
    try {
        mdoc.type = doc.getString("type");
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document type");
    }
    try {
        mdoc.urls = new String[] { doc.getString("url") };
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document url");
    }
    try {
        mdoc.pages = doc.getString("pages");
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document pages");
    }
    try {
        mdoc.docabstract = doc.getString("abstract");
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document abstract");
    }

    try {
        JSONArray authors = doc.getJSONArray("authors");
        String[] strAuthors = new String[authors.length()];
        for (int j = 0; j < authors.length(); j++) {
            strAuthors[j] = authors.getString(j);
        }
        mdoc.authors = strAuthors;
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document authors");
    }

    try {

        JSONArray tags = doc.getJSONArray("tags");
        String[] mtags = new String[tags.length()];
        for (int j = 0; j < tags.length(); j++) {
            mtags[j] = tags.getString(j);
        }
        mdoc.tags = mtags;
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document tags");
    }

    try {
        JSONObject ids = doc.getJSONObject("identifiers");
        mdoc.identifiers = new HashMap<String, String>();
        JSONArray names = ids.names();
        for (int j = 0; j < names.length(); j++) {
            mdoc.identifiers.put(names.getString(j), ids.getString(names.getString(j)));
        }
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document identifiers");
    }

    try {
        JSONObject ids = doc.getJSONObject("discipline");
        mdoc.discipline = new HashMap<String, String>();
        JSONArray names = ids.names();
        for (int j = 0; j < names.length(); j++) {
            mdoc.discipline.put(names.getString(j), ids.getString(names.getString(j)));
        }
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document disciplines");
    }

    return mdoc;
}

From source file:gmc.hotplate.util.JsonParser.java

public List<Recipe> parseMessage(JSONObject obj) {
    List<Recipe> recipes = new ArrayList<Recipe>();
    try {/*from  w ww. j ava2s  . c o  m*/
        JSONArray jsonRecipes = obj.getJSONArray(TAG_RECIPES);
        for (int i = 0; i < jsonRecipes.length(); i++) {
            Recipe recipe = parseRecipeObject(jsonRecipes.getJSONObject(i));
            if (recipe != null) {
                recipes.add(recipe);
            }
        }
    } catch (JSONException e) {
        Log.w(LOG_TAG, "ParseMessage() error: " + e.getMessage());
    }
    return recipes;
}

From source file:gmc.hotplate.util.JsonParser.java

public Recipe parseRecipeObject(JSONObject obj) {
    Recipe recipe = null;//from   w w w  .  j av  a  2  s  .com
    try {
        int recipeId = obj.getInt(TAG_RECIPE_ID);
        String recipeName = obj.getString(TAG_RECIPE_NAME);
        String recipeDescription = obj.getString(TAG_RECIPE_DESCRIPTION);
        int personCount = obj.getInt(TAG_RECIPE_PERSON);
        JSONArray jsonSteps = obj.getJSONArray(TAG_RECIPE_STEPS);
        List<Step> steps = new ArrayList<Step>();
        for (int i = 0; i < jsonSteps.length(); i++) {
            Step step = parseStepObject(jsonSteps.getJSONObject(i));
            if (step != null) {
                steps.add(step);
            }
        }

        List<Ingredient> ingredients = new ArrayList<Ingredient>();
        JSONArray jsonIngredients = obj.getJSONArray(TAG_RECIPE_INGREDIENTS);
        for (int i = 0; i < jsonIngredients.length(); i++) {
            Ingredient ingredient = parseIngredientObject(jsonIngredients.getJSONObject(i));
            if (ingredient != null) {
                ingredients.add(ingredient);
            }
        }

        List<String> categories = new ArrayList<String>();
        if (obj.has(TAG_RECIPE_CATEGORIES)) {
            JSONArray jsonCategories = obj.getJSONArray(TAG_RECIPE_CATEGORIES);
            for (int i = 0; i < jsonCategories.length(); i++) {
                String tag = jsonCategories.getString(i);
                categories.add(tag);
            }
        }
        recipe = new Recipe(recipeId, recipeName, recipeDescription, personCount, steps);
        recipe.setIngredients(ingredients);
        recipe.setCategories(categories);
    } catch (JSONException e) {
        Log.w(LOG_TAG, "ParseRecipe() error: " + e.getMessage());
    }

    return recipe;
}

From source file:org.wso2.carbon.connector.integration.test.gototraining.GototrainingConnectorIntegrationTest.java

/**
 * Positive test case for listTrainings method with mandatory parameters.
 *//*w  ww  .java  2  s  .c  o  m*/
@Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateTrainingWithMandatoryParameters",
        "testCreateTrainingWithOptionalParameters" }, description = "gototraining {listTrainings} integration test with mandatory parameters.")
public void testListTrainingsWithMandatoryParameters() throws IOException, JSONException {

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

    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_listTrainings_mandatory.json");

    final String apiEndPoint = apiRequestUrl + "/organizers/" + connectorProperties.getProperty("organizerKey")
            + "/trainings/";

    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);

    final JSONArray esbArray = new JSONArray(esbRestResponse.getBody().getString("output"));
    final JSONArray apiArray = new JSONArray(apiRestResponse.getBody().getString("output"));

    Assert.assertEquals(esbArray.length(), apiArray.length());
    Assert.assertEquals(esbArray.getJSONObject(0).getString("name"),
            apiArray.getJSONObject(0).getString("name"));
    Assert.assertEquals(esbArray.getJSONObject(0).getString("description"),
            apiArray.getJSONObject(0).getString("description"));
    Assert.assertEquals(esbArray.getJSONObject(0).getJSONArray("times").getJSONObject(0).getString("startDate"),
            apiArray.getJSONObject(0).getJSONArray("times").getJSONObject(0).getString("startDate"));
}

From source file:org.wso2.carbon.connector.integration.test.gototraining.GototrainingConnectorIntegrationTest.java

/**
 * Positive test case for listOrganizers method with mandatory parameters.
 *///  w  w  w  .  ja  v a2s .c o m
@Test(dependsOnMethods = { "testCreateTrainingWithMandatoryParameters" }, groups = {
        "wso2.esb" }, description = "gototraining {listOrganizers} integration test with mandatory parameters.")
public void testListOrganizersWithMandatoryParameters() throws IOException, JSONException {

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

    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_listOrganizers_mandatory.json");

    final String apiEndPoint = apiRequestUrl + "/organizers/" + connectorProperties.getProperty("organizerKey")
            + "/trainings/" + connectorProperties.getProperty("trainingKeyMandatory") + "/organizers";

    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);

    final JSONArray esbArray = new JSONArray(esbRestResponse.getBody().getString("output"));
    final JSONArray apiArray = new JSONArray(apiRestResponse.getBody().getString("output"));

    Assert.assertEquals(esbArray.length(), apiArray.length());
    Assert.assertEquals(esbArray.getJSONObject(0).getString("givenName"),
            apiArray.getJSONObject(0).getString("givenName"));
    Assert.assertEquals(esbArray.getJSONObject(0).getString("email"),
            apiArray.getJSONObject(0).getString("email"));
    Assert.assertEquals(esbArray.getJSONObject(0).getString("surname"),
            apiArray.getJSONObject(0).getString("surname"));
}

From source file:org.wso2.carbon.connector.integration.test.gototraining.GototrainingConnectorIntegrationTest.java

/**
 * Positive test case for listRegistrants method with mandatory parameters.
 *///from www .j  a va 2  s . c  o m
@Test(groups = { "wso2.esb" }, dependsOnMethods = {
        "testAddRegistrantWithMandatoryParameters" }, description = "gototraining {listRegistrants} integration test with mandatory parameters.")
public void testListRegistrantsWithMandatoryParameters() throws IOException, JSONException {

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

    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_listRegistrants_mandatory.json");

    final String apiEndPoint = apiRequestUrl + "/organizers/" + connectorProperties.getProperty("organizerKey")
            + "/trainings/" + connectorProperties.getProperty("trainingKeyMandatory") + "/registrants";

    final RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET",
            apiRequestHeadersMap);

    final JSONArray esbArray = new JSONArray(esbRestResponse.getBody().getString("output"));
    final JSONArray apiArray = new JSONArray(apiRestResponse.getBody().getString("output"));

    Assert.assertEquals(esbArray.length(), apiArray.length());
    Assert.assertEquals(esbArray.getJSONObject(0).getString("givenName"),
            apiArray.getJSONObject(0).getString("givenName"));
    Assert.assertEquals(esbArray.getJSONObject(0).getString("email"),
            apiArray.getJSONObject(0).getString("email"));
    Assert.assertEquals(esbArray.getJSONObject(0).getString("status"),
            apiArray.getJSONObject(0).getString("status"));
}

From source file:org.schedulesdirect.grabber.ProgramTask.java

@Override
public void run() {
    long start = System.currentTimeMillis();
    DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.PROGRAMS, clnt.getHash(),
            clnt.getUserAgent(), clnt.getBaseUrl());
    try {/*from   ww w  .  j  av a2  s.  c  om*/
        JSONArray resp = Config.get().getObjectMapper().readValue(req.submitForJson(this.req), JSONArray.class);
        for (int i = 0; i < resp.length(); ++i) {
            JSONObject o = resp.getJSONObject(i);
            String id = o.optString("programID", "<unknown>");
            if (!JsonResponseUtils.isErrorResponse(o)) {
                if (id.startsWith("EP"))
                    seriesIds.add(Program.convertToSeriesId(id));
                Path p = vfs.getPath(targetDir, String.format("%s.txt", id));
                Files.write(p, o.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
            } else if (JsonResponseUtils.getErrorCode(o) == ApiResponse.INVALID_PROGID
                    || JsonResponseUtils.getErrorCode(o) == ApiResponse.PROGRAMID_QUEUED) {
                String msg = String.format("Missing program object: %s", id);
                if (!logMissingAtDebug)
                    LOG.warn(msg);
                else
                    LOG.debug(msg);
                if (retrySet != null)
                    retrySet.add(id);
            } else
                throw new InvalidJsonObjectException("Error received for Program", o.toString(3));
        }
    } catch (JSONException | JsonParseException e) {
        Grabber.failedTask = true;
        LOG.error("JSONError!", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        Grabber.failedTask = true;
        LOG.error("IOError receiving program data; filling in empty program info for non-existent program ids!",
                e);
        try {
            JSONArray ids = this.req;
            for (int i = 0; i < ids.length(); ++i) {
                String id = ids.getString(i);
                Path p = vfs.getPath(targetDir, String.format("%s.txt", id));
                if (!Files.exists(p))
                    Files.write(p, Program.EMPTY_PROGRAM.getBytes(ZipEpgClient.ZIP_CHARSET));
            }
        } catch (Exception x) {
            LOG.error("Unexpected error!", x);
            throw new RuntimeException(x);
        }
    }
    LOG.info(String.format("Completed ProgramTask in %dms [%d programs]", System.currentTimeMillis() - start,
            this.req.length()));
}