Example usage for org.json JSONObject length

List of usage examples for org.json JSONObject length

Introduction

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

Prototype

public int length() 

Source Link

Document

Get the number of keys stored in the JSONObject.

Usage

From source file:org.uiautomation.ios.UIAModels.predicate.AbstractCriteria.java

@SuppressWarnings("unchecked")
public static <T extends Criteria> T parse(JSONObject serialized, CriteriaDecorator decorator) {
    try {/*from w  w  w . j  a v  a2  s . co  m*/
        int nbKeys = serialized.length();
        switch (nbKeys) {
        case KEYS_IN_EMPTY_CRITERIA:
            return (T) new EmptyCriteria();
        case KEYS_IN_COMPOSED_CRITERIA:
            String key = (String) serialized.keys().next();
            CompositionType type = CompositionType.valueOf(key);
            return (T) buildComposedCriteria(serialized, type, decorator);
        case KEYS_IN_LOCATION_CRITERIA:
            int x = serialized.getInt("x");
            int y = serialized.getInt("y");
            return (T) buildLocationCriteria(serialized, x, y, decorator);
        case KEYS_IN_PROPERTY_CRITERIA:
            String method = serialized.getString("method");
            String tmp = method.substring(0, 1).toUpperCase() + method.toLowerCase().substring(1) + "Criteria";
            String clazz = AbstractCriteria.class.getPackage().getName() + "." + tmp;
            Class<? extends PropertyEqualCriteria> c = (Class<? extends PropertyEqualCriteria>) Class
                    .forName(clazz);
            return (T) buildPropertyBaseCriteria(serialized, c, decorator);
        default:
            throw new InvalidSelectorException("can't find the type : " + serialized.toString());
        }
    } catch (Exception e) {
        throw new WebDriverException(e);
    }

}

From source file:org.hypertopic.HypertopicMapTest.java

@Test
public void getAttributes() throws Exception {
    JSONObject attributes = this.item.getAttributes();
    assertEquals("bar", attributes.getString("foo"));
    assertEquals(1, attributes.length());
}

From source file:org.loklak.android.client.SuggestClient.java

public static ResultList<QueryEntry> suggest(final String protocolhostportstub, final String q,
        final String source, final int count, final String order, final String orderby,
        final int timezoneOffset, final String since, final String until, final String selectby,
        final int random) {
    ResultList<QueryEntry> rl = new ResultList<QueryEntry>();
    String urlstring = "";
    try {//  w ww.j  a v  a 2  s.  c  om
        urlstring = protocolhostportstub + "/api/suggest.json?q="
                + URLEncoder.encode(q.replace(' ', '+'), "UTF-8") + "&timezoneOffset=" + timezoneOffset
                + "&count=" + count + "&source=" + (source == null ? "all" : source)
                + (order == null ? "" : ("&order=" + order)) + (orderby == null ? "" : ("&orderby=" + orderby))
                + (since == null ? "" : ("&since=" + since)) + (until == null ? "" : ("&until=" + until))
                + (selectby == null ? "" : ("&selectby=" + selectby))
                + (random < 0 ? "" : ("&random=" + random)) + "&minified=true";
        JSONObject json = JsonIO.loadJson(urlstring);
        if (json == null || json.length() == 0)
            return rl;
        JSONArray queries = json.getJSONArray("queries");
        if (queries != null) {
            for (int i = 0; i < queries.length(); i++) {
                JSONObject query = queries.getJSONObject(i);
                if (query == null)
                    continue;
                QueryEntry qe = new QueryEntry(query);
                rl.add(qe);
            }
        }

        JSONObject metadata = json.getJSONObject("search_metadata");
        if (metadata != null) {
            long hits = metadata.getLong("hits");
            rl.setHits(hits);
        }
    } catch (Throwable e) {
        Log.e("SuggestClient", e.getMessage(), e);
    }
    return rl;
}

From source file:com.jsonstore.api.JSONStoreQueryPart.java

/**
 * @exclude/*from   w w w .j ava2 s  .  c o  m*/
 */
