Java Code Examples for org.json.simple.JSONObject#keySet()

The following examples show how to use org.json.simple.JSONObject#keySet() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LoopTaskPanel.java    From Explvs-AIO with MIT License 6 votes vote down vote up
@Override
public JSONObject toJSON() {
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("type", TaskType.LOOP.name());
    jsonObject.put("taskCount", taskCountField.getText());
    jsonObject.put("randomize", randomizeTasksCheckBox.isSelected());

    LoopDurationType loopDurationType = (LoopDurationType) loopDurationTypeSelector.getSelectedItem();

    if (loopDurationType == LoopDurationType.ITERATIONS) {
        jsonObject.put("iterationCount", iterationCountField.getText());
    } else if (loopDurationType == loopDurationType.INFINITE) {
        jsonObject.put("loopForever", true);
    } else if (loopDurationType == LoopDurationType.TIME) {
        JSONObject durationObj = durationPanel.toJSON();
        for (Object key : durationObj.keySet()) {
            jsonObject.put(key, durationObj.get(key));
        }
    }
    return jsonObject;
}
 
Example 2
Source File: JDBCTestUtils.java    From jdbc-cb with Apache License 2.0 6 votes vote down vote up
/***
 * Extract Data Information from file
 * @param filePath
 * @return
 * @throws FileNotFoundException
 * @throws IOException
 * @throws ParseException
 */
public static HashMap<String, HashMap<String, JSONObject>> extractDataInformationFromFile(String filePath) 
		throws FileNotFoundException, IOException, ParseException{
	JSONParser parser = new JSONParser();
	HashMap<String, HashMap<String, JSONObject>> bucketDataMap = new HashMap<String, HashMap<String, JSONObject>>();
	JDBCTestUtils.extractFolder(filePath);
	String dataDumpPath=filePath.replace(".zip", "");
	File folder = new File(dataDumpPath);
	for(File file : folder.listFiles()){
		Object obj = parser.parse(new FileReader(file.getAbsolutePath()));
        JSONObject jsonObject = (JSONObject) obj;
        HashMap<String, JSONObject> dataMap = new HashMap<String, JSONObject>();
        for(Object key : jsonObject.keySet()){
        	JSONObject jsonValue = (JSONObject) jsonObject.get(key.toString());
        	dataMap.put(key.toString(), jsonValue);
        }
        bucketDataMap.put(file.getName().replace(".txt", ""), dataMap);   
	}
	return bucketDataMap;
}
 
Example 3
Source File: ServiceInfo.java    From sepia-assist-server with MIT License 6 votes vote down vote up
/**
 * Add a custom trigger sentence for a given language to the collection with predefined parameters, e.g. "Bring me home" with "location=home". 
 * If the service registers itself as a custom services this will be used.
 * @param sentence - a sample sentence
 * @param language - language code for this sentence
 * @param normParameters - predefined parameters for this sentence in normalized format (not extracted yet)
 */
public ServiceInfo addCustomTriggerSentenceWithNormalizedParameters(String sentence, String language, JSONObject normParameters){
	List<String> list = customTriggerSentences.get(language);
	if (list == null){
		list = new ArrayList<>();
		customTriggerSentences.put(language, list);
	}
	//tag parameters
	for (Object keyObj : normParameters.keySet()){
		String key = (String) keyObj;
		JSON.put(normParameters, key, Interview.INPUT_NORM + JSON.getString(normParameters, key));
	}
	//build sentence + cmdSummary
	sentence = sentence + ";;" + Converters.makeCommandSummary(this.intendedCommand, normParameters);
	list.add(sentence);
	return this;
}
 
Example 4
Source File: ParallelEnricher.java    From metron with Apache License 2.0 6 votes vote down vote up
private static JSONObject join(JSONObject left, JSONObject right) {
  JSONObject message = new JSONObject();
  message.putAll(left);
  message.putAll(right);
  List<Object> emptyKeys = new ArrayList<>();
  for(Object key : message.keySet()) {
    Object value = message.get(key);
    if(value == null || value.toString().length() == 0) {
      emptyKeys.add(key);
    }
  }
  for(Object o : emptyKeys) {
    message.remove(o);
  }
  return message;
}
 
