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.alfresco.repo.web.scripts.wiki.AbstractWikiWebScript.java

/**
 * Generates an activity entry for the link
 * //from w ww  .jav  a2  s  . c  o  m
 * @param event    a String representing the event.
 * @param wikiPage the wiki page generating the activity.
 * @param site     the site in which the wiki page was created.
 * @param req      the {@link WebScriptRequest}.
 * @param json JSONObject
 * @param additionalData any additional data required for the activity.
 */
protected void addActivityEntry(String event, WikiPageInfo wikiPage, SiteInfo site, WebScriptRequest req,
        JSONObject json, Map<String, String> additionalData) {
    // What page is this for?
    String page = req.getParameter("page");
    if (page == null && json != null) {
        if (json.containsKey("page")) {
            page = (String) json.get("page");
        }
    }
    if (page == null) {
        // Default
        page = "wiki";
    }

    try {
        StringWriter activityJson = new StringWriter();
        JSONWriter activity = new JSONWriter(activityJson);
        activity.startObject();
        activity.writeValue("title", wikiPage.getTitle());
        activity.writeValue("page", page + "?title=" + URLEncoder.encodeUriComponent(wikiPage.getTitle()));
        for (Map.Entry<String, String> entry : additionalData.entrySet()) {
            activity.writeValue(entry.getKey(), entry.getValue());
        }
        activity.endObject();

        activityService.postActivity("org.alfresco.wiki.page-" + event, site.getShortName(),
                WIKI_SERVICE_ACTIVITY_APP_NAME, activityJson.toString());
    } catch (Exception e) {
        // Warn, but carry on
        logger.warn("Error adding wiki page " + event + " to activities feed", e);
    }
}

From source file:org.alfresco.repo.web.scripts.wiki.AbstractWikiWebScript.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
    if (templateVars == null) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "No parameters supplied");
    }/*from  w w w.ja  v  a  2  s  . c  o  m*/

    // Parse the JSON, if supplied
    JSONObject json = null;
    String contentType = req.getContentType();
    if (contentType != null && contentType.indexOf(';') != -1) {
        contentType = contentType.substring(0, contentType.indexOf(';'));
    }
    if (MimetypeMap.MIMETYPE_JSON.equals(contentType)) {
        JSONParser parser = new JSONParser();
        try {
            json = (JSONObject) parser.parse(req.getContent().getContent());
        } catch (IOException | ParseException io) {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Invalid JSON: " + io.getMessage());
        }
    }

    // Get the site short name. Try quite hard to do so...
    String siteName = templateVars.get("siteId");
    if (siteName == null) {
        siteName = req.getParameter("site");
    }
    if (siteName == null && json != null) {
        if (json.containsKey("siteid")) {
            siteName = (String) json.get("siteid");
        } else if (json.containsKey("siteId")) {
            siteName = (String) json.get("siteId");
        } else if (json.containsKey("site")) {
            siteName = (String) json.get("site");
        }
    }
    if (siteName == null) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "No site given");
    }

    // Grab the requested site
    SiteInfo site = siteService.getSite(siteName);
    if (site == null) {
        String error = "Could not find site: " + siteName;
        throw new WebScriptException(Status.STATUS_NOT_FOUND, error);
    }

    String pageTitle = templateVars.get("pageTitle");

    // Have the real work done
    return executeImpl(site, pageTitle, req, json, status, cache);
}

From source file:org.apache.ambari.view.capacityscheduler.ConfigurationService.java

private JSONObject getJsonObject(String response) {
    if (response == null || response.isEmpty()) {
        return null;
    }//from w ww. j av  a  2s.c om
    JSONObject jsonObject = (JSONObject) JSONValue.parse(response);

    if (jsonObject.get("status") != null && (Long) jsonObject.get("status") >= 400L) {
        // Throw exception if HTTP status is not OK
        String message;
        if (jsonObject.containsKey("message")) {
            message = (String) jsonObject.get("message");
        } else {
            message = "without message";
        }
        throw new ServiceFormattedException("Proxy: Server returned error " + jsonObject.get("status") + " "
                + message + ". Check Capacity-Scheduler instance properties.");
    }
    return jsonObject;
}

From source file:org.apache.ambari.view.hive.resources.files.FileServiceTest.java

