Example usage for org.json JSONObject optJSONObject

List of usage examples for org.json JSONObject optJSONObject

Introduction

In this page you can find the example usage for org.json JSONObject optJSONObject.

Prototype

public JSONObject optJSONObject(String key) 

Source Link

Document

Get an optional JSONObject associated with a key.

Usage

From source file:ee.vvk.ivotingverification.util.JSONParser.java

private void parseJsonColors(JSONObject json) throws JSONException {
    colors = json.optJSONObject(TAG_COLORS);
    if (colors.length() > 0) {
        C.frameBackground = colors.optString("frame_background", C.frameBackground);
        C.mainWindowForeground = colors.optString("main_window_foreground", C.mainWindowForeground);
        C.errorWindowForeground = colors.optString("error_window_foreground", C.errorWindowForeground);
        C.loadingWindow = colors.optString("loading_window_background", C.loadingWindow);
        C.loadingWindowForeground = colors.optString("loading_window_foreground", C.loadingWindowForeground);
        C.mainWindow = colors.optString("main_window", C.mainWindow);
        C.mainWindowShadow = colors.optString("main_window_shadow", C.mainWindowShadow);
        C.errorWindow = colors.optString("error_window", C.errorWindow);
        C.errorWindowShadow = colors.optString("error_window_shadow", C.errorWindowShadow);
        C.btnBackground = colors.optString("btn_background", C.btnBackground);
        C.btnForeground = colors.optString("btn_foreground", C.btnForeground);
        C.btnVerifyForeground = colors.optString("btn_verify_foreground", C.btnVerifyForeground);
        C.btnVerifyBackgroundStart = colors.optString("btn_verify_background_start",
                C.btnVerifyBackgroundStart);
        C.btnVerifyBackgroundCenter = colors.optString("btn_verify_background_center",
                C.btnVerifyBackgroundCenter);
        C.btnVerifyBackgroundEnd = colors.optString("btn_verify_background_end", C.btnVerifyBackgroundEnd);
        C.lblBackground = colors.optString("lbl_background", C.lblBackground);
        C.lblForeground = colors.optString("lbl_foreground", C.lblForeground);
        C.lblShadow = colors.optString("lbl_shadow", C.lblShadow);
        C.lblOuterContainerBackground = colors.optString("lbl_outer_container_background",
                C.lblOuterContainerBackground);
        C.lblOuterContainerForeground = colors.optString("lbl_outer_container_foreground",
                C.lblOuterContainerForeground);
        C.lblInnerContainerBackground = colors.optString("lbl_inner_container_background",
                C.lblInnerContainerBackground);
        C.lblInnerContainerForeground = colors.optString("lbl_inner_container_foreground",
                C.lblInnerContainerForeground);
        C.lblCloseTimeoutForeground = colors.optString("lbl_close_timeout_foreground",
                C.lblCloseTimeoutForeground);
        C.lblCloseTimeoutBackgroundStart = colors.optString("lbl_close_timeout_background_start",
                C.lblCloseTimeoutBackgroundStart);
        C.lblCloseTimeoutBackgroundCenter = colors.optString("lbl_close_timeout_background_center",
                C.lblCloseTimeoutBackgroundCenter);
        C.lblCloseTimeoutBackgroundEnd = colors.optString("lbl_close_timeout_background_end",
                C.lblCloseTimeoutBackgroundEnd);
        C.lblCloseTimeoutShadow = colors.optString("lbl_close_timeout_shadow", C.lblCloseTimeoutShadow);
        C.lblOuterInnerContainerDivider = colors.optString("lbl_outer_inner_container_divider",
                C.lblOuterInnerContainerDivider);
    }/*from ww w. j a v  a 2 s  .c om*/
}

From source file:ee.vvk.ivotingverification.util.JSONParser.java

private void parseJsonParams(JSONObject json) throws JSONException {
    params = json.optJSONObject(TAG_PARAMS);
    if (params.length() > 0) {
        C.appURL = params.optString("app_url", C.appURL);
        C.helpURL = params.optString("help_url", C.helpURL);
        C.closeTimeout = params.optInt("close_timeout", C.closeTimeout);
        C.closeInterval = params.optInt("close_interval", C.closeInterval);
        C.publicKey = params.optString("public_key", C.publicKey);
    }//from   w  w w  .ja  v a2s . co m
}

From source file:ee.vvk.ivotingverification.util.JSONParser.java

