Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

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

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

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. 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 assignTerms(Storage storage, String path, JSONObject data)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException {
    JSONObject fields = data.optJSONObject("fields");
    String insId = "";

    if (fields.has("terms")) {
        Record vr = this.spec.getRecord("vocab");
        Record thisr = spec.getRecord("vocab");
        String sid = fields.getString("shortIdentifier");
        String name = fields.getString("displayName");
        insId = "vocab-" + sid;
        if (create) {
            Map<String, String> options = new HashMap<String, String>();
            options.put("id", insId);
            options.put("title", name);
            options.put("web-url", sid);
            options.put("title-ref", sid);

            Instance ins = new Instance(thisr, options);
            vr.addInstance(ins);/*from   w w  w  .java 2s.  c  o  m*/
        }
        ctl.get(storage, sid, vr, 0);
    }

}

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  www  .j a va  2s .  com
                                    "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:org.collectionspace.chain.csp.webui.record.RecordCreateUpdate.java

private boolean setPayloadField(String fieldName, JSONObject payloadOut, JSONObject fieldsSrc,
        JSONObject dataSrc, String defaultValue) throws JSONException {
    boolean result = true;

    if (fieldsSrc != null && fieldsSrc.has(fieldName)) {
        payloadOut.put(fieldName, fieldsSrc.getString(fieldName));
    } else if (dataSrc != null && dataSrc.has(fieldName)) {
        payloadOut.put(fieldName, dataSrc.getString(fieldName));
    } else if (defaultValue != null) {
        payloadOut.put(fieldName, defaultValue);
    } else {//  w ww .  j  av a2 s.co m
        result = false;
    }

    return result;
}

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

private void store_set(Storage storage, UIRequest request, String path) throws UIException {
    try {//from   w ww  . j  av a2s .  c  om
        JSONObject restrictions = new JSONObject();
        JSONObject data = request.getJSONBody();

        if (this.base.equals("role")) {
            JSONObject fields = data.optJSONObject("fields");
            if ((fields.optString("roleName") == null || fields.optString("roleName").equals(""))
                    && fields.optString("displayName") != null) {
                String test = fields.optString("displayName");
                test = test.toUpperCase();
                test.replaceAll("\\W", "_");
                fields.put("roleName", "ROLE_" + test);
                data.put("fields", fields);
            }
            // If we are updating a role, then we need to clear the userperms cache
            // Note that creating a role does not impact things until we assign it
            if (!create) {
                ResponseCache.clearCache(ResponseCache.USER_PERMS_CACHE);
            }
        }

        if (this.record.getID().equals("media")) {
            JSONObject fields = data.optJSONObject("fields");
            // Handle linked media references
            if (!fields.has("blobCsid") || StringUtils.isEmpty(fields.getString("blobCsid"))) { // If has blobCsid, already has media link so do nothing more
                // No media, so consider the source
                // "sourceUrl" is not a declared field in the app layer config, but the UI passes it in
                // Can consider mapping srcUri to this if want to clean that up
                if (fields.has("sourceUrl")) {
                    // We have a source - see where it is from
                    String uri = fields.getString("sourceUrl");
                    if (uri.contains(BLOBS_SERVICE_URL_PATTERN)) {
                        // This is an uploaded blob, so just pull the csid and set into blobCsid
                        String[] parts = uri.split(BLOBS_SERVICE_URL_PATTERN); // Split to get CSID
                        String[] bits = parts[1].split("/"); // Strip off anything trailing the CSID
                        fields.put("blobCsid", bits[0]);
                    } else { // This must be an external Url source
                        // External Source is handled as params to the CREATE/UPDATE of the media record
                        restrictions.put(Record.BLOB_SOURCE_URL, uri);
                        // Tell the Services to delete the original after creating derivatives
                        restrictions.put(Record.BLOB_PURGE_ORIGINAL, Boolean.toString(true));
                    }
                    fields.remove("sourceUrl");
                    data.put("fields", fields);
                }
            }
        }

        if (this.record.getID().equals("output")) {
            //
            // Invoke a report
            //
            ReportUtils.invokeReport(this, storage, request, path);
        } else if (this.record.getID().equals("batchoutput")) {
            //do a read instead of a create as reports are special and evil

            JSONObject fields = data.optJSONObject("fields");
            JSONObject payload = new JSONObject();
            payload.put("mode", "single");

            if (fields.has("mode")) {
                payload.put("mode", fields.getString("mode"));
            }
            if (fields.has("docType")) {
                String type = spec.getRecordByWebUrl(fields.getString("docType")).getServicesTenantSg();
                payload.put("docType", type);
            }
            if (fields.has("singleCSID")) {
                payload.put("singleCSID", fields.getString("singleCSID"));
            } else if (fields.has("groupCSID")) {
                payload.put("singleCSID", fields.getString("csid"));
            }

            JSONObject out = storage.retrieveJSON(base + "/" + path, payload);

            byte[] data_array = (byte[]) out.get("getByteBody");
            String contentDisp = out.has("contentdisposition") ? out.getString("contentdisposition") : null;
            request.sendUnknown(data_array, out.getString("contenttype"), contentDisp);
            request.setCacheMaxAgeSeconds(0); // Ensure we do not cache report output.
            //request.sendJSONResponse(out);
            request.setOperationPerformed(create ? Operation.CREATE : Operation.UPDATE);
        } else {
            //
            // <Please document this clause.>
            //
            FieldSet displayNameFS = this.record.getDisplayNameField();
            String displayNameFieldName = (displayNameFS != null) ? displayNameFS.getID() : null;
            boolean remapDisplayName = false;
            String remapDisplayNameValue = null;
            boolean quickie = false;
            if (create) {
                quickie = (data.has("_view") && data.getString("_view").equals("autocomplete"));
                remapDisplayName = quickie && !"displayName".equals(displayNameFieldName);
                // Check to see if displayName field needs remapping from UI
                if (remapDisplayName) {
                    // Need to map the field for displayName, and put it into a proper structure
                    JSONObject fields = data.getJSONObject("fields");
                    remapDisplayNameValue = fields.getString("displayName");
                    if (remapDisplayNameValue != null) {
                        // This needs generalizing, in case the remapped name is nested
                        /*
                         * From vocab handling where we know where the termDisplayName is
                        FieldSet parentTermGroup = (FieldSet)displayNameFS.getParent();
                        JSONArray parentTermInfoArray = new JSONArray();
                        JSONObject termInfo = new JSONObject();
                        termInfo.put(displayNameFieldName, remapDisplayNameValue);
                        parentTermInfoArray.put(termInfo);
                        */
                        fields.put(displayNameFieldName, remapDisplayNameValue);
                        fields.remove("displayName");
                    }
                }
                path = sendJSON(storage, null, data, restrictions); // REM - We needed a way to send query params, so I'm adding "restrictions" here
                data.put("csid", path);
                data.getJSONObject("fields").put("csid", path);
                // Is this needed???
                /*
                String refName = data.getJSONObject("fields").getString("refName");
                data.put("urn", refName);
                data.getJSONObject("fields").put("urn", refName);
                // This seems wrong - especially when we create from existing.
                if(remapDisplayName){
                   JSONObject newdata = new JSONObject();
                   newdata.put("urn", refName);
                   newdata.put("displayName",quickieDisplayName);
                   data = newdata;
                }
                 */
            } else {
                path = sendJSON(storage, path, data, restrictions);
            }

            if (path == null) {
                throw new UIException("Insufficient data for create (no fields?)");
            }

            if (this.base.equals("role")) {
                assignPermissions(storage, path, data);
            }
            if (this.base.equals("termlist")) {
                assignTerms(storage, path, data);
            }

            data = reader.getJSON(storage, path); // We do a GET now to read back what we created.
            if (quickie) {
                JSONObject newdata = new JSONObject();
                JSONObject fields = data.getJSONObject("fields");
                String displayName = fields.getString(remapDisplayName ? displayNameFieldName : "displayName");
                newdata.put("displayName", remapDisplayNameValue);
                String refName = fields.getString("refName");
                newdata.put("urn", refName);
                data = newdata;
            }

            request.sendJSONResponse(data);
            request.setOperationPerformed(create ? Operation.CREATE : Operation.UPDATE);
            if (create)
                request.setSecondaryRedirectPath(new String[] { url_base, path });
        }
    } catch (JSONException x) {
        throw new UIException("Failed to parse JSON: " + x, x);
    } catch (ExistException x) {
        UIException uiexception = new UIException(x.getMessage(), 0, "", x);
        request.sendJSONResponse(uiexception.getJSON());
    } catch (UnimplementedException x) {
        throw new UIException("Unimplemented exception: " + x, x);
    } catch (UnderlyingStorageException x) {
        UIException uiexception = new UIException(x.getMessage(), x.getStatus(), x.getUrl(), x);
        request.setStatus(x.getStatus());
        request.setFailure(true, uiexception);
        request.sendJSONResponse(uiexception.getJSON());
    } catch (Exception x) {
        throw new UIException(x);
    }

}

