Example usage for org.json.simple JSONArray forEach

List of usage examples for org.json.simple JSONArray forEach

Introduction

In this page you can find the example usage for org.json.simple JSONArray forEach.

Prototype

@Override
public void forEach(Consumer<? super E> action) 

Source Link

Usage

From source file:io.openvidu.java.client.OpenVidu.java

/**
 * Lists all existing recordings//  www. ja  va  2s  . c o  m
 *
 * @return A {@link java.util.List} with all existing recordings
 * 
 * @throws OpenViduJavaClientException
 * @throws OpenViduHttpException
 */
@SuppressWarnings("unchecked")
public List<Recording> listRecordings() throws OpenViduJavaClientException, OpenViduHttpException {
    HttpGet request = new HttpGet(OpenVidu.urlOpenViduServer + API_RECORDINGS);
    HttpResponse response;
    try {
        response = OpenVidu.httpClient.execute(request);
    } catch (IOException e) {
        throw new OpenViduJavaClientException(e.getMessage(), e.getCause());
    }

    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
            List<Recording> recordings = new ArrayList<>();
            JSONObject json = httpResponseToJson(response);
            JSONArray array = (JSONArray) json.get("items");
            array.forEach(item -> {
                recordings.add(new Recording((JSONObject) item));
            });
            return recordings;
        } else {
            throw new OpenViduHttpException(statusCode);
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}

From source file:io.openvidu.java.client.Session.java

@SuppressWarnings("unchecked")
protected Session resetSessionWithJson(JSONObject json) {
    this.sessionId = (String) json.get("sessionId");
    this.createdAt = (long) json.get("createdAt");
    this.recording = (boolean) json.get("recording");
    SessionProperties.Builder builder = new SessionProperties.Builder()
            .mediaMode(MediaMode.valueOf((String) json.get("mediaMode")))
            .recordingMode(RecordingMode.valueOf((String) json.get("recordingMode")))
            .defaultOutputMode(Recording.OutputMode.valueOf((String) json.get("defaultOutputMode")));
    if (json.containsKey("defaultRecordingLayout")) {
        builder.defaultRecordingLayout(RecordingLayout.valueOf((String) json.get("defaultRecordingLayout")));
    }//from ww w.  ja  v  a  2 s. c  o  m
    if (json.containsKey("defaultCustomLayout")) {
        builder.defaultCustomLayout((String) json.get("defaultCustomLayout"));
    }
    if (this.properties != null && this.properties.customSessionId() != null) {
        builder.customSessionId(this.properties.customSessionId());
    } else if (json.containsKey("customSessionId")) {
        builder.customSessionId((String) json.get("customSessionId"));
    }
    this.properties = builder.build();
    JSONArray jsonArrayConnections = (JSONArray) ((JSONObject) json.get("connections")).get("content");
    this.activeConnections.clear();
    jsonArrayConnections.forEach(connection -> {
        JSONObject con = (JSONObject) connection;

        Map<String, Publisher> publishers = new ConcurrentHashMap<>();
        JSONArray jsonArrayPublishers = (JSONArray) con.get("publishers");
        jsonArrayPublishers.forEach(publisher -> {
            JSONObject pubJson = (JSONObject) publisher;
            JSONObject mediaOptions = (JSONObject) pubJson.get("mediaOptions");
            Publisher pub = new Publisher((String) pubJson.get("streamId"), (long) pubJson.get("createdAt"),
                    (boolean) mediaOptions.get("hasAudio"), (boolean) mediaOptions.get("hasVideo"),
                    mediaOptions.get("audioActive"), mediaOptions.get("videoActive"),
                    mediaOptions.get("frameRate"), mediaOptions.get("typeOfVideo"),
                    mediaOptions.get("videoDimensions"));
            publishers.put(pub.getStreamId(), pub);
        });

        List<String> subscribers = new ArrayList<>();
        JSONArray jsonArraySubscribers = (JSONArray) con.get("subscribers");
        jsonArraySubscribers.forEach(subscriber -> {
            subscribers.add((String) ((JSONObject) subscriber).get("streamId"));
        });

        this.activeConnections.put((String) con.get("connectionId"),
                new Connection((String) con.get("connectionId"), (long) con.get("createdAt"),
                        OpenViduRole.valueOf((String) con.get("role")), (String) con.get("token"),
                        (String) con.get("location"), (String) con.get("platform"),
                        (String) con.get("serverData"), (String) con.get("clientData"), publishers,
                        subscribers));
    });
    return this;
}

From source file:io.openvidu.java.client.OpenVidu.java

/**
 * Updates every property of every active Session with the current status they
 * have in OpenVidu Server. After calling this method you can access the updated
 * list of active sessions by calling/* w  ww .j  a  v  a 2s.  c om*/
 * {@link io.openvidu.java.client.OpenVidu#getActiveSessions()}
 * 
 * @return true if any Session status has changed with respect to the server,
 *         false if not. This applies to any property or sub-property of any of
 *         the sessions locally stored in OpenVidu Java Client
 * 
 * @throws OpenViduHttpException
 * @throws OpenViduJavaClientException
 */
@SuppressWarnings("unchecked")
public boolean fetch() throws OpenViduJavaClientException, OpenViduHttpException {
    HttpGet request = new HttpGet(OpenVidu.urlOpenViduServer + API_SESSIONS);

    HttpResponse response;
    try {
        response = OpenVidu.httpClient.execute(request);
    } catch (IOException e) {
        throw new OpenViduJavaClientException(e.getMessage(), e.getCause());
    }

    try {
        int statusCode = response.getStatusLine().getStatusCode();
        if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
            JSONObject jsonSessions = httpResponseToJson(response);
            JSONArray jsonArraySessions = (JSONArray) jsonSessions.get("content");

            // Set to store fetched sessionIds and later remove closed sessions
            Set<String> fetchedSessionIds = new HashSet<>();
            // Boolean to store if any Session has changed
            final boolean[] hasChanged = { false };
            jsonArraySessions.forEach(session -> {
                String sessionId = (String) ((JSONObject) session).get("sessionId");
                fetchedSessionIds.add(sessionId);
                OpenVidu.activeSessions.computeIfPresent(sessionId, (sId, s) -> {
                    String beforeJSON = s.toJson();
                    s = s.resetSessionWithJson((JSONObject) session);
                    String afterJSON = s.toJson();
                    boolean changed = !beforeJSON.equals(afterJSON);
                    hasChanged[0] = hasChanged[0] || changed;
                    log.info("Available session '{}' info fetched. Any change: {}", sessionId, changed);
                    return s;
                });
                OpenVidu.activeSessions.computeIfAbsent(sessionId, sId -> {
                    log.info("New session '{}' fetched", sessionId);
                    hasChanged[0] = true;
                    return new Session((JSONObject) session);
                });
            });

            // Remove closed sessions from activeSessions map
            OpenVidu.activeSessions = OpenVidu.activeSessions.entrySet().stream().filter(entry -> {
                if (fetchedSessionIds.contains(entry.getKey())) {
                    return true;
                } else {
                    log.info("Removing closed session {}", entry.getKey());
                    hasChanged[0] = true;
                    return false;
                }
            }).collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
            log.info("Active sessions info fetched: {}", OpenVidu.activeSessions.keySet());
            return hasChanged[0];
        } else {
            throw new OpenViduHttpException(statusCode);
        }
    } finally {
        EntityUtils.consumeQuietly(response.getEntity());
    }
}