Java Code Examples for org.json.JSONArray#forEach()

The following examples show how to use org.json.JSONArray#forEach() . 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: Network.java    From yacy_grid_mcp with GNU Lesser General Public License v2.1 9 votes vote down vote up
@SuppressWarnings("unchecked")
public List<Peer> getMCPServiceList() {
    Set<String> failstubs = new HashSet<>();
    JSONArray ja = null;
    loop: for (Set<String> a: new Set[]{mcpActiveAddresses, mcpPassiveAddresses}) {
        for (String hostprotocolstub: a) {
            try {
                ServiceResponse response = APIServer.getAPI(ServicesService.NAME).serviceImpl(hostprotocolstub, new JSONObject());
                ja = response.getArray();
                break loop;
            } catch (IOException e) {
                failstubs.add(hostprotocolstub);
            }
        }
    }
    removeMCP(failstubs);
    List<Peer> list = new ArrayList<>();
    if (ja == null) return list;
    ja.forEach(j -> list.add(new Peer((JSONObject) j)));
    return list;
}
 
Example 2
Source File: ReleaseTool.java    From apicurio-studio with Apache License 2.0 9 votes vote down vote up
/**
 * Returns all issues (as JSON nodes) that were closed since the given date.
 * @param since
 * @param githubPAT
 */
private static List<JSONObject> getIssuesForRelease(String since, String githubPAT) throws Exception {
    List<JSONObject> rval = new ArrayList<>();

    String currentPageUrl = "https://api.github.com/repos/apicurio/apicurio-studio/issues";
    int pageNum = 1;
    while (currentPageUrl != null) {
        System.out.println("Querying page " + pageNum + " of issues.");
        HttpResponse<JsonNode> response = Unirest.get(currentPageUrl)
                .queryString("since", since)
                .queryString("state", "closed")
                .header("Accept", "application/json")
                .header("Authorization", "token " + githubPAT).asJson();
        if (response.getStatus() != 200) {
            throw new Exception("Failed to list Issues: " + response.getStatusText());
        }
        JSONArray issueNodes = response.getBody().getArray();
        issueNodes.forEach(issueNode -> {
            JSONObject issue = (JSONObject) issueNode;
            String closedOn = issue.getString("closed_at");
            if (since.compareTo(closedOn) < 0) {
                if (!isIssueExcluded(issue)) {
                    rval.add(issue);
                } else {
                    System.out.println("Skipping issue (excluded): " + issue.getString("title"));
                }
            } else {
                System.out.println("Skipping issue (old release): " + issue.getString("title"));
            }
        });

        System.out.println("Processing page " + pageNum + " of issues.");
        System.out.println("    Found " + issueNodes.length() + " issues on page.");
        String allLinks = response.getHeaders().getFirst("Link");
        Map<String, Link> links = Link.parseAll(allLinks);
        if (links.containsKey("next")) {
            currentPageUrl = links.get("next").getUrl();
        } else {
            currentPageUrl = null;
        }
        pageNum++;
    }

    return rval;
}
 
Example 3
Source File: DefaultJsonObject.java    From cloud-security-xsuaa-integration with Apache License 2.0 7 votes vote down vote up
private List<JsonObject> convertToJsonObjects(JSONArray jsonArray) {
	List<JsonObject> jsonObjects = new ArrayList<>();
	jsonArray.forEach(jsonArrayObject -> {
		if (jsonArrayObject instanceof JSONObject) {
			jsonObjects.add(new DefaultJsonObject(jsonArrayObject.toString()));
		} else {
			throw new JsonParsingException("Array does not only contain json objects!");
		}
	});
	return jsonObjects;
}
 
Example 4
Source File: SimManager.java    From AppiumTestDistribution with GNU General Public License v3.0 7 votes vote down vote up
public boolean isSimulatorObjectAvailableInCapsJson() {
    JSONArray hostMachines = capabilityManager.getCapabilitiesArrayFromKey("hostMachines");
    final boolean[] firstSimulatorObject = {false};

    if (hostMachines != null) {
        hostMachines.forEach(simulatorObject -> {
            if (((JSONObject) simulatorObject).has("simulators")) {
                firstSimulatorObject[0] = true;
            }
        });
    }
    return firstSimulatorObject[0];
}
 