Example 5
Source File: JSONRecordReader.java    From incubator-retired-pirk with Apache License 2.0 6 votes vote down vote up
public void toMapWritable(Text line) throws ParseException
{
  JSONObject jsonObj = (JSONObject) jsonParser.parse(line.toString());
  for (Object key : jsonObj.keySet())
  {
    Text mapKey = new Text(key.toString());
    Text mapValue = new Text();
    if (jsonObj.get(key) != null)
    {
      if (dataSchema.isArrayElement(key.toString()))
      {
        String[] elements = StringUtils.jsonArrayStringToList(jsonObj.get(key).toString());
        TextArrayWritable aw = new TextArrayWritable(elements);
        value.put(mapKey, aw);
      }
      else
      {
        mapValue.set(jsonObj.get(key).toString());
        value.put(mapKey, mapValue);
      }
    }
  }
}
 
Example 6
Source File: SolrWriter.java    From metron with Apache License 2.0 6 votes vote down vote up
public Collection<SolrInputDocument> toDocs(Iterable<BulkMessage<JSONObject>> messages) {
  Collection<SolrInputDocument> ret = new ArrayList<>();
  for(BulkMessage<JSONObject> bulkWriterMessage: messages) {
    SolrInputDocument document = new SolrInputDocument();
    JSONObject message = bulkWriterMessage.getMessage();
    for (Object key : message.keySet()) {
      Object value = message.get(key);
      if (value instanceof Iterable) {
        for (Object v : (Iterable) value) {
          document.addField("" + key, v);
        }
      } else {
        document.addField("" + key, value);
      }
    }
    if (!document.containsKey(Constants.GUID)) {
      document.addField(Constants.GUID, UUID.randomUUID().toString());
    }
    ret.add(document);
  }
  return ret;
}
 
Example 7
Source File: JDBCTestUtils.java    From jdbc-cb with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static JSONArray extractDataIntoRowsAndColumnsAsMap(JSONArray jsonArray){
   	JSONArray listOfObjects = new JSONArray();
   	for(Object obj:jsonArray){
   		HashMap<String, String> m = new HashMap<String, String>();
   		JSONObject jsonObj = (JSONObject) obj;
   		for(Object key:jsonObj.keySet()){
   			Object value = jsonObj.get(key);
   			if(value != null){
   				m.put(key.toString(), value.toString());
   			}
   		}
   		JSONObject jobj = new JSONObject();
   		jobj.putAll(m);
   		listOfObjects.add(jobj);
   	}
   	return listOfObjects;
   }
 
Example 8
Source File: RestJSONResponseParser.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve properties from JSON response.
 * <p/>
 * @param json JSON response.
 * @return Properties from JSON response.
 */
private Properties parseProperties(JSONObject json) {
    Properties result = new Properties();
    JSONObject properties = (JSONObject)json.get("properties");
    if (properties != null) {
        for (Object key : properties.keySet()) {
            String value = (String) properties.get(key);
            result.setProperty((String)key, value);
        }
    }
    return result;
}
 
Example 9
Source File: HadoopUtils.java    From ankush with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static Set<String> getHostsFromJsonString(String nodesInfoJson,
		String nodeType) throws RegisterClusterException {
	JSONObject jsonNodesInfo = JsonMapperUtil.objectFromString(
			nodesInfoJson, JSONObject.class);
	if (jsonNodesInfo != null) {
		return jsonNodesInfo.keySet();
	}
	throw new RegisterClusterException("Could not fetch " + nodeType
			+ " nodes information from NameNodeInfo bean.");
}
 
Example 10
Source File: Serialization.java    From PlayerVaults with GNU General Public License v3.0 5 votes vote down vote up
@Deprecated
public static Map<String, Object> toMap(JSONObject object) {
    Map<String, Object> map = new HashMap<>();

    // Weird case of bad meta causing null map to be passed here.
    if (object == null) {
        return map;
    }

    for (Object key : object.keySet()) {
        map.put(key.toString(), fromJson(object.get(key)));
    }
    return map;
}
 
