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.eclipse.orion.server.tests.servlets.git.GitPushTest.java

@Test
public void testPushFromLog() throws Exception {
    // clone a repo
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = getClonePath(workspaceId, project);
    clone(clonePath);//from  w  w  w  .  j  a v  a 2 s.c  om

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

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

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

    // change
    JSONObject testTxt = getChild(project, "test.txt");
    modifyFile(testTxt, "incoming change");

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

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

    // log again
    JSONObject logResponse = logObject(gitHeadUri);
    assertEquals(2, logResponse.getJSONArray(ProtocolConstants.KEY_CHILDREN).length());

    JSONObject toRefBranch = logResponse.getJSONObject(GitConstants.KEY_LOG_TO_REF);
    JSONArray remoteLocations = toRefBranch.getJSONArray(GitConstants.KEY_REMOTE);
    assertEquals(1, remoteLocations.length());
    String remoteBranchLocation = remoteLocations.getJSONObject(0).getJSONArray(ProtocolConstants.KEY_CHILDREN)
            .getJSONObject(0).getString(ProtocolConstants.KEY_LOCATION);

    // push
    request = getPostGitRemoteRequest(remoteBranchLocation, Constants.HEAD, false, false);
    response = webConversation.getResponse(request);
    ServerStatus status = waitForTask(response);
    assertTrue(status.toString(), status.isOK());
}

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

