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

The following examples show how to use org.json.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: VbaJsonParser.java    From genesis with GNU General Public License v3.0 7 votes vote down vote up
/**
 * Parses the JSON object into a Snippet that contains VBA macro code.
 *
 * @param json the JSON to be parsed
 * @return a snippet with information and the VBA macro code in it
 * @throws JsonParseException is thrown when the parsing of the JSON object
 * results in an error
 */
@Override
public Snippet parse(JSONObject json) throws JsonParseException {
    //Snippet snippet = super.parseSnippetInformation(json.getJSONObject("information"));
    Snippet snippet = super.parseSnippetInformation(json);
    //Get the JSON class object from the JSONObject
    json = json.getJSONObject("class");
    //Create the class object based on the given architecture
    Architecture architecture = Architecture.valueOf(json.getString("architecture"));
    //Create the VBA class object
    IClass vbaClass = new VbaClass(architecture);
    //Iterate through all techniques
    vbaClass.setTechniques(super.getTechniques(json.getJSONArray("techniques")));
    //Get the script field
    String script = json.getString("script");
    //Add the functions to the VBA class object
    vbaClass = addScriptAsFunction(vbaClass, script);

    //Get all variables from the JSON object
    JSONObject variablesJson = json.getJSONObject("variables");
    //Iterate through all variables
    for (String variableName : variablesJson.keySet()) {
        //Get the variable type based on the variable's name (which is the key in the set)
        String variableType = variablesJson.getString(variableName);
        //Create a variable object
        IVariable variable = new VbaVariable(variableName, variableType);
        //Add the variable to the class
        vbaClass.addVariable(variable);
    }

    //Set the class object
    snippet.setClassObject(vbaClass);
    //Return the snippet
    return snippet;
}
 
Example 2
Source File: DatasetJSONReader.java    From Heracles with GNU General Public License v3.0 7 votes vote down vote up
private void processAnnotatable(DataEntity ann, JSONObject annJSON, HashMap<Integer, DataEntity> oldIds){
	oldIds.put(annJSON.getInt("id"), ann);
	JSONObject annotationsJSON = annJSON.getJSONObject("annotations");
	for (String annotationKey : annotationsJSON.keySet()){
		ann.putAnnotation(annotationKey, translateJSONToProperObject(ann.getDataset(), annotationKey, annotationsJSON));
	}
}
 
Example 3
Source File: JsonParser.java    From training with MIT License 7 votes vote down vote up
@Override
public Map<String, String> parseText(String text) {
	JSONObject json = new JSONObject(text);
	Map<String, String> map = new HashMap<>();
	for (String key : json.keySet()) {
		map.put(key, json.optString(key));
	}
	return map;
}
 
Example 4
Source File: ClassEntity.java    From GsonFormat with Apache License 2.0 6 votes vote down vote up
public boolean isSame(JSONObject o) {
    if (o == null) {
        return false;
    }
    boolean same = true;
    for (String key : o.keySet()) {
        same = false;
        for (FieldEntity field : fields) {
            if (field.getKey().equals(key)) {
                if (field.isSameType(o.get(key))) {
                    same = true;
                }
                break;
            }
        }
        if (!same) {
            break;
        }
    }
    return same;
}
 
