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:com.rapid.actions.Database.java

public Database(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // call the super parameterless constructor which sets the xml version
    super();// ww w. j  a v a 2  s .  c  om
    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties, except for query
        if (!"query".equals(key) && !"showLoading".equals(key) && !"childDatabaseActions".equals(key)
                && !"successActions".equals(key) && !"errorActions".equals(key) && !"childActions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }

    // try and build the query object
    JSONObject jsonQuery = jsonAction.optJSONObject("query");

    // check we got one
    if (jsonQuery != null) {
        // get the parameters                  
        ArrayList<Parameter> inputs = getParameters(jsonQuery.optJSONArray("inputs"));
        ArrayList<Parameter> outputs = getParameters(jsonQuery.optJSONArray("outputs"));
        String sql = jsonQuery.optString("SQL");
        boolean multiRow = jsonQuery.optBoolean("multiRow");
        int databaseConnectionIndex = jsonQuery.optInt("databaseConnectionIndex");
        // make the object
        _query = new Query(inputs, outputs, sql, multiRow, databaseConnectionIndex);
    }

    // look for showLoading
    _showLoading = jsonAction.optBoolean("showLoading");

    // grab any successActions
    JSONArray jsonChildDatabaseActions = jsonAction.optJSONArray("childDatabaseActions");
    // if we had some 
    if (jsonChildDatabaseActions != null) {
        // instantiate collection
        _childDatabaseActions = new ArrayList<Database>();
        // loop them
        for (int i = 0; i < jsonChildDatabaseActions.length(); i++) {
            // get one
            JSONObject jsonChildDatabaseAction = jsonChildDatabaseActions.getJSONObject(i);
            // instantiate and add to collection
            _childDatabaseActions.add(new Database(rapidServlet, jsonChildDatabaseAction));
        }
    }

    // grab any successActions
    JSONArray jsonSuccessActions = jsonAction.optJSONArray("successActions");
    // if we had some instantiate our collection
    if (jsonSuccessActions != null)
        _successActions = Control.getActions(rapidServlet, jsonSuccessActions);

    // grab any errorActions
    JSONArray jsonErrorActions = jsonAction.optJSONArray("errorActions");
    // if we had some instantiate our collection
    if (jsonErrorActions != null)
        _errorActions = Control.getActions(rapidServlet, jsonErrorActions);

}

From source file:com.rapid.actions.Database.java

public JSONObject doQuery(RapidRequest rapidRequest, JSONObject jsonAction, Application application,
        DataFactory df) throws Exception {

    // place holder for the object we're going to return
    JSONObject jsonData = null;//from  www  . j  a va2 s  .  c  om

    // retrieve the sql
    String sql = _query.getSQL();

    // only if there is some sql is it worth going further
    if (sql != null) {

        // get any json inputs
        JSONObject jsonInputData = jsonAction.optJSONObject("data");

        // initialise the parameters list
        ArrayList<Parameters> parametersList = new ArrayList<Parameters>();

        // populate the parameters from the inputs collection (we do this first as we use them as the cache key due to getting values from the session)
        if (_query.getInputs() == null) {

            // just add an empty parameters member if no inputs
            parametersList.add(new Parameters());

        } else {

            // if there is input data
            if (jsonInputData != null) {

                // get any input fields
                JSONArray jsonFields = jsonInputData.optJSONArray("fields");
                // get any input rows
                JSONArray jsonRows = jsonInputData.optJSONArray("rows");

                // if we have fields and rows
                if (jsonFields != null && jsonRows != null) {

                    // loop the input rows (only the top row if not multirow)
                    for (int i = 0; i < jsonRows.length() && (_query.getMultiRow() || i == 0); i++) {

                        // get this jsonRow
                        JSONArray jsonRow = jsonRows.getJSONArray(i);
                        // make the parameters for this row
                        Parameters parameters = new Parameters();

                        // loop the query inputs
                        for (Parameter input : _query.getInputs()) {
                            // get the input id
                            String id = input.getItemId();
                            // get the input field
                            String field = input.getField();
                            // add field to id if present
                            if (field != null && !"".equals(field))
                                id += "." + field;
                            // retain the value
                            String value = null;
                            // if it looks like a control, or a system value (bit of extra safety checking)
                            if ("P".equals(id.substring(0, 1)) && id.indexOf("_C") > 0
                                    || id.indexOf("System.") == 0) {
                                // loop the json inputs looking for the value
                                if (jsonInputData != null) {
                                    for (int j = 0; j < jsonFields.length(); j++) {
                                        // get the id from the fields
                                        String jsonId = jsonFields.optString(j);
                                        // if the id we want matches this one 
                                        if (id.toLowerCase().equals(jsonId.toLowerCase())) {
                                            // get the value
                                            value = jsonRow.optString(j, null);
                                            // no need to keep looking
                                            break;
                                        }
                                    }
                                }
                            }
                            // if still null try the session
                            if (value == null)
                                value = (String) rapidRequest.getSessionAttribute(input.getItemId());
                            // add the parameter
                            parameters.add(value);
                        }

                        // add the parameters to the list
                        parametersList.add(parameters);

                    } // row loop

                } // input fields and rows check

            } // input data check

        } // query inputs check

        // placeholder for the action cache
        ActionCache actionCache = rapidRequest.getRapidServlet().getActionCache();

        // if an action cache was found
        if (actionCache != null) {

            // log that we found action cache
            _logger.debug("Database action cache found");

            // attempt to fetch data from the cache
            jsonData = actionCache.get(application.getId(), getId(), parametersList.toString());

        }

        // if there isn't a cache or no data was retrieved
        if (jsonData == null) {

            try {

                // instantiate jsonData
                jsonData = new JSONObject();
                // fields collection
                JSONArray jsonFields = new JSONArray();
                // rows collection can start initialised
                JSONArray jsonRows = new JSONArray();

                // trim the sql
                sql = sql.trim();

                // check the verb
                if (sql.toLowerCase().startsWith("select") || sql.toLowerCase().startsWith("with")) {

                    // set readonly to true (makes for faster querying)
                    df.setReadOnly(true);

                    // loop the parameterList getting a result set for each parameters (input row)
                    for (Parameters parameters : parametersList) {

                        // get the result set!
                        ResultSet rs = df.getPreparedResultSet(rapidRequest, sql, parameters);

                        // get it's meta data for the field names
                        ResultSetMetaData rsmd = rs.getMetaData();

                        // got fields indicator
                        boolean gotFields = false;

                        // loop the result set
                        while (rs.next()) {

                            // initialise the row
                            JSONArray jsonRow = new JSONArray();

                            // loop the columns
                            for (int i = 0; i < rsmd.getColumnCount(); i++) {
                                // add the field name to the fields collection if not done yet
                                if (!gotFields)
                                    jsonFields.put(rsmd.getColumnLabel(i + 1));
                                // get the column type
                                int columnType = rsmd.getColumnType(i + 1);
                                // add the data to the row according to it's type   
                                switch (columnType) {
                                case (Types.NUMERIC):
                                    jsonRow.put(rs.getDouble(i + 1));
                                    break;
                                case (Types.INTEGER):
                                    jsonRow.put(rs.getInt(i + 1));
                                    break;
                                case (Types.BIGINT):
                                    jsonRow.put(rs.getLong(i + 1));
                                    break;
                                case (Types.FLOAT):
                                    jsonRow.put(rs.getFloat(i + 1));
                                    break;
                                case (Types.DOUBLE):
                                    jsonRow.put(rs.getDouble(i + 1));
                                    break;
                                default:
                                    jsonRow.put(rs.getString(i + 1));
                                }
                            }
                            // add the row to the rows collection
                            jsonRows.put(jsonRow);
                            // remember we now have our fields
                            gotFields = true;

                        }

                        // close the record set
                        rs.close();

                    }

                } else {

                    // assume rows affected is 0
                    int rows = 0;

                    // sql check
                    if (sql.length() > 0) {

                        // perform update for all incoming parameters (one parameters collection for each row)
                        for (Parameters parameters : parametersList) {
                            rows += df.getPreparedUpdate(rapidRequest, sql, parameters);
                        }

                        // add a psuedo field 
                        jsonFields.put("rows");

                        // create a row array
                        JSONArray jsonRow = new JSONArray();
                        // add the rows updated
                        jsonRow.put(rows);
                        // add the row we just made
                        jsonRows.put(jsonRow);

                    }

                }

                // add the fields to the data object
                jsonData.put("fields", jsonFields);
                // add the rows to the data object
                jsonData.put("rows", jsonRows);

                // check for any child database actions
                if (_childDatabaseActions != null) {
                    // if there really are some
                    if (_childDatabaseActions.size() > 0) {
                        // get any child data
                        JSONArray jsonChildQueries = jsonAction.optJSONArray("childQueries");
                        // if there was some
                        if (jsonChildQueries != null) {
                            // loop
                            for (int i = 0; i < jsonChildQueries.length(); i++) {
                                // fetch the data
                                JSONObject jsonChildAction = jsonChildQueries.getJSONObject(i);
                                // read the index (the position of the child this related to
                                int index = jsonChildAction.getInt("index");
                                // get the relevant child action
                                Database childDatabaseAction = _childDatabaseActions.get(index);
                                // get the resultant child data
                                JSONObject jsonChildData = childDatabaseAction.doQuery(rapidRequest,
                                        jsonChildAction, application, df);

                                // a map for indexes of matching fields between our parent and child
                                Map<Integer, Integer> fieldsMap = new HashMap<Integer, Integer>();
                                // the child fields
                                JSONArray jsonChildFields = jsonChildData.getJSONArray("fields");
                                if (jsonChildFields != null) {
                                    // loop the parent fields
                                    for (int j = 0; j < jsonFields.length(); j++) {
                                        // loop the child fields
                                        for (int k = 0; k < jsonChildFields.length(); k++) {
                                            // get parent field
                                            String field = jsonFields.getString(j);
                                            // get child field
                                            String childField = jsonChildFields.getString(k);
                                            // if both not null
                                            if (field != null && childField != null) {
                                                // check for match
                                                if (field.toLowerCase().equals(childField.toLowerCase()))
                                                    fieldsMap.put(j, k);
                                            }
                                        }
                                    }
                                }

                                // add a field for the results of this child action
                                jsonFields.put("childAction" + (i + 1));

                                // if matching fields
                                if (fieldsMap.size() > 0) {
                                    // an object with a null value for when there is no match
                                    Object nullObject = null;
                                    // get the child rows
                                    JSONArray jsonChildRows = jsonChildData.getJSONArray("rows");
                                    // if we had some
                                    if (jsonChildRows != null) {
                                        // loop the parent rows
                                        for (int j = 0; j < jsonRows.length(); j++) {
                                            // get the parent row
                                            JSONArray jsonRow = jsonRows.getJSONArray(j);
                                            // make a new rows collection for the child subset
                                            JSONArray jsonChildRowsSubset = new JSONArray();
                                            // loop the child rows
                                            for (int k = 0; k < jsonChildRows.length(); k++) {
                                                // get the child row
                                                JSONArray jsonChildRow = jsonChildRows.getJSONArray(k);
                                                // assume no matches
                                                int matches = 0;
                                                // loop the fields map
                                                for (Integer l : fieldsMap.keySet()) {
                                                    // parent value
                                                    Object parentValue = null;
                                                    // get the value if there are enough
                                                    if (jsonRow.length() > l)
                                                        parentValue = jsonRow.get(l);
                                                    // child value
                                                    Object childValue = null;
                                                    if (jsonChildRow.length() > l)
                                                        childValue = jsonChildRow.get(fieldsMap.get(l));
                                                    // non null check
                                                    if (parentValue != null && childValue != null) {
                                                        // a string we will concert the child value to
                                                        String parentString = null;
                                                        // check the parent value type
                                                        if (parentValue.getClass() == String.class) {
                                                            parentString = (String) parentValue;
                                                        } else if (parentValue.getClass() == Integer.class) {
                                                            parentString = Integer
                                                                    .toString((Integer) parentValue);
                                                        } else if (parentValue.getClass() == Long.class) {
                                                            parentString = Long.toString((Long) parentValue);
                                                        } else if (parentValue.getClass() == Double.class) {
                                                            parentString = Double
                                                                    .toString((Double) parentValue);
                                                        } else if (parentValue.getClass() == Boolean.class) {
                                                            parentString = Boolean
                                                                    .toString((Boolean) parentValue);
                                                        }
                                                        // a string we will convert the child value to
                                                        String childString = null;
                                                        // check the parent value type
                                                        if (childValue.getClass() == String.class) {
                                                            childString = (String) childValue;
                                                        } else if (childValue.getClass() == Integer.class) {
                                                            childString = Integer
                                                                    .toString((Integer) childValue);
                                                        } else if (childValue.getClass() == Long.class) {
                                                            childString = Long.toString((Long) childValue);
                                                        } else if (childValue.getClass() == Double.class) {
                                                            childString = Double.toString((Double) childValue);
                                                        } else if (childValue.getClass() == Boolean.class) {
                                                            childString = Boolean
                                                                    .toString((Boolean) childValue);
                                                        }
                                                        // non null check
                                                        if (parentString != null && childString != null) {
                                                            // do the match!
                                                            if (parentString.equals(childString))
                                                                matches++;
                                                        }
                                                    } // values non null                                          
                                                } // field map loop
                                                  // if we got some matches for all the fields add this row to the subset
                                                if (matches == fieldsMap.size())
                                                    jsonChildRowsSubset.put(jsonChildRow);
                                            } // child row loop
                                              // if our child subset has rows in it
                                            if (jsonChildRowsSubset.length() > 0) {
                                                // create a new childSubset object
                                                JSONObject jsonChildDataSubset = new JSONObject();
                                                // add the fields
                                                jsonChildDataSubset.put("fields", jsonChildFields);
                                                // add the subset of rows
                                                jsonChildDataSubset.put("rows", jsonChildRowsSubset);
                                                // add the child database action data subset
                                                jsonRow.put(jsonChildDataSubset);
                                            } else {
                                                // add an empty cell
                                                jsonRow.put(nullObject);
                                            }
                                        } // parent row loop                                 
                                    } // jsonChildRows null check
                                } else {
                                    // loop the parent rows
                                    for (int j = 0; j < jsonRows.length(); j++) {
                                        // get the row
                                        JSONArray jsonRow = jsonRows.getJSONArray(j);
                                        // add the child database action data
                                        jsonRow.put(jsonChildData);
                                    }
                                } // matching fields check

                            } // jsonChildQueries loop
                        } // jsonChildQueries null check                      
                    } // _childDatabaseActions size > 0                                                      
                } // _childDatabaseActions not null

                // cache if in use
                if (actionCache != null)
                    actionCache.put(application.getId(), getId(), parametersList.toString(), jsonData);

            } catch (Exception ex) {

                // log the error
                _logger.error(ex);

                // close the data factory and silently fail
                try {
                    df.close();
                } catch (Exception ex2) {
                }

                // only throw if no action cache
                if (actionCache == null) {
                    throw ex;
                } else {
                    _logger.debug("Error not shown to user due to cache : " + ex.getMessage());
                }

            } // jsonData not null

        } // jsonData == null

    } // got sql

    return jsonData;

}

From source file:com.danlvse.weebo.model.User.java

public static User parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }/*from  w w w .jav  a2 s. c o  m*/

    User user = new User();
    user.id = jsonObject.optString("id", "");
    user.idstr = jsonObject.optString("idstr", "");
    user.screen_name = jsonObject.optString("screen_name", "");
    user.name = jsonObject.optString("name", "");
    user.province = jsonObject.optInt("province", -1);
    user.city = jsonObject.optInt("city", -1);
    user.location = jsonObject.optString("location", "");
    user.description = jsonObject.optString("description", "");
    user.url = jsonObject.optString("url", "");
    user.profile_image_url = jsonObject.optString("profile_image_url", "");
    user.profile_url = jsonObject.optString("profile_url", "");
    user.cover_image_phone = jsonObject.optString("cover_image_phone", "");
    user.cover_image = jsonObject.optString("cover_image", "");
    user.domain = jsonObject.optString("domain", "");
    user.weihao = jsonObject.optString("weihao", "");
    user.gender = jsonObject.optString("gender", "");
    user.followers_count = jsonObject.optInt("followers_count", 0);
    user.friends_count = jsonObject.optInt("friends_count", 0);
    user.statuses_count = jsonObject.optInt("statuses_count", 0);
    user.favourites_count = jsonObject.optInt("favourites_count", 0);
    user.created_at = jsonObject.optString("created_at", "");
    user.following = jsonObject.optBoolean("following", false);
    user.allow_all_act_msg = jsonObject.optBoolean("allow_all_act_msg", false);
    user.geo_enabled = jsonObject.optBoolean("geo_enabled", false);
    user.verified = jsonObject.optBoolean("verified", false);
    user.verified_type = jsonObject.optInt("verified_type", -1);
    user.remark = jsonObject.optString("remark", "");
    user.status = Feed.parse(jsonObject.optJSONObject("status"));
    user.allow_all_comment = jsonObject.optBoolean("allow_all_comment", true);
    user.avatar_large = jsonObject.optString("avatar_large", "");
    user.avatar_hd = jsonObject.optString("avatar_hd", "");
    user.verified_reason = jsonObject.optString("verified_reason", "");
    user.follow_me = jsonObject.optBoolean("follow_me", false);
    user.online_status = jsonObject.optInt("online_status", 0);
    user.bi_followers_count = jsonObject.optInt("bi_followers_count", 0);
    user.lang = jsonObject.optString("lang", "");

    user.star = jsonObject.optString("star", "");
    user.mbtype = jsonObject.optString("mbtype", "");
    user.mbrank = jsonObject.optString("mbrank", "");
    user.block_word = jsonObject.optString("block_word", "");

    return user;
}

