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.neo4j.gis.spatial.indexfilter.DynamicIndexReader.java

private boolean queryNodeProperties(Node node, JSONObject properties) {
    if (properties != null) {
        if (properties.containsKey("geometry")) {
            System.out.println("Unexpected 'geometry' in query string");
            properties.remove("geometry");
        }// w  ww  .j  a  va 2s.  co m

        for (Object key : properties.keySet()) {
            Object value = node.getProperty(key.toString(), null);
            Object match = properties.get(key);
            // TODO: Find a better way to solve minor type mismatches (Long!=Integer) than the string conversion below
            if (value == null
                    || (match != null && !value.equals(match) && !value.toString().equals(match.toString()))) {
                return false;
            }
        }
    }

    return true;
}

From source file:org.opennms.netmgt.notifd.AbstractSlackCompatibleNotificationStrategy.java

/** {@inheritDoc} */
@SuppressWarnings("unchecked")
public int send(List<Argument> arguments) {

    m_arguments = arguments;/*from   w ww .  ja va  2 s  . com*/

    String url = getUrl();
    if (url == null) {
        LOG.error("send: url must not be null");
        return 1;
    }
    String iconUrl = getIconUrl();
    String iconEmoji = getIconEmoji();
    String channel = getChannel();
    String message = buildMessage(arguments);

    final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setConnectionTimeout(3000)
            .setSocketTimeout(3000).useSystemProxySettings();

    HttpPost postMethod = new HttpPost(url);

    JSONObject jsonData = new JSONObject();
    jsonData.put("username", getUsername());
    if (iconUrl != null) {
        jsonData.put("icon_url", iconUrl);
    }
    if (iconEmoji != null) {
        jsonData.put("icon_emoji", iconEmoji);
    }
    if (channel != null) {
        jsonData.put("channel", channel);
    }
    jsonData.put("text", message);

    if (jsonData.containsKey("icon_url") && jsonData.containsKey("icon_emoji")) {
        LOG.warn("Both URL and emoji specified for icon. Sending both; behavior is undefined.");
    }

    LOG.debug("Prepared JSON POST data for webhook is: {}", jsonData.toJSONString());
    final HttpEntity entity = new StringEntity(jsonData.toJSONString(), ContentType.APPLICATION_JSON);
    postMethod.setEntity(entity);
    // Mattermost 1.1.0 does not like having charset specified alongside Content-Type
    postMethod.setHeader("Content-Type", "application/json");

    String contents = null;
    int statusCode = -1;
    try {
        CloseableHttpResponse response = clientWrapper.getClient().execute(postMethod);
        statusCode = response.getStatusLine().getStatusCode();
        contents = EntityUtils.toString(response.getEntity());
        LOG.debug("send: Contents is: {}", contents);
    } catch (IOException e) {
        LOG.error("send: I/O problem with webhook post/response: {}", e);
        throw new RuntimeException("Problem with webhook post: " + e.getMessage());
    } finally {
        IOUtils.closeQuietly(clientWrapper);
    }

    if ("ok".equals(contents)) {
        LOG.debug("Got 'ok' back from webhook, indicating success.");
        statusCode = 0;
    } else {
        LOG.info("Got a non-ok response from webhook, attempting to dissect response.");
        LOG.error("Webhook returned non-OK response to notification post: {}",
                formatWebhookErrorResponse(statusCode, contents));
        statusCode = 1;
    }

    return statusCode;
}

From source file:org.openstack.storlet.sbus.ServerSBusInDatagram.java

/**
 * Parses a raw message coming from the wire.
 * The incoming message is constructed by the ClientSBusOutDatagram.
 * The message is structured as follows:
 * Array of file descriptors, already parsed in SBusRawMessage
 * A command related json string of the following structure:
 * {/*from  w w  w . j  a v a2  s.c  om*/
 *     "command": "command encoded as string",
 *     "params": {                            // This element is optional
 *         "key1": "value1",
 *         ...
 *     },
 *     "task_id": "task id encoded as string" // This element is optional
 * }
 * File descriptors metadata, encoded as a JSON array with one
 * element per file descriptor. The i'th element in the array
 * consists of the metadata of the i'th element in the file
 * descriptors array:
 * [
 *     {
 *         "storlets": {
 *             "type": "the fd type encoded as string",  // Mandatory
 *             ... // Additional optional storlets metadata
 *         },
 *         "storage": {
 *             "metadata key1": "metadata value 1",
 *             ...
 *        }
 *     },
 *     ...
 * ]
 * All the values in the above JSON elemens are strings.
 * Once constructed the class provides all necessary accessors to the parsed
 * fields.
 * @param msg   the raw mwssage consisting of the string encoded json formats
 * @see SBusPythonFacade.ClientSBusOutDatagram the python code that serilializes the datagram
 * @see SBusPythonFacade.ServerSBusInDatagram the equivalent python code
 */
