Example usage for org.json JSONArray length

List of usage examples for org.json JSONArray length

Introduction

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

Prototype

public int length() 

Source Link

Document

Get the number of elements in the JSONArray, included nulls.

Usage

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

/**
 * The answer of an cognition contains a list of the mind-melted arguments as one thought
 * @return a list of answer thoughts//from w  w w. ja v  a2 s.  c o m
 */
public List<SusiThought> getAnswers() {
    List<SusiThought> answers = new ArrayList<>();
    if (this.json.has("answers")) {
        JSONArray a = this.json.getJSONArray("answers");
        for (int i = 0; i < a.length(); i++)
            answers.add(new SusiThought(a.getJSONObject(i)));
    }
    return answers;
}

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

/**
 * The cognition is the result of a though extraction. We can reconstruct
 * the dispute as list of last mindstates using the cognition data.
 * @return a backtrackable thought reconstructed from the cognition data
 *///from  w w w .ja v a 2 s .co m
public SusiThought recallDispute() {
    SusiThought dispute = new SusiThought();
    if (this.json.has("answers")) {
        JSONArray answers = this.json.getJSONArray("answers"); // in most cases there is only one answer
        for (int i = answers.length() - 1; i >= 0; i--) {
            SusiThought clonedThought = new SusiThought(answers.getJSONObject(i));
            dispute.addObservation("query", this.json.getString("query")); // we can unify "query" in queries
            SusiAction expressionAction = null;
            for (SusiAction a : clonedThought.getActions()) {
                ArrayList<String> phrases = a.getPhrases();
                if (phrases.size() > 0) {
                    expressionAction = a;
                    break;
                }
            }
            if (expressionAction != null)
                dispute.addObservation("answer", expressionAction.getPhrases().get(0)); // we can unify with "answer" in queries

            // add all data from the old dispute
            JSONArray clonedData = clonedThought.getData();
            if (clonedData.length() > 0) {
                JSONObject row = clonedData.getJSONObject(0);
                row.keySet().forEach(key -> {
                    if (key.startsWith("_"))
                        dispute.addObservation(key, row.getString(key));
                });
                //data.put(clonedData.get(0));
            }
        }
    }
    return dispute;
}

From source file:com.googlecode.android_scripting.facade.ui.UiFacade.java

/**
 * This will override the default behaviour of keys while in the fullscreen mode. ie:
 * //from ww  w  .j a  va  2s .  com
 * <pre>
 *   droid.fullKeyOverride([24,25],True)
 * </pre>
 * 
 * This will override the default behaviour of the volume keys (codes 24 and 25) so that they do
 * not actually adjust the volume. <br>
 * Returns a list of currently overridden keycodes.
 */
