Example usage for org.json.simple JSONObject containsKey

List of usage examples for org.json.simple JSONObject containsKey

Introduction

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

Prototype

boolean containsKey(Object key);

Source Link

Document

Returns true if this map contains a mapping for the specified key.

Usage

From source file:org.geotools.data.couchdb.client.CouchDBResponse.java

private String getErrorAndReason() {
    if (!isHttpOK()) {
        JSONObject err = (JSONObject) json;
        String res = null;//from  ww  w.  j  av  a2  s  . c o  m
        if (err.containsKey("error")) {
            res = err.get("error").toString();
        }
        if (err.containsKey("reason")) {
            res = res == null ? "" : res + ",";
            res = res + err.get("reason").toString();
        }
        if (res == null) {
            res = err.toJSONString();
        }
        return res;
    } else {
        throw new IllegalStateException("not an error");
    }
}

From source file:org.geotools.data.couchdb.CouchDBDataStore.java

@Override
protected List<Name> createTypeNames() throws IOException {
    List<Name> names = new ArrayList<Name>();
    JSONObject design = dbconn().getDesignDocument();

    // for now, expect that db is spatial
    // for each spatial view find a normal view with the same name
    // the spatial view should be setup to return id only
    // the normal view must return geojson
    // @todo delegate to strategy for db layout
    JSONObject spatial = (JSONObject) design.get("spatial"); // safe - internal to geocouch
    JSONObject views = (JSONObject) design.get("views"); // safe - internal to geocouch
    for (Object key : spatial.keySet()) {
        if (views.containsKey(key)) {
            // using the dot separator is ok, since dbnames cannot contain dots
            names.add(new NameImpl(couchURL, dbName + "." + key.toString()));
        }/* w w  w  .  jav a2s. c o m*/
    }
    return names;
}

From source file:org.imsglobal.lti.toolProvider.service.ToolSettings.java

/**
 * Get the tool settings./*from  www .  j  a  va 2 s . c  o m*/
 *
 * @param int          $mode       Mode for request (optional, default is current level only)
 *
 * @return mixed The array of settings if successful, otherwise false
 */
@SuppressWarnings("rawtypes")
public Map<String, List<String>> get(int mode) {
    JSONObject response = new JSONObject();
    Map<String, List<String>> parameter = new HashMap<String, List<String>>();
    if (mode == MODE_ALL_LEVELS) {
        LTIUtil.setParameter(parameter, "bubble", "all");
    } else if (mode == MODE_DISTINCT_NAMES) {
        LTIUtil.setParameter(parameter, "bubble", "distinct");
    }
    LTIMessage http = this.send("GET", parameter);
    JSONObject responseJson = http.getResponseJson();
    if (!http.isOk()) {
        response = null;
    } else if (simple) {
        response = responseJson;
    } else if (responseJson.containsKey("@graph")) {
        JSONObject graph = (JSONObject) responseJson.get("@graph");
        for (Object level : graph.keySet()) {
            JSONObject jlevel = (JSONObject) level;
            JSONObject settings = (JSONObject) jlevel.get("custom");
            settings.remove("@id");

            String type = (String) jlevel.get("@type");
            String theLevel = LEVEL_NAMES.get(type);

            response.put(theLevel, settings);
        }
    }
    //response is a JSONObject, with keys pointing to JSON objects.  Need to parse this down to 
    //Map<String, List<String>> to match the rest of the library, and get it out of JSON
    return parseToMap(response);
}

From source file:org.jasig.ssp.reference.AbstractReferenceTest.java

/**
 * Tests supported HTTP methods with negative tests. Should be authenticated before running.
 * Note: invalid content can be valid and this method will make changes to make it invalid
 *     Do not expect passed objects to be valid after this test.
 * @param urlToTest//  w w  w . j a  va2  s .  c o m
 * @param invalidContentToPostPut
 * @param validContentToVerify
 */