Example 5
Source File: GettingStartedIntegrationTest.java    From getting-started with MIT License 6 votes vote down vote up
@Test
void testGetCurrencyConversion() {
  Response<JSONObject> response = GettingStarted.getCurrencyConversion("NOK", "EUR");

  assertThat(response.getHttpResponse().getStatusCode())
      .as("Test if status code is 200/OK").isEqualTo(200);

  JSONObject json = response.getAwsResponse();

  assertThat(json.length()).as("Check that object contains correct amount of parameters").isEqualTo(12);

  Set<String> keySet;
  keySet = json.keySet();
  assertThat(keySet.contains("quoteCurrency")).as("That object contains quoteCurrency").isTrue();
  assertThat(keySet.contains("country")).as("That object contains country").isTrue();
  assertThat(keySet.contains("amount")).as("That object contains amount").isTrue();
  assertThat(keySet.contains("buyRateTransfer")).as("That object contains buyRateTransfer").isTrue();
  assertThat(keySet.contains("midRate")).as("That object contains midRate").isTrue();
  assertThat(keySet.contains("sellRateTransfer")).as("That object contains sellRateTransfer").isTrue();
  assertThat(keySet.contains("sellRateCash")).as("That object contains sellRateCash").isTrue();
  assertThat(keySet.contains("changeInMidRate")).as("That object contains changeInMidRate").isTrue();
  assertThat(keySet.contains("buyRateCash")).as("That object contains buyRateCash").isTrue();
  assertThat(keySet.contains("updatedDate")).as("That object contains updatedDate").isTrue();
  assertThat(keySet.contains("previousMidRate")).as("That object contains previousMidRate").isTrue();
  assertThat(keySet.contains("baseCurrency")).as("That object contains baseCurrency").isTrue();
}
 
Example 6
Source File: FuzzyJsonTester.java    From datamill with ISC License 6 votes vote down vote up
private static boolean areJsonObjectsSimilarEnough(JSONObject expected, JSONObject actual) {
    if (!actual.keySet().containsAll(expected.keySet())) {
        return false;
    }

    for (String propertyName : expected.keySet()) {
        Object expectedProperty = expected.get(propertyName);
        Object actualProperty = actual.get(propertyName);

        if (expectedProperty != null && !isSimilar(expectedProperty, actualProperty)) {
            return false;
        }
    }

    return true;
}
 
Example 7
Source File: SusiThought.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 5 votes vote down vote up
public String getObservation(String featureName) {
    JSONArray table = this.getData();
    if (table != null && table.length() > 0) {
        for (int rc = 0; rc < table.length(); rc++) {
            JSONObject row = table.getJSONObject(rc);
            for (String key: row.keySet()) {
                if (key.equals(featureName)) return row.get(key).toString();
            }
        }
    }
    return null;
}
 
Example 8
Source File: WindowsRawIpProxyProvider.java    From G-Earth with MIT License 5 votes vote down vote up
public static boolean isNoneConnected(String actual_host) {
    JSONObject connections = getCurrentConnectionsCache(actual_host);

    BigInteger timeoutTimestamp = BigInteger.valueOf(System.currentTimeMillis() - 60000);
    for (String key : connections.keySet()) {
        JSONObject connection = connections.getJSONObject(key);
        if (!key.equals(INSTANCE_ID.toString())) {
            if (connection.getBigInteger("timestamp").compareTo(timeoutTimestamp) > 0) {
                return false;
            }
        }
    }
    return true;
}
 
Example 9
Source File: ServerContainer.java    From Ptero4J with MIT License 5 votes vote down vote up
private static Map<String, String> getEnvironmentVariablesMap(JSONObject json) {
    Map<String, String> vars = new HashMap<>();
    for (String key : json.keySet()) {
        vars.put(key, json.getString(key));
    }
    return vars;
}
 
Example 10
Source File: Properties.java    From ict with Apache License 2.0 5 votes vote down vote up
public static Properties fromJSON(JSONObject json) {
    java.util.Properties propObject = new java.util.Properties();
    for (String key : json.keySet()) {
        Object value = json.get(key);
        if (value == null)
            value = "";
        if (value instanceof JSONArray) {
            value = value.toString().replace("[", "").replace("]", "").replace("\"", "");
        }
        propObject.put(key, value.toString());
    }
    return new Properties(propObject);
}
 