private void assertFileJsonResponseSanity(JSONObject obj) {
    Assert.assertTrue(obj.containsKey("file"));
}

From source file:org.apache.drill.exec.physical.impl.TestLocalExchange.java

private static void jsonExchangeOrderChecker(String plan, boolean isDemuxEnabled, int expectedNumMuxes,
        String hashExprPattern) throws Exception {
    final JSONObject planObj = (JSONObject) new JSONParser().parse(plan);
    assertNotNull("Corrupted query plan: null", planObj);
    final JSONArray graphArray = (JSONArray) planObj.get("graph");
    assertNotNull("No graph array present", graphArray);
    int i = 0;/*  w  w w .j  av a  2s . co  m*/
    int k = 0;
    int prevExprsArraySize = 0;
    boolean foundExpr = false;
    int muxesCount = 0;
    for (Object object : graphArray) {
        final JSONObject popObj = (JSONObject) object;
        if (popObj.containsKey("pop") && popObj.get("pop").equals("project")) {
            if (popObj.containsKey("exprs")) {
                final JSONArray exprsArray = (JSONArray) popObj.get("exprs");
                for (Object exprObj : exprsArray) {
                    final JSONObject expr = (JSONObject) exprObj;
                    if (expr.containsKey("ref") && expr.get("ref").equals("`" + HASH_EXPR_NAME + "`")) {
                        // found a match. Let's see if next one is the one we need
                        final String hashField = (String) expr.get("expr");
                        assertNotNull("HashExpr field can not be null", hashField);
                        assertTrue("HashExpr field does not match pattern", hashField.matches(hashExprPattern));
                        k = i;
                        foundExpr = true;
                        muxesCount++;
                        break;
                    }
                }
                if (foundExpr) {
                    // will be reset to prevExprsArraySize-1 on the last project of the whole stanza
                    prevExprsArraySize = exprsArray.size();
                }
            }
        }
        if (!foundExpr) {
            continue;
        }
        // next after project with hashexpr
        if (k == i - 1) {
            assertTrue("UnorderedMux should follow Project with HashExpr",
                    popObj.containsKey("pop") && popObj.get("pop").equals(MUX_EXCHANGE_CONST));
        }
        if (k == i - 2) {
            assertTrue(
                    "HashToRandomExchange should follow UnorderedMux which should follow Project with HashExpr",
                    popObj.containsKey("pop") && popObj.get("pop").equals(HASH_EXCHANGE));
            // is HashToRandom is using HashExpr
            assertTrue("HashToRandomExchnage should use hashExpr",
                    popObj.containsKey("expr") && popObj.get("expr").equals("`" + HASH_EXPR_NAME + "`"));
        }
        // if Demux is enabled it also should use HashExpr
        if (isDemuxEnabled && k == i - 3) {
            assertTrue("UnorderdDemuxExchange should follow HashToRandomExchange",
                    popObj.containsKey("pop") && popObj.get("pop").equals(DEMUX_EXCHANGE_CONST));
            // is HashToRandom is using HashExpr
            assertTrue("UnorderdDemuxExchange should use hashExpr",
                    popObj.containsKey("expr") && popObj.get("expr").equals("`" + HASH_EXPR_NAME + "`"));
        }
        if ((isDemuxEnabled && k == i - 4) || (!isDemuxEnabled && k == i - 3)) {
            // it should be a project without hashexpr, check if number of exprs is 1 less then in first project
            assertTrue("Should be project without hashexpr",
                    popObj.containsKey("pop") && popObj.get("pop").equals("project"));
            final JSONArray exprsArray = (JSONArray) popObj.get("exprs");
            assertNotNull("Project should have some fields", exprsArray);
            assertEquals("Number of fields in closing project should be one less then in starting project",
                    prevExprsArraySize, exprsArray.size());

            // Now let's reset all the counters, flags if we are going to have another batch of those exchanges
            k = 0;
            foundExpr = false;
            prevExprsArraySize = 0;
        }
        i++;
    }
    assertEquals("Number of Project/Mux/HashExchange/... ", expectedNumMuxes, muxesCount);
}

From source file:org.apache.eagle.jpm.spark.history.crawl.JHFSparkEventReader.java