public final void referenceNegativeSupportedMethodTest(final String urlToTest,
        final JSONObject invalidContentToPostPut, final JSONObject validContentToVerify) {

    int checkResultCount = 0;

    //get all (store results to check at the end)
    Response checkItemCount = expect().statusCode(200).log().ifError().contentType("application/json").when()
            .get(urlToTest);

    String result = checkItemCount.getBody().jsonPath().getJsonObject("results").toString();

    if (StringUtils.isNotBlank(result)) {
        checkResultCount = Integer.parseInt(result);
    } else {
        LOGGER.error("Get all method failed in Negative Test! No results returned.");
        fail("GET all failed Negative Tests.");
    }

    //get invalid id
    expect().statusCode(404).contentType("application/json").when()
            .get(urlToTest + "/70b982b0-68d7-11e3-949a-0800200c9a66");

    invalidContentToPostPut.remove("id");
    final String name = invalidContentToPostPut.get("name").toString();
    invalidContentToPostPut.remove("name");

    //post empty name
    expect().statusCode(400).given().contentType("application/json").body(invalidContentToPostPut).when()
            .post(urlToTest);

    invalidContentToPostPut.put("name", name);

    if (invalidContentToPostPut.containsKey("code")) {
        invalidContentToPostPut.remove("code");

        //post empty code
        expect().statusCode(500).given().contentType("application/json").body(invalidContentToPostPut).when()
                .post(urlToTest);
    }

    invalidContentToPostPut.put("objectStatus", "");

    //put
    expect().statusCode(500).given().contentType("application/json").body(invalidContentToPostPut).when()
            .put(urlToTest + "/" + validContentToVerify.get("id"));

    //verify put didn't work
    expect().statusCode(200).contentType("application/json").body("", equalTo(validContentToVerify)).when()
            .get(urlToTest + "/" + validContentToVerify.get("id"));

    //delete
    expect().statusCode(404).when().delete(urlToTest + "/70b982b0-68d7-11e3-949a-0800200c9a66");

    //get all (verify result # is unchanged)
    expect().statusCode(200).log().ifError().contentType("application/json")
            .body("results", equalTo(checkResultCount)).when().get(urlToTest);

}

From source file:org.jenkinsci.plugins.drupal.beans.DrushInvocation.java

/**
 * Return true if the site is already installed, false otherwise.
 *//*from   w ww .ja  va  2 s  .c  o  m*/
public boolean status() {
    ArgumentListBuilder args = getArgumentListBuilder();
    args.add("status").add("--format=json");

    OutputStream json = new ByteArrayOutputStream();
    try {
        execute(args, new StreamTaskListener(json));
    } catch (IOException e1) {
        listener.getLogger().println(e1);
        return false;
    } catch (InterruptedException e2) {
        listener.getLogger().println(e2);
        return false;
    }

    JSONObject values = (JSONObject) JSONValue.parse(json.toString());
    if (values == null) {
        listener.getLogger().println("[DRUPAL] Could not determine the site status.");
        return false;
    }

    return values.containsKey("db-name");
}

From source file:org.jolokia.backend.BackendManagerTest.java

@Test
public void convertError() throws MalformedObjectNameException {
    BackendManager backendManager = new BackendManager(config, log);
    Exception exp = new IllegalArgumentException("Hans", new IllegalStateException("Kalb"));
    JmxRequest req = new JmxRequestBuilder(RequestType.READ, "java.lang:type=Memory").build();
    JSONObject jsonError = (JSONObject) backendManager.convertExceptionToJson(exp, req);
    assertTrue(!jsonError.containsKey("stackTrace"));
    assertEquals(jsonError.get("message"), "Hans");
    assertEquals(((JSONObject) jsonError.get("cause")).get("message"), "Kalb");
    backendManager.destroy();//  www  . j a va 2 s . c  om
}

From source file:org.jolokia.client.J4pClient.java

private void verifyBulkJsonResponse(JSONAware pJsonResponse) throws J4pException {
    if (!(pJsonResponse instanceof JSONArray)) {
        if (pJsonResponse instanceof JSONObject) {
            JSONObject errorObject = (JSONObject) pJsonResponse;

            if (!errorObject.containsKey("status") || (Long) errorObject.get("status") != 200) {
                throw new J4pRemoteException(null, errorObject);
            }/*  ww w .  j av a2 s  .com*/
        }
        throw new J4pException("Invalid JSON answer for a bulk request (expected an array but got a "
                + pJsonResponse.getClass() + ")");
    }
}