Example 11
Source File: BundleDataUtil.java    From aem-ide-tooling-4-intellij with Apache License 2.0 5 votes vote down vote up
public static Map<String, String> getData(OsgiClient osgiClient, String bundleSymbolicName) throws OsgiClientException {
    Map<String, String> answer = new HashMap<>();
    RepositoryInfo repositoryInfo = getRepositoryInfo(osgiClient);
    GetMethod method = new GetMethod(repositoryInfo.appendPath("system/console/bundles/" + bundleSymbolicName + ".json"));
    HttpClient client = getHttpClient(osgiClient);

    try {
        int result = client.executeMethod(method);
        if (result != HttpStatus.SC_OK) {
            throw new HttpException("Got status code " + result + " for call to " + method.getURI());
        }
        try ( InputStream input = method.getResponseBodyAsStream() ) {
            JSONObject object = new JSONObject(new JSONTokener(new InputStreamReader(input)));
            JSONArray bundleData = object.getJSONArray("data");
            if(bundleData.length() > 1) {
                throw new OsgiClientException("More than one Bundle found");
            } else {
                JSONObject bundle = bundleData.getJSONObject(0);
                for(Object item: bundle.keySet()) {
                    String name = item + "";
                    String value = bundle.get(name) + "";
                    answer.put(name, value);
                }
            }
        }
    } catch (IOException | JSONException e) {
        throw new OsgiClientException(e);
    } finally {
        method.releaseConnection();
    }
    return answer;
}
 
Example 12
Source File: CosmosRenderer.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Given a (fully rendered) marathon.json, returns what the resulting environment would look like.
 */
private static Map<String, String> getMarathonAppEnvironment(String marathonJsonContent) {
  JSONObject marathonJson = new JSONObject(marathonJsonContent);
  Map<String, String> env = new HashMap<>();

  if (marathonJson.has("env")) {
    JSONObject marathonEnvJson = marathonJson.getJSONObject("env");
    for (String key : marathonEnvJson.keySet()) {
      env.put(key, marathonEnvJson.getString(key));
    }
  }

  // In addition to the 'env' entries, simulate the injected envvars produced by Marathon for any listed ports:
  if (marathonJson.has("portDefinitions")) {
    JSONArray portsJson = marathonJson.getJSONArray("portDefinitions");
    for (int i = 0; i < portsJson.length(); ++i) {
      JSONObject portJson = portsJson.getJSONObject(i);
      // Determine a port value. Simulate a random ephemeral port if the value is 0.
      int portVal = portJson.getInt("port");
      if (portVal == 0) {
        // Default ephemeral port range on linux is 32768 through 60999. Let's simulate that.
        // See: /proc/sys/net/ipv4/ip_local_port_range
        portVal = RANDOM.nextInt(61000 - 32768 /* result: 0 thru 28231 */) + 32768;
      }
      // Each port is advertised against its index (e.g. $PORTN), and against its name (e.g. $PORT_NAME).
      String portStr = String.valueOf(portVal);
      env.put(String.format("PORT%d", i), portStr);
      if (portJson.has("name")) {
        env.put(String.format("PORT_%s", portJson.getString("name").toUpperCase()), portStr);
      }
    }
  }
  return env;
}
 
Example 13
Source File: CosmosRenderer.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Finds string entries in the provided tree and writes them to {@code config} under the provided path. Used for
 * Universe resource.json files.
 * <p>
 * For example, {"a": {"b": {"c": "d"}} } => {"a.b.c": "d"}
 */
private static void flattenTree(String path, JSONObject node, Map<String, String> config) {
  for (String key : node.keySet()) {
    Object val = node.get(key);
    String entryPath = path.isEmpty() ? key : String.format("%s.%s", path, key);
    if (val instanceof JSONObject) {
      flattenTree(entryPath, (JSONObject) val, config); // RECURSE
    } else {
      config.put(entryPath, val.toString());
    }
  }
}
 
Example 14
Source File: GenericJsonParser.java    From genesis with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Gets all arguments from a JSON object.
 *
 * @param json the JSON object to be parsed
 * @return a mapping in which the keys are the variable names and the value
 * is the type or body of the variable (depending on the usage within the
 * JSON object and the language in which it is used). The mapping can be
 * empty if no argument are given.
 */