From source file:com.example.protocol.SHOT.java

public void fromJson(JSONObject jsonObject) throws JSONException {
    if (null == jsonObject) {
        return;//from w ww  . ja  v  a  2s .  c o  m
    }

    JSONArray subItemArray;

    this.id = jsonObject.optInt("id");

    this.title = jsonObject.optString("title");

    this.url = jsonObject.optString("url");

    this.short_url = jsonObject.optString("short_url");

    this.image_url = jsonObject.optString("image_url");

    this.image_teaser_url = jsonObject.optString("image_teaser_url");

    this.width = jsonObject.optInt("width");

    this.height = jsonObject.optInt("height");

    this.views_count = jsonObject.optInt("views_count");

    this.likes_count = jsonObject.optInt("likes_count");

    this.comments_count = jsonObject.optInt("comments_count");

    this.rebounds_count = jsonObject.optInt("rebounds_count");

    this.rebounds_source_id = jsonObject.optInt("rebounds_source_id");

    this.created_at = jsonObject.optString("created_at");

    this.player = new PLAYER();
    this.player.fromJson(jsonObject.optJSONObject("player"));
}

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//  w w w  .  j  av  a2  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:fr.immotronic.ubikit.pems.enocean.impl.item.data.EEP0503xxDataImpl.java

public static EEP0503xxDataImpl constructDataFromRecord(JSONObject lastKnownData) {
    if (lastKnownData == null)
        return new EEP0503xxDataImpl(null, null);

    try {/*from   ww  w.j  a v  a  2  s.  co m*/
        SwitchEvent[] switchEvents = new SwitchEvent[4];
        for (int i = 0; i < switchEvents.length; i++) {
            JSONObject o = lastKnownData.optJSONObject("switchEvent" + i);
            if (o == null)
                switchEvents[i] = null;
            else
                switchEvents[i] = new SwitchEventImpl(o);
        }

        Date date = new Date(lastKnownData.getLong("date"));

        return new EEP0503xxDataImpl(switchEvents, date);
    } catch (JSONException e) {
        Logger.error(LC.gi(), null,
                "constructDataFromRecord(): An exception while building a sensorData from a JSONObject SHOULD never happen. Check the code !",
                e);
        return new EEP0503xxDataImpl(null, null);
    }
}