Example 11
Source File: DB.java    From sepia-assist-server with MIT License 5 votes vote down vote up
/**
 * Write data for a user directly without security restrictions (we need this to set user-roles for example).<br>
 * NOTE: use only if you KNOW what you are doing!
 * @param userId - ID of user to edit (NOT email! GUUID)
 * @param data - JSON with (full or partial) document data to set/update
 * @return success/fail
 * @throws Exception
 */
public static boolean writeAccountDataDirectly(String userId, JSONObject data) throws Exception{
	//TODO: I'm not happy with splitting this up here by database. We could add it to the account-interface
	//but in principle we don't want to have unsecured methods there :-(
	int code;
	
	//Elasticsearch
	if (Config.authAndAccountDB.equals("elasticsearch")){
		Elasticsearch es = new Elasticsearch();
		//Connect
		code = es.updateDocument(DB.USERS, "all", userId, data);
	
	//DynamoDB
	}else if (Config.authAndAccountDB.equals("dynamo_db")){
		JSONObject flatJson = JSON.makeFlat(data, "", null);
		ArrayList<String> keys = new ArrayList<>();
		ArrayList<Object> objects = new ArrayList<>();
		for (Object kO : flatJson.keySet()){
			String k = kO.toString();
			keys.add(k);
			objects.add(flatJson.get(k));
		}
		//Connect
		code = DynamoDB.writeAny(DB.USERS, DynamoDB.PRIMARY_USER_KEY, userId, 
				keys.toArray(new String[0]), objects.toArray(new Object[0]));
	//ERROR
	}else{
		throw new RuntimeException("Writing account data directly failed due to missing DB implementation!");
	}
	if (code != 0){
		throw new RuntimeException("Writing account data directly for user '" + userId + "' failed with code: " + code);
	}
	return true;
}
 
Example 12
Source File: Name.java    From sepia-assist-server with MIT License 5 votes vote down vote up
/**
 * Make sure all entries are free of malicious code.
 * @param json - JSONObject representing name
 * @return cleaned up JSON
 */
public static JSONObject cleanUpNameJson(JSONObject json){
	for (Object kObj : json.keySet()){
		String entry = JSON.getStringOrDefault(json, (String) kObj, "");
		//JSON.put(json, (String) kObj, Converters.escapeHTML(entry));
		JSON.put(json, (String) kObj, entry.replaceAll("[^\\w\\s#\\-\\+&]","").replaceAll("\\s+", " ").trim());
	}
	return json;
}
 
Example 13
Source File: LocaleDataUtils.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
private Map<String, String> getTerriContain(){
	Map<String, String> containMap = new HashMap<String, String>();
	String fileName = "cldr-core-" + CLDRUtils.CLDR_VERSION + "/supplemental/territoryContainment.json";
	String json = CLDRUtils.readZip(fileName, CLDRConstants.CORE_ZIP_FILE_PATH);
	JSONObject contents = JSONUtil.string2JSON(json);
	JSONObject object = (JSONObject) JSONUtil.select(contents, "supplemental.territoryContainment");
	for (Object key : object.keySet()) {
		containMap.put(key.toString(), key.toString());
	}
	return containMap;
}
 
Example 14
Source File: LocaleDataUtils.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * get all cldr scripts data
 *
 * @return
 */
public Map<String, String> getAllScripts() {
	Map<String, String> scriptsMap = new HashMap<String, String>();
	String fileName = "cldr-core-" + CLDRUtils.CLDR_VERSION + "/scriptMetadata.json";
	String json = CLDRUtils.readZip(fileName, CLDRConstants.CORE_ZIP_FILE_PATH);
	JSONObject allScriptsContents = JSONUtil.string2JSON(json);
	JSONObject object = (JSONObject) JSONUtil.select(allScriptsContents, "scriptMetadata");
	for (Object key : object.keySet()) {
		scriptsMap.put(key.toString(), key.toString());
	}
	return scriptsMap;
}
 