private void handleEnvironmentSet(JSONObject event) {
    app.setConfig(new JobConfig());
    JSONObject sparkProps = (JSONObject) event.get("Spark Properties");

    String[] props = { "spark.yarn.app.id", "spark.executor.memory", "spark.driver.host", "spark.driver.port",
            "spark.driver.memory", "spark.scheduler.pool", "spark.executor.cores", "spark.yarn.am.memory",
            "spark.yarn.am.cores", "spark.yarn.executor.memoryOverhead", "spark.yarn.driver.memoryOverhead",
            "spark.yarn.am.memoryOverhead", "spark.master" };

    String[] additionalJobConf = null;
    if (conf.hasPath("spark.jobConf.additional.info")) {
        additionalJobConf = conf.getString("spark.jobConf.additional.info").split(",\\s*");
    }/*ww  w . ja va 2 s  . c o  m*/

    String[] jobConf = (String[]) ArrayUtils.addAll(additionalJobConf, props);
    for (String prop : jobConf) {
        if (sparkProps.containsKey(prop)) {
            app.getConfig().getConfig().put(prop, (String) sparkProps.get(prop));
        }
    }
}

From source file:org.apache.eagle.jpm.spark.history.crawl.JHFSparkEventReader.java

private void handleStageComplete(JSONObject event) {
    JSONObject stageInfo = JSONUtils.getJSONObject(event, "Stage Info");
    int stageId = JSONUtils.getInt(stageInfo, "Stage ID");
    int stageAttemptId = JSONUtils.getInt(stageInfo, "Stage Attempt ID");
    String key = this.generateStageKey(Integer.toString(stageId), Integer.toString(stageAttemptId));
    SparkStage stage = stages.get(key);/*from w  ww.java2 s . c o  m*/

    // If "Submission Time" is not available, use the "Launch Time" of "Task ID" = 0.
    Long submissionTime = JSONUtils.getLong(stageInfo, "Submission Time", firstTaskLaunchTime);

    stage.setSubmitTime(submissionTime);

    long completeTime = JSONUtils.getLong(stageInfo, "Completion Time", lastEventTime);
    stage.setCompleteTime(completeTime);
    this.lastEventTime = completeTime;

    if (stageInfo != null && stageInfo.containsKey("Failure Reason")) {
        stage.setStatus(SparkEntityConstant.SparkStageStatus.FAILED.toString());
    } else {
        stage.setStatus(SparkEntityConstant.SparkStageStatus.COMPLETE.toString());
    }
}

From source file:org.apache.hadoop.mapreduce.approx.lib.input.SampleRecordReader.java

