Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

From source file:ai.susi.mind.SusiThought.java

public String getObservation(String featureName) {
    JSONArray table = this.getData();
    if (table != null && table.length() > 0) {
        for (int rc = 0; rc < table.length(); rc++) {
            JSONObject row = table.getJSONObject(rc);
            for (String key : row.keySet()) {
                if (key.equals(featureName))
                    return row.get(key).toString();
            }//  w w w. j av  a 2 s. c  om
        }
    }
    return null;
}

From source file:ai.susi.mind.SusiThought.java

/**
 * Unification applies a piece of memory within the current argument to a statement
 * which creates an instantiated statement
 * @param statement/*from   w  ww. j  a  v a  2s.  c  o m*/
 * @return the instantiated statement with elements of the argument applied as much as possible
 */
public String unify(String statement) {
    if (statement.indexOf('$') < 0)
        return statement;
    JSONArray table = this.getData();
    if (table != null && table.length() > 0) {
        for (int rownum = 0; rownum < table.length(); rownum++) {
            JSONObject row = table.getJSONObject(rownum);
            for (String key : row.keySet()) {
                int i;
                while ((i = statement.indexOf("$" + key + "$")) >= 0) {
                    statement = statement.substring(0, i) + row.get(key).toString()
                            + statement.substring(i + key.length() + 2);
                }
                if (statement.indexOf('$') < 0)
                    break;
            }
            if (statement.indexOf('$') < 0)
                break;
        }
    }
    return statement;
}

From source file:org.collectionspace.chain.csp.persistence.services.TestAccount.java