public ServerSBusInDatagram(final SBusRawMessage msg) throws ParseException {
    this.fds = msg.getFiles();
    numFDs = this.fds == null ? 0 : this.fds.length;

    JSONObject jsonCmdParams = (JSONObject) (new JSONParser().parse(msg.getParams()));
    this.command = (String) jsonCmdParams.get("command");
    this.params = new HashMap<String, String>();
    if (jsonCmdParams.containsKey("params")) {
        JSONObject jsonParams = (JSONObject) jsonCmdParams.get("params");
        for (Object key : jsonParams.keySet()) {
            this.params.put((String) key, (String) jsonParams.get(key));
        }
    }
    if (jsonCmdParams.containsKey("task_id")) {
        this.taskID = (String) jsonCmdParams.get("task_id");
    }

    String strMD = msg.getMetadata();
    this.metadata = (HashMap<String, HashMap<String, String>>[]) new HashMap[getNFiles()];
    JSONArray jsonarray = (JSONArray) (new JSONParser().parse(strMD));
    Iterator it = jsonarray.iterator();
    int i = 0;
    while (it.hasNext()) {
        this.metadata[i] = new HashMap<String, HashMap<String, String>>();
        HashMap<String, String> storletsMetadata = new HashMap<String, String>();
        HashMap<String, String> storageMetadata = new HashMap<String, String>();
        JSONObject jsonobject = (JSONObject) it.next();
        if (jsonobject.containsKey("storage")) {
            populateMetadata(storageMetadata, (JSONObject) jsonobject.get("storage"));
        }
        if (!jsonobject.containsKey("storlets")) {
        } else {
            populateMetadata(storletsMetadata, (JSONObject) jsonobject.get("storlets"));
        }
        this.metadata[i].put("storage", storageMetadata);
        this.metadata[i].put("storlets", storletsMetadata);
        i++;
    }
}

From source file:org.pentaho.osgi.platform.webjars.WebjarsURLConnectionTest.java

private void verifyRequireJson(ZipFile zipInputStream, String artifactId, String version)
        throws IOException, ParseException {
    ZipEntry entry = zipInputStream.getEntry("META-INF/js/require.json");
    assertNotNull(entry);/*from w  ww. j a v a 2 s .c o  m*/

    String jsonFile = IOUtils.toString(zipInputStream.getInputStream(entry), "UTF-8");

    JSONObject json = (JSONObject) parser.parse(jsonFile);

    assertTrue("dependency metadata exists", json.containsKey("requirejs-osgi-meta"));
    final JSONObject meta = (JSONObject) json.get("requirejs-osgi-meta");

    assertTrue("artifact info exists", meta.containsKey("artifacts"));
    final JSONObject artifactInfo = (JSONObject) meta.get("artifacts");

    assertTrue("artifact is " + artifactId, artifactInfo.containsKey(artifactId));
    final JSONObject versionInfo = (JSONObject) artifactInfo.get(artifactId);

    assertTrue("version is " + version, versionInfo.containsKey(version));
}

From source file:org.PrimeSoft.MCPainter.Drawing.Statue.PlayerStatueDescription.java