@Rpc(description = "Override default key actions")
public JSONArray fullKeyOverride(
        @RpcParameter(name = "keycodes", description = "List of keycodes to override") JSONArray keycodes,
        @RpcParameter(name = "enable", description = "Turn overriding or off") @RpcDefault(value = "true") Boolean enable)
        throws JSONException {
    for (int i = 0; i < keycodes.length(); i++) {
        int value = (int) keycodes.getLong(i);
        if (value > 0) {
            if (enable) {
                if (!mOverrideKeys.contains(value)) {
                    mOverrideKeys.add(value);
                }
            } else {
                int index = mOverrideKeys.indexOf(value);
                if (index >= 0) {
                    mOverrideKeys.remove(index);
                }
            }
        }
    }
    if (mFullScreenTask != null) {
        mFullScreenTask.setOverrideKeys(mOverrideKeys);
    }
    return new JSONArray(mOverrideKeys);
}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private void setRelations(Storage storage, String csid, JSONArray relations)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException {
    deleteAllRelations(storage, csid);//from  w ww  . jav a  2s .co m
    for (int i = 0; i < relations.length(); i++) {
        // Extract data from miniobject
        JSONObject in = relations.getJSONObject(i);
        String dst_type = spec.getRecordByWebUrl(in.getString("recordtype")).getID();
        String dst_id = in.getString("csid");
        String type = in.getString("relationshiptype");
        // Create relation
        JSONObject r = new JSONObject();
        r.put("src", base + "/" + csid);
        r.put("dst", dst_type + "/" + dst_id);
        r.put("type", type);
        storage.autocreateJSON("relations/main", r, null);
    }
}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private JSONObject getPermID(Storage storage, String name, String queryString, String permbase,
        JSONArray actions)//from   w ww.  j ava2 s. c  o m
        throws JSONException, UIException, ExistException, UnimplementedException, UnderlyingStorageException {

    JSONObject permitem = new JSONObject();
    JSONObject permrestrictions = new JSONObject();
    permrestrictions.put("keywords", name);
    permrestrictions.put("queryTerm", "actGrp");
    permrestrictions.put("queryString", queryString);
    JSONObject data = searcher.getJSON(storage, permrestrictions, "items", permbase);

    String permid = "";
    JSONArray items = data.getJSONArray("items");
    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);
        String resourcename = item.getString("summary");
        String actionGroup = item.getString("number");
        //need to do a double check as the query is an inexact match
        if (resourcename.equals(name) && actionGroup.equals(queryString)) {
            permid = item.getString("csid");
        }
    }
    if (permid.equals("")) {

        //create the permission
        /**
         * {
        "effect": "PERMIT",
        "resourceName": "testthing2",
                
        "action":[{"name":"CREATE"},{"name":"READ"},{"name":"UPDATE"},{"name":"DELETE"},{"name":"SEARCH"}]
        }
         */

        JSONObject permission_add = new JSONObject();
        permission_add.put("effect", "PERMIT");
        permission_add.put("description", "created because we couldn't find a match");
        permission_add.put("resourceName", name);
        permission_add.put("actionGroup", queryString);
        permission_add.put("action", actions);

        permid = storage.autocreateJSON(spec.getRecordByWebUrl("permission").getID(), permission_add, null);

    }

    if (!permid.equals("")) {
        permitem.put("resourceName", name);
        permitem.put("permissionId", permid);
        permitem.put("actionGroup", queryString);
    }
    return permitem;

}