@Test
public void testPushNewBranchToSecondaryRemote() throws Exception {
    // see bug 353557
    URI workspaceLocation = createWorkspace(getMethodName());
    IPath[] clonePaths = createTestProjects(workspaceLocation);
    String workspaceId = workspaceIdFromLocation(workspaceLocation);

    for (int i = 0; i < clonePaths.length; i++) {
        IPath clonePath = clonePaths[i];
        // clone a  repo
        JSONObject clone = clone(clonePath);
        String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
        String cloneLocation = clone.getString(ProtocolConstants.KEY_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 remotesLocation = clone.getString(GitConstants.KEY_REMOTE);
        // expect only origin
        getRemote(remotesLocation, 1, 0, Constants.DEFAULT_REMOTE_NAME);

        // create secondary repository
        IPath randomLocation = AllGitTests.getRandomLocation();
        randomLocation = randomLocation.addTrailingSeparator().append(Constants.DOT_GIT);
        File dotGitDir = randomLocation.toFile().getCanonicalFile();
        Repository db2 = FileRepositoryBuilder.create(dotGitDir);
        assertFalse(dotGitDir.exists());
        db2.create(false /* non bare */);

        // dummy commit to start off master branch
        File dummyFile = new File(dotGitDir.getParentFile(), "test.txt");
        dummyFile.createNewFile();/*  w  ww .ja v  a2 s. co  m*/
        createFile(dummyFile.toURI(), "dummy");
        Git git2 = new Git(db2);
        git2.add().addFilepattern(".").call();
        git2.commit().setMessage("dummy commit").call();

        // create remote
        response = addRemote(remotesLocation, "secondary", dotGitDir.getParentFile().toURL().toString());
        String secondaryRemoteLocation = response.getHeaderField(ProtocolConstants.HEADER_LOCATION);
        assertNotNull(secondaryRemoteLocation);

        // list remotes
        request = getGetRequest(remotesLocation);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject remotes = new JSONObject(response.getText());
        JSONArray remotesArray = remotes.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        // expect origin and new remote
        assertEquals(2, remotesArray.length());

        // create branch, checkout
        response = branch(branchesLocation, "branch");
        JSONObject branch = new JSONObject(response.getText());
        checkoutBranch(cloneLocation, "branch");

        // modify, add, commit
        JSONObject testTxt = getChild(folder, "test.txt");
        modifyFile(testTxt, "branch change");
        addFile(testTxt);
        commitFile(testTxt, "branch commit", false);

        // push the new branch
        JSONArray remoteBranchLocations = branch.getJSONArray(GitConstants.KEY_REMOTE);
        assertEquals(2, remoteBranchLocations.length());
        String remoteBranchLocation = null;
        if (remoteBranchLocations.getJSONObject(0).getString(ProtocolConstants.KEY_NAME).equals("secondary")) {
            remoteBranchLocation = remoteBranchLocations.getJSONObject(0)
                    .getJSONArray(ProtocolConstants.KEY_CHILDREN).getJSONObject(0)
                    .getString(ProtocolConstants.KEY_LOCATION);
        } else if (remoteBranchLocations.getJSONObject(1).getString(ProtocolConstants.KEY_NAME)
                .equals("secondary")) {
            remoteBranchLocation = remoteBranchLocations.getJSONObject(1)
                    .getJSONArray(ProtocolConstants.KEY_CHILDREN).getJSONObject(0)
                    .getString(ProtocolConstants.KEY_LOCATION);
        }
        assertNotNull(remoteBranchLocation);
        ServerStatus pushStatus = push(remoteBranchLocation, Constants.HEAD, false);
        assertTrue(pushStatus.isOK());

        // see bug 354144
        request = getGetRequest(branch.getString(ProtocolConstants.KEY_LOCATION));
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        branch = new JSONObject(response.getText());
        remoteBranchLocations = branch.getJSONArray(GitConstants.KEY_REMOTE);
        // now, there should be only one remote branch returned
        assertEquals(1, remoteBranchLocations.length());
        assertEquals("secondary", remoteBranchLocations.getJSONObject(0).getString(ProtocolConstants.KEY_NAME));
        assertEquals("secondary/branch",
                remoteBranchLocations.getJSONObject(0).getJSONArray(ProtocolConstants.KEY_CHILDREN)
                        .getJSONObject(0).getString(ProtocolConstants.KEY_NAME));

        // clone the secondary branch and check if the new branch is there
        JSONObject secondProject = createProjectOrLink(workspaceLocation, getMethodName() + "-second-" + i,
                null);
        IPath secondClonePath = getClonePath(workspaceId, secondProject);
        URIish uri = new URIish(dotGitDir.getParentFile().toURI().toURL());
        JSONObject clone2 = clone(uri, null, secondClonePath, null, null, null);
        String cloneLocation2 = clone2.getString(ProtocolConstants.KEY_LOCATION);
        String branchesLocation2 = clone2.getString(GitConstants.KEY_BRANCH);

        String remotesLocation2 = clone2.getString(GitConstants.KEY_REMOTE);
        // expecting two branches, second named "branch"
        JSONObject remoteBranch2 = getRemoteBranch(remotesLocation2, 2, 1, "branch");
        String remoteBranchName2 = remoteBranch2.getString(ProtocolConstants.KEY_NAME);

        // create tracking branch and check it out
        response = branch(branchesLocation2, null /* deduct from the remote branch name */, remoteBranchName2);
        JSONObject branch2 = new JSONObject(response.getText());
        response = checkoutBranch(cloneLocation2, branch2.getString(ProtocolConstants.KEY_NAME));
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        // check file content
        String cloneContentLocation2 = clone2.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
        request = getGetRequest(cloneContentLocation2);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject folder2 = new JSONObject(response.getText());
        JSONObject testTxt2 = getChild(folder2, "test.txt");
        assertEquals("branch change", getFileContent(testTxt2));
    }
}

From source file:nl.hnogames.domoticzapi.Parsers.SwitchesParser.java

@Override
public void parseResult(String result) {
    try {/*from  w  w w  . j a  va  2s  .c  o  m*/
        JSONArray jsonArray = new JSONArray(result);
        ArrayList<SwitchInfo> mSwitches = new ArrayList<>();

        if (jsonArray.length() > 0) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject row = jsonArray.getJSONObject(i);
                mSwitches.add(new SwitchInfo(row));
            }
        }

        switchesReceiver.onReceiveSwitches(mSwitches);
    } catch (JSONException e) {
        Log.e(TAG, "ScenesParser JSON exception");
        e.printStackTrace();
        switchesReceiver.onError(e);
    }
}

