Example usage for org.json JSONObject has

List of usage examples for org.json JSONObject has

Introduction

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

Prototype

public boolean has(String key) 

Source Link

Document

Determine if the JSONObject contains a specific key.

Usage

From source file:com.github.cambierr.lorawanpacket.semtech.PushData.java

public PushData(byte[] _randoms, ByteBuffer _raw) throws MalformedPacketException {
    super(_randoms, PacketType.PUSH_DATA);
    _raw.order(ByteOrder.LITTLE_ENDIAN);

    if (_raw.remaining() < 8) {
        throw new MalformedPacketException("too short");
    }/*from  w w  w.j  av a  2 s .  c  o m*/

    gatewayEui = new byte[8];
    _raw.get(gatewayEui);

    byte[] json = new byte[_raw.remaining()];
    _raw.get(json);
    JSONObject jo;

    try {
        jo = new JSONObject(new String(json));
    } catch (JSONException ex) {
        throw new MalformedPacketException("malformed json");
    }

    stats = new ArrayList<>();
    rxpks = new ArrayList<>();

    if (jo.has("rxpk")) {
        if (!jo.get("rxpk").getClass().equals(JSONArray.class)) {
            throw new MalformedPacketException("malformed json (rxpk)");
        }
        JSONArray rxpk = jo.getJSONArray("rxpk");

        for (int i = 0; i < rxpk.length(); i++) {
            rxpks.add(new Rxpk(rxpk.getJSONObject(i)));
        }
    }

    if (jo.has("stat")) {
        if (!jo.get("stat").getClass().equals(JSONArray.class)) {
            throw new MalformedPacketException("malformed json (stat)");
        }
        JSONArray stat = jo.getJSONArray("stat");

        for (int i = 0; i < stat.length(); i++) {
            stats.add(new Stat(stat.getJSONObject(i)));
        }
    }

}

From source file:edu.rit.csh.androidwebnews.SearchActivity.java