public Map<String, String> getArguments(JSONObject json) {
    //Creates the map to store all argumentts in, where the variable name is the key, and the value is the value
    Map<String, String> arguments = new HashMap<>();
    //Iterate through the keyset of the JSON object
    for (String variableName : json.keySet()) {
        //Gets the variable value, based on the varaible name
        String variableValue = json.getString(variableName);
        //Store the combination in the map
        arguments.put(variableName, variableValue);
    }
    //Return the map with all arguments
    return arguments;
}
 
Example 15
Source File: CosStsClient.java    From qcloud-cos-sts-sdk with MIT License 5 votes vote down vote up
private static JSONObject downCompat(JSONObject resultJson) {
    JSONObject dcJson = new JSONObject();

    for (String key : resultJson.keySet()) {
        Object value = resultJson.get(key);
        if (value instanceof JSONObject) {
            dcJson.put(headerToLowerCase(key), downCompat((JSONObject) value));
        } else {
            String newKey = "Token".equals(key) ? "sessionToken" : headerToLowerCase(key);
            dcJson.put(newKey, resultJson.get(key));
        }
    }

    return dcJson;
}
 
Example 16
Source File: CosmosRenderer.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
/**
 * Finds entries nested under 'properties' nodes in the provided JSON {@code node} and writes them to {@code config}
 * under the provided path. Used for Universe config.json files.
 * <p>
 * For example, {"a": {"properties": {"b": {"default": "c"}, "d": {"properties": {"e": {"default": "f"}}}}}} =>
 * {"a.b": "c", "a.b.d.e": "f"}
 */
private static void flattenPropertyTree(String path, JSONObject node, Map<String, String> config) {
  if (node.has("default")) {
    // So... this is a fun little hack that fixes the fact that we remove too many escapes
    // when parsing escaped strings.
    config.put(path, node.get("default").toString().replaceAll("\"", "\\\\\""));
  }
  if (node.has("type") && node.getString("type").equals("object") && node.has("properties")) {
    JSONObject props = node.getJSONObject("properties");
    for (String key : props.keySet()) {
      String entryPath = path.isEmpty() ? key : String.format("%s.%s", path, key);
      flattenPropertyTree(entryPath, props.getJSONObject(key), config); // RECURSE
    }
  }
}
 
Example 17
Source File: Step2bGoldReasonAnnotator.java    From argument-reasoning-comprehension-task with Apache License 2.0 4 votes vote down vote up
public static SortedMap<String, SortedSet<SingleWorkerAssignment<JSONArray>>> loadGlobalReasonAssignments(
        File mTurkOutputCSVFile)
        throws Exception
{
    MTurkOutputReader outputReader = new MTurkOutputReader(false, mTurkOutputCSVFile);

    // argId, set of assignments -- the json array is a list of annotated segments
    SortedMap<String, SortedSet<SingleWorkerAssignment<JSONArray>>> globalReasonAssignments = new TreeMap<>();

    for (Map<String, String> row : outputReader) {

        String workerId = row.get("workerid");
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy",
                Locale.ENGLISH);
        Date time = dateFormat.parse(row.get("assignmentaccepttime"));

        // claims
        String jsonResults = row.get("Answer.collectedAnnotationResults");

        JSONObject jsonObject = new JSONObject(jsonResults);

        // iterate over argIDs
        for (Object argIdObject : jsonObject.keySet()) {
            String argId = argIdObject.toString();
            JSONObject argumentJsonAnnotations = jsonObject.getJSONObject(argId);
            JSONArray segments = argumentJsonAnnotations.getJSONArray("segments");

            // we don't need this one in fact...
            boolean noReasons = argumentJsonAnnotations.getBoolean("noReasons");

            SingleWorkerAssignment<JSONArray> singleWorkerAssignment = new SingleWorkerAssignment<>(
                    workerId, time, segments);

            // update the global map
            if (!globalReasonAssignments.containsKey(argId)) {
                globalReasonAssignments
                        .put(argId, new TreeSet<SingleWorkerAssignment<JSONArray>>());
            }
            globalReasonAssignments.get(argId).add(singleWorkerAssignment);
        }
    }
    return globalReasonAssignments;
}
 