From source file:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private void assignPermissions(Storage storage, String path, JSONObject data)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException {
    JSONObject fields = data.optJSONObject("fields");

    JSONArray permdata = new JSONArray();
    JSONObject permcheck = new JSONObject();
    if (fields.has("permissions")) {
        JSONArray permissions = fields.getJSONArray("permissions");
        for (int i = 0; i < permissions.length(); i++) {
            JSONObject perm = permissions.getJSONObject(i);

            Record recordForPermResource = Generic.RecordNameServices(spec, perm.getString("resourceName"));
            if (recordForPermResource != null) {
                if (recordForPermResource.hasSoftDeleteMethod()) {
                    JSONObject permitem = getWorkflowPerm(storage, recordForPermResource,
                            perm.getString("resourceName"), perm.getString("permission"),
                            DELETE_WORKFLOW_TRANSITION);
                    if (permitem.has("permissionId")) {
                        if (permcheck.has(permitem.getString("resourceName"))) {
                            //ignore as we have duplicate name - eek
                            log.warn(//from  w w  w .ja  v  a 2s .  c  o  m
                                    "RecordCreateUpdate.assignPermissions got duplicate workflow/delete permission for: "
                                            + permitem.getString("resourceName"));
                        } else {
                            permcheck.put(permitem.getString("resourceName"), permitem);
                            permdata.put(permitem);
                        }
                    }
                }
                if (recordForPermResource.supportsLocking()) {
                    JSONObject permitem = getWorkflowPerm(storage, recordForPermResource,
                            perm.getString("resourceName"), perm.getString("permission"),
                            LOCK_WORKFLOW_TRANSITION);
                    if (permitem.has("permissionId")) {
                        if (permcheck.has(permitem.getString("resourceName"))) {
                            //ignore as we have duplicate name - eek
                            log.warn(
                                    "RecordCreateUpdate.assignPermissions got duplicate workflow/lock permission for: "
                                            + permitem.getString("resourceName"));
                        } else {
                            permcheck.put(permitem.getString("resourceName"), permitem);
                            permdata.put(permitem);
                        }
                    }
                }
            }
            JSONObject permitem = getPerm(storage, recordForPermResource, perm.getString("resourceName"),
                    perm.getString("permission"));
            if (permitem.has("permissionId")) {
                if (permcheck.has(permitem.getString("resourceName"))) {
                    //ignore as we have duplicate name - eek
                    log.warn("RecordCreateUpdate.assignPermissions got duplicate permission for: "
                            + permitem.getString("resourceName"));
                } else {
                    permcheck.put(permitem.getString("resourceName"), permitem);
                    permdata.put(permitem);
                }
            }
        }
    }

    //log.info("permdata"+permdata.toString());
    JSONObject roledata = new JSONObject();
    roledata.put("roleName", fields.getString("roleName"));

    String[] ids = path.split("/");
    roledata.put("roleId", ids[ids.length - 1]);

    JSONObject accountrole = new JSONObject();
    JSONObject arfields = new JSONObject();
    arfields.put("role", roledata);
    arfields.put("permission", permdata);
    accountrole.put("fields", arfields);
    //log.info("WAAA"+arfields.toString());
    if (fields != null)
        path = storage.autocreateJSON(spec.getRecordByWebUrl("permrole").getID(), arfields, null);
}

From source file:com.google.blockly.model.FieldDropdown.java

/**
 * Loads a FieldDropdown from JSON. This is usually used for the {@link BlockFactory}'s
 * prototype instances./*from   w w  w .  j a  va2s  .  co  m*/
 *
 * @param json The JSON representing the object.
 * @return A new FieldDropdown instance.
 * @throws BlockLoadingException
 */
public static FieldDropdown fromJson(JSONObject json) throws BlockLoadingException {
    String name = json.optString("name");
    if (TextUtils.isEmpty(name)) {
        throw new BlockLoadingException("field_dropdown \"name\" attribute must not be empty.");
    }

    JSONArray jsonOptions = json.optJSONArray("options");
    ArrayList<Option> optionList = null;
    if (jsonOptions != null) {
        int count = jsonOptions == null ? 0 : jsonOptions.length();
        optionList = new ArrayList<>(count);

        for (int i = 0; i < count; i++) {
            JSONArray option = null;
            try {
                option = jsonOptions.getJSONArray(i);
            } catch (JSONException e) {
                throw new BlockLoadingException("Error reading dropdown options.", e);
            }
            if (option != null && option.length() == 2) {
                try {
                    String displayName = option.getString(0);
                    String value = option.getString(1);
                    if (TextUtils.isEmpty(value)) {
                        throw new BlockLoadingException("Option values may not be empty");
                    }
                    optionList.add(new Option(value, displayName));
                } catch (JSONException e) {
                    throw new BlockLoadingException("Error reading option values.", e);
                }
            }
        }
    }
    return new FieldDropdown(name, new Options(optionList));
}

From source file:net.straylightlabs.archivo.net.MindCommandRecordingFolderItemSearch.java