@Override
public void update(String jsonString) {
    JSONObject obj;
    if (jsonString.startsWith("Error:")) { // error in the Async Task
        ConnectionExceptionDialog dialog = new ConnectionExceptionDialog(this, jsonString);
        dialog.show();/*from  www . ja v  a2s  .  co  m*/
    } else {
        try {
            obj = new JSONObject(jsonString);
            if (obj.has("error")) {
                if (!dialog.isShowing()) {
                    dialog.show();
                }
            } else if (obj.has("newsgroups")) {
                sf.update(hc.getNewsGroupFromString(jsonString));
            }

        } catch (JSONException ignored) {

        }
    }
}

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

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

    for (IPath[] clonePath : clonePaths) {
        // clone 1
        JSONObject clone1 = clone(clonePath[0]);
        String cloneLocation1 = clone1.getString(ProtocolConstants.KEY_LOCATION);
        String contentLocation1 = clone1.getString(ProtocolConstants.KEY_CONTENT_LOCATION);
        String branchesLocation1 = clone1.getString(GitConstants.KEY_BRANCH);

        // clone 1 - get project1 metadata
        WebRequest request = getGetRequest(contentLocation1);
        WebResponse response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project1 = new JSONObject(response.getText());
        JSONObject gitSection1 = project1.getJSONObject(GitConstants.KEY_GIT);
        String gitRemoteUri1 = gitSection1.getString(GitConstants.KEY_REMOTE);
        String gitIndexUri1 = gitSection1.getString(GitConstants.KEY_INDEX);
        String gitHeadUri1 = gitSection1.getString(GitConstants.KEY_HEAD);

        // clone 1 - create branch "a"
        response = branch(branchesLocation1, "a");
        JSONObject newBranch = new JSONObject(response.getText());
        JSONArray remoteBranchLocations1 = newBranch.getJSONArray(GitConstants.KEY_REMOTE);
        assertEquals(1, remoteBranchLocations1.length());

        // clone 1 - checkout "a"
        final String newBranchName = "a";
        response = checkoutBranch(cloneLocation1, newBranchName);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

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

        // clone 1 - add
        request = GitAddTest.getPutGitIndexRequest(gitIndexUri1);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

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

        // clone 1 - push "a"
        int i = 0;
        String remoteBranchName = remoteBranchLocations1.getJSONObject(0)
                .getJSONArray(ProtocolConstants.KEY_CHILDREN).getJSONObject(i)
                .getString(ProtocolConstants.KEY_NAME);
        if (!remoteBranchName.equals("origin/a")) {
            i = 1;/*  w w w  . ja v a  2s. co m*/
            remoteBranchName = remoteBranchLocations1.getJSONObject(0)
                    .getJSONArray(ProtocolConstants.KEY_CHILDREN).getJSONObject(i)
                    .getString(ProtocolConstants.KEY_NAME);
        }
        assertEquals("origin/a", remoteBranchName);
        String remoteBranchLocation1 = remoteBranchLocations1.getJSONObject(0)
                .getJSONArray(ProtocolConstants.KEY_CHILDREN).getJSONObject(i)
                .getString(ProtocolConstants.KEY_LOCATION);
        ServerStatus pushStatus = push(remoteBranchLocation1, Constants.HEAD, false);
        assertEquals(true, pushStatus.isOK());

        // clone 1 - list remote branches - expect 2
        JSONObject remote1 = getRemote(gitRemoteUri1, 1, 0, Constants.DEFAULT_REMOTE_NAME);
        String remoteLocation1 = remote1.getString(ProtocolConstants.KEY_LOCATION);

        request = GitRemoteTest.getGetGitRemoteRequest(remoteLocation1);
        response = webConversation.getResponse(request);
        ServerStatus status = waitForTask(response);
        assertTrue(status.toString(), status.isOK());
        remote1 = status.getJsonData();
        JSONArray refsArray = remote1.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        assertEquals(2, refsArray.length());
        JSONObject ref = refsArray.getJSONObject(0);
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + newBranchName,
                ref.getString(ProtocolConstants.KEY_FULL_NAME));
        ref = refsArray.getJSONObject(1);
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER,
                ref.getString(ProtocolConstants.KEY_FULL_NAME));

        // clone 2 
        JSONObject clone2 = clone(clonePath[1]);
        String cloneLocation2 = clone2.getString(ProtocolConstants.KEY_LOCATION);
        String contentLocation2 = clone2.getString(ProtocolConstants.KEY_CONTENT_LOCATION);

        // clone 2 - get project2 metadata
        request = getGetRequest(contentLocation2);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        JSONObject project2 = new JSONObject(response.getText());
        JSONObject gitSection2 = project2.getJSONObject(GitConstants.KEY_GIT);
        String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE);

        // clone 2 - check if the branch "a" is available
        JSONObject remote2 = getRemote(gitRemoteUri2, 1, 0, Constants.DEFAULT_REMOTE_NAME);
        String remoteLocation2 = remote2.getString(ProtocolConstants.KEY_LOCATION);

        request = GitRemoteTest.getGetGitRemoteRequest(remoteLocation2);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        remote2 = new JSONObject(response.getText());
        refsArray = remote2.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        assertEquals(2, refsArray.length());
        ref = refsArray.getJSONObject(0);
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER,
                ref.getString(ProtocolConstants.KEY_FULL_NAME));
        ref = refsArray.getJSONObject(1);
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + newBranchName,
                ref.getString(ProtocolConstants.KEY_FULL_NAME));
        String remoteBranchLocation2 = ref.getString(ProtocolConstants.KEY_LOCATION);

        // clone 2 - checkout branch "a"
        response = checkoutBranch(cloneLocation2, newBranchName);

        // clone 1 - delete remote branch "a"
        push(remoteBranchLocation1, "", false, false);

        // clone 1 - list remote branches - expect 1
        request = GitRemoteTest.getGetGitRemoteRequest(remoteLocation1);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        remote1 = new JSONObject(response.getText());
        refsArray = remote1.getJSONArray(ProtocolConstants.KEY_CHILDREN);
        assertEquals(1, refsArray.length());
        ref = refsArray.getJSONObject(0);
        assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER,
                ref.getString(ProtocolConstants.KEY_FULL_NAME));

        // clone 2 - fetch
        request = GitFetchTest.getPostGitRemoteRequest(remoteBranchLocation2, true, false);
        response = webConversation.getResponse(request);
        status = waitForTask(response);
        assertFalse(status.toString(), status.isOK());

        // clone 2 - fetch task should fail
        JSONObject statusJson = status.toJSON();
        JSONObject result = statusJson.has("Result") ? statusJson.getJSONObject("Result") : statusJson;
        assertEquals("Error", result.getString("Severity"));
    }
}

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

