Example usage for org.json.simple JSONObject keySet

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

Introduction

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

Prototype

Set<K> keySet();

Source Link

Document

Returns a Set view of the keys contained in this map.

Usage

From source file:nl.trivento.albero.web.json.JsonContextDecoder.java

private Map<String, Object> decodeVariables(JSONObject jsonVariables) {
    Map<String, Object> variables = new HashMap<String, Object>();

    for (Object name : jsonVariables.keySet()) {
        Map<String, Object> partialVariables = variables;

        String[] nameParts = ((String) name).split("\\.");

        for (int i = 0; i < nameParts.length - 1; i++) {
            String namePart = nameParts[i];

            if (!partialVariables.containsKey(namePart)) {
                partialVariables.put(namePart, new HashMap<String, Object>());
            }/*from  www  .j  ava  2  s.com*/

            @SuppressWarnings("unchecked")
            Map<String, Object> newPartialVariables = (Map<String, Object>) partialVariables.get(namePart);

            partialVariables = newPartialVariables;
        }

        partialVariables.put(nameParts[nameParts.length - 1], decodeVariable(jsonVariables.get(name)));
    }

    return variables;
}

From source file:nl.uva.sne.disambiguators.WikipediaOnline.java

private Set<Term> getCandidateTerms(String jsonString, String originalTerm)
        throws ParseException, IOException, MalformedURLException, InterruptedException, ExecutionException {
    Set<Term> terms = new HashSet<>();
    Set<Term> termsToReturn = new HashSet<>();
    JSONObject jsonObj = (JSONObject) JSONValue.parseWithException(jsonString);
    JSONObject query = (JSONObject) jsonObj.get("query");
    JSONObject pages = (JSONObject) query.get("pages");
    Set<String> keys = pages.keySet();
    for (String key : keys) {
        JSONObject jsonpage = (JSONObject) pages.get(key);
        Term t = TermFactory.create(jsonpage, originalTerm);
        if (t != null) {
            terms.add(t);// w w w  . j  a v  a 2  s  . co m
        }
    }
    if (terms.size() > 0) {
        Map<String, List<String>> cats = getCategories(terms);
        for (Term t : terms) {
            boolean add = true;
            List<String> cat = cats.get(t.getUID());
            t.setCategories(cat);
            for (String g : t.getGlosses()) {
                if (g != null && g.contains("may refer to:")) {
                    Set<Term> referToTerms = getReferToTerms(g, originalTerm);
                    if (referToTerms != null) {
                        for (Term rt : referToTerms) {
                            String url = "https://en.wikipedia.org/?curid=" + rt.getUID();
                            rt.setUrl(url);
                            termsToReturn.add(rt);
                        }
                    }
                    add = false;
                    break;
                }
            }
            if (add) {
                String url = "https://en.wikipedia.org/?curid=" + t.getUID();
                t.setUrl(url);
                termsToReturn.add(t);
            }
        }
    }
    return termsToReturn;
}

From source file:org.alfresco.rest.api.impl.activities.ActivitySummaryParser.java

Map<String, Object> convertJSONObjectToMap(JSONObject jo) throws JSONException {
    Map<String, Object> model = new HashMap<String, Object>();

    for (Object key : jo.keySet()) {
        Object value = jo.get(key);
        if (value instanceof JSONObject) {
            model.put((String) key, convertJSONObjectToMap((JSONObject) value));
        } else if (value instanceof JSONArray) {
            model.put((String) key, convertJSONArrayToList((JSONArray) value));
        } else if (value == null) {
            model.put((String) key, null);
        } else {//from   www . ja va  2  s . co  m
            if ((value instanceof String) && autoConvertISO8601
                    && (matcherISO8601.matcher((String) value).matches())) {
                value = ISO8601DateFormat.parse((String) value);
            }

            if ((value instanceof String) && isNodeRef((String) value)) {
                try {
                    value = new NodeRef((String) value);
                } catch (AlfrescoRuntimeException e) {
                    // cannot convert to a nodeRef, just keep as a string
                    logger.warn("Cannot convert activity summary NodeRef string " + value + " to a NodeRef");
                }
            }

            model.put((String) key, value);
        }
    }

    return model;
}

From source file:org.alfresco.web.cmm.CMMService.java

/**
 * Model operation service call. Provide a proxy through to the given repo API and provides a hook
 * for client business logic pertinent that may be required for each operation.
 * // w  w  w  .j a  v  a  2  s. c  o  m
 * @param status
 * @param modelName
 * @param json
 * @throws IOException
 */