private void parseJsonElections(JSONObject json) throws JSONException {
    elections = json.optJSONObject(TAG_ELECTIONS);
    if (elections.length() > 0) {
        Iterator<String> myIter = elections.keys();
        HashMap<String, String> electionsMap = new HashMap<String, String>();

        while (myIter.hasNext()) {
            String tempValue = myIter.next();
            electionsMap.put(tempValue, elections.optString(tempValue, tempValue));
        }// w  w  w  .  j  a  v a 2s  .  c om
        C.elections = electionsMap;
    }
}

From source file:com.phelps.liteweibo.model.weibo.Group.java

public static Group parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }//  ww  w  .j  av  a 2s .  c  o m

    Group group = new Group();
    group.user = User.parse(jsonObject.optJSONObject("user"));
    group.id = jsonObject.optString("id");
    group.idStr = jsonObject.optString("idstr");
    group.name = jsonObject.optString("name");
    group.mode = jsonObject.optString("mode");
    group.visible = jsonObject.optInt("visible");
    group.like_count = jsonObject.optInt("like_count");
    group.member_count = jsonObject.optInt("member_count");
    group.description = jsonObject.optString("description");
    group.profile_image_url = jsonObject.optString("profile_image_url");
    group.createAtTime = jsonObject.optString("create_time", "");

    JSONArray jsonArray = jsonObject.optJSONArray("tags");
    if (jsonArray != null && jsonObject.length() > 0) {
        int length = jsonArray.length();
        group.tags = new ArrayList<Tag>(length);
        for (int ix = 0; ix < length; ix++) {
            group.tags.add(Tag.parse(jsonArray.optJSONObject(ix)));
        }
    }

    return group;
}

From source file:org.catnut.metadata.Comment.java

@Override
public ContentValues convert(JSONObject data) {
    ContentValues values = new ContentValues();
    values.put(BaseColumns._ID, data.optLong(Constants.ID));
    values.put(created_at, data.optString(created_at));
    values.put(columnText, data.optString(text));
    values.put(source, data.optString(source));
    JSONObject user = data.optJSONObject(User.SINGLE);
    if (user != null) {
        values.put(uid, user.optLong(Constants.ID));
    }/*from w ww.ja  v  a 2s  .com*/
    values.put(status, data.optString(status));
    values.put(reply_comment, data.optString(reply_comment));
    return values;
}

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

