Example usage for org.json JSONObject getNames

List of usage examples for org.json JSONObject getNames

Introduction

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

Prototype

public static String[] getNames(Object object) 

Source Link

Document

Get an array of field names from an Object.

Usage

From source file:com.dianping.lion.util.JsonParser.java

/**
 * ??configInstances?/*from  w ww. ja va  2  s  .c om*/
 * @param dbContent ?DB?
 * @return
 * @throws Exception
 */
public Map<ConfigInstance, Boolean> getConfigInstances(String dbContent) throws Exception {
    Map<ConfigInstance, Boolean> cis = new HashMap<ConfigInstance, Boolean>();
    JSONObject jsonObj = new JSONObject(dbContent);
    String[] names = JSONObject.getNames(jsonObj);
    List<String> dbAliases = new ArrayList<String>();
    for (int i = 0; i < names.length; i++) {
        if (!TIMESTAMP.equals(names[i])) {
            dbAliases.add(names[i]);
        }
    }
    for (int i = 0; i < dbAliases.size(); i++) {
        JSONObject envDSContent = jsonObj.getJSONObject(dbAliases.get(i));
        String[] envs = JSONObject.getNames(envDSContent);
        for (int j = 0; j < envs.length; j++) {
            if (REMOVED.equals(envs[j])) {
                continue;
            }
            ConfigInstance ci = new ConfigInstance();
            Config config = getConfigService().findConfigByKey("data-source." + dbAliases.get(i));
            ci.setConfigId(config.getId());
            Environment env = getEnvService().findEnvByName(envs[j].toLowerCase());
            ci.setEnvId(env.getId());
            ci.setValue(envDSContent.getString(envs[j]));
            boolean isRemovedContains = false;
            isRemovedContains = envDSContent.getJSONObject(envs[j]).has(REMOVED);
            if (isRemovedContains) {
                cis.put(ci, true);
            } else {
                cis.put(ci, false);
            }
        }
    }
    return cis;
}

From source file:com.jennifer.ui.chart.ChartBuilder.java

private void drawGrid() {
    JSONObject grid = builderoptions.getJSONObject("grid");

    String[] names = JSONObject.getNames(grid);
    if (names == null)
        return;/*from  www  .j  a  va2s.  co  m*/

    if (grid != null && grid.names().length() > 0) {

        // create default cusotm grid
        if (grid.has("type")) {
            grid = new JSONObject().put("c", new JSONArray().put(JSONUtil.clone(grid)));
        }

        if (!builderoptions.has("scales")) {
            builderoptions.put("scales", new JSONObject());
        }

        JSONObject scales = (JSONObject) builderoptions.getJSONObject("scales");

        JSONArray keys = grid.names();

        for (int i = 0, len = keys.length(); i < len; i++) {
            String key = keys.getString(i);
            Orient orient = Orient.CUSTOM;

            if ("x".equals(key)) {
                orient = Orient.BOTTOM;
            } else if ("y".equals(key)) {
                orient = Orient.LEFT;
            } else if ("x1".equals(key)) {
                orient = Orient.TOP;
            } else if ("y1".equals(key)) {
                orient = Orient.RIGHT;
            }

            if (!scales.has(key)) {
                scales.put(key, new JSONArray());
            }

            JSONArray scale = (JSONArray) scales.getJSONArray(key);

            Object objGrid = grid.get(key);

            if (!(objGrid instanceof JSONArray) && !(objGrid instanceof JSONArray)) {
                JSONArray o = new JSONArray();
                o.put(JSONUtil.clone(grid.getJSONObject(key)));

                grid.put(key, o);
            } else if (objGrid instanceof JSONArray) {
                grid.put(key, JSONUtil.clone((JSONArray) objGrid));
            }

            JSONArray gridObject = (JSONArray) grid.getJSONArray(key);

            for (int keyIndex = 0, gridLen = gridObject.length(); keyIndex < gridLen; keyIndex++) {

                JSONObject g = JSONUtil.clone(gridObject.getJSONObject(keyIndex));

                Class cls = grids.get(g.getString("type"));
                Grid newGrid = null;

                try {
                    newGrid = (Grid) cls
                            .getDeclaredConstructor(Orient.class, ChartBuilder.class, JSONObject.class)
                            .newInstance(orient, this, g);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }

                JSONObject ret = (JSONObject) newGrid.render();

                int dist = g.optInt("dist", 0);
                Transform root = (Transform) ret.get("root");

                if ("y".equals(key)) {
                    root.translate(area("x") - dist, area("y"));
                } else if ("y1".equals(key)) {
                    root.translate(area("x2") + dist, area("y"));
                } else if ("x".equals(key)) {
                    root.translate(area("x"), area("y2") + dist);
                } else if ("x1".equals(key)) {
                    root.translate(area("x"), area("y") - dist);
                }

                this.root.append(root);

                scales.getJSONArray(key).put(keyIndex, newGrid);

            }

        }
    }
}

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/*ww  w . jav  a  2  s  .co 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);
                        }
                    }
                }
            }
        }
    }
}