From source file:com.example.wcl.test_weiboshare.StatusList.java

public static StatusList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }//from w  w  w  . j  av a  2s. c  o m

    StatusList statuses = new StatusList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        statuses.hasvisible = jsonObject.optBoolean("hasvisible", false);
        statuses.previous_cursor = jsonObject.optString("previous_cursor", "0");
        statuses.next_cursor = jsonObject.optString("next_cursor", "0");
        statuses.total_number = jsonObject.optInt("total_number", 0);

        JSONArray jsonArray = jsonObject.optJSONArray("statuses");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            statuses.statusList = new ArrayList<Status>(length);
            for (int ix = 0; ix < length; ix++) {
                statuses.statusList.add(Status.parse(jsonArray.getJSONObject(ix)));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return statuses;
}

From source file:com.imalu.alyou.activity.ConcernlistFragment.java

public void getJsonObj(JSONArray array) throws JSONException {

    ConsernResponse con = new ConsernResponse();
    for (int i = 0; i < array.length(); i++) {
        JSONObject jsonObject = new JSONObject();
        jsonObject = array.getJSONObject(i);
        ConsernPerson person = new ConsernPerson();
        con.setJsonObject(jsonObject);/* w  w w. j  ava  2 s.co m*/
        person.setId(con.getId());
        person.setJifen(con.getJifen());
        person.setUsername(con.getUserName());
        person.setSocietykey(con.getSocietyKey());
        person.setHeadpicture(con.getHeadPicture());
        concerns.add(person);
    }

}

From source file:com.heliosapm.opentsdb.client.opentsdb.OpenTsdbPutResponseHandler.java

/**
 * Handles reported errors in the metrics post response
 * @param arr The JSON array of errors/*  w ww  .ja v a 2s.com*/
 * @param log The logger to log the errors with
 */