protected String serviceModelOperation(Status status, String modelName, JSONObject json) throws IOException {
    final String opId = (String) json.get(JSON_OPERATION);

    // repository API mapping operation - collect arguments, data blob - http method is as called
    JSONObject data = (JSONObject) json.get(JSON_DATA);

    // map operation to URL and apply arguments
    String url = operationMapping.get(opId);
    if (url == null) {
        throw new IllegalArgumentException("Specified API operation does not map to a known URL: " + opId);
    }
    final Map<String, String> args = new HashMap<>();
    JSONObject arguments = (JSONObject) json.get(JSON_ARGUMENTS);
    if (arguments != null) {
        for (String key : (Set<String>) arguments.keySet()) {
            args.put(key, URLEncoder.encode((String) arguments.get(key)));
        }
    }
    url = UriUtils.replaceUriTokens(url, args);

    if (logger.isDebugEnabled())
        logger.debug("Executing service operation: " + opId + " with URL: " + url + " method: "
                + this.getDescription().getMethod() + " - using data:\n"
                + (data != null ? data.toJSONString() : "null"));

    // pre operation business logic
    Map<String, String> updatedForms = null;
    Response preResponse = null;
    switch (opId) {
    case OP_DELETE_MODEL:
    case OP_DEACTIVATE_MODEL: {
        // get model ready to remove it from dictionary if deactive is successful
        JSONObject model = getModel(modelName);
        String prefix = (String) model.get("namespacePrefix");
        preResponse = getConnector().call(
                "/api/dictionary?model=" + URLEncoder.encode(prefix) + ":" + URLEncoder.encode(modelName));
        break;
    }

    case OP_EDIT_MODEL: {
        // if a model has form definitions, they may need updating to ensure a modified Model Prefix is applied
        // to the widget IDs within the forms - we use the "prefix:field" approach for widget IDs for form elements
        JSONObject model = getModel(modelName);
        String oldPrefix = (String) model.get("namespacePrefix");
        String newPrefix = (String) data.get("namespacePrefix");
        // if the prefix has changed then the IDs of the widgets in the form definitions will now be incorrect
        if (!newPrefix.equals(oldPrefix)) {
            ExtensionModule module = getExtensionModule(modelName);
            if (module != null) {
                // retrieve existing form definitions from extension configuration
                updatedForms = getFormDefinitions(module);
                if (updatedForms.size() != 0) {
                    for (String formId : updatedForms.keySet()) {
                        // modify the form JSON string - we want to replace "oldprefix:fieldid" with "newprefix:fieldid" to
                        // ensure the widget IDs in the form will match the expected namespace ID of the custom model
                        String form = updatedForms.get(formId);
                        updatedForms.put(formId,
                                form.replace("\"id\":\"" + oldPrefix + ":", "\"id\":\"" + newPrefix + ":"));
                    }
                }
            }
        }
        break;
    }
    }

    // prepare proxied JSON body data and make the call
    Response res;
    if (data != null) {
        // make the request with the given data payload
        res = getAPIConnector().call(url,
                new ConnectorContext(HttpMethod.valueOf(this.getDescription().getMethod())),
                new ByteArrayInputStream(data.toJSONString().getBytes("UTF-8")));
    } else {
        // no body required for this request
        res = getAPIConnector().call(url,
                new ConnectorContext(HttpMethod.valueOf(this.getDescription().getMethod())));
    }

    if (logger.isDebugEnabled())
        logger.debug("Response: " + res.getStatus().getCode() + "\n" + res.getResponse());

    int statusCode = res.getStatus().getCode();
    if (statusCode >= 200 && statusCode < 300) {
        // if we get here successfully, then perform post operation business logic
        switch (opId) {
        case OP_ACTIVATE_MODEL: {
            if (logger.isDebugEnabled())
                logger.debug("ACTIVATE model config id: " + modelName);

            updateDictionaryForModel(modelName);

            buildExtensionModule(status, modelName, null, true);

            break;
        }

        case OP_DEACTIVATE_MODEL: {
            if (logger.isDebugEnabled())
                logger.debug("DEACTIVATE model config id: " + modelName);

            // update dictionary - remove classes relating to this namespace
            if (preResponse != null && preResponse.getStatus().getCode() == Status.STATUS_OK) {
                this.dictionary.updateRemoveClasses(preResponse.getResponse());
            } else {
                if (logger.isWarnEnabled())
                    logger.warn("Unable to update Share local Data Dictionary as Repository API call failed.");
            }

            buildExtensionModule(status, modelName, null, false);

            break;
        }

        case OP_CREATE_MODEL: {
            // NOTE: no need to update Dictionary - new model begins lifecycle as deactivated
            break;
        }

        case OP_EDIT_MODEL: {
            // NOTE: no need to update Dictionary - only deactivated models can be edited

            // updating to ensure form definitions are updated after a Model Prefix change 
            if (updatedForms != null && updatedForms.size() != 0) {
                buildExtensionModule(status, modelName,
                        new FormOperation(FormOperationEnum.Create, updatedForms), false);
            }
            break;
        }

        case OP_DELETE_MODEL: {
            if (logger.isDebugEnabled())
                logger.debug("Deleting extension and form definitions for model: " + modelName);

            // Delete the model - so delete the entire module definition and related configurations
            deleteExtensionModule(status, modelName);

            // NOTE: no need to update Dictionary - only inactive models can be deleted and therefore already processed
            break;
        }

        case OP_CREATE_TYPE:
        case OP_EDIT_TYPE: {
            // update the dictionary is the model is currently active
            if (isModelActive(getModel(modelName))) {
                updateDictionaryForModel(modelName);

                buildExtensionModule(status, modelName, null, true);
            }

            break;
        }

        case OP_DELETE_TYPE:
        case OP_DELETE_PROPERTY_GROUP: {
            // NOTE: no need to update Dictionary - only inactive models can have types or aspects deleted!
            break;
        }

        case OP_CREATE_PROPERTY_GROUP:
        case OP_EDIT_PROPERTY_GROUP: {
            // update the dictionary is the model is currently active
            if (isModelActive(getModel(modelName))) {
                buildExtensionModule(status, modelName, null, true);

                updateDictionaryForModel(modelName);
            }

            break;
        }

        case OP_CREATE_PROPERTY:
        case OP_DELETE_PROPERTY: {
            if (isModelActive(getModel(modelName))) {
                // TODO: could update Dictionary if the granularity of properties are ever used...?

                buildExtensionModule(status, modelName, null, true);
            }
            break;
        }
        }
    }
    status.setCode(statusCode);
    return res.getResponse();
}

