Example usage for org.json JSONArray get

List of usage examples for org.json JSONArray get

Introduction

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

Prototype

public Object get(int index) throws JSONException 

Source Link

Document

Get the object value associated with an index.

Usage

From source file:edu.wpi.margrave.SQSReader.java

protected static Formula handleStatementPAR(Object obj, String varname, String parentsortname,
        Formula theTarget, MVocab vocab, String prepend) throws MGEUnsupportedSQS, JSONException,
        MGEBadIdentifierName, MGEUnknownIdentifier, MGEManagerException {
    // obj may be a JSONObject (Principal examples)
    //   with a child with a value OR array of values

    //"Principal": {
    //"AWS": "*"/* w w  w. ja v a 2 s  .c  o  m*/
    //}

    //"Principal": {
    //"AWS": ["123456789012","555566667777"]
    //}

    // may also be a simple value (Action example)
    // or an array of values (Resource examples)

    // "Action": ["SQS:SendMessage","SQS:ReceiveMessage"],
    // "Resource": "/987654321098/queue1"

    // TODO: the example principal from "Element Descriptions" doesn't parse...
    //"Principal":[
    //             "AWS": "123456789012",
    //             "AWS": "999999999999"
    //          ]
    // is this just a bad example?

    // *****************************
    // Step 1: Is this a JSONObject? If so, it should have only one key. Prepend that key
    // to all predicate names produced by its value.
    if (obj instanceof JSONObject) {
        JSONObject jobj = (JSONObject) obj;
        JSONArray names = jobj.names();
        if (names.length() != 1)
            throw new MGEUnsupportedSQS("Number of keys != 1 as expected: " + obj.toString());

        Object inner = jobj.get((String) names.get(0));
        return handleStatementPAR(inner, varname, parentsortname, theTarget, vocab,
                prepend + MEnvironment.sIDBSeparator + names.get(0));
    }

    // Now if obj is a simple value, we have a predicate name.
    // If it is an array of length n, we have n predicate names.      
    if (obj instanceof JSONArray) {
        JSONArray jarr = (JSONArray) obj;
        HashSet<Formula> possibleValues = new HashSet<Formula>();

        for (int ii = 0; ii < jarr.length(); ii++) {
            //MEnvironment.errorStream.println(prepend+"="+jarr.get(ii));

            Formula theatom = makeSQSAtom(vocab, varname, parentsortname, prepend + "=" + jarr.get(ii));
            possibleValues.add(theatom);

        }

        theTarget = MFormulaManager.makeAnd(theTarget, MFormulaManager.makeDisjunction(possibleValues));

    } else {
        Formula theatom = makeSQSAtom(vocab, varname, parentsortname, prepend + "=" + obj);
        theTarget = MFormulaManager.makeAnd(theTarget, theatom);
    }

    return theTarget;
}

From source file:notaql.performance.PerformanceTest.java

private static List<JSONObject> readArray(Path path) throws IOException {
    final String input = Files.lines(path).collect(Collectors.joining());
    final JSONArray jsonArray = new JSONArray(input);

    final List<JSONObject> elements = new LinkedList<>();
    for (int i = 0; i < jsonArray.length(); i++) {
        final Object element = jsonArray.get(i);
        if (!(element instanceof JSONObject))
            throw new IOException("Expecting an array of objects as input.");
        elements.add((JSONObject) element);
    }//from  w  w  w.j  a va2  s . c  o m

    return elements;
}

From source file:com.epam.gepard.rest.jira.JiraSiteHandler.java

/**
 * Get a Jira query result in a map form.
 *
 * @param query is the jira query// w w w.  j  av  a  2 s.com
 * @return with the map of JIRA_ID - ticketInfo in JSONObject pairs as result of a Jira query.
 * @throws IOException   in case of problem
 * @throws JSONException in case of problem
 */
public ConcurrentHashMap<String, JSONObject> collectIssues(final String query)
        throws IOException, JSONException {
    String jqlURL = getListOfIssuesByQueryUrl(query);
    WebRequest requestSettings = new WebRequest(new URL(jqlURL), HttpMethod.GET);
    requestSettings.setAdditionalHeader("Content-type", "application/json");
    UnexpectedPage infoPage = webClient.getPage(requestSettings);
    if (infoPage.getWebResponse().getStatusCode() == HTTP_RESPONSE_OK) {
        String ticketList = infoPage.getWebResponse().getContentAsString();
        JSONObject obj = new JSONObject(ticketList);
        String maxResults = obj.getString("maxResults");
        String total = obj.getString("total");
        if (Integer.valueOf(maxResults) < Integer.valueOf(total)) {
            throw new SimpleGepardException("ERROR: Too many issues belong to given query (" + total
                    + "), please change the query to shorten the result list.");
        }
        JSONArray array = obj.getJSONArray("issues");
        ConcurrentHashMap<String, JSONObject> map = new ConcurrentHashMap<>();
        for (int i = 0; i < array.length(); i++) {
            JSONObject o = (JSONObject) array.get(i);
            map.put(o.getString("key"), o);
        }
        return map;
    }
    throw new SimpleGepardException("ERROR: Cannot fetch Issue list from JIRA, status code:"
            + infoPage.getWebResponse().getStatusCode());
}