From source file:org.jolokia.client.request.J4pReadResponse.java

/**
 * Get the value for a certain MBean and a given attribute. This method is especially
 * useful if the request leading to this response was done for multiple MBeans (i.e.
 * a read for an MBean pattern) and multiple attributes. However, this method can be
 * used for a request for single MBeans and single attributes as well, but then the given
 * parameters must match the parameters given in the request.
 *
 * @param pObjectName name of the Mbean or <code>null</code> if the request was only for a single
 *        Mbeans in which case this single MBean is taken from the request
 * @param pAttribute the attribute or <code>null</code> if the request was for a single
 *        attribute in which case the attribute name is taken from the request
 * @param <V> the object type of the return value ({@link String},{@link Map} or {@link List})
 * @return the value//  ww w  .  j a v a 2s . com
 * @throws IllegalArgumentException if there was no value for the given parameters or if <code>null</code>
 *         was given for given for one or both arguments and the request was for multiple MBeans
 *         or attributes.
 */
public <V> V getValue(ObjectName pObjectName, String pAttribute) {
    ObjectName requestMBean = getRequest().getObjectName();
    if (requestMBean.isPattern()) {
        JSONObject mAttributes = getAttributesForObjectNameWithPatternRequest(pObjectName);
        if (!mAttributes.containsKey(pAttribute)) {
            throw new IllegalArgumentException("No attribute " + pAttribute + " for ObjectName " + pObjectName
                    + " returned for" + " the given request");
        }
        return (V) mAttributes.get(pAttribute);
    } else {
        return (V) getValue(pAttribute);
    }
}

From source file:org.jolokia.client.request.J4pReadResponse.java

/**
 * Get the value for a single attribute. This method is appropriate if the request was done for a single
 * MBean (no pattern), but multiple attributes. If it is called for a request with non-pattern MBean
 * and a single attribute, the given attribute must match the attribute of the request. If this method is
 * called with a <code>null</code> argument, then it will return the value if the request was for
 * a single attribute, otherwise it will raise an {@link IllegalArgumentException}
 *
 * @param pAttribute attribute for which to get the value
 * @param <V> value type/*  w  w w.j  av a2s . c  o m*/
 * @return value
 * @throws IllegalArgumentException if the attribute could not be found in the return value or if this method
 * is called with a <code>null</code> argument, but the request leads to multiple attribute return values.
 */
public <V> V getValue(String pAttribute) {
    J4pReadRequest request = getRequest();
    ObjectName requestBean = request.getObjectName();
    if (requestBean.isPattern()) {
        throw new IllegalArgumentException(
                "Attributes without ObjectName can be fetched only for non-pattern request (current: "
                        + requestBean.getCanonicalName() + ")");
    }
    // The attribute names are the same as from the request
    if (request.hasSingleAttribute()) {
        // Contains only a single attribute:
        if (pAttribute != null && !pAttribute.equals(request.getAttribute())) {
            throw new IllegalArgumentException(
                    "Given attribute " + pAttribute + " doesnt match single attribute " + "given "
                            + request.getAttribute() + " in the request");
        }
        return (V) getValue();
    } else {
        JSONObject attributes = getValue();
        if (pAttribute == null) {
            throw new IllegalArgumentException(
                    "Cannot use null-attribute name to fetch a value from a multi-attribute request");
        }
        if (!attributes.containsKey(pAttribute)) {
            throw new IllegalArgumentException(
                    "No such key " + pAttribute + " in the set of returned attribute values");
        }
        return (V) attributes.get(pAttribute);
    }
}

From source file:org.jolokia.client.request.ValidatingResponseExtractor.java

public <RESP extends J4pResponse<REQ>, REQ extends J4pRequest> RESP extract(REQ pRequest, JSONObject pJsonResp)
        throws J4pRemoteException {

    int status = pJsonResp.containsKey("status") ? ((Long) pJsonResp.get("status")).intValue() : 0;

    if (!allowedCodes.contains(status)) {
        throw new J4pRemoteException(pRequest, pJsonResp);
    }/* w w w .  ja v a  2s.  co  m*/
    return status == 200 ? pRequest.<RESP>createResponse(pJsonResp) : null;
}