Example 15
Source File: DiscovererAPI.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
private boolean satisfyAllConstraints(JSONObject constraintsObject, Offering offering) {
    String toscaString = offering.toTosca();
    Set keys = constraintsObject.keySet();

    for (Object key : keys) {
        String constraintName = (String) key;
        String constraintValue = (String) constraintsObject.get(key);

        if (!satisfyConstraint(constraintName, constraintValue, toscaString))
            return false;
    }

    return true;
}
 
Example 16
Source File: JSONWriter.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
private void writeJsonObject(JSONObject jObj) throws IOException {
	writeLine("{");
	indentAdd();

	Set keys = jObj.keySet();
	int keyNum = keys.size();
	int count = 0;
	for (Iterator it = keys.iterator(); it.hasNext(); ) {
		String key = (String) it.next();
		Object val = jObj.get(key);

		writeIndent();
		this.writer.write(JSONValue.toJSONString(key));
		this.writer.write(": ");

		writeObject(val);

		count++;
		if (count < keyNum) {
			writeLine(",");
		} else {
			writeLine("");
		}
	}
	indentRemove();
	writeIndent();
	this.writer.write("}");
}
 
Example 17
Source File: BreakTaskPanel.java    From Explvs-AIO with MIT License 5 votes vote down vote up
@Override
public JSONObject toJSON() {
    JSONObject taskJSONObject = new JSONObject();
    taskJSONObject.put("type", TaskType.BREAK.name());

    JSONObject durationObj = durationPanel.toJSON();
    for (Object key : durationObj.keySet()) {
        taskJSONObject.put(key, durationObj.get(key));
    }

    taskJSONObject.put("logout", logoutCheckBox.isSelected());

    return taskJSONObject;
}
 
Example 18
Source File: AvroMultipleInputsUtil.java    From datafu with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the schema for a particular input split. 
 * 
 * @param conf configuration to get schema from
 * @param split input split to get schema for
 * @return schema
 */
public static Schema getInputKeySchemaForSplit(Configuration conf, InputSplit split) 
{    
  String path = ((FileSplit)split).getPath().toString();
  _log.info("Determining schema for input path " + path);
  JSONObject schemas;
  try
  {
    schemas = getInputSchemas(conf);
  }
  catch (ParseException e1)
  {
    throw new RuntimeException(e1);
  }
  Schema schema = null;
  if (schemas != null)
  {
    for (Object keyObj : schemas.keySet())
    {
      String key = (String)keyObj;
      _log.info("Checking against " + key);
      if (path.startsWith(key))
      {
        schema = new Schema.Parser().parse((String)schemas.get(key));
        _log.info("Input schema found: " + schema.toString(true));
        break;
      }
    }
  }
  if (schema == null)
  {
    _log.info("Could not determine input schema");
  }
  return schema;
}
 