From source file:com.epam.gepard.rest.jira.JiraSiteHandler.java

/**
 * Detect the actual workflow possibilities of the ticket, from its actual status.
 *
 * @param ticket is the id/*from   www. j av  a2 s  .  com*/
 * @return with String representation of the list of possibilities, in form of statusTransferId;newStatusName strings
 * @throws IOException   in case of problem
 * @throws JSONException in case of problem
 */
public String detectWorkflow(final String ticket) throws IOException, JSONException {
    String jqlURL;

    //first detect status
    String ticketFields = getTicketFields(ticket);
    JSONObject fieldObj = new JSONObject(ticketFields);
    fieldObj = fieldObj.getJSONObject("fields");
    fieldObj = fieldObj.getJSONObject("status");
    String status = "@" + fieldObj.get("name").toString();

    //then collect possible transactions
    jqlURL = getIssueTransitionsUrl(ticket);
    WebRequest requestSettings = new WebRequest(new URL(jqlURL), HttpMethod.GET);
    requestSettings.setAdditionalHeader("Content-type", "application/json");
    UnexpectedPage infoPage = webClient.getPage(requestSettings);
    if (infoPage.getWebResponse().getStatusCode() == HTTP_RESPONSE_OK) {
        String ticketList = infoPage.getWebResponse().getContentAsString();
        JSONObject obj = new JSONObject(ticketList);
        JSONArray array = obj.getJSONArray("transitions");
        List<String> toList = new ArrayList<>();
        toList.add(status);
        for (int i = 0; i < array.length(); i++) {
            JSONObject o = (JSONObject) array.get(i);
            JSONObject o2 = o.getJSONObject("to");
            String toPossibility = o2.get("name").toString();
            String toPossibilityID = o.get("id").toString(); //it is the transition id not the status id
            toList.add(toPossibilityID + ";" + toPossibility);
        }
        return toList.toString();
    }
    throw new SimpleGepardException("ERROR: Cannot fetch Issue transition possibilities from JIRA, for ticket: "
            + ticket + ", Status code:" + infoPage.getWebResponse().getStatusCode());
}

From source file:com.macmoim.pang.FoodListFragment.java

/**
 * Parsing json reponse and passing the data to feed view list adapter
 *//*  w ww  .jav a  2s  . c  o m*/
private void ParseJsonFeed(JSONObject response, boolean toClearArray) {
    if (mRecyclerView == null) {
        return;
    }
    if (toClearArray) {
        feedItems.clear();
    }
    try {
        if ("success".equals(response.getString("ret_val"))) {
            JSONArray feedArray = response.getJSONArray("post_info");

            int length = feedArray.length();
            for (int i = 0; i < length; i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                FoodItem item = new FoodItem();
                item.setId(feedObj.getInt("id"));
                item.setName(feedObj.getString("title"));
                item.setUserId(feedObj.getString("user_id"));
                item.setUserName(feedObj.getString("user_name"));

                // Image might be null sometimes
                String image = feedObj.isNull("img_path") ? null : feedObj.getString("img_path");
                item.setImge(image);
                item.setTimeStamp(feedObj.getString("date"));

                item.setLikeSum(feedObj.getString("like_sum"));
                String score = feedObj.getString("score");
                item.setScore("null".equals(score) ? "0" : score);

                Log.d(TAG, "parseJsonFeed dbname " + feedObj.getString("img_path"));
                feedItems.add(0, item);
            }

            // notify data changes to list adapater
            mRecyclerView.getAdapter().notifyDataSetChanged();
        } else {
            Log.e(TAG, "return fail : " + response.getString("ret_detail"));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:santandersensors_server.CollectThread.java

@Override
public void run() {
    while (true) {
        this.updateDate();
        try {//w w w. ja v  a  2  s. co m
            //Raccolgo i dati dall'url
            JsonUtils santanderJsonRaw = new JsonUtils().read(new URL(this.URL));
            //Estraggo l'array e la lista dei tipi di sensori
            JSONArray santanderJsonArray = santanderJsonRaw.getArray("markers");
            this.santanderSensorArray = this.client.getJsonArrayOnceFromCollection(this.typeColl, "type");
            for (int i = 0; i < santanderJsonArray.length(); i++) {
                try {
                    //Per ogni stringa dell'array "markers" riformatto la stringa JSON
                    this.santanderJson = (JSONObject) santanderJsonArray.get(i);
                    this.reformatJsonString();
                    //Inserisco la stringa JSON modificata nelle collection del DB
                    if (!this.issueControl()) { //controllo eventuli problemi
                        this.client.insertInCollection(this.collection, this.santanderJson);
                        this.client.insertInCollection(this.lastdataColl, this.santanderJson);
                        this.sensorsStatistics[0]++;
                    }
                    //Inserisco le stringhe dei sensori con problemi nella collection degli scarti
                    else {
                        this.client.insertInCollection(this.discardColl, this.santanderJson);
                        this.sensorsStatistics[2]++;
                    }
                } catch (Exception e) {
                    this.sensorsStatistics[1]++;
                }
            }
            //aggiorno la collection sulle informazioni dell'ultima raccolta.
            this.printStastics(); //stampo le informazioni sulla raccolta
            this.resetStatistics(); //cancello le informazioni sulla raccolta
            Thread.sleep(lapse * 1000);
            this.client.removeFromCollection(this.lastdataColl, "{}");
        } catch (Exception e) {
            System.out.print(e);
            break;
        }
    }
}

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

@Test
public void testListDeleteTags() 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);
        String gitTagUri = gitSection.getString(GitConstants.KEY_TAG);

        JSONArray tags = listTags(gitTagUri);
        assertEquals(0, tags.length());/*from w  w w. ja  v a2s. c  o  m*/

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

        JSONObject commit = commitsArray.getJSONObject(0);
        String commitId = commit.getString(ProtocolConstants.KEY_NAME);
        String commitLocation = commit.getString(ProtocolConstants.KEY_LOCATION);

        tag(gitTagUri, "tag1", commitId);

        tags = listTags(gitTagUri);
        assertEquals(1, tags.length());
        assertEquals("tag1", tags.getJSONObject(0).get(ProtocolConstants.KEY_NAME));

        // update commit with tag
        tag(commitLocation, "tag2");

        tags = listTags(gitTagUri);
        assertEquals(2, tags.length());
        assertEquals("tag2", tags.getJSONObject(0).get(ProtocolConstants.KEY_NAME));

        // delete 'tag1'
        JSONObject tag1 = tags.getJSONObject(1);
        assertEquals("tag1", tag1.get(ProtocolConstants.KEY_NAME));
        String tag1Uri = tag1.getString(ProtocolConstants.KEY_LOCATION);
        deleteTag(tag1Uri);

        tags = listTags(gitTagUri);
        assertEquals(1, tags.length());
        assertEquals("tag2", tags.getJSONObject(0).get(ProtocolConstants.KEY_NAME));

        // check if the deleted tag is gone
        request = getGetGitTagRequest(tag1Uri);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode());
    }
}

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