Example 18
Source File: CloudFoundryManager.java    From open-Autoscaler with Apache License 2.0 4 votes vote down vote up
private List<CFInstanceStats> getApplicationStatsByAppId(String appId) throws IOException {
    List<CFInstanceStats> statsList = new ArrayList<CFInstanceStats>();
    String url = this.target + "/v2/apps/" + appId + "/stats";

    WebResource webResource = restClient.resource(url);
    String response = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
            .header("Authorization", "Bearer " + this.accessToken).get(String.class);

    JSONObject jsonObj = new JSONObject(response);
    Set<String> keySet = jsonObj.keySet();
    logger.debug(String.format("%d instances for app %s", keySet.size(), appId));
    for (String key : keySet) {
        Object id = key;
        JSONObject jsonStats = (JSONObject) jsonObj.get(key);

        Map<String, Object> attributes = new HashMap<String, Object>();

        String state = (String) jsonStats.get("state");
        // only count in RUNNING instance
        if (!InstanceState.RUNNING.equals(InstanceState.valueOf(state))) {
        	logger.warn(String.format("instace %s of %s is not RUNNING: %s ", id, appId, state));
            continue;
        }
        attributes.put("state", state);

        Map<String, Object> statsMap = new HashMap<String, Object>();
        JSONObject statsObj = (JSONObject) jsonStats.get("stats");
        statsMap.put("name", statsObj.get("name"));
        statsMap.put("host", statsObj.get("host"));
        statsMap.put("port", statsObj.get("port"));
        statsMap.put("uptime", Double.parseDouble(statsObj.get("uptime").toString()));
        statsMap.put("mem_quota", statsObj.get("mem_quota"));
        statsMap.put("disk_quota", statsObj.get("disk_quota"));
        statsMap.put("fds_quota", statsObj.get("fds_quota"));

        Map<String, Object> usageMap = new HashMap<String, Object>();
        JSONObject usageObj = (JSONObject) statsObj.get("usage");
        usageMap.put("time", usageObj.get("time"));
        usageMap.put("cpu", Double.parseDouble(usageObj.get("cpu").toString()));
        usageMap.put("mem", Double.parseDouble(usageObj.get("mem").toString()));
        usageMap.put("disk", Integer.parseInt(usageObj.get("disk").toString()));

        statsMap.put("usage", usageMap);

        attributes.put("stats", statsMap);

        CFInstanceStats stats = new CFInstanceStats(id.toString(), attributes);
        statsList.add(stats);
    }

    if (statsList.size() == 0) {
        statsList = null;
    }
    return statsList;
}
 