private void parseTuple(JSONObject tuple, QueryPartOperation operation, List<JSONStoreQueryPartItem> result)
        throws JSONStoreFindException {
    //Enforce restrictions:
    if (tuple.length() == 0) {
        throw new JSONStoreFindException(
                "Cannot parse query content part. An internal error occurred parsing part tuple", null);
    }
    Iterator<String> tupleIterator = tuple.keys();
    while (tupleIterator.hasNext()) {
        String key = tupleIterator.next();
        Object val;
        try {
            val = tuple.get(key);
        } catch (JSONException e) {
            throw new JSONStoreFindException(
                    "Cannot parse query content query part. An internal error occurred parsing part tuple", e);
        }

        JSONStoreQueryPartItem part = parseItem(key, false, operation, val);
        if (part != null)
            result.add(part);
    }

}

From source file:com.idean.atthack.network.RequestHelper.java

private void writeBody(HttpURLConnection urlConnection, JSONObject obj) {
    try {//w  w  w. ja v  a 2 s  . c  om
        String body = obj.toString();
        if (obj.length() == 0 || TextUtils.isEmpty(body)) {
            return;
        }
        urlConnection.setRequestProperty("Content-Type", "application/json");

        PrintWriter writer = new PrintWriter(new BufferedOutputStream(urlConnection.getOutputStream()));
        writer.print(body); // presumably in UTF-8
        writer.flush();
        Log.d(TAG, "Wrote request body: \n\n" + body);
    } catch (Exception e) {
        Log.w(TAG, "Unable to send request body", e);
    }
}

From source file:com.novartis.opensource.yada.test.ServiceTest.java

/** 
 * Tests many aspects of {@code harmonyMap} or {@code h} YADA parameter results including
 * for CSV: column counts, header values, row counts, row/column content; and for JSON:
 * singular result set, correct mapped/unmapped keys and values, record count.
 * @param query the query to execute/*from w  w  w .  j a v a  2  s.c  o m*/
 * @throws YADAQueryConfigurationException when request creation fails
 * @throws YADAResponseException when the test result is invalid
 */
