Example usage for org.json JSONObject get

List of usage examples for org.json JSONObject get

Introduction

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

Prototype

public Object get(String key) throws JSONException 

Source Link

Document

Get the value object associated with a key.

Usage

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

private void deleteAllRelations(Storage storage, String csid)
        throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException {
    JSONObject r = new JSONObject();
    r.put("src", base + "/" + csid);
    // XXX needs pagination support CSPACE-1819
    JSONObject data = storage.getPathsJSON("relations/main", r);
    String[] paths = (String[]) data.get("listItems");
    for (String relation : paths) {
        storage.deleteJSON("relations/main/" + relation);
    }//from  w w w  .  j  a va2  s . co m
}

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

private void store_set(Storage storage, UIRequest request, String path) throws UIException {
    try {/* w  w w  .  j  a va2  s .  c  o m*/
        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:org.everit.json.schema.IntegrationTest.java

@Parameters(name = "{2}")
public static List<Object[]> params() {
    List<Object[]> rval = new ArrayList<>();
    Reflections refs = new Reflections("org.everit.json.schema.draft4", new ResourcesScanner());
    Set<String> paths = refs.getResources(Pattern.compile(".*\\.json"));
    for (String path : paths) {
        if (path.indexOf("/optional/") > -1 || path.indexOf("/remotes/") > -1) {
            continue;
        }/*from w w  w .j a  va  2  s .  c o  m*/
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        JSONArray arr = loadTests(IntegrationTest.class.getResourceAsStream("/" + path));
        for (int i = 0; i < arr.length(); ++i) {
            JSONObject schemaTest = arr.getJSONObject(i);
            JSONArray testcaseInputs = schemaTest.getJSONArray("tests");
            for (int j = 0; j < testcaseInputs.length(); ++j) {
                JSONObject input = testcaseInputs.getJSONObject(j);
                Object[] params = new Object[5];
                params[0] = "[" + fileName + "]/" + schemaTest.getString("description");
                params[1] = schemaTest.get("schema");
                params[2] = "[" + fileName + "]/" + input.getString("description");
                params[3] = input.get("data");
                params[4] = input.getBoolean("valid");
                rval.add(params);
            }
        }
    }
    return rval;
}

From source file:com.phonegap.App.java

/**
 * Load the url into the webview.//from w  ww  .  j  a v a  2  s .c o  m
 * 
 * @param url
 * @param props         Properties that can be passed in to the DroidGap activity (i.e. loadingDialog, wait, ...)
 * @throws JSONException 
 */
public void loadUrl(String url, JSONObject props) throws JSONException {
    System.out.println("App.loadUrl(" + url + "," + props + ")");
    int wait = 0;

    // If there are properties, then set them on the Activity
    if (props != null) {
        JSONArray keys = props.names();
        for (int i = 0; i < keys.length(); i++) {
            String key = keys.getString(i);
            if (key.equals("wait")) {
                wait = props.getInt(key);
            } else {
                Object value = props.get(key);
                if (value == null) {

                } else if (value.getClass().equals(String.class)) {
                    this.ctx.getIntent().putExtra(key, (String) value);
                } else if (value.getClass().equals(Boolean.class)) {
                    this.ctx.getIntent().putExtra(key, (Boolean) value);
                } else if (value.getClass().equals(Integer.class)) {
                    this.ctx.getIntent().putExtra(key, (Integer) value);
                }
            }
        }
    }

    // If wait property, then delay loading
    if (wait > 0) {
        ((DroidGap) this.ctx).loadUrl(url, wait);
    } else {
        ((DroidGap) this.ctx).loadUrl(url);
    }
}

From source file:com.dzt.uberclone.HomeFragment.java

private void setLocationName(String json) {
    String locationname = "";
    try {//from  w  w  w. j ava2 s  .  co m
        JSONObject jsonObject = new JSONObject(json);
        try {

            locationname = ((JSONArray) jsonObject.get("results")).getJSONObject(0)
                    .getString("formatted_address");

        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Log.d("location = ", locationname);
    selectPickup.setText(locationname);
    getNearbyUbers();
}

From source file:edu.mit.scratch.ScratchProject.java

public ScratchProject update() throws ScratchProjectException {
    try {/*from   w w  w.j av  a 2  s  . c o  m*/
        final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build();

        final CookieStore cookieStore = new BasicCookieStore();
        final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en");
        lang.setDomain(".scratch.mit.edu");
        lang.setPath("/");
        cookieStore.addCookie(lang);

        final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig)
                .setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64)"
                        + " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/" + "537.36")
                .setDefaultCookieStore(cookieStore).build();
        CloseableHttpResponse resp;

        final HttpUriRequest update = RequestBuilder.get()
                .setUri("https://scratch.mit.edu/api/v1/project/" + this.getProjectID() + "/?format=json")
                .addHeader("Accept",
                        "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
                .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu")
                .addHeader("Accept-Encoding", "gzip, deflate, sdch")
                .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json")
                .addHeader("X-Requested-With", "XMLHttpRequest").build();
        try {
            resp = httpClient.execute(update);
            System.out.println(resp.getStatusLine().toString());
        } catch (final IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        } catch (UnsupportedOperationException | IOException e) {
            e.printStackTrace();
            throw new ScratchProjectException();
        }

        final StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null)
            result.append(line);
        System.out.println("projdata:" + result.toString());
        final JSONObject jsonOBJ = new JSONObject(result.toString().trim());

        final Iterator<?> keys = jsonOBJ.keys();

        while (keys.hasNext()) {
            final String key = "" + keys.next();
            final Object o = jsonOBJ.get(key);
            if (o instanceof JSONObject)
                this.creator = "" + ((JSONObject) o).get("username");
            else {
                final String val = "" + o;

                switch (key) {
                case "creator":
                    this.creator = val;
                    break;
                case "datetime_shared":
                    this.share_date = val;
                    break;
                case "description":
                    this.description = val;
                    break;
                case "favorite_count":
                    this.favorite_count = val;
                    break;
                case "id":
                    this.ID = Integer.parseInt(val);
                    break;
                case "love_count":
                    this.love_count = val;
                    break;
                case "resource_uri":
                    this.resource_uri = val;
                    break;
                case "thumbnail":
                    this.thumbnail = val;
                    break;
                case "title":
                    this.title = val;
                    break;
                case "view_count":
                    this.view_count = val;
                    break;
                default:
                    System.out.println("Missing reference:" + key);
                    break;
                }
            }
        }
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    } catch (final IOException e) {
        e.printStackTrace();
        throw new ScratchProjectException();
    }

    return this;
}

From source file:org.indigo.cdmi.backend.radosgw.JsonResponseTranlator.java

/**
 * Basing on passed profileInfo, creates object of type BackendCapability.
 * //from  www  .  j a v  a2s  .  co m
 * @param profileInfo Profile described in JSOSObject.
 * @return Object of BackendCapability derived from passed profileInfo.
 */
private BackendCapability createBackedCapability(JSONObject profileInfo) {

    /*
     * determine value of name parameter to be used with BackendCapability 
     */
    String profileName = profileInfo.getString(JSON_KEY_NAME);

    /*
     * determine value of type attribute to be used with BackendCapability
     */
    BackendCapability.CapabilityType type = null;
    String typeAsString = profileInfo.getString(JSON_KEY_TYPE);
    switch (typeAsString) {
    case CDMI_OBJECT_TYPE_CONTAINER:
        type = BackendCapability.CapabilityType.CONTAINER;
        break;
    case CDMI_OBJECT_TYPE_DATAOBJECT:
        type = BackendCapability.CapabilityType.DATAOBJECT;
        break;
    default:
        throw new RuntimeException("Unknown capability type");
    }

    /*
     * create new instance of BackendCapability 
     * (it is empty for now, the metadata and capabilities properties have to be created, 
     * populated and passed to the BackendCapability object)
     */
    final BackendCapability returnBackendCapability = new BackendCapability(profileName, type);

    /*
     * create capabilities object (to be populated and injected into returned BackendCapability)
     */
    Map<String, Object> capabilities = new HashMap<>();

    /*
     * Add always present capabilities
     */
    capabilities.put("cdmi_capabilities_templates", "true");
    capabilities.put("cdmi_capabilities_exact_inherit", "true");

    /*
     * create metadata object (to be populated and injected into returned BackendCapability)
     */
    Map<String, Object> metadata = new HashMap<>();

    /*
     * iterate through metadata in profileInfo and populate capabilities and 
     * metadata in BackendCapability object
     */
    JSONObject metadataObj = profileInfo.getJSONObject(JSON_KEY_METADATA);

    log.debug("Processing metadata array from profile returned by BackendGateway");

    Iterator<?> keys = metadataObj.keys();
    while (keys.hasNext()) {

        /*
         * get key name for current item in metadata array
         */
        String key = (String) keys.next();

        /*
         * get value assigned to the current key, and convert the value to String
         * NOTE: The convention is required because returned value can be for example of array type 
         * or of another JSONObject, it not necessary has to be String, so usage of 
         * metadataObj.getString(key) would be wrong 
         */
        Object valueObj = metadataObj.get(key);

        log.debug("Current metadata key: {}", key);
        log.debug("Current metadata value: {}", valueObj);
        log.debug("Metadata value class/type is: {}", valueObj.getClass());

        /*
         * Create key and value to be added to capabilities.
         * Separate variables for key and value objects are introduced deliberately 
         * to note that in future or in case of any special values, an additional 
         * logic / calculation can be required to obtain key and value to be used 
         * with capabilities map 
         */
        String cdmiCapabilityKey = key;
        String cdmiCapabilityValue = "true";

        /*
         * add "calculated" key and value to the capabilities map
         */
        capabilities.put(cdmiCapabilityKey, cdmiCapabilityValue);

        /*
         * see above comments for capabilities related keys and values
         */
        String cdmiMetadataKey = key;
        Object cdmiMetadataValue = valueObj;

        /*
         * add "calculated" key and value to the metadata map
         */
        metadata.put(cdmiMetadataKey, cdmiMetadataValue);

    } // while()

    //capabilities.put("cdmi_capabilities_allowed", "true");

    /*
     * process allowed profiles
     */
    try {

        JSONArray allowedProfiles = profileInfo.getJSONArray(JSON_KEY_ALLOWED_PROFILES);
        String profilesUris = profilesToUris(allowedProfiles, retriveObjectTypeAsString(profileInfo));
        log.debug("allowedProfiles: {}", allowedProfiles);
        log.debug("profilesURIs: {}", profilesUris);

        metadata.put("cdmi_capabilities_allowed", profilesUris);

    } catch (JSONException ex) {

        log.debug("No {} key in processed JSON document", JSON_KEY_ALLOWED_PROFILES);

    } // try{}

    returnBackendCapability.setCapabilities(capabilities);
    returnBackendCapability.setMetadata(metadata);

    return returnBackendCapability;

}

From source file:org.indigo.cdmi.backend.radosgw.JsonResponseTranlator.java

/**
 * Basing on passed JSON in String format, creates object of CdmiObjecStatus.
 * (Translates JSON in String format into CdmiObjectStatus)
 *///from w  w w . j  av  a  2  s. c  o m
@Override
public CdmiObjectStatus getCdmiObjectStatus(String gatewayResponse) {

    //log.debug("Translate {} to CdmiObjectStatus", gatewayResponse);

    Map<String, Object> monitoredAttributes = new HashMap<>();

    JSONObject profile = new JSONObject(gatewayResponse);
    //log.debug("profile: {}", profile);

    JSONObject metadataProvided = profile.getJSONObject("metadata_provided");
    //log.debug("metadata_provided: {}", metadataProvided);

    Iterator<?> keys = metadataProvided.keys();
    while (keys.hasNext()) {

        /*
         * get key name for current item in metadata array
         */
        String key = (String) keys.next();
        //log.debug("key: {}", key);

        Object metadataProvidedAsObj = metadataProvided.get(key);
        //String metadataProvidedAsString = metadataProvidedAsObj.toString();

        //monitoredAttributes.put(key, metadataProvidedAsString);
        monitoredAttributes.put(key, metadataProvidedAsObj);

    }

    String profileName = profile.getString("name");
    String type = profile.getString("type");

    String currentCapabilitiesUri = "/cdmi_capabilities/" + type + "/" + profileName;

    return new CdmiObjectStatus(monitoredAttributes, currentCapabilitiesUri, null);

}

From source file:com.mobile.system.db.abatis.AbatisService.java

/**
  */*  w ww. ja  v a  2  s .  c  om*/
  */
public int execute(String sqlId, JSONObject json) {

    Map<String, Object> map = null;
    if (json != null) {
        map = new HashMap<String, Object>();

        for (int j = 0; j < json.names().length(); j++) {
            String strKey = null;
            try {
                strKey = (String) json.names().get(j);
                map.put(strKey, json.get(strKey));
            } catch (JSONException ex) {
                Logger.getLogger(AbatisService.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    return execute(sqlId, map);
}

From source file:org.cloudfoundry.client.lib.util.JsonUtil.java

public static Map<String, Object> convertJsonToMap(JSONObject json) throws JSONException {
    Map<String, Object> retMap = new HashMap<String, Object>();
    JSONObject jo = new JSONObject(json.toString());
    for (String key : JsonUtil.keys(jo)) {
        if (jo.get(key.toString()) instanceof JSONObject) {
            retMap.put(key.toString(), convertJsonToMap(jo.getJSONObject(key.toString())));
        } else {// w ww .  ja v  a 2 s.  c  o m
            retMap.put(key.toString(), jo.getString(key.toString()));
        }
    }
    return retMap;
}