Example 19
Source File: PlotHandler.java    From EchoQuery with GNU General Public License v2.0 4 votes vote down vote up
@Override
public SpeechletResponse respond(Intent intent, Session session) {
  List<ColumnName> axes = new ArrayList<>();

  if (intent.getSlot(SlotUtil.PLOT_COLUMN_1).getValue() != null) {
    axes.add(SlotUtil.parseColumnSlot(
        intent.getSlot(SlotUtil.PLOT_COLUMN_1).getValue()));
  }
  if (intent.getSlot(SlotUtil.PLOT_COLUMN_2).getValue() != null) {
    axes.add(SlotUtil.parseColumnSlot(
        intent.getSlot(SlotUtil.PLOT_COLUMN_2).getValue()));
  }

  List<String> matches = new ArrayList<>();
  JSONObject columnData = new JSONObject(VisualizationUtil.getUserData(
      session.getUser().getUserId()).getJSONArray("sessions.result")
      .getString(0));
  for (ColumnName axis : axes) {
    for (String column : columnData.keySet()) {
      System.out.println(column);
      String[] tableColumn = column.split("\\.");
      System.out.println(Arrays.toString(tableColumn));
      if (axis.getTable().isPresent()
          && axis.getTable().get().equals(tableColumn[0])
          && axis.getColumn().get().equals(tableColumn[1])) {
        matches.add(column);
        break;
      }
      if (!axis.getTable().isPresent()
          && axis.getColumn().get().equals(tableColumn[1])) {
        matches.add(column);
        break;
      }
    }
  }

  VisualizationUtil.updatePlotColumns(matches, session);

  String description = "";
  switch (matches.size()) {
    case 0:
      description = "I am not sure what columns to plot, please try again.";
      break;
    case 1:
      description = "Here is a histogram of "
          + Joiner.on(" ").join(matches.get(0).split("\\.")) + ".";
      break;
    case 2:
      description = "Here is a heatmap of "
          + Joiner.on(" ").join(matches.get(0).split("\\.")) + " versus "
          + Joiner.on(" ").join(matches.get(1).split("\\.")) + ".";
      break;
  }

  if (description.isEmpty()) {
    return Response.unexpectedError(session);
  }

  VisualizationUtil.updateDisplayText(description, session);
  return Response.say(description, session);
}
 
Example 20
Source File: ReadPlista.java    From StreamingRec with Apache License 2.0 4 votes vote down vote up
/**
 * This method extracts the information about a user click from a json
 * string
 * 
 * @param jsonstr -
 * @param eventNotification -
 * @return a csv line
 */
private static String readRecommendationRequestOrEventNotification(String jsonstr, boolean eventNotification) {
	//parse the JSON sting to a json object
	JSONObject linejson = new JSONObject(jsonstr);
	// context
	JSONObject contextRR = linejson.getJSONObject("context");
	// each context object contains object of type: simple, lists, cluster
	JSONObject simpleRR = contextRR.getJSONObject("simple");
	JSONObject listRR = contextRR.getJSONObject("lists");

	//create a tmp transaction project (click info + some item metadata 
	//that needs to be merged to item objects later)
	TmpPlistaTransaction transaction = new TmpPlistaTransaction();
	// each list object contains a list of tuples
	// code_11 is Category of the news article
	if (listRR.has("11")) {
		JSONArray categoryArray = listRR.getJSONArray("11");
		if (categoryArray.length() > 1) {
			System.err.println("More than one category.");
		} else if (categoryArray.length() == 1) {
			transaction.category = categoryArray.getInt(0);
		}
	}

	// each simple objects contains a list of tuples
	// code_27 is publisher ID
	if (simpleRR.has("27")) {
		transaction.publisher = simpleRR.getInt("27");
	}

	// code_57 is user cookie
	if (simpleRR.has("57")) {
		transaction.cookie = simpleRR.getLong("57");
	}
	
	// code_25 is item ID
	if (simpleRR.has("25")) {
		transaction.item = new Item();
		transaction.item.id = simpleRR.getLong("25");
	}

	// timestamp
	if (linejson.has("timestamp")) {
		transaction.timestamp = new Date(linejson.getLong("timestamp"));
	}

	// Different branch for event notification
	if (eventNotification) {
		// We dont need to differentiate between event notification and
		// recommendation request right now.
		// But maybe in the future. We can do it here.
	}
	
	JSONObject clustersRR = contextRR.getJSONObject("clusters");
	//keywords
	if (extractText && clustersRR.has("33")) {
		Object object = clustersRR.get("33");
		if(!(object instanceof JSONArray)){
			//replace special line-breaking character 0xAD
			JSONObject keywordObj = (JSONObject) object;
			transaction.keywords = new Object2IntOpenHashMap<>();
			for (String key : keywordObj.keySet()) {
				transaction.keywords.addTo(key.replaceAll(",", " ").replaceAll(Character.toString((char) 0xAD), ""), keywordObj.getInt(key));
			}
		}			
	}

	// create CSV line
	return transaction.toString();
}