From source file:org.apache.cassandra.tools.SSTableImport.java

/**
 * Convert a JSON formatted file to an SSTable.
 * /* ww w. ja va 2s .co  m*/
 * @param jsonFile the file containing JSON formatted data
 * @param keyspace keyspace the data belongs to
 * @param cf column family the data belongs to
 * @param ssTablePath file to write the SSTable to
 * @throws IOException for errors reading/writing input/output
 * @throws ParseException for errors encountered parsing JSON input
 */
public static void importJson(String jsonFile, String keyspace, String cf, String ssTablePath)
        throws IOException, ParseException {
    ColumnFamily cfamily = ColumnFamily.create(keyspace, cf);
    String cfType = cfamily.type(); // Super or Standard
    IPartitioner<?> partitioner = DatabaseDescriptor.getPartitioner();
    DataOutputBuffer dob = new DataOutputBuffer();

    try {
        JSONObject json = (JSONObject) JSONValue.parseWithException(new FileReader(jsonFile));

        SSTableWriter writer = new SSTableWriter(ssTablePath, json.size(), partitioner);
        List<DecoratedKey<?>> decoratedKeys = new ArrayList<DecoratedKey<?>>();

        for (String key : (Set<String>) json.keySet())
            decoratedKeys.add(partitioner.decorateKey(key));
        Collections.sort(decoratedKeys);

        for (DecoratedKey<?> rowKey : decoratedKeys) {
            if (cfType.equals("Super"))
                addToSuperCF((JSONObject) json.get(rowKey.key), cfamily);
            else
                addToStandardCF((JSONArray) json.get(rowKey.key), cfamily);

            ColumnFamily.serializer().serializeWithIndexes(cfamily, dob);
            writer.append(rowKey, dob);
            dob.reset();
            cfamily.clear();
        }

        writer.closeAndOpenReader();
    } catch (ClassCastException cce) {
        throw new RuntimeException("Invalid JSON input, or incorrect column family.", cce);
    }
}

From source file:org.apache.eagle.jpm.spark.running.parser.SparkApplicationParser.java