public void testAccountSearch() {

    Storage ss;// ww w  .  j  av a  2 s .  com
    try {
        ss = makeServicesStorage();
        /* 
         *  arggg how do I get it to do an exact match */
        JSONObject data = ss.getPathsJSON("users/", new JSONObject("{\"email\":\"bob@indigo-e.co.uk\"}"));
        String[] paths = (String[]) data.get("listItems");

        if (paths.length >= 1) {
            for (int i = 0; i < paths.length; i++) {
                //log.info(paths[i] +"  : "+ i +" of "+ paths.length);
            }
        }
    } catch (CSPDependencyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExistException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnimplementedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnderlyingStorageException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.collectionspace.chain.csp.persistence.services.TestAccount.java

@Test
public void testAccountCreate() throws Exception {
    Storage ss = makeServicesStorage();//from w w w . j  a va2 s .  c  o  m
    /* delete user so we can create it later - will return 404 if user doesn't exist */
    JSONObject data = ss.getPathsJSON("users/", new JSONObject("{\"userId\":\"test31@collectionspace.org\"}"));
    String[] paths = (String[]) data.get("listItems");
    if (paths.length > 0)
        ss.deleteJSON("users/" + paths[0]);

    JSONObject u1 = getJSON("user1.json");
    /* create the user based on json */
    /* will give a hidden 500 error if userid is not unique (useful eh?) */
    String path = ss.autocreateJSON("users/", u1, null);
    assertNotNull(path);
    JSONObject u2 = getJSON("user1.json");
    ss.updateJSON("users/" + path, u2, new JSONObject());
    JSONObject u3 = ss.retrieveJSON("users/" + path, new JSONObject());
    assertNotNull(u3);
    // Check output
    assertEquals("Test Mccollectionspace.org", u3.getString("screenName"));
    assertEquals("test31@collectionspace.org", u3.getString("userId"));
    assertEquals("test31@collectionspace.org", u3.getString("email"));
    assertEquals("active", u3.getString("status"));
    // Check the method we're about to use to check if login works works
    creds.setCredential(ServicesStorageGenerator.CRED_USERID, "test31@collectionspace.org");
    creds.setCredential(ServicesStorageGenerator.CRED_PASSWORD, "blahblah");
    cache.reset();
    ReturnedDocument out = conn.getXMLDocument(RequestMethod.GET, "collectionobjects", null, creds, cache);
    assertFalse(out.getStatus() == 200);
    // Check login works
    creds.setCredential(ServicesStorageGenerator.CRED_USERID, "test31@collectionspace.org");
    creds.setCredential(ServicesStorageGenerator.CRED_PASSWORD, "testtestt");
    cache.reset();
    out = conn.getXMLDocument(RequestMethod.GET, "collectionobjects", null, creds, cache);
    log.debug("Status", out.getStatus());
    //assertTrue(out.getStatus()==200);
    //
    ss.deleteJSON("users/" + path);
    /* tidy up and delete user */
}

From source file:com.google.wave.api.impl.EventDataSerializer.java

@Override
public Object unmarshall(SerializerState state, Class clazz, Object json) throws UnmarshallException {
    if (!EventData.class.isAssignableFrom(clazz)) {
        throw new UnmarshallException(clazz.getName() + " is not assignable from EventType");
    }//from ww  w .ja v  a2 s  . c o m

    JSONObject jsonObject = (JSONObject) json;
    EventData event = null;
    try {
        String modifiedBy = (String) ser.unmarshall(state, String.class, jsonObject.get("modifiedBy"));
        Long timestamp = (Long) ser.unmarshall(state, Long.class, jsonObject.get("timestamp"));
        EventType eventType = EventType.valueOf(jsonObject.getString("type"));
        Map<String, Object> properties = (Map<String, Object>) ser.unmarshall(state, Map.class,
                jsonObject.getJSONObject("properties"));
        event = new EventData(eventType, modifiedBy, timestamp);
        event.setProperties(properties);
    } catch (JSONException jsonx) {
        throw new UnmarshallException("Event could not be unmarshalled.");
    }
    return event;
}

From source file:griffon.plugins.preferences.persistors.JsonPreferencesPersistor.java

@SuppressWarnings({ "unchecked", "ConstantConditions" })
private void readInto(@Nonnull JSONObject json, @Nonnull PreferencesNode node) {
    for (Object k : json.keySet()) {
        String key = String.valueOf(k);
        Object value = json.get(key);
        if (value instanceof JSONObject) {
            readInto((JSONObject) value, node.node(key));
        } else if (value instanceof JSONArray) {
            try {
                node.putAt(key, expand((JSONArray) value));
            } catch (IllegalArgumentException iae) {
                throw new IllegalArgumentException(
                        "Invalid value for '" + node.path() + "." + key + "' => " + value, iae);
            }//from   w ww . j  a va  2s  .c o  m
        } else if (value instanceof Number || value instanceof Boolean || value instanceof CharSequence) {
            node.putAt(key, value);
        } else {
            throw new IllegalArgumentException(
                    "Invalid value for '" + node.path() + "." + key + "' => " + value);
        }
    }
}

From source file:org.everit.json.schema.ValidationExceptionTest.java

@Test
public void toJSONNullPointerToViolation() {
    ValidationException subject = new ValidationException(BooleanSchema.INSTANCE, null, "exception message",
            Collections.emptyList(), "type");
    JSONObject actual = subject.toJSON();
    Assert.assertEquals(JSONObject.NULL, actual.get("pointerToViolation"));
}

From source file:org.wso2.carbon.sampledevice.api.util.ZipUtil.java

private String getBase64EncodedAPIAppKey(String apiAppCredentialsAsJSONString) {

    JSONObject jsonObject = new JSONObject(apiAppCredentialsAsJSONString);
    String consumerKey = jsonObject.get(ApiApplicationConstants.OAUTH_CLIENT_ID).toString();
    String consumerSecret = jsonObject.get(ApiApplicationConstants.OAUTH_CLIENT_SECRET).toString();
    String stringToEncode = consumerKey + ":" + consumerSecret;
    return Base64.encodeBase64String(stringToEncode.getBytes());
}

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

@Test
public void testMergeRemovingFolders() throws Exception {
    // see org.eclipse.jgit.api.MergeCommandTest.testMergeRemovingFolders()
    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());
        String folderChildrenLocation = folder.getString(ProtocolConstants.KEY_CHILDREN_LOCATION);
        String folderLocation = folder.getString(ProtocolConstants.KEY_LOCATION);
        JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT);
        String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX);
        String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD);

        String folderName = "folder1";
        request = getPostFilesRequest(folderLocation + "/", getNewDirJSON(folderName).toString(), folderName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
        JSONObject folder1 = getChild(folder, "folder1");

        String fileName = "file1.txt";
        request = getPostFilesRequest(folder1.getString(ProtocolConstants.KEY_LOCATION),
                getNewFileJSON(fileName).toString(), fileName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        fileName = "file2.txt";
        request = getPostFilesRequest(folder1.getString(ProtocolConstants.KEY_LOCATION),
                getNewFileJSON(fileName).toString(), fileName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        folderName = "folder2";
        request = getPostFilesRequest(folderLocation + "/", getNewDirJSON(folderName).toString(), folderName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
        JSONObject folder2 = getChild(folder, "folder2");

        fileName = "file1.txt";
        request = getPostFilesRequest(folder2.getString(ProtocolConstants.KEY_LOCATION),
                getNewFileJSON(fileName).toString(), fileName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

        fileName = "file2.txt";
        request = getPostFilesRequest(folder2.getString(ProtocolConstants.KEY_LOCATION),
                getNewFileJSON(fileName).toString(), fileName);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());

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

        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "folders and files", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        deleteFile(folder1);/*from   w  w  w .j  a  v  a2 s. co  m*/

        deleteFile(folder2);

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

        request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "removing folders", false);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());

        JSONArray commitsArray = log(gitHeadUri);
        assertEquals(3, commitsArray.length());
        JSONObject commit = commitsArray.getJSONObject(0);
        assertEquals("removing folders", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        String toMerge = commit.getString(ProtocolConstants.KEY_NAME);
        commit = commitsArray.getJSONObject(1);
        assertEquals("folders and files", commit.get(GitConstants.KEY_COMMIT_MESSAGE));
        String toCheckout = commit.getString(ProtocolConstants.KEY_NAME);

        Repository db1 = getRepositoryForContentLocation(cloneContentLocation);
        Git git = new Git(db1);
        git.checkout().setName(toCheckout).call();

        JSONObject merge = merge(gitHeadUri, toMerge);
        MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT));
        assertEquals(MergeStatus.FAST_FORWARD, mergeResult);

        request = getGetRequest(folderChildrenLocation);
        response = webConversation.getResponse(request);
        assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
        List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText()));
        assertNull(getChildByName(children, "folder1"));
        assertNull(getChildByName(children, "folder2"));
    }
}

From source file:com.leanengine.JsonDecode.java

private static Map<String, Object> accountPropsFromJson(JSONObject jsonNode)
        throws LeanException, JSONException {
    Map<String, Object> props = new HashMap<String, Object>(jsonNode.length());

    // must have some properties
    if (jsonNode.length() == 0)
        throw new LeanException(LeanError.Type.ServerError,
                "Malformed reply: JSON parameter 'providerProperties' must not be empty.");

    Iterator fieldNames = jsonNode.keys();
    while (fieldNames.hasNext()) {
        String field = (String) fieldNames.next();
        props.put(field, jsonNode.get(field));
    }//w w  w.  j a  v  a2  s  . co  m
    return props;
}