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:com.piusvelte.hydra.MySQLConnection.java

@SuppressWarnings("unchecked")
@Override/*from  w  w  w.ja v a2s. c o m*/
public JSONObject insert(String object, String[] columns, String[] values) {
    JSONObject response = new JSONObject();
    JSONArray errors = new JSONArray();
    Statement s = null;
    ResultSet rs = null;
    try {
        StringBuilder sb = new StringBuilder();
        for (int i = 0, l = columns.length; i < l; i++) {
            if (i > 0)
                sb.append(",");
            sb.append(columns[i].replaceAll("\\.", "_"));
        }
        String columnsStr = sb.toString();
        sb = new StringBuilder();
        for (int i = 0, l = values.length; i < l; i++) {
            if (i > 0)
                sb.append(",");
            sb.append(values[i]);
        }
        String valuesStr = sb.toString();
        s = mConnection.createStatement();
        rs = s.executeQuery(String.format(INSERT_QUERY, object, columnsStr, valuesStr).toString());
        response.put("result", getResult(rs));
    } catch (SQLException e) {
        errors.add(e.getMessage());
    } finally {
        if (s != null) {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    errors.add(e.getMessage());
                }
            }
            try {
                s.close();
            } catch (SQLException e) {
                errors.add(e.getMessage());
            }
        }
    }
    response.put("errors", errors);
    if (!response.containsKey("result")) {
        JSONArray rows = new JSONArray();
        JSONArray rowData = new JSONArray();
        rows.add(rowData);
        response.put("result", rows);
    }
    return response;
}

From source file:com.piusvelte.hydra.UnidataConnection.java

@SuppressWarnings("unchecked")
@Override/*from   www.  j  a  v  a  2  s  . c om*/
public JSONObject subroutine(String object, String[] arguments) {
    JSONObject response = new JSONObject();
    try {
        UniSubroutine subr = mSession.subroutine(object, arguments.length);
        for (int i = 0, l = arguments.length; i < l; i++)
            subr.setArg(i, arguments[i]);
        subr.call();

        JSONArray rows = new JSONArray();
        int maxSize = 1;
        ArrayList<String[]> colArr = new ArrayList<String[]>();
        for (int i = 0, l = arguments.length; i < l; i++) {
            String[] mvArr = subr.getArg(i).toString().split(UniTokens.AT_VM, -1);
            if (mvArr.length > maxSize)
                maxSize = mvArr.length;
            colArr.add(mvArr);
        }
        for (int row = 0; row < maxSize; row++) {
            JSONArray rowData = new JSONArray();
            for (int col = 0; col < arguments.length; col++) {
                String[] mvArr = colArr.get(col);
                if (row < mvArr.length)
                    rowData.add(mvArr[row]);
                else
                    rowData.add("");
            }
            rows.add(rowData);
        }
        response.put("result", rows);
    } catch (UniSessionException e) {
        e.printStackTrace();
    } catch (UniSubroutineException e) {
        e.printStackTrace();
    }
    if (!response.containsKey("result")) {
        JSONArray rows = new JSONArray();
        JSONArray rowData = new JSONArray();
        rows.add(rowData);
        response.put("result", rows);
    }
    return response;
}

From source file:com.piusvelte.hydra.MSSQLConnection.java

@SuppressWarnings("unchecked")
@Override/*from w ww  .  ja v a2s .  co  m*/
public JSONObject insert(String object, String[] columns, String[] values) {
    JSONObject response = new JSONObject();
    JSONArray errors = new JSONArray();
    Statement s = null;
    ResultSet rs = null;
    try {
        StringBuilder sb = new StringBuilder();
        for (int i = 0, l = columns.length; i < l; i++) {
            if (i > 0)
                sb.append(",");
            sb.append(columns[i].replaceAll("\\.", "_"));
        }
        String columnsStr = sb.toString();
        sb = new StringBuilder();
        for (int i = 0, l = values.length; i < l; i++) {
            if (i > 0)
                sb.append(",");
            sb.append(values[i]);
        }
        String valuesStr = sb.toString();
        s = mConnection.createStatement();
        rs = s.executeQuery(String.format(INSERT_QUERY, object, columnsStr, valuesStr).toString());
        response.put("result", getResult(rs));
    } catch (SQLException e) {
        errors.add(e.getMessage());
        e.printStackTrace();
    } finally {
        if (s != null) {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    errors.add(e.getMessage());
                }
            }
            try {
                s.close();
            } catch (SQLException e) {
                errors.add(e.getMessage());
            }
        }
    }
    response.put("errors", errors);
    if (!response.containsKey("result")) {
        JSONArray rows = new JSONArray();
        JSONArray rowData = new JSONArray();
        rows.add(rowData);
        response.put("result", rows);
    }
    return response;
}