private Map<String, List<Recording>> mapSeriesToRecordings(JSONArray items) {
    Map<String, List<Recording>> seriesToRecordings = new HashMap<>();
    for (int i = 0; i < items.length(); i++) {
        JSONObject o = items.getJSONObject(i);
        String bodyId = o.getString(BODY_ID);
        tivo.setBodyId(bodyId);//  www .  j a  v  a  2  s .  c om
        String recordingId = o.getString("childRecordingId");
        MindCommandRecordingSearch command = new MindCommandRecordingSearch(recordingId, bodyId);
        try {
            command.executeOn(this.client);
            Recording recording = command.getRecording();
            String seriesTitle = recording.getSeriesTitle();
            if (seriesToRecordings.containsKey(seriesTitle)) {
                seriesToRecordings.get(seriesTitle).add(recording);
            } else {
                List<Recording> recordings = new ArrayList<>();
                recordings.add(recording);
                seriesToRecordings.put(seriesTitle, recordings);
            }
        } catch (IOException e) {
            logger.error("Error: ", e);
        }
    }
    return seriesToRecordings;
}

From source file:com.googlecode.CallerLookup.Main.java

public void parseLookupEntries() {
    mLookupEntries = new HashMap<String, LookupEntry>();
    mUserLookupEntries = new HashMap<String, LookupEntry>();

    boolean updateFound = false;
    for (String fileName : getApplicationContext().fileList()) {
        if (fileName.equals(UPDATE_FILE)) {
            try {
                FileInputStream file = getApplicationContext().openFileInput(UPDATE_FILE);
                XmlPullParser xml = Xml.newPullParser();
                xml.setInput(file, null);
                parseLookupEntries(xml, mLookupEntries);
                file.close();//from w  w  w. j  a  v a2 s  . co  m
                updateFound = true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (fileName.equals(SAVED_FILE)) {
            try {
                FileInputStream file = getApplicationContext().openFileInput(SAVED_FILE);
                InputStreamReader reader = new InputStreamReader(file);
                char[] content = new char[8000];
                reader.read(content);
                JSONArray userLookupEntries = new JSONArray(new String(content));
                int count = userLookupEntries.length();
                for (int i = 0; i < count; i++) {
                    JSONObject userLookupEntry = userLookupEntries.getJSONObject(i);
                    mUserLookupEntries.put(userLookupEntry.getString("name"), new LookupEntry(userLookupEntry));
                }
                file.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    if (!updateFound) {
        XmlResourceParser xml = getApplicationContext().getResources().getXml(R.xml.lookups);
        parseLookupEntries(xml, mLookupEntries);
        xml.close();
    }
}

From source file:ti.mobileapptracker.MobileapptrackerModule.java

private List<MATEventItem> convertToMATEventItems(Object[] arrItemMaps) {
    List<MATEventItem> listItems = new ArrayList<MATEventItem>();

    try {/*w w  w. j a  v  a2 s  .  c  om*/
        JSONArray arr = new JSONArray(Arrays.toString(arrItemMaps));

        for (int i = 0; i < arr.length(); i++) {
            JSONObject item = arr.getJSONObject(i);

            String itemName = item.getString("item");
            int quantity = 0;
            double unitPrice = 0;
            double revenue = 0;
            String attribute1 = null;
            String attribute2 = null;
            String attribute3 = null;
            String attribute4 = null;
            String attribute5 = null;

            if (item.has("quantity")) {
                quantity = item.getInt("quantity");
            }
            if (item.has("unit_price")) {
                unitPrice = item.getDouble("unit_price");
            }
            if (item.has("revenue")) {
                revenue = item.getDouble("revenue");
            }

            if (item.has("attribute_sub1")) {
                attribute1 = item.getString("attribute_sub1");
            }
            if (item.has("attribute_sub2")) {
                attribute2 = item.getString("attribute_sub2");
            }
            if (item.has("attribute_sub3")) {
                attribute3 = item.getString("attribute_sub3");
            }
            if (item.has("attribute_sub4")) {
                attribute4 = item.getString("attribute_sub4");
            }
            if (item.has("attribute_sub5")) {
                attribute5 = item.getString("attribute_sub5");
            }

            MATEventItem eventItem = new MATEventItem(itemName, quantity, unitPrice, revenue, attribute1,
                    attribute2, attribute3, attribute4, attribute5);
            listItems.add(eventItem);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return listItems;
}