private JobConfig parseJobConfig(InputStream is) throws Exception {
    JobConfig jobConfig = new JobConfig();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
        String line;/*from   w  w  w .j  a v  a2  s .  c o  m*/
        boolean stop = false;
        while ((line = reader.readLine()) != null && !stop) {
            try {
                JSONParser parser = new JSONParser();
                JSONObject eventObj = (JSONObject) parser.parse(line);

                if (eventObj != null) {
                    String eventType = (String) eventObj.get("Event");
                    LOG.info("Event type: " + eventType);
                    if (eventType.equalsIgnoreCase(SparkEventType.SparkListenerEnvironmentUpdate.toString())) {
                        stop = true;
                        JSONObject sparkProps = (JSONObject) eventObj.get("Spark Properties");
                        for (Object key : sparkProps.keySet()) {
                            jobConfig.put((String) key, (String) sparkProps.get(key));
                        }
                    }
                }
            } catch (Exception e) {
                LOG.error(String.format("Fail to parse %s.", line), e);
            }
        }

        return jobConfig;
    }
}

From source file:org.apache.manifoldcf.crawler.connectors.confluence.ConfluenceContent.java

protected static void addMetadataToMap(String parent, Object cval, Map<String, List<String>> currentMap) {

    if (cval == null)
        return;//from  www .j  av  a 2 s. co m

    // See if it is a basic type
    if (cval instanceof String || cval instanceof Number || cval instanceof Boolean) {
        List<String> current = currentMap.get(parent);
        if (current == null) {
            current = new ArrayList<String>();
            currentMap.put(parent, current);
        }
        current.add(cval.toString());
        return;
    }

    // See if it is an array
    if (cval instanceof JSONArray) {
        JSONArray ja = (JSONArray) cval;
        for (Object subpiece : ja) {
            addMetadataToMap(parent, subpiece, currentMap);
        }
        return;
    }

    // See if it is a JSONObject
    if (cval instanceof JSONObject) {
        JSONObject jo = (JSONObject) cval;
        String append = "";
        if (parent.length() > 0) {
            append = parent + "_";
        }
        for (Object key : jo.keySet()) {
            Object value = jo.get(key);
            if (value == null) {
                continue;
            }
            String newKey = append + key;
            addMetadataToMap(newKey, value, currentMap);
        }
        return;
    }

    throw new IllegalArgumentException("Unknown object to addMetadataToMap: " + cval.getClass().getName());
}

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

@SuppressWarnings("unchecked")
@Override/*  ww w .  j a va  2  s  . 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;
    }

}

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

@SuppressWarnings("unchecked")
@Override/*from  w  w w .j  a v a 2s  . co  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 threat = (JSONObject) enrichment.get(enrichment_tag);

        int cnt = 0;
        Object enriched_key = null;

        for (Object key : threat.keySet()) {
            JSONObject tmp = (JSONObject) threat.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 threatQualifier = (JSONObject) threat.get(enriched_key);

        alert.put("designated_host", host);
        String description =

                new StringBuilder().append("Threat Intelligence match for ")
                        .append(content.get(enriched_key).toString()).append(" from source: ")
                        .append(threatQualifier.keySet().iterator().next().toString()).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;
    }

}

From source file:org.apache.metron.elasticsearch.writer.ElasticsearchWriter.java

@Override
public void write(String sensorType, WriterConfiguration configurations, Iterable<Tuple> tuples,
        List<JSONObject> messages) throws Exception {
    String indexPostfix = dateFormat.format(new Date());
    BulkRequestBuilder bulkRequest = client.prepareBulk();

    for (JSONObject message : messages) {

        String indexName = sensorType;

        if (configurations != null) {
            indexName = configurations.getIndex(sensorType);
        }//from   w w w .  java  2  s. co m

        indexName = indexName + "_index_" + indexPostfix;

        JSONObject esDoc = new JSONObject();
        for (Object k : message.keySet()) {

            deDot(k.toString(), message, esDoc);

        }

        IndexRequestBuilder indexRequestBuilder = client.prepareIndex(indexName, sensorType + "_doc");

        indexRequestBuilder = indexRequestBuilder.setSource(esDoc.toJSONString());
        Object ts = esDoc.get("timestamp");
        if (ts != null) {
            indexRequestBuilder = indexRequestBuilder.setTimestamp(ts.toString());
        }
        bulkRequest.add(indexRequestBuilder);

    }

    BulkResponse resp = bulkRequest.execute().actionGet();

    if (resp.hasFailures()) {

        throw new Exception(resp.buildFailureMessage());

    }

}