public boolean nextKeyValue1() throws IOException, InterruptedException {
    while (nextKeyValueOrg()) {
        String currentValue = ((Text) this.getCurrentValue()).toString();
        JSONObject jsonCurrentValue = null;
        try {/*from   ww w .j ava2s.  com*/
            jsonCurrentValue = (JSONObject) parser.parse(currentValue);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //LOG.info(currentValue);
        String[] keys = this.split.getKeys(idx - 1).split(Pattern.quote("*+*"));
        for (String key : keys) {
            //*************************************************************************fields separator**********************
            String[] fields = key.split(Pattern.quote("+*+"));
            boolean containCurrentKey = true;

            for (int i = 0; i < fields.length; i++) {
                //LOG.info("filter:" + field);
                String[] jsonwhere = whereKeys[fields.length - 1 - i].split(Pattern.quote("="))[0]
                        .split(Pattern.quote("."));
                JSONObject jsonkey = jsonCurrentValue;
                String jsonvalue = "";
                boolean flag = true;
                for (int j = 0; j < jsonwhere.length; j++) {
                    flag = true;
                    if (jsonkey.containsKey(jsonwhere[j])) {
                        if (fields[i].equals("true")) {
                            continue;
                        }
                        if (jsonkey.get(jsonwhere[j]).getClass().getName().equals("java.lang.String")) {
                            jsonvalue = (String) jsonkey.get(jsonwhere[j]);
                            flag = false;
                        } else {
                            jsonkey = (JSONObject) jsonkey.get(jsonwhere[j]);
                        }
                    } else {
                        containCurrentKey = false;
                        break;
                    }
                }
                if (!containCurrentKey) {
                    break;
                }
                if (fields[i].equals("true")) {
                    continue;
                }
                if (flag) {
                    jsonvalue = jsonkey.toString();
                }
                if (!jsonvalue.toLowerCase().contains(fields[i].toLowerCase())) {
                    containCurrentKey = false;
                    break;
                }
            }
            if (containCurrentKey) {
                return true;
            }
        }
    }
    return false;
}

From source file:org.apache.metron.alerts.adapters.AllAlertAdapter.java

@SuppressWarnings("unchecked")
@Override//from w ww .  j a v a 2  s . c  o  m
public Map<String, JSONObject> alert(JSONObject raw_message) {

    Map<String, JSONObject> alerts = new HashMap<String, JSONObject>();
    JSONObject content = (JSONObject) raw_message.get("message");

    JSONObject enrichment = null;

    if (raw_message.containsKey("enrichment"))
        enrichment = (JSONObject) raw_message.get("enrichment");

    JSONObject alert = new JSONObject();

    String source = "unknown";
    String dest = "unknown";
    String host = "unknown";

    if (content.containsKey("ip_src_addr")) {
        source = content.get("ip_src_addr").toString();

        if (RangeChecker.checkRange(loaded_whitelist, source))
            host = source;
    }

    if (content.containsKey("ip_dst_addr")) {
        dest = content.get("ip_dst_addr").toString();

        if (RangeChecker.checkRange(loaded_whitelist, dest))
            host = dest;
    }

    alert.put("designated_host", host);
    alert.put("description", content.get("original_string").toString());
    alert.put("priority", "MED");

    String alert_id = generateAlertId(source, dest, 0);

    alert.put("alert_id", alert_id);
    alerts.put(alert_id, alert);

    alert.put("enrichment", enrichment);

    return alerts;

}

From source file:org.apache.metron.alerts.adapters.CIFAlertsAdapter.java

@SuppressWarnings("unchecked")
@Override/*from   w w  w.j  a v  a2s.c o m*/
public Map<String, JSONObject> alert(JSONObject raw_message) {

    System.out.println("LOOKING FOR ENRICHMENT TAG: " + enrichment_tag);

    Map<String, JSONObject> alerts = new HashMap<String, JSONObject>();
    JSONObject content = (JSONObject) raw_message.get("message");

    JSONObject enrichment = null;

    if (raw_message.containsKey("enrichment"))
        enrichment = (JSONObject) raw_message.get("enrichment");
    else
        return null;

    if (enrichment.containsKey(enrichment_tag)) {

        System.out.println("FOUND TAG: " + enrichment_tag);

        JSONObject cif = (JSONObject) enrichment.get(enrichment_tag);

        int cnt = 0;
        Object enriched_key = null;

        for (Object key : cif.keySet()) {
            JSONObject tmp = (JSONObject) cif.get(key);
            cnt = cnt + tmp.size();
            if (tmp.size() > 0)
                enriched_key = key;
        }

        if (cnt == 0) {
            System.out.println("TAG HAS NO ELEMENTS");
            return null;
        }

        JSONObject alert = new JSONObject();

        String source = "unknown";
        String dest = "unknown";
        String host = "unknown";

        if (content.containsKey("ip_src_addr")) {
            source = content.get("ip_src_addr").toString();

            if (RangeChecker.checkRange(loaded_whitelist, source))
                host = source;
        }

        if (content.containsKey("ip_dst_addr")) {
            dest = content.get("ip_dst_addr").toString();

            if (RangeChecker.checkRange(loaded_whitelist, dest))
                host = dest;
        }

        JSONObject cifQualifier = (JSONObject) cif.get(enriched_key);

        alert.put("designated_host", host);
        String description = new StringBuilder().append(host).append(" communicated with a host (")
                .append(content.get(enriched_key).toString()).append(") identified as ")
                .append(cifQualifier.keySet().iterator().next().toString()).append(" by CIF").toString();
        alert.put("description", description);
        alert.put("priority", "MED");

        String alert_id = generateAlertId(source, dest, 0);

        alert.put("alert_id", alert_id);
        alerts.put(alert_id, alert);

        alert.put("enrichment", enrichment);

        return alerts;
    } else {
        System.out.println("DID NOT FIND TAG: " + enrichment_tag);
        return null;
    }

}