public String getSkinFile(String playerName) {
    JSONObject responseUUID = HttpUtils.downloadJson(String.format(NAME_TO_UUID_URL, playerName));
    if (responseUUID == null || !responseUUID.containsKey("id")) {
        MCPainterMain.log("Unable to get session UUID for " + playerName);
        return null;
    }//from w w w .  ja  va2s . c  o  m

    JSONObject profile = HttpUtils.downloadJson(String.format(UUID_TO_PROFILE_URL, responseUUID.get("id")));
    if (profile == null || !profile.containsKey("properties")) {
        MCPainterMain.log("Unable to get player profile for " + playerName);
        return null;
    }

    JSONArray properties = (JSONArray) (profile.get("properties"));
    for (int i = 0; i < properties.size(); i++) {
        JSONObject prop = (JSONObject) properties.get(i);

        if (!prop.containsKey("name") || !prop.get("name").equals("textures") || !prop.containsKey("value")) {
            continue;
        }

        byte[] data = s_base64.decode((String) prop.get("value"));
        if (data == null || data.length <= 0) {
            continue;
        }

        JSONObject textureEntry = null;

        try {
            textureEntry = (JSONObject) JSONValue.parseWithException(new String(data));
        } catch (ParseException ex) {
            continue;
        }

        if (!textureEntry.containsKey("textures")) {
            continue;
        }

        textureEntry = (JSONObject) textureEntry.get("textures");

        if (textureEntry.containsKey("SKIN")) {
            textureEntry = (JSONObject) textureEntry.get("SKIN");
        }

        if (textureEntry.containsKey("url")) {
            return (String) textureEntry.get("url");
        }
    }

    MCPainterMain.log("Unable to detect the texture profile " + playerName);
    return null;
}

From source file:org.PrimeSoft.MCPainter.utils.JSONExtensions.java

/**
 * Try get a complex value from JSON object
 *
 * @param o/*ww  w. j a v a 2  s . co m*/
 * @param property
 * @return
 */
public static JSONObject tryGet(JSONObject o, String property) {
    if (o == null || property == null) {
        return null;
    }

    if (!o.containsKey(property)) {
        return null;
    }

    Object value = o.get(property);
    if (value instanceof JSONObject) {
        return (JSONObject) value;
    }

    return null;
}

From source file:org.PrimeSoft.MCPainter.utils.JSONExtensions.java

/**
 * Try to get a string value from JSON object
 *
 * @param o//from  w w  w .  java  2s  .c om
 * @param property
 * @param defaultValue
 * @return
 */
public static String tryGetString(JSONObject o, String property, String defaultValue) {
    if (o == null || property == null) {
        return defaultValue;
    }

    if (!o.containsKey(property)) {
        return defaultValue;
    }

    Object value = o.get(property);

    if (value == null) {
        return defaultValue;
    }

    return value.toString();
}

From source file:org.PrimeSoft.MCPainter.utils.JSONExtensions.java

/**
 * Try to get a int value from JSON object
 *
 * @param o/*from w w  w  .  jav a  2s.  c o  m*/
 * @param property
 * @param defaultValue
 * @return
 */
public static int tryGetInt(JSONObject o, String property, int defaultValue) {
    if (o == null || property == null) {
        return defaultValue;
    }

    if (!o.containsKey(property)) {
        return defaultValue;
    }

    Object value = o.get(property);

    if (value == null || !(value instanceof Integer)) {
        return defaultValue;
    }

    return (Integer) value;
}

From source file:org.PrimeSoft.MCPainter.utils.JSONExtensions.java

/**
 * Try to get a boolean value from JSON object
 *
 * @param o/*from   ww w.j a  v  a2s.  c  om*/
 * @param property
 * @param defaultValue
 * @return
 */
public static boolean tryGetBool(JSONObject o, String property, boolean defaultValue) {
    if (o == null || property == null) {
        return defaultValue;
    }

    if (!o.containsKey(property)) {
        return defaultValue;
    }

    Object value = o.get(property);

    if (value == null || !(value instanceof Boolean)) {
        return defaultValue;
    }

    return (Boolean) value;
}

From source file:org.PrimeSoft.MCPainter.utils.JSONExtensions.java

/**
 * Try to get a double value from JSON object
 *
 * @param o/*from ww w. j av  a 2  s  . c om*/
 * @param property
 * @param defaultValue
 * @return
 */
public static double tryGetDouble(JSONObject o, String property, double defaultValue) {
    if (o == null || property == null) {
        return defaultValue;
    }

    if (!o.containsKey(property)) {
        return defaultValue;
    }

    Object value = o.get(property);

    if (value == null) {
        return defaultValue;
    }

    if (value instanceof Long) {
        return (double) ((Long) value);
    }

    if (value instanceof Integer) {
        return (double) ((Integer) value);
    }

    if (value instanceof Double) {
        return (Double) value;
    }

    if (value instanceof Float) {
        return (Float) value;
    }

    return defaultValue;
}