@Test
public void testPushBranch() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);

    // clone1: create
    JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null);
    IPath clonePath1 = getClonePath(workspaceId, project1);
    JSONObject clone1 = clone(clonePath1);
    String cloneLocation1 = clone1.getString(ProtocolConstants.KEY_LOCATION);
    String branchesLocation1 = clone1.getString(GitConstants.KEY_BRANCH);

    // get project1 metadata
    WebRequest request = getGetRequest(project1.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project1 = new JSONObject(response.getText());
    JSONObject gitSection1 = project1.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection1);/*from ww w. j  a  va  2 s  .  com*/
    String gitIndexUri1 = gitSection1.getString(GitConstants.KEY_INDEX);
    String gitHeadUri1 = gitSection1.getString(GitConstants.KEY_HEAD);

    // clone1: branch 'a'
    response = branch(branchesLocation1, "a");
    JSONObject branch = new JSONObject(response.getText());

    checkoutBranch(cloneLocation1, "a");

    // clone1: change
    JSONObject testTxt1 = getChild(project1, "test.txt");
    modifyFile(testTxt1, "branch 'a' change");

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

    // clone1: commit
    request = GitCommitTest.getPostGitCommitRequest(gitHeadUri1, "incoming branch 'a' commit", false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    // clone1: push by remote branch
    JSONArray remoteBranchLocations = branch.getJSONArray(GitConstants.KEY_REMOTE);
    assertEquals(1, remoteBranchLocations.length());
    String remoteBranchLocation = remoteBranchLocations.getJSONObject(0)
            .getJSONArray(ProtocolConstants.KEY_CHILDREN).getJSONObject(0)
            .getString(ProtocolConstants.KEY_LOCATION);
    ServerStatus pushStatus = push(remoteBranchLocation, Constants.HEAD, false);
    assertTrue(pushStatus.isOK());

    // clone1: get the remote branch name
    request = getGetRequest(remoteBranchLocation);
    response = webConversation.getResponse(request);
    JSONObject remoteBranch1 = new JSONObject(response.getText());
    String remoteBranchName1 = remoteBranch1.getString(ProtocolConstants.KEY_NAME);

    // clone2
    JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null);
    IPath clonePath2 = getClonePath(workspaceId, project2);
    JSONObject clone2 = clone(clonePath2);
    String cloneLocation2 = clone2.getString(ProtocolConstants.KEY_LOCATION);
    String branchesLocation2 = clone2.getString(GitConstants.KEY_BRANCH);

    // get project2 metadata
    request = getGetRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project2 = new JSONObject(response.getText());
    JSONObject gitSection2 = project2.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection2);

    // create a local branch 'a' tracking remoteBranchName1 and checkout 'a'
    response = branch(branchesLocation2, "a", remoteBranchName1);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    response = checkoutBranch(cloneLocation2, "a");
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

    JSONObject testTxt2 = getChild(project2, "test.txt");
    request = getGetRequest(testTxt2.getString(ProtocolConstants.KEY_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals("branch 'a' change", response.getText());
}

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

@Test
public void testPushRejected() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);

    // clone1/*  w  ww.j  a v a2  s. co m*/
    JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null);
    IPath clonePath1 = getClonePath(workspaceId, project1);
    clone(clonePath1);

    // get project1 metadata
    WebRequest request = getGetRequest(project1.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project1 = new JSONObject(response.getText());
    JSONObject gitSection1 = project1.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection1);
    String gitRemoteUri1 = gitSection1.optString(GitConstants.KEY_REMOTE);
    String gitIndexUri1 = gitSection1.optString(GitConstants.KEY_INDEX);
    String gitHeadUri1 = gitSection1.optString(GitConstants.KEY_HEAD);

    // clone2
    JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null);
    IPath clonePath2 = getClonePath(workspaceId, project2);
    clone(clonePath2);

    // get project2 metadata
    request = getGetRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project2 = new JSONObject(response.getText());
    JSONObject gitSection2 = project2.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection2);
    String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);
    String gitIndexUri2 = gitSection2.getString(GitConstants.KEY_INDEX);
    String gitHeadUri2 = gitSection2.getString(GitConstants.KEY_HEAD);

    // clone1: change
    JSONObject testTxt1 = getChild(project1, "test.txt");
    modifyFile(testTxt1, "clone1 change");

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

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

    // clone1: push
    ServerStatus pushStatus = push(gitRemoteUri1, 1, 0, Constants.MASTER, Constants.HEAD, false);
    assertEquals(true, pushStatus.isOK());

    // clone2: change
    JSONObject testTxt2 = getChild(project2, "test.txt");
    modifyFile(testTxt2, "clone2 change");

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

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

    // clone2: push
    pushStatus = push(gitRemoteUri2, 1, 0, Constants.MASTER, Constants.HEAD, false);
    assertEquals(IStatus.WARNING, pushStatus.getSeverity());

    Status pushResult = Status.valueOf(pushStatus.getMessage());
    assertEquals(Status.REJECTED_NONFASTFORWARD, pushResult);
}

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

@Test
public void testPushTags() throws Exception {
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);

    // clone1/*  w w  w. jav  a  2s.  co  m*/
    JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null);
    IPath clonePath1 = getClonePath(workspaceId, project1);
    clone(clonePath1);

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

    JSONObject gitSection1 = project1.optJSONObject(GitConstants.KEY_GIT);
    assertNotNull(gitSection1);
    String gitRemoteUri1 = gitSection1.optString(GitConstants.KEY_REMOTE);
    String gitTagUri1 = gitSection1.optString(GitConstants.KEY_TAG);

    // clone2
    JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null);
    IPath clonePath2 = getClonePath(workspaceId, project2);
    clone(clonePath2);

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

    JSONObject gitSection2 = project2.getJSONObject(GitConstants.KEY_GIT);
    String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);
    String gitHeadUri2 = gitSection2.getString(GitConstants.KEY_HEAD);
    String gitTagUri2 = gitSection2.getString(GitConstants.KEY_TAG);

    // clone1: tag HEAD with 'tag'
    tag(gitTagUri1, "tag", Constants.HEAD);

    ServerStatus pushStatus = push(gitRemoteUri1, 1, 0, Constants.MASTER, Constants.HEAD, true);
    assertEquals(true, pushStatus.isOK());

    // clone2: list tags
    JSONArray tags = listTags(gitTagUri2);
    assertEquals(0, tags.length());

    // clone2: fetch + merge
    JSONObject remoteBranch = getRemoteBranch(gitRemoteUri2, 1, 0, Constants.MASTER);
    String remoteBranchLocation2 = remoteBranch.getString(ProtocolConstants.KEY_LOCATION);
    fetch(remoteBranchLocation2);
    String id = remoteBranch.getString(ProtocolConstants.KEY_ID);
    merge(gitHeadUri2, id);

    // clone2: list tags again
    tags = listTags(gitTagUri2);
    assertEquals(1, tags.length());
}