protected static void processErrors(final JSONArray arr, final Logger log) {
    if (arr == null || arr.length() < 1)
        return;
    try {
        final int sz = arr.length();
        for (int i = 0; i < sz; i++) {
            JSONObject dp = arr.getJSONObject(i).getJSONObject("datapoint");
            log.error("BAD METRIC: metric:{}, tags:{}", dp.get("metric"), dp.get("tags"));
            // TODO: build a metric name that can be used to filter submissions 
            // so these don't get sent again.
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }
}

From source file:com.liferay.mobile.android.v62.announcementsflag.AnnouncementsFlagService.java

public JSONObject getFlag(long entryId, int value) throws Exception {
    JSONObject _command = new JSONObject();

    try {/*from w  w w .j a  v  a 2 s .  co  m*/
        JSONObject _params = new JSONObject();

        _params.put("entryId", entryId);
        _params.put("value", value);

        _command.put("/announcementsflag/get-flag", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}

From source file:com.nosoop.json.VDF.java

/**
 * Recursively searches for JSONObjects, checking if they should be
 * formatted as arrays, then converted./*from ww  w .  jav a2 s .c  o  m*/
 *
 * @param object An input JSONObject converted from VDF.
 * @return JSONObject containing the input JSONObject with objects changed
 * to arrays where applicable.
 * @throws JSONException
 */
private static JSONObject convertVDFArrays(JSONObject object) throws JSONException {
    JSONObject resp = new JSONObject();

    if (!object.keys().hasNext()) {
        return resp;
    }

    for (@SuppressWarnings("unchecked")
    Iterator<String> iter = object.keys(); iter.hasNext();) {
        String name = iter.next();
        JSONObject thing = object.optJSONObject(name);

        if (thing != null) {
            // Note:  Empty JSONObjects are also treated as arrays.
            if (containsVDFArray(thing)) {
                @SuppressWarnings("unchecked")
                Iterator<String> iter2 = thing.keys();
                List<String> sortingKeys = new ArrayList<String>();
                while (iter2.hasNext())
                    sortingKeys.add(iter2.next());
                Collections.sort(sortingKeys, new Comparator<String>() {
                    // Integers-as-strings comparator.
                    @Override
                    public int compare(String t, String t1) {
                        int i = Integer.parseInt(t), i1 = Integer.parseInt(t1);
                        return i - i1;
                    }
                });

                JSONArray sortedKeys = new JSONArray(sortingKeys);

                if (sortedKeys.length() > 0) {
                    JSONArray sortedObjects = thing.toJSONArray(sortedKeys);

                    for (int i = 0; i < sortedObjects.length(); i++) {
                        JSONObject arrayObject = sortedObjects.getJSONObject(i);

                        /**
                         * See if any values are also JSONObjects that
                         * should be arrays.
                         */
                        sortedObjects.put(i, convertVDFArrays(arrayObject));
                    }

                    /**
                     * If this JSONObject represents a non-empty array in
                     * VDF format, convert it to a JSONArray.
                     */
                    resp.put(name, sortedObjects);
                } else {
                    /**
                     * If this JSONObject represents an empty array, give it
                     * an empty JSONArray.
                     */
                    resp.put(name, new JSONArray());
                }
            } else {
                /**
                 * If this JSONObject is not a VDF array, see if its values
                 * are before adding.
                 */
                resp.put(name, convertVDFArrays(thing));
            }
        } else {
            /**
             * It's a plain data value. Add it in.
             */
            resp.put(name, object.get(name));
        }
    }

    /**
     * Return the converted JSONObject.
     */
    return resp;
}

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

public ItemPowerCube(JSONArray json) throws JSONException {
    super(ItemType.PowerCube, json);

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

    mEnergy = powerCube.getInt("energy");
}

From source file:com.jennifer.ui.chart.widget.LegendWidget.java

@Override
public Object draw() {

    double x = 0, y = 0, total_width = 0, total_height = 0, max_width = 0, max_height = 0;

    for (int i = 0, len = brush.length(); i < len; i++) {
        int index = brush.getInt(i);
        JSONObject brushObject = chart.brush(index);

        JSONArray arr = getLegendIcon(brushObject);

        for (int k = 0, kLen = arr.length(); k < kLen; k++) {
            JSONObject obj = arr.getJSONObject(k);

            double w = obj.getDouble("width");
            double h = obj.getDouble("height");
            Transform icon = (Transform) obj.get("icon");

            //root.append(icon);
            icon.translate(x, y);/*from  w ww.j a  va 2s . c  o  m*/

            if ("bottom".equals(position) || "top".equals(position)) {
                x += w;
                total_width += w;

                if (max_height < h) {
                    max_height = h;
                }
            } else {
                y += h;
                total_height += h;

                if (max_width < w) {
                    max_width = w;
                }
            }

        }
    }

    if ("bottom".equals(position) || "top".equals(position)) {
        y = ("bottom".equals(position)) ? chart.area("y2") + chart.padding("bottom") - max_height
                : chart.area("y") - chart.padding("top");

        if ("start".equals(align)) {
            x = chart.area("x");
        } else if ("center".equals(align)) {
            x = chart.area("x") + (chart.area("width") / 2.0 - total_width / 2.0);
        } else if ("end".equals(align)) {
            x = chart.area("x2") - total_width;
        }

    } else {
        x = ("left".equals(position)) ? chart.area("x") - max_width : chart.area("x2") + 20;

        if ("start".equals(align)) {
            y = chart.area("y");
        } else if ("center".equals(align)) {
            y = chart.area("y") + (chart.area("height") / 2.0 - total_height / 2.0);
        } else if ("end".equals(align)) {
            y = chart.area("y2") - total_height;
        }

    }

    root.translate(x + 0.5, y + 0.5);

    return new JSONObject().put("root", root);
}