Example 5
Source File: ElasticsearchRESTUtil.java    From kmanager with Apache License 2.0 4 votes vote down vote up
public static Map<String, List<OffsetStat>> offset(String group, String topic, String start, String end) {
  Map<String, List<OffsetStat>> statsMap = new HashMap<String, List<OffsetStat>>();
  String indexPrefix = SystemManager.getConfig().getEsIndex();
  try {
    ElasticsearchAssistEntity assistEntity = ScrollSearchTemplate.getInterval(start, end);

    List<String> indexes = new ArrayList<String>();
    assistEntity.getIndexs().forEach(a -> {
      indexes.add(indexPrefix + "-" + a);
    });

    String[] esHost = SystemManager.getConfig().getEsHosts().split("[,;]")[0].split(":");

    String url = "http://" + esHost[0] + ":" + esHost[1] + "/" + String.join(",", indexes) + "/"
        + SystemManager.getElasticSearchOffsetType() + "/_search?ignore_unavailable=true&allow_no_indices=true";

    ResponseEntity<String> response = REST.exchange(url, HttpMethod.POST,
        new HttpEntity<String>(ScrollSearchTemplate.getOffset(group, topic, assistEntity), headers), String.class);
    String searchResult = response.getBody();
    JSONObject temp = new JSONObject(searchResult);
    JSONArray temp2 = temp.getJSONObject("aggregations").getJSONObject("aggs").getJSONArray("buckets");
    List<OffsetStat> stats = new ArrayList<OffsetStat>();
    temp2.forEach(obj -> {
      JSONObject item = (JSONObject) obj;
      JSONArray xx = item.getJSONObject("group").getJSONArray("buckets");
      for (int i = 0; i < xx.length(); i++) {
        JSONObject item2 = xx.getJSONObject(i);
        JSONArray xxx = item2.getJSONObject("topic").getJSONArray("buckets");
        for (int j = 0; j < xxx.length(); j++) {
          JSONObject item3 = xxx.getJSONObject(j);
          stats.add(new OffsetStat(item.getLong("key"), item2.get("key").toString(), item3.get("key").toString(),
              item3.getJSONObject("offset").getLong("value"), item3.getJSONObject("lag").getLong("value")));
        }
      }
    });

    stats.forEach(a -> {
      String topicName = a.getTopic();
      if (topicName == null || topicName.length() == 0) {
        topicName = "empty";
      }
      if (statsMap.containsKey(topicName)) {
        statsMap.get(topicName).add(a);
      } else {
        List<OffsetStat> arr = new ArrayList<OffsetStat>();
        arr.add(a);
        statsMap.put(topicName, arr);
      }
    });

    statsMap.forEach((key, val) -> {
      for (int i = val.size() - 1; i > 0; i--) {
        val.get(i).setOffset(val.get(i).getOffset() - val.get(i - 1).getOffset());
      }
      val.remove(0);
    });

  } catch (Exception e) {
    // TODO
    LOG.error("Damn...", e);
  }
  return statsMap;
}
 
Example 6
Source File: Board.java    From codenjoy with GNU General Public License v3.0 4 votes vote down vote up
private void parseHistory(JSONArray historyJson) {
    this.history = new ArrayList<>();
    historyJson.forEach(reportJson -> {
        history.add(DailyReport.fromJson(reportJson));
    });
}
 
Example 7
Source File: Container.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * Constructing an {@link Container} object from container metadata.
 * @param metadata The metadata of the container in JSON.
 * @throws JSONException If fails to parse metadata.
 */