From source file:com.example.espn.headlines.Util.java

/**
 * Parse a server response into a JSON Object. This is a basic
 * implementation using org.json.JSONObject representation. More
 * sophisticated applications may wish to do their own parsing.
 *
 * The parsed JSON is checked for a variety of error fields and
 * a FacebookException is thrown if an error condition is set,
 * populated with the error message and error type or code if
 * available./*w  w w .j a v a 2s.  co m*/
 *
 * @param response - string representation of the response
 * @return the response as a JSON Object
 * @throws JSONException - if the response is not valid JSON
 * @throws FacebookError - if an error condition is set
 */
public static JSONObject parseJson(String response) throws JSONException, FacebookError {
    // Edge case: when sending a POST request to /[post_id]/likes
    // the return value is 'true' or 'false'. Unfortunately
    // these values cause the JSONObject constructor to throw
    // an exception.
    if (response.equals("false")) {
        throw new FacebookError("request failed");
    }
    if (response.equals("true")) {
        response = "{value : true}";
    }
    JSONObject json = new JSONObject(response);

    // errors set by the server are not consistent
    // they depend on the method and endpoint
    if (json.has("error")) {
        JSONObject error = json.getJSONObject("error");
        throw new FacebookError(error.getString("message"), error.getString("type"), 0);
    }
    if (json.has("error_code") && json.has("error_msg")) {
        throw new FacebookError(json.getString("error_msg"), "",
                Integer.parseInt(json.getString("error_code")));
    }
    if (json.has("error_code")) {
        throw new FacebookError("request failed", "", Integer.parseInt(json.getString("error_code")));
    }
    if (json.has("error_msg")) {
        throw new FacebookError(json.getString("error_msg"));
    }
    if (json.has("error_reason")) {
        throw new FacebookError(json.getString("error_reason"));
    }
    return json;
}

From source file:net.henriquerocha.android.codebits.api.User.java

public User(JSONObject jsonObject) throws JSONException {
    this.name = jsonObject.getString("name");
    this.bio = jsonObject.getString("bio");
    this.karma = jsonObject.getString("karma");
    this.avatar = jsonObject.getString("avatar");
}

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);/*from  ww  w .  java2s  .  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 av a  2s  .  c  o 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 {//from www. ja va  2s .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;
}