From source file:com.piusvelte.hydra.UnidataConnection.java

@SuppressWarnings("unchecked")
@Override/*from  w ww  . j  a  va2 s .c o  m*/
public JSONObject insert(String object, String[] columns, String[] values) {
    JSONObject response = new JSONObject();
    JSONArray errors = new JSONArray();
    UniFile uFile = null;
    try {
        String recordID = getRecordID(object, columns, values);
        int[] locs = getDictLocs(object, columns);
        try {
            uFile = mSession.openFile(object);
            UniDynArray record = new UniDynArray();
            for (int c = 0; (c < columns.length) && (c < values.length); c++) {
                // don't try to write the Colleague I-descriptors
                if ((locs[c] > 0) && !("@ID").equals(columns[c]))
                    record.insert(locs[c], values[c]);
            }
            uFile.write(recordID, record);
        } catch (UniSessionException e) {
            e.printStackTrace();
            errors.add("error opening file: " + object + ": " + e.getMessage());
        } catch (UniFileException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
        errors.add(e.getMessage());
    } finally {
        if (uFile != null) {
            try {
                uFile.close();
            } catch (UniFileException e) {
                e.printStackTrace();
            }
        }
    }
    response.put("errors", errors);
    if (!response.containsKey("result")) {
        JSONArray rows = new JSONArray();
        JSONArray rowData = new JSONArray();
        rows.add(rowData);
        response.put("result", rows);
    }
    return response;
}

From source file:eu.hansolo.fx.weatherfx.darksky.DarkSky.java

public boolean update(final double LATITUDE, final double LONGITUDE) {
    // Update only if lastUpdate is older than 10 min
    if (Instant.now().minusSeconds(600).isBefore(lastUpdate))
        return true;

    StringBuilder response = new StringBuilder();
    try {/* ww w .j  a v a  2 s  .c  o m*/
        forecast.clear();
        alerts.clear();

        final String URL_STRING = createUrl(LATITUDE, LONGITUDE, unit, language, Exclude.HOURLY,
                Exclude.MINUTELY, Exclude.FLAGS);
        final HttpsURLConnection CONNECTION = (HttpsURLConnection) new URL(URL_STRING).openConnection();
        final BufferedReader IN = new BufferedReader(new InputStreamReader(CONNECTION.getInputStream()));
        String inputLine;
        while ((inputLine = IN.readLine()) != null) {
            response.append(inputLine).append("\n");
        }
        IN.close();

        Object obj = JSONValue.parse(response.toString());
        JSONObject jsonObj = (JSONObject) obj;

        latitude = Double.parseDouble(jsonObj.getOrDefault("latitude", 0).toString());
        longitude = Double.parseDouble(jsonObj.getOrDefault("longitude", 0).toString());
        timeZone = TimeZone.getTimeZone(jsonObj.getOrDefault("timezone", "").toString());

        // Update today data
        JSONObject currently = (JSONObject) jsonObj.get("currently");
        setDataPoint(today, currently);

        // Update forecast data
        JSONObject daily = (JSONObject) jsonObj.get("daily");
        JSONArray days = (JSONArray) daily.get("data");

        // Update today with more data
        JSONObject day0 = (JSONObject) days.get(0);
        today.setSunriseTime(epochStringToLocalDateTime(day0.getOrDefault("sunriseTime", 0).toString()));
        today.setSunsetTime(epochStringToLocalDateTime(day0.getOrDefault("sunsetTime", 0).toString()));
        today.setPrecipProbability(Double.parseDouble(day0.getOrDefault("precipProbability", 0).toString()));
        today.setPrecipType(PrecipType
                .valueOf(day0.getOrDefault("precipType", "none").toString().toUpperCase().replace("-", "_")));

        for (int i = 1; i < days.size(); i++) {
            JSONObject day = (JSONObject) days.get(i);
            DataPoint dataPoint = new DataPoint();
            setDataPoint(dataPoint, day);
            forecast.add(dataPoint);
        }

        // Update alert data
        if (jsonObj.containsKey("alerts")) {
            JSONArray alerts = (JSONArray) jsonObj.get("alerts");
            for (Object alertObj : alerts) {
                JSONObject alertJson = (JSONObject) alertObj;
                Alert alert = new Alert();
                alert.setTitle(alertJson.get("title").toString());
                alert.setDescription(alertJson.get("description").toString());
                alert.setTime(epochStringToLocalDateTime(alertJson.getOrDefault("time", 0).toString()));
                alert.setExpires(epochStringToLocalDateTime(alertJson.getOrDefault("expires", 0).toString()));
                alerts.add(alert);
            }
        }

        lastUpdate = Instant.now();

        return true;
    } catch (IOException ex) {
        System.out.println(ex);
        return false;
    }
}

From source file:com.opensoc.enrichment.common.GenericEnrichmentBolt.java

@SuppressWarnings("unchecked")
public void execute(Tuple tuple) {

    LOG.trace("[OpenSOC] Starting enrichment");

    JSONObject in_json = null;
    String key = null;/*w ww .  j  a  va  2  s . co m*/

    try {

        key = tuple.getStringByField("key");
        in_json = (JSONObject) tuple.getValueByField("message");

        if (in_json == null || in_json.isEmpty())
            throw new Exception("Could not parse binary stream to JSON");

        if (key == null)
            throw new Exception("Key is not valid");

        LOG.trace("[OpenSOC] Received tuple: " + in_json);

        JSONObject message = (JSONObject) in_json.get("message");

        if (message == null || message.isEmpty())
            throw new Exception("Could not extract message from JSON: " + in_json);

        LOG.trace("[OpenSOC] Extracted message: " + message);

        for (String jsonkey : _jsonKeys) {
            LOG.trace("[OpenSOC] Processing:" + jsonkey + " within:" + message);

            String jsonvalue = (String) message.get(jsonkey);
            LOG.trace("[OpenSOC] Processing: " + jsonkey + " -> " + jsonvalue);

            if (null == jsonvalue) {
                LOG.trace("[OpenSOC] Key " + jsonkey + "not present in message " + message);
                continue;
            }

            // If the field is empty, no need to enrich
            if (jsonvalue.length() == 0) {
                continue;
            }

            JSONObject enrichment = cache.getUnchecked(jsonvalue);
            LOG.trace("[OpenSOC] Enriched: " + jsonkey + " -> " + enrichment);

            if (enrichment == null)
                throw new Exception("[OpenSOC] Could not enrich string: " + jsonvalue);

            if (!in_json.containsKey("enrichment")) {
                in_json.put("enrichment", new JSONObject());
                LOG.trace("[OpenSOC] Starting a string of enrichments");
            }

            JSONObject enr1 = (JSONObject) in_json.get("enrichment");

            if (enr1 == null)
                throw new Exception("Internal enrichment is empty");

            if (!enr1.containsKey(_enrichment_tag)) {
                enr1.put(_enrichment_tag, new JSONObject());
                LOG.trace("[OpenSOC] Starting a new enrichment");
            }

            LOG.trace("[OpenSOC] ENR1 is: " + enr1);

            JSONObject enr2 = (JSONObject) enr1.get(_enrichment_tag);
            enr2.put(jsonkey, enrichment);

            LOG.trace("[OpenSOC] ENR2 is: " + enr2);

            enr1.put(_enrichment_tag, enr2);
            in_json.put("enrichment", enr1);
        }

        LOG.debug("[OpenSOC] Generated combined enrichment: " + in_json);

        _collector.emit("message", new Values(key, in_json));
        _collector.ack(tuple);

        if (_reporter != null) {
            emitCounter.inc();
            ackCounter.inc();
        }
    } catch (Exception e) {

        LOG.error("[OpenSOC] Unable to enrich message: " + in_json);
        _collector.fail(tuple);

        if (_reporter != null) {
            failCounter.inc();
        }

        JSONObject error = ErrorGenerator.generateErrorMessage("Enrichment problem: " + in_json, e);
        _collector.emit("error", new Values(error));
    }

}

From source file:eumetsat.pn.common.ISO2JSON.java

/**
 * Parse the hierarchy name to tentatively form facets
 *
 * @param hierarchyNames//  w  w w.  j a  va2  s  . c  o  m
 */
@SuppressWarnings("unchecked")
private JSONObject parseThemeHierarchy(String fid, JSONArray hierarchyNames) {
    String dummy = null;
    JSONObject jsonObject = new JSONObject();

    for (Object hName : hierarchyNames) {
        dummy = (String) hName;

        String[] elems = dummy.split("\\.");

        //           log.trace("Analyze " + dummy);
        if (elems[0].equalsIgnoreCase("sat")) {
            if (elems[1].equalsIgnoreCase("METOP")) {
                jsonObject.put("satellite", "METOP");

                if (elems.length > 2) {
                    //there is an instrument
                    jsonObject.put("instrument", elems[2]);
                }
            } else if (elems[1].startsWith("JASON")) {
                jsonObject.put("satellite", elems[1]);

                if (elems.length > 2) {
                    //there is an instrument
                    jsonObject.put("instrument", elems[2]);
                }
            } else {
                jsonObject.put("satellite", elems[1]);
            }
        } else if (elems[0].equalsIgnoreCase("theme")) {
            if (elems[1].equalsIgnoreCase("par") && elems.length > 2) {
                if (elems[2].equalsIgnoreCase("sea_surface_temperature")) {
                    elems[2] = "sst";
                } else if (elems[2].equalsIgnoreCase("level_0_data")) {
                    elems[2] = "level0 ";
                } else if (elems[2].equalsIgnoreCase("level_1_data")) {
                    elems[2] = "level1";
                } else if (elems[2].equalsIgnoreCase("level_2_data")) {
                    elems[2] = "level2";
                }

                if (!jsonObject.containsKey("category")) {
                    JSONArray array = new JSONArray();
                    array.add(elems[2]);
                    jsonObject.put("category", array);
                } else {
                    ((JSONArray) (jsonObject.get("category"))).add(elems[2]);
                }

            }
        } else if (elems[0].equalsIgnoreCase("dis")) {
            if (elems.length == 2) {
                if (!elems[1].equalsIgnoreCase("Eumetcast")) {
                    if (!jsonObject.containsKey("distribution")) {
                        JSONArray array = new JSONArray();
                        array.add(elems[1]);
                        jsonObject.put("distribution", array);
                    } else {
                        ((JSONArray) (jsonObject.get("distribution"))).add(elems[1]);
                    }
                }

            } else {
                log.debug("***  ALERT ALERT. DIS is different: " + hName);
            }
        } else if (elems[0].equalsIgnoreCase("SBA")) {
            if (elems.length == 2) {
                if (!jsonObject.containsKey("societalBenefitArea")) {
                    JSONArray array = new JSONArray();
                    array.add(elems[1]);
                    jsonObject.put("societalBenefitArea", array);
                } else {
                    ((JSONArray) (jsonObject.get("societalBenefitArea"))).add(elems[1]);
                }

            } else {
                log.debug("***  ALERT ALERT. SBA is different: " + hName);
            }
        }
    }

    return jsonObject;
}

From source file:com.paniclauncher.data.Settings.java

@SuppressWarnings("unchecked")
public void checkMojangStatus() {
    JSONParser parser = new JSONParser();
    try {/* w  ww.j  a v  a 2 s .c o  m*/
        Object obj = parser.parse(Utils.urlToString("http://status.mojang.com/check"));
        JSONArray jsonObject = (JSONArray) obj;
        Iterator<JSONObject> iterator = jsonObject.iterator();
        while (iterator.hasNext()) {
            JSONObject object = iterator.next();
            if (object.containsKey("login.minecraft.net")) {
                if (((String) object.get("login.minecraft.net")).equalsIgnoreCase("green")) {
                    minecraftLoginServerUp = true;
                }
            } else if (object.containsKey("session.minecraft.net")) {
                if (((String) object.get("session.minecraft.net")).equalsIgnoreCase("green")) {
                    minecraftSessionServerUp = true;
                }
            }
        }
    } catch (ParseException e) {
        this.console.logStackTrace(e);
    }
}

From source file:com.piusvelte.hydra.UnidataConnection.java

@SuppressWarnings("unchecked")
@Override//from   www. j  av  a 2s  . com
public JSONObject delete(String object, String selection) {
    JSONObject response = new JSONObject();
    JSONArray errors = new JSONArray();
    UniCommand uCommand = null;
    UniFile uFile = null;
    try {
        uCommand = mSession.command();
        if (selection == null)
            uCommand.setCommand(String.format(SIMPLE_QUERY_FORMAT, object).toString());
        else
            uCommand.setCommand(String.format(SELECTION_QUERY_FORMAT, object, selection).toString());
        UniSelectList uSelect = mSession.selectList(0);
        uCommand.exec();
        uFile = mSession.openFile(object);
        UniString recordID = null;
        while ((recordID = uSelect.next()).length() > 0)
            uFile.deleteRecord(recordID);
        JSONArray rows = new JSONArray();
        JSONArray rowData = new JSONArray();
        rows.add(rowData);
        response.put("result", rows);
    } catch (UniSessionException e) {
        e.printStackTrace();
        errors.add("error getting command: " + e.getMessage());
    } catch (UniCommandException e) {
        e.printStackTrace();
        errors.add(e.getMessage());
    } catch (UniSelectListException e) {
        e.printStackTrace();
        errors.add(e.getMessage());
    } catch (UniFileException e) {
        e.printStackTrace();
        errors.add(e.getMessage());
    } finally {
        if (uFile != null) {
            try {
                uFile.close();
            } catch (UniFileException e) {
                e.printStackTrace();
            }
        }
    }
    response.put("errors", errors);
    if (!response.containsKey("result")) {
        JSONArray rows = new JSONArray();
        JSONArray rowData = new JSONArray();
        rows.add(rowData);
        response.put("result", rows);
    }
    return response;
}

From source file:com.opensoc.alerts.TelemetryAlertsBolt.java

@SuppressWarnings("unchecked")
public void execute(Tuple tuple) {

    LOG.trace("[OpenSOC] Starting to process message for alerts");
    JSONObject original_message = null;
    String key = null;/*from w w w.java 2 s  .c o  m*/

    try {

        key = tuple.getStringByField("key");
        original_message = (JSONObject) tuple.getValueByField("message");

        if (original_message == null || original_message.isEmpty())
            throw new Exception("Could not parse message from byte stream");

        if (key == null)
            throw new Exception("Key is not valid");

        LOG.trace("[OpenSOC] Received tuple: " + original_message);

        JSONObject alerts_tag = new JSONObject();
        Map<String, JSONObject> alerts_list = _adapter.alert(original_message);
        JSONArray uuid_list = new JSONArray();

        if (alerts_list == null || alerts_list.isEmpty()) {
            System.out.println("[OpenSOC] No alerts detected in: " + original_message);
            _collector.ack(tuple);
            _collector.emit("message", new Values(key, original_message));
        } else {
            for (String alert : alerts_list.keySet()) {
                uuid_list.add(alert);

                LOG.trace("[OpenSOC] Checking alerts cache: " + alert);

                if (cache.getIfPresent(alert) == null) {
                    System.out.println("[OpenSOC]: Alert not found in cache: " + alert);

                    JSONObject global_alert = new JSONObject();
                    global_alert.putAll(_identifier);
                    global_alert.putAll(alerts_list.get(alert));
                    global_alert.put("timestamp", System.currentTimeMillis());
                    _collector.emit("alert", new Values(global_alert));

                    cache.put(alert, "");

                } else
                    LOG.trace("Alert located in cache: " + alert);

                LOG.debug("[OpenSOC] Alerts are: " + alerts_list);

                if (original_message.containsKey("alerts")) {
                    JSONArray already_triggered = (JSONArray) original_message.get("alerts");

                    uuid_list.addAll(already_triggered);
                    LOG.trace("[OpenSOC] Messages already had alerts...tagging more");
                }

                original_message.put("alerts", uuid_list);

                LOG.debug("[OpenSOC] Detected alerts: " + alerts_tag);

                _collector.ack(tuple);
                _collector.emit("message", new Values(key, original_message));

            }

            /*
             * if (metricConfiguration != null) { emitCounter.inc();
             * ackCounter.inc(); }
             */
        }

    } catch (Exception e) {
        e.printStackTrace();
        LOG.error("Failed to tag message :" + original_message);
        e.printStackTrace();
        _collector.fail(tuple);

        /*
         * if (metricConfiguration != null) { failCounter.inc(); }
         */

        JSONObject error = ErrorGenerator.generateErrorMessage("Alerts problem: " + original_message, e);
        _collector.emit("error", new Values(error));
    }
}