Example usage for org.json JSONArray getJSONObject

List of usage examples for org.json JSONArray getJSONObject

Introduction

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

Prototype

public JSONObject getJSONObject(int index) throws JSONException 

Source Link

Document

Get the JSONObject associated with an index.

Usage

From source file:org.schedulesdirect.grabber.ProgramTask.java

@Override
public void run() {
    long start = System.currentTimeMillis();
    DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.PROGRAMS, clnt.getHash(),
            clnt.getUserAgent(), clnt.getBaseUrl());
    try {//from w  w w. j  av a2 s.c  om
        JSONArray resp = Config.get().getObjectMapper().readValue(req.submitForJson(this.req), JSONArray.class);
        for (int i = 0; i < resp.length(); ++i) {
            JSONObject o = resp.getJSONObject(i);
            String id = o.optString("programID", "<unknown>");
            if (!JsonResponseUtils.isErrorResponse(o)) {
                if (id.startsWith("EP"))
                    seriesIds.add(Program.convertToSeriesId(id));
                Path p = vfs.getPath(targetDir, String.format("%s.txt", id));
                Files.write(p, o.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET), StandardOpenOption.WRITE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE);
            } else if (JsonResponseUtils.getErrorCode(o) == ApiResponse.INVALID_PROGID
                    || JsonResponseUtils.getErrorCode(o) == ApiResponse.PROGRAMID_QUEUED) {
                String msg = String.format("Missing program object: %s", id);
                if (!logMissingAtDebug)
                    LOG.warn(msg);
                else
                    LOG.debug(msg);
                if (retrySet != null)
                    retrySet.add(id);
            } else
                throw new InvalidJsonObjectException("Error received for Program", o.toString(3));
        }
    } catch (JSONException | JsonParseException e) {
        Grabber.failedTask = true;
        LOG.error("JSONError!", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        Grabber.failedTask = true;
        LOG.error("IOError receiving program data; filling in empty program info for non-existent program ids!",
                e);
        try {
            JSONArray ids = this.req;
            for (int i = 0; i < ids.length(); ++i) {
                String id = ids.getString(i);
                Path p = vfs.getPath(targetDir, String.format("%s.txt", id));
                if (!Files.exists(p))
                    Files.write(p, Program.EMPTY_PROGRAM.getBytes(ZipEpgClient.ZIP_CHARSET));
            }
        } catch (Exception x) {
            LOG.error("Unexpected error!", x);
            throw new RuntimeException(x);
        }
    }
    LOG.info(String.format("Completed ProgramTask in %dms [%d programs]", System.currentTimeMillis() - start,
            this.req.length()));
}

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//  ww  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  .  j a  v a  2  s  . c o  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: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  w w .  jav  a 2  s.  c  om
    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 w w .j av  a 2 s.  com*/
        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(/*  w  w w  .  java 2  s.  c  om*/
                                    "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.liferay.mobile.android.v7.announcementsentry.AnnouncementsEntryService.java

public JSONObject addEntry(long plid, long classNameId, long classPK, String title, String content, String url,
        String type, int displayDateMonth, int displayDateDay, int displayDateYear, int displayDateHour,
        int displayDateMinute, boolean displayImmediately, int expirationDateMonth, int expirationDateDay,
        int expirationDateYear, int expirationDateHour, int expirationDateMinute, int priority, boolean alert)
        throws Exception {
    JSONObject _command = new JSONObject();

    try {/*  www . j av  a  2s .com*/
        JSONObject _params = new JSONObject();

        _params.put("plid", plid);
        _params.put("classNameId", classNameId);
        _params.put("classPK", classPK);
        _params.put("title", checkNull(title));
        _params.put("content", checkNull(content));
        _params.put("url", checkNull(url));
        _params.put("type", checkNull(type));
        _params.put("displayDateMonth", displayDateMonth);
        _params.put("displayDateDay", displayDateDay);
        _params.put("displayDateYear", displayDateYear);
        _params.put("displayDateHour", displayDateHour);
        _params.put("displayDateMinute", displayDateMinute);
        _params.put("displayImmediately", displayImmediately);
        _params.put("expirationDateMonth", expirationDateMonth);
        _params.put("expirationDateDay", expirationDateDay);
        _params.put("expirationDateYear", expirationDateYear);
        _params.put("expirationDateHour", expirationDateHour);
        _params.put("expirationDateMinute", expirationDateMinute);
        _params.put("priority", priority);
        _params.put("alert", alert);

        _command.put("/announcementsentry/add-entry", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}

From source file:com.liferay.mobile.android.v7.announcementsentry.AnnouncementsEntryService.java

public JSONObject getEntry(long entryId) throws Exception {
    JSONObject _command = new JSONObject();

    try {//from  w  w w  .  j a  va2 s. c o m
        JSONObject _params = new JSONObject();

        _params.put("entryId", entryId);

        _command.put("/announcementsentry/get-entry", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}

From source file:com.liferay.mobile.android.v7.announcementsentry.AnnouncementsEntryService.java

public JSONObject updateEntry(long entryId, String title, String content, String url, String type,
        int displayDateMonth, int displayDateDay, int displayDateYear, int displayDateHour,
        int displayDateMinute, boolean displayImmediately, int expirationDateMonth, int expirationDateDay,
        int expirationDateYear, int expirationDateHour, int expirationDateMinute, int priority)
        throws Exception {
    JSONObject _command = new JSONObject();

    try {//from w  w w  .  ja v  a2s. c  om
        JSONObject _params = new JSONObject();

        _params.put("entryId", entryId);
        _params.put("title", checkNull(title));
        _params.put("content", checkNull(content));
        _params.put("url", checkNull(url));
        _params.put("type", checkNull(type));
        _params.put("displayDateMonth", displayDateMonth);
        _params.put("displayDateDay", displayDateDay);
        _params.put("displayDateYear", displayDateYear);
        _params.put("displayDateHour", displayDateHour);
        _params.put("displayDateMinute", displayDateMinute);
        _params.put("displayImmediately", displayImmediately);
        _params.put("expirationDateMonth", expirationDateMonth);
        _params.put("expirationDateDay", expirationDateDay);
        _params.put("expirationDateYear", expirationDateYear);
        _params.put("expirationDateHour", expirationDateHour);
        _params.put("expirationDateMinute", expirationDateMinute);
        _params.put("priority", priority);

        _command.put("/announcementsentry/update-entry", _params);
    } catch (JSONException _je) {
        throw new Exception(_je);
    }

    JSONArray _result = session.invoke(_command);

    if (_result == null) {
        return null;
    }

    return _result.getJSONObject(0);
}

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 . jav  a  2 s  .  co  m
        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;
}