From source file:org.uiautomation.ios.mobileSafari.events.inserted.ChildIframeInserted.java

public ChildIframeInserted(JSONObject message) throws JSONException {
    super(message);

    JSONObject params = message.optJSONObject("params").getJSONObject("node");

    JSONObject json = params.getJSONObject("contentDocument");
    contentDocument = new NodeId(json.getInt("nodeId"));
}

From source file:de.jaetzold.philips.hue.HueBridge.java

/**
 * Attempt to verify the given username is allowed to access the bridge instance.
 * If the username is not allowed (or not given, meaning <code>null</code>) and <code>waitForGrant</code> is <code>true</code>,
 * the method then waits for up to 30 seconds to be granted access to the bridge. This would be done by pressing the bridges button.
 * If authentication succeeds, the username for which it succeeded is then saved and the method returns <code>true</code>.
 *
 * <p>See <a href="http://developers.meethue.com/4_configurationapi.html#41_create_user">Philips hue API, Section 4.1</a> for further reference.</p>
 *
 * @see #authenticate(boolean)//from  w  ww  .j  av a2s .  co  m
 *
 * @param usernameToTry a username to authenticate with or null if a new one should be generated by the bridge if access is granted through pressing the hardware button.
 * @param waitForGrant if true, this method blocks for up to 30 seconds or until access to the bridge is allowed, whichever comes first.
 *
 * @return true, if this bridge API instance has now a username that is verified to be allowed to access the bridge device.
 */
public boolean authenticate(String usernameToTry, boolean waitForGrant) {
    if (usernameToTry != null && !usernameToTry.matches("\\s*[-\\w]{10,40}\\s*")) {
        throw new IllegalArgumentException(
                "A username must be 10-40 characters long and may only contain the characters -,_,a-b,A-B,0-9");
    }

    if (!isAuthenticated() || !equalEnough(username, usernameToTry)) {
        // if we have an usernameToTry then check that first whether it already exists
        // I just don't get why a "create new user" request for an existing user results in the same 101 error as when the user does not exist.
        // But for this reason this additional preliminary request is necessary.
        if (!equalEnough(null, usernameToTry)) {
            try {
                completeSync(usernameToTry);
                authenticated = true;
            } catch (HueCommException e) {
                e.printStackTrace();
            }
        }

        if (!isAuthenticated()) {
            long start = System.currentTimeMillis();
            int waitSeconds = 30;
            do {
                JSONObject response = new JSONObject();
                try {
                    final JSONWriter jsonWriter = new JSONStringer().object().key("devicetype")
                            .value(deviceType);
                    if (usernameToTry != null && usernameToTry.trim().length() >= 10) {
                        jsonWriter.key("username").value(usernameToTry.trim());
                    }
                    // use comm directly here because the user is not currently set
                    response = comm.request(POST, "api", jsonWriter.endObject().toString()).get(0);
                } catch (IOException e) {
                    log.log(Level.WARNING, "IOException on create user request", e);
                }
                final JSONObject success = response.optJSONObject("success");
                if (success != null && success.has("username")) {
                    username = success.getString("username");
                    authenticated = true;
                    waitForGrant = false;
                } else {
                    final JSONObject error = response.optJSONObject("error");
                    if (error != null && error.has("type")) {
                        if (error.getInt("type") != 101) {
                            log.warning("Got unexpected error on create user: " + error);
                            waitForGrant = false;
                        }
                    }
                }
                if (waitForGrant) {
                    if (System.currentTimeMillis() - start > waitSeconds * 1000) {
                        waitForGrant = false;
                    } else {
                        try {
                            Thread.sleep(900 + Math.round(Math.random() * 100));
                        } catch (InterruptedException e) {
                        }
                    }
                }
            } while (waitForGrant);
        }
    }

    if (isAuthenticated() && !initialSyncDone) {
        completeSync(username);
    }

    return isAuthenticated();
}