@Test
public void testTagFromLogAll() 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 cloneCommitUri = clone.getString(GitConstants.KEY_COMMIT);

        // 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 folderTagUri = gitSection.getString(GitConstants.KEY_TAG);

        // get the full log
        JSONArray commits = log(cloneCommitUri);
        assertEquals(1, commits.length());
        String commitLocation = commits.getJSONObject(0).getString(ProtocolConstants.KEY_LOCATION);

        // tag//from w ww.j a  v  a2s.  co  m
        tag(commitLocation, "tag1");

        // check
        JSONArray tags = listTags(folderTagUri);
        assertEquals(1, tags.length());
        assertEquals("tag1", tags.getJSONObject(0).get(ProtocolConstants.KEY_NAME));
    }
}

From source file:io.selendroid.SelendroidCapabilities.java

private Object decode(Object o) throws JSONException {
    if (o instanceof JSONArray) {
        List<Object> res = new ArrayList<Object>();
        JSONArray array = (JSONArray) o;
        for (int i = 0; i < array.length(); i++) {
            Object r = array.get(i);
            res.add(decode(r));/* w  ww. j  a  v  a  2 s.c  o  m*/
        }
        return res;
    } else {
        return o;
    }
}

From source file:com.bloc.blocparty.TimelineFragment.java

private void getFeedRequest(final Session session) {
    Bundle params = new Bundle();
    /* make the API call */
    new Request(session, "/me/home", params, HttpMethod.GET, new Request.Callback() {
        public void onCompleted(Response response) {

            GraphObject graphObject = response.getGraphObject();

            if (graphObject != null) {
                JSONObject jsonObject = graphObject.getInnerJSONObject();
                try {
                    JSONArray array = jsonObject.getJSONArray("data");

                    for (int i = 0; i < array.length(); i++) {
                        JSONObject object = (JSONObject) array.get(i);
                        //Log.d("raw object is ", object.toString());
                        if (object.has("picture")) {
                            PhotoPost post = new PhotoPost();
                            String url = object.getString("picture");
                            //Log.d("picture ", url);
                            post.setImageUrl(url);
                            post.setId(object.getString("id"));
                            if (object.has("story")) {
                                post.setStory(object.getString("story"));
                            }/*from w w w .j  a  v a2  s  .  c o m*/
                            photoArray.add(post);
                        }
                    }
                    Log.d("photoarray size is ", String.valueOf(photoArray.size()));
                    PhotoPostAdapter adapter = new PhotoPostAdapter(getActivity(), photoArray);
                    listView.setAdapter(adapter);

                    for (PhotoPost p : photoArray) {
                        p.loadImage(adapter);
                    }
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }

        }
    }).executeAsync();

}