Example 19
Source File: ReleaseJsonProperties.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private ReleaseInfo manageRelease(String key, Object arelease) {
    ReleaseInfo ri = new ReleaseInfo(key);
    // mandatory element
    JSONObject jsonrelease = (JSONObject) arelease;
    ri.setPosition(Integer.parseInt((String) getJSONInfo(jsonrelease, "position", "Order of release starting")));
    // previous release date
    JSONObject previousrelease = (JSONObject) getJSONInfo(jsonrelease, "previousreleasedate", "Apidoc: Date of previous Release");
    ri.setPreviousRelease(
            (String) getJSONInfo(previousrelease, "day", "Apidoc: day of previous Release"),
            (String) getJSONInfo(previousrelease, "month", "Apidoc: month of previous Release"),
            (String) getJSONInfo(previousrelease, "year", "Apidoc: year of previous Release"));
    // date of release
    JSONObject releasedate = (JSONObject) getJSONInfo(jsonrelease, "releasedate", "Apidoc: Date of Release vote");
    ri.setReleaseDate(
            (String) getJSONInfo(releasedate, "day", "Apidoc: day of previous Release"),
            (String) getJSONInfo(releasedate, "month", "Apidoc: month of previous Release"),
            (String) getJSONInfo(releasedate, "year", "Apidoc: year of previous Release"));

    // tlp or not
    ri.setMaturity((String) getJSONInfo(jsonrelease, "tlp", "Statut of release - TLP or not"));
    // version name
    ri.setVersion((String) getJSONInfo(jsonrelease, "versionName", "Version name"));
    ri.setApidocurl((String) getJSONInfo(jsonrelease, "apidocurl", "Apidoc: URL"));
    ri.setJavaApiDocurl((String) getJSONInfo(jsonrelease, "jdk_apidoc", "Apidoc: javadoc for java jdk"));
    ri.setUpdateUrl((String) getJSONInfo(jsonrelease, "update_url", "Update catalog"));
    ri.setPluginsUrl((String) getJSONInfo(jsonrelease, "plugin_url", "Plugin URL"));
    // optional section
    JSONObject milestone = (JSONObject) jsonrelease.get("milestones");
    if (milestone != null) {
        for (Object object : milestone.keySet()) {
            // ri.add(manageRelease(object.toString(), releaseList.get(object)));
            JSONObject milestonedata = (JSONObject) milestone.get(object);
            MileStone m = new MileStone((String) object);
            // mandatory
            m.setPosition(Integer.parseInt((String) getJSONInfo(milestonedata, "position", "Order of milestone in release")));
            // optional
            Object vote = milestonedata.get("vote");
            if (vote != null) {
                m.setVote(Integer.parseInt((String) vote));
            }
            m.setVersion((String) milestonedata.get("version"));
            ri.addMileStone(m);
        }
        Collections.sort(ri.milestones);
    }

    return ri;
}
 
Example 20
Source File: DockerAction.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public DockerContainerDetail getDetail(DockerContainer container) throws DockerException {
    JSONObject value = getRawDetails(DockerEntityType.Container, container.getId());
    String name = (String) value.get("Name");
    DockerContainer.Status status = DockerContainer.Status.STOPPED;
    JSONObject state = (JSONObject) value.get("State");
    if (state != null) {
        boolean paused = (Boolean) getOrDefault(state, "Paused", false);
        if (paused) {
            status = DockerContainer.Status.PAUSED;
        } else {
            boolean running = (Boolean) getOrDefault(state, "Running", false);
            if (running) {
                status = DockerContainer.Status.RUNNING;
            }
        }
    }

    boolean tty = false;
    boolean stdin = false;
    JSONObject config = (JSONObject) value.get("Config");
    if (config != null) {
        tty = (boolean) getOrDefault(config, "Tty", false);
        stdin = (boolean) getOrDefault(config, "OpenStdin", false);
    }
    JSONObject ports = (JSONObject) ((JSONObject) value.get("NetworkSettings")).get("Ports");
    if (ports == null || ports.isEmpty()) {
        return new DockerContainerDetail(name, status, stdin, tty);
    } else {
        List<PortMapping> portMapping = new ArrayList<>();
        for (String containerPortData : (Set<String>) ports.keySet()) {
            JSONArray hostPortsArray = (JSONArray) ports.get(containerPortData);
            if (hostPortsArray != null && !hostPortsArray.isEmpty()) {
                Matcher m = PORT_PATTERN.matcher(containerPortData);
                if (m.matches()) {
                    int containerPort = Integer.parseInt(m.group(1));
                    String type = m.group(2).toUpperCase(Locale.ENGLISH);
                    int hostPort = Integer.parseInt((String) ((JSONObject) hostPortsArray.get(0)).get("HostPort"));
                    String hostIp = (String) ((JSONObject) hostPortsArray.get(0)).get("HostIp");
                    portMapping.add(new PortMapping(ExposedPort.Type.valueOf(type), containerPort, hostPort, hostIp));
                } else {
                    LOGGER.log(Level.FINE, "Unparsable port: {0}", containerPortData);
                }
            }
        }
        return new DockerContainerDetail(name, status, stdin, tty, portMapping);
    }
}