@Test
public void testPushRemoteRejected() 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 a2s. 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 gitRemoteUri = gitSection.getString(GitConstants.KEY_REMOTE);

    // 1st commit
    JSONObject testTxt = getChild(project, "test.txt");
    modifyFile(testTxt, "1st change");
    addFile(testTxt);
    commitFile(testTxt, "1st change commit", false);

    // push
    ServerStatus pushStatus = push(gitRemoteUri, 1, 0, Constants.MASTER, Constants.HEAD, false);
    assertEquals(IStatus.OK, pushStatus.getSeverity());

    // 2nd commit
    modifyFile(testTxt, "2nd change");
    addFile(testTxt);
    commitFile(testTxt, "2nd change commit", false);

    FileUtils.delete(new File(gitDir, Constants.DOT_GIT + "/objects/pack/"), FileUtils.RECURSIVE);

    pushStatus = push(gitRemoteUri, 1, 0, Constants.MASTER, Constants.HEAD, false);
    assertEquals(IStatus.WARNING, pushStatus.getSeverity());
    Status pushResult = Status.valueOf(pushStatus.getMessage());
    assertEquals(Status.REJECTED_OTHER_REASON, pushResult);
    JSONObject jsonResult = pushStatus.toJSON();
    if (jsonResult.has("JsonData")) {
        jsonResult = jsonResult.getJSONObject("JsonData");
    }
    assertTrue(jsonResult.toString(), jsonResult.has("DetailedMessage"));
    assertTrue(jsonResult.getString("DetailedMessage"),
            jsonResult.getString("DetailedMessage").matches("^object [\\da-f]+ missing$"));
}

From source file:com.cloverstudio.spika.couchdb.ConnectionHandler.java

public static String getError(InputStream inputStream) throws IOException, JSONException {

    String error = "Unknown Spika Error: ";

    String jsonString = getString(inputStream);
    JSONObject jsonObject = jObjectFromString(jsonString);
    if (jsonObject.has("message")) {
        error = jsonObject.getString("message");
    } else {// www.j  ava2  s.c  om
        error += jsonObject.toString();
    }
    return error;
}

From source file:com.cloverstudio.spika.couchdb.ConnectionHandler.java

public static String getError(JSONObject jsonObject) {

    String error = "Unknown Spika Error: ";

    if (jsonObject.has("message")) {
        try {//from ww w  . j a  v  a 2  s  . co  m
            error = jsonObject.getString("message");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        error += jsonObject.toString();
    }
    return error;
}

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)//  w w  w.j av a2s. c  om
 *
 * @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();
}

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

private void completeSync(String username) {
    try {/*from w  w w . j a  va  2 s  .c o  m*/
        final List<JSONObject> response = comm.request(GET, "api/" + username.trim(), "");
        if (response.size() > 0) {
            final JSONObject datastore = response.get(0);
            if (datastore.has("error")) {
                throw new HueCommException(datastore.getJSONObject("error"));
            }
            if (datastore.has("config") && datastore.has("lights") && datastore.has("groups")) {
                parseConfig(datastore.getJSONObject("config"));
                parseLights(datastore.getJSONObject("lights"));
                parseGroups(datastore.getJSONObject("groups"));
                this.setUsername(username);
                initialSyncDone = true;
            } else {
                throw new HueCommException("Incomplete response. Missing at least one of config/lights/groups");
            }
        } else {
            throw new HueCommException("Empty response");
        }
    } catch (IOException e) {
        throw new HueCommException(e);
    }
}

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

List<JSONObject> checkedSuccessRequest(HueBridgeComm.RM method, String userPath, Object json) {
    final List<JSONObject> response = request(method, userPath, json);
    for (JSONObject entry : response) {
        if (!entry.has("success")) {
            throw new HueCommException(entry.getJSONObject("error"));
        }/*from w  w  w. j  a  va2  s. com*/
    }
    return response;
}

From source file:jessmchung.groupon.parsers.PriceParser.java

@Override
public Price parse(JSONObject json) throws JSONException {
    Price obj = new Price();
    if (json.has("currencyCode"))
        obj.setCurrencyCode(json.getString("currencyCode"));
    if (json.has("amount"))
        obj.setAmount(json.getDouble("amount"));
    if (json.has("formattedAmount"))
        obj.setFormattedAmount(json.getString("formattedAmount"));

    return obj;//  ww  w .  j  a v a 2 s . com
}