@Test(enabled = true, dataProvider = "QueryTests", groups = { "options" })
@QueryFile(list = {})
public void testHarmonizer(String query) throws YADAQueryConfigurationException, YADAResponseException {
    String[] allKeys = { COL_INTEGER, COL_INTEGER_LC, COL_HM_INT, COL_NUMBER, COL_NUMBER_LC, COL_HM_FLOAT,
            COL_DATE, COL_DATE_LC, COL_HM_DATE, COL_TIME, COL_TIME_LC, COL_HM_TIME };
    String[] intKeys = { COL_INTEGER, COL_INTEGER_LC, COL_HM_INT };
    String[] floatKeys = { COL_NUMBER, COL_NUMBER_LC, COL_HM_FLOAT };
    String[] dateKeys = { COL_DATE, COL_DATE_LC, COL_HM_DATE };
    String[] timeKeys = { COL_TIME, COL_TIME_LC, COL_HM_TIME };
    Service svc = prepareTest(query);
    YADARequest req = svc.getYADARequest();
    req.setPageSize(new String[] { "-1" });
    JSONArray spec = req.getHarmonyMap();
    String result = svc.execute();

    int qCount = StringUtils.countMatches(query, "qname") + StringUtils.countMatches(query, "q=");
    String line = null;
    int lineCount = 0;
    if (req.getFormat().equals(YADARequest.FORMAT_CSV)) {
        logStringResult(result);
        Pattern rx = Pattern.compile(
                "^(\"([A-Z,]+)\"),(\"([0-9]+)\")?,(\"([0-9.]+)\")?,?(\"(201[3-5]-0[0-9]-[0-9]{2}(\\s00:00:00)?|1362373200|1396584000)\")?,?(\"(201[3-5]-0[0-9]-[0-9]{2} ([0-9]{2}:){2}[0-9]{2}|1441500273000)(\\.0)?\")?$");
        // count columns
        // check for correct values in mapped columns

        try (BufferedReader br = new BufferedReader(new StringReader(result))) {
            while ((line = br.readLine()) != null) {
                if (lineCount > 0) {
                    Matcher m = rx.matcher(line);
                    Assert.assertTrue(m.matches());
                    // first query only returns three columns
                    if (lineCount < 9) {
                        Assert.assertTrue(validateInteger(m.group(4))); // col 2
                        Assert.assertTrue(validateNumber(m.group(6))); // col 3
                        Assert.assertNull(m.group(8)); // col 4
                        Assert.assertNull(m.group(11)); // col 5
                    } else if (lineCount > 8 && lineCount < 17)
                    // 2nd query
                    {
                        Assert.assertNull(m.group(4)); // col 2
                        Assert.assertNull(m.group(6)); // col 3
                        Assert.assertTrue(validateDate(m.group(8))); // col4
                        Assert.assertTrue(validateTime(m.group(11))); // col5
                    } else
                    // 3rd query
                    {
                        Assert.assertNull(m.group(4)); // col 2
                        Assert.assertNull(m.group(6)); // col 3
                        Assert.assertNull(m.group(8)); // col 4
                        Assert.assertTrue(validateTime(m.group(11))); // col5
                    }
                }
                lineCount++;
            }
        } catch (IOException e) {
            throw new YADAResponseException("Result was unreadable.", e);
        } catch (ParseException e) {
            throw new YADAResponseException("Result was unparsable.", e);
        }

        //TODO confirm correct mapped/unmapped column headers

        // count rows 
        Assert.assertEquals(lineCount - 1, qCount * 8);

        //TODO check for "empty values" in unmapped columns

    } else if (req.getFormat().equals(YADARequest.FORMAT_XML)) {
        //TODO harmony map xml validation
        logMarkupResult(result);
    } else if (req.getFormat().equals(YADARequest.FORMAT_HTML)) {
        logMarkupResult(result);
        Pattern rx = Pattern.compile(
                "^<tr>(<td>([A-Z,]+)</td>)(<td>([0-9]+)?</td>)(<td>([0-9.]+)?</td>)(<td>(201[3-5]-0[0-9]-[0-9]{2}(\\s00:00:00)?|1362373200|1396584000)?</td>)?(<td>((201[3-5]-0[0-9]-[0-9]{2} ([0-9]{2}:){2}[0-9]{2}|1441500273000)(\\.0)?)?</td>)?</tr>$");
        Pattern end = Pattern.compile("^</tbody>|</table>|</body>|</html>$");
        try (BufferedReader br = new BufferedReader(new StringReader(result))) {
            while ((line = br.readLine()) != null) {
                Matcher mEnd = end.matcher(line);
                if (lineCount > 9 && !mEnd.matches()) {
                    Matcher m = rx.matcher(line);
                    Assert.assertTrue(m.matches());
                    // first query only returns three columns
                    if (lineCount < 18) {
                        Assert.assertTrue(validateInteger(m.group(4))); // col 2
                        Assert.assertTrue(validateNumber(m.group(6))); // col 3
                        Assert.assertNull(m.group(8)); // col 4
                        Assert.assertNull(m.group(11)); // col 5
                    } else if (lineCount > 17 && lineCount < 26)
                    // 2nd query
                    {
                        Assert.assertNull(m.group(4)); // col 2
                        Assert.assertNull(m.group(6)); // col 3
                        Assert.assertTrue(validateDate(m.group(8))); // col4
                        Assert.assertTrue(validateTime(m.group(11))); // col5
                    } else
                    // 3rd query
                    {
                        Assert.assertNull(m.group(4)); // col 2
                        Assert.assertNull(m.group(6)); // col 3
                        Assert.assertNull(m.group(8)); // col 4
                        Assert.assertTrue(validateTime(m.group(11))); // col5
                    }
                } else {
                    //TODO confirm correct mapped/unmapped column headers
                }
                lineCount++;
            }
        } catch (IOException e) {
            throw new YADAResponseException("Result was unreadable.", e);
        } catch (ParseException e) {
            throw new YADAResponseException("Result was unparsable.", e);
        }

        // count rows 
        Assert.assertEquals(lineCount - 1, (qCount * 8) + 13); // adding 13 for non-data row html tags
    } else // JSON
    {
        JSONParamsEntry q;
        YADAParam p;
        qCount = 1;
        int resultCount = 8;
        if (YADAUtils.useJSONParams(req)) {
            JSONParams jp = req.getJsonParams();
            String[] qnameKeys = jp.getKeys();
            qCount = qnameKeys.length;
            for (String qname : qnameKeys) {
                q = jp.get(qname);
                p = q.getParam(YADARequest.PS_HARMONYMAP);
                if (null == spec)
                    spec = new JSONArray();
                if (null != p)
                    spec.put(new JSONObject(p.getValue()));
            }
        }
        JSONObject jo = new JSONObject(result);
        logJSONResult(jo);

        // confirm singular result set
        Assert.assertNull(jo.optJSONObject(RESULTSETS));
        Assert.assertTrue(jo.has(RESULTSET));
        //      // check record count
        int actualRecCount = jo.getJSONObject(RESULTSET).getInt(RECORDS);
        int expectRecCount = qCount * resultCount;
        Assert.assertEquals(actualRecCount, expectRecCount, "Result count invalid for query: " + query);

        // confirm correct mapped/unmapped keys
        JSONArray rows = jo.getJSONObject(RESULTSET).getJSONArray(ROWS);

        // For each query, find the hmap
        // test 8 records corresponding to query index
        // NOTE: This does not test for presence of unmapped keys, but does test all values
        for (int i = 0; i < rows.length() / 8; i++) // 1-3 sets of 8
        {
            JSONObject currentSpec = new JSONObject(); // the hmap spec
            if (spec.length() == 1)
                currentSpec = spec.getJSONObject(0); // it's a global request param
            else {
                for (int j = spec.length() - 1; j >= 0; j--) {
                    currentSpec = spec.getJSONObject(j); // it's an embedded param, and JSONArray returns in reverse order
                }
            }

            // Deconstruct spec into keys and vals
            String[] currentSpecKeys = new String[currentSpec.length()];
            String[] currentSpecVals = new String[currentSpec.length()];
            int j = 0;
            if (currentSpec.length() > 0) {
                for (String key : JSONObject.getNames(currentSpec)) {
                    currentSpecKeys[j] = key;
                    currentSpecVals[j] = currentSpec.getString(key);
                    j++;
                }
            }

            // check results
            for (j = 0; j < resultCount; j++) // for each set of results
            {
                JSONObject row = rows.getJSONObject(j); // the "row"
                String[] rowKeys = JSONObject.getNames(row);
                for (String key : rowKeys) // iterate over the row keys 
                {
                    if (key.matches("[A-Z]+")) // upper case are spec vals
                        Assert.assertTrue(ArrayUtils.contains(currentSpecVals, key)); // row key is in current spec vals
                    else {
                        Assert.assertFalse(ArrayUtils.contains(currentSpecVals, key)); // row key is not current spec vals
                        Assert.assertFalse(ArrayUtils.contains(currentSpecKeys, key)); // row key is in current spec keys
                    }
                }

                for (String col : allKeys) // confirm datatype of values
                {
                    if (row.has(col)) {
                        try {
                            if (ArrayUtils.contains(intKeys, col))
                                Assert.assertTrue(validateInteger(row.getString(col)));
                            else if (ArrayUtils.contains(floatKeys, col))
                                Assert.assertTrue(validateNumber(row.getString(col)));
                            else if (ArrayUtils.contains(dateKeys, col))
                                Assert.assertTrue(validateDate(row.getString(col)));
                            else if (ArrayUtils.contains(timeKeys, col))
                                Assert.assertTrue(validateTime(row.getString(col)));
                        } catch (ParseException e) {
                            String msg = "Unable to validate result.";
                            throw new YADAResponseException(msg, e);
                        }
                    }
                }
            }
        }
    }
}

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

public JSONObject readAIMLLesson(File file) throws Exception {
    // read the file as string
    BufferedReader br = new BufferedReader(new FileReader(file));
    String str;//from   w w w .  j a v a 2 s .  c  o  m
    StringBuilder buf = new StringBuilder();
    while ((str = br.readLine()) != null)
        buf.append(str);
    br.close();

    // parse the string as xml into a node object
    InputStream is = new ByteArrayInputStream(buf.toString().getBytes("UTF-8"));
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(is);
    doc.getDocumentElement().normalize();
    Node root = doc.getDocumentElement();
    Node node = root;
    NodeList nl = node.getChildNodes();
    JSONObject json = new JSONObject();
    JSONArray skills = new JSONArray();
    json.put("skills", skills);
    for (int i = 0; i < nl.getLength(); i++) {
        String nodename = nl.item(i).getNodeName().toLowerCase();
        if (nodename.equals("category")) {
            JSONObject skill = readAIMLCategory(nl.item(i));
            if (skill != null && skill.length() > 0)
                skills.put(skill);
        }
        System.out.println("ROOT NODE " + nl.item(i).getNodeName());
    }
    return json;
}