private Container(JSONObject metadata, short parentAccountId) throws JSONException {
  if (metadata == null) {
    throw new IllegalArgumentException("metadata cannot be null.");
  }
  this.parentAccountId = parentAccountId;
  short metadataVersion = (short) metadata.getInt(JSON_VERSION_KEY);
  switch (metadataVersion) {
    case JSON_VERSION_1:
      id = (short) metadata.getInt(CONTAINER_ID_KEY);
      name = metadata.getString(CONTAINER_NAME_KEY);
      status = ContainerStatus.valueOf(metadata.getString(STATUS_KEY));
      deleteTriggerTime = CONTAINER_DELETE_TRIGGER_TIME_DEFAULT_VALUE;
      description = metadata.optString(DESCRIPTION_KEY);
      encrypted = ENCRYPTED_DEFAULT_VALUE;
      previouslyEncrypted = PREVIOUSLY_ENCRYPTED_DEFAULT_VALUE;
      cacheable = !metadata.getBoolean(IS_PRIVATE_KEY);
      backupEnabled = BACKUP_ENABLED_DEFAULT_VALUE;
      mediaScanDisabled = MEDIA_SCAN_DISABLED_DEFAULT_VALUE;
      replicationPolicy = null;
      ttlRequired = TTL_REQUIRED_DEFAULT_VALUE;
      securePathRequired = SECURE_PATH_REQUIRED_DEFAULT_VALUE;
      contentTypeWhitelistForFilenamesOnDownload = CONTENT_TYPE_WHITELIST_FOR_FILENAMES_ON_DOWNLOAD_DEFAULT_VALUE;
      break;
    case JSON_VERSION_2:
      id = (short) metadata.getInt(CONTAINER_ID_KEY);
      name = metadata.getString(CONTAINER_NAME_KEY);
      status = ContainerStatus.valueOf(metadata.getString(STATUS_KEY));
      deleteTriggerTime = metadata.optLong(CONTAINER_DELETE_TRIGGER_TIME_KEY, CONTAINER_DELETE_TRIGGER_TIME_DEFAULT_VALUE);
      description = metadata.optString(DESCRIPTION_KEY);
      encrypted = metadata.optBoolean(ENCRYPTED_KEY, ENCRYPTED_DEFAULT_VALUE);
      previouslyEncrypted = metadata.optBoolean(PREVIOUSLY_ENCRYPTED_KEY, PREVIOUSLY_ENCRYPTED_DEFAULT_VALUE);
      cacheable = metadata.optBoolean(CACHEABLE_KEY, CACHEABLE_DEFAULT_VALUE);
      backupEnabled = metadata.optBoolean(BACKUP_ENABLED_KEY, BACKUP_ENABLED_DEFAULT_VALUE);
      mediaScanDisabled = metadata.optBoolean(MEDIA_SCAN_DISABLED_KEY, MEDIA_SCAN_DISABLED_DEFAULT_VALUE);
      replicationPolicy = metadata.optString(REPLICATION_POLICY_KEY, null);
      ttlRequired = metadata.optBoolean(TTL_REQUIRED_KEY, TTL_REQUIRED_DEFAULT_VALUE);
      securePathRequired = metadata.optBoolean(SECURE_PATH_REQUIRED_KEY, SECURE_PATH_REQUIRED_DEFAULT_VALUE);
      JSONArray contentTypeWhitelistForFilenamesOnDownloadJson =
          metadata.optJSONArray(CONTENT_TYPE_WHITELIST_FOR_FILENAMES_ON_DOWNLOAD);
      if (contentTypeWhitelistForFilenamesOnDownloadJson != null) {
        contentTypeWhitelistForFilenamesOnDownload = new HashSet<>();
        contentTypeWhitelistForFilenamesOnDownloadJson.forEach(
            contentType -> contentTypeWhitelistForFilenamesOnDownload.add(contentType.toString()));
      } else {
        contentTypeWhitelistForFilenamesOnDownload = CONTENT_TYPE_WHITELIST_FOR_FILENAMES_ON_DOWNLOAD_DEFAULT_VALUE;
      }
      break;
    default:
      throw new IllegalStateException("Unsupported container json version=" + metadataVersion);
  }
  checkPreconditions(name, status, encrypted, previouslyEncrypted);
}