POM dependencies clean-uo and udpate. GSON everywhere.

pull/391/head
pabloFuente 2020-02-01 13:17:31 +01:00
parent 35d8490180
commit 57440660b8
11 changed files with 292 additions and 313 deletions

View File

@ -65,32 +65,27 @@
</distributionManagement> </distributionManagement>
<dependencies> <dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${version.httpclient}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${version.gson}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${version.slf4j}</version>
</dependency>
<dependency> <dependency>
<groupId>junit</groupId> <groupId>junit</groupId>
<artifactId>junit</artifactId> <artifactId>junit</artifactId>
<version>${version.junit}</version> <version>${version.junit}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${version.httpclient}</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>${version.json-simple}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.26</version>
</dependency>
</dependencies> </dependencies>
<profiles> <profiles>

View File

@ -37,6 +37,7 @@ import javax.net.ssl.SSLContext;
import org.apache.http.HttpHeaders; import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider; import org.apache.http.client.CredentialsProvider;
@ -52,13 +53,14 @@ import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy; import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
public class OpenVidu { public class OpenVidu {
private static final Logger log = LoggerFactory.getLogger(OpenVidu.class); private static final Logger log = LoggerFactory.getLogger(OpenVidu.class);
@ -187,25 +189,24 @@ public class OpenVidu {
* to <i>false</i>)</li> * to <i>false</i>)</li>
* </ul> * </ul>
*/ */
@SuppressWarnings("unchecked")
public Recording startRecording(String sessionId, RecordingProperties properties) public Recording startRecording(String sessionId, RecordingProperties properties)
throws OpenViduJavaClientException, OpenViduHttpException { throws OpenViduJavaClientException, OpenViduHttpException {
HttpPost request = new HttpPost(this.hostname + API_RECORDINGS + API_RECORDINGS_START); HttpPost request = new HttpPost(this.hostname + API_RECORDINGS + API_RECORDINGS_START);
JSONObject json = new JSONObject(); JsonObject json = new JsonObject();
json.put("session", sessionId); json.addProperty("session", sessionId);
json.put("name", properties.name()); json.addProperty("name", properties.name());
json.put("outputMode", properties.outputMode().name()); json.addProperty("outputMode", properties.outputMode().name());
json.put("hasAudio", properties.hasAudio()); json.addProperty("hasAudio", properties.hasAudio());
json.put("hasVideo", properties.hasVideo()); json.addProperty("hasVideo", properties.hasVideo());
if (Recording.OutputMode.COMPOSED.equals(properties.outputMode()) && properties.hasVideo()) { if (Recording.OutputMode.COMPOSED.equals(properties.outputMode()) && properties.hasVideo()) {
json.put("resolution", properties.resolution()); json.addProperty("resolution", properties.resolution());
json.put("recordingLayout", json.addProperty("recordingLayout",
(properties.recordingLayout() != null) ? properties.recordingLayout().name() : ""); (properties.recordingLayout() != null) ? properties.recordingLayout().name() : "");
if (RecordingLayout.CUSTOM.equals(properties.recordingLayout())) { if (RecordingLayout.CUSTOM.equals(properties.recordingLayout())) {
json.put("customLayout", (properties.customLayout() != null) ? properties.customLayout() : ""); json.addProperty("customLayout", (properties.customLayout() != null) ? properties.customLayout() : "");
} }
} }
@ -420,7 +421,6 @@ public class OpenVidu {
* @throws OpenViduJavaClientException * @throws OpenViduJavaClientException
* @throws OpenViduHttpException * @throws OpenViduHttpException
*/ */
@SuppressWarnings("unchecked")
public List<Recording> listRecordings() throws OpenViduJavaClientException, OpenViduHttpException { public List<Recording> listRecordings() throws OpenViduJavaClientException, OpenViduHttpException {
HttpGet request = new HttpGet(this.hostname + API_RECORDINGS); HttpGet request = new HttpGet(this.hostname + API_RECORDINGS);
HttpResponse response; HttpResponse response;
@ -434,10 +434,10 @@ public class OpenVidu {
int statusCode = response.getStatusLine().getStatusCode(); int statusCode = response.getStatusLine().getStatusCode();
if ((statusCode == org.apache.http.HttpStatus.SC_OK)) { if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
List<Recording> recordings = new ArrayList<>(); List<Recording> recordings = new ArrayList<>();
JSONObject json = httpResponseToJson(response); JsonObject json = httpResponseToJson(response);
JSONArray array = (JSONArray) json.get("items"); JsonArray array = json.get("items").getAsJsonArray();
array.forEach(item -> { array.forEach(item -> {
recordings.add(new Recording((JSONObject) item)); recordings.add(new Recording(item.getAsJsonObject()));
}); });
return recordings; return recordings;
} else { } else {
@ -529,7 +529,6 @@ public class OpenVidu {
* @throws OpenViduHttpException * @throws OpenViduHttpException
* @throws OpenViduJavaClientException * @throws OpenViduJavaClientException
*/ */
@SuppressWarnings("unchecked")
public boolean fetch() throws OpenViduJavaClientException, OpenViduHttpException { public boolean fetch() throws OpenViduJavaClientException, OpenViduHttpException {
HttpGet request = new HttpGet(this.hostname + API_SESSIONS); HttpGet request = new HttpGet(this.hostname + API_SESSIONS);
@ -543,19 +542,19 @@ public class OpenVidu {
try { try {
int statusCode = response.getStatusLine().getStatusCode(); int statusCode = response.getStatusLine().getStatusCode();
if ((statusCode == org.apache.http.HttpStatus.SC_OK)) { if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
JSONObject jsonSessions = httpResponseToJson(response); JsonObject jsonSessions = httpResponseToJson(response);
JSONArray jsonArraySessions = (JSONArray) jsonSessions.get("content"); JsonArray jsonArraySessions = jsonSessions.get("content").getAsJsonArray();
// Set to store fetched sessionIds and later remove closed sessions // Set to store fetched sessionIds and later remove closed sessions
Set<String> fetchedSessionIds = new HashSet<>(); Set<String> fetchedSessionIds = new HashSet<>();
// Boolean to store if any Session has changed // Boolean to store if any Session has changed
final boolean[] hasChanged = { false }; final boolean[] hasChanged = { false };
jsonArraySessions.forEach(session -> { jsonArraySessions.forEach(session -> {
String sessionId = (String) ((JSONObject) session).get("sessionId"); String sessionId = (session.getAsJsonObject()).get("sessionId").getAsString();
fetchedSessionIds.add(sessionId); fetchedSessionIds.add(sessionId);
this.activeSessions.computeIfPresent(sessionId, (sId, s) -> { this.activeSessions.computeIfPresent(sessionId, (sId, s) -> {
String beforeJSON = s.toJson(); String beforeJSON = s.toJson();
s = s.resetSessionWithJson((JSONObject) session); s = s.resetSessionWithJson(session.getAsJsonObject());
String afterJSON = s.toJson(); String afterJSON = s.toJson();
boolean changed = !beforeJSON.equals(afterJSON); boolean changed = !beforeJSON.equals(afterJSON);
hasChanged[0] = hasChanged[0] || changed; hasChanged[0] = hasChanged[0] || changed;
@ -565,7 +564,7 @@ public class OpenVidu {
this.activeSessions.computeIfAbsent(sessionId, sId -> { this.activeSessions.computeIfAbsent(sessionId, sId -> {
log.info("New session '{}' fetched", sessionId); log.info("New session '{}' fetched", sessionId);
hasChanged[0] = true; hasChanged[0] = true;
return new Session(this, (JSONObject) session); return new Session(this, session.getAsJsonObject());
}); });
}); });
@ -589,15 +588,13 @@ public class OpenVidu {
} }
} }
private JSONObject httpResponseToJson(HttpResponse response) throws OpenViduJavaClientException { private JsonObject httpResponseToJson(HttpResponse response) throws OpenViduJavaClientException {
JSONParser parser = new JSONParser();
JSONObject json;
try { try {
json = (JSONObject) parser.parse(EntityUtils.toString(response.getEntity())); JsonObject json = JsonParser.parseString(EntityUtils.toString(response.getEntity())).getAsJsonObject();
} catch (org.apache.http.ParseException | ParseException | IOException e) { return json;
} catch (JsonSyntaxException | ParseException | IOException e) {
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); throw new OpenViduJavaClientException(e.getMessage(), e.getCause());
} }
return json;
} }
} }

View File

@ -17,7 +17,8 @@
package io.openvidu.java.client; package io.openvidu.java.client;
import org.json.simple.JSONObject; import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/** /**
* See {@link io.openvidu.java.client.Connection#getPublishers()}. * See {@link io.openvidu.java.client.Connection#getPublishers()}.
@ -39,19 +40,27 @@ public class Publisher {
private String typeOfVideo; private String typeOfVideo;
private String videoDimensions; private String videoDimensions;
protected Publisher(String streamId, long createdAt, boolean hasAudio, boolean hasVideo, Object audioActive, protected Publisher(String streamId, long createdAt, boolean hasAudio, boolean hasVideo, JsonElement audioActive,
Object videoActive, Object frameRate, Object typeOfVideo, Object videoDimensions) { JsonElement videoActive, JsonElement frameRate, JsonElement typeOfVideo, JsonElement videoDimensions) {
this.streamId = streamId; this.streamId = streamId;
this.createdAt = createdAt; this.createdAt = createdAt;
this.hasAudio = hasAudio; this.hasAudio = hasAudio;
this.hasVideo = hasVideo; this.hasVideo = hasVideo;
this.audioActive = (Boolean) audioActive; if (audioActive != null && !audioActive.isJsonNull()) {
this.videoActive = (Boolean) videoActive; this.audioActive = audioActive.getAsBoolean();
if (frameRate != null) { }
this.frameRate = ((Long) frameRate).intValue(); if (videoActive != null && !videoActive.isJsonNull()) {
this.videoActive = videoActive.getAsBoolean();
}
if (frameRate != null && !frameRate.isJsonNull()) {
this.frameRate = frameRate.getAsInt();
}
if (typeOfVideo != null && !typeOfVideo.isJsonNull()) {
this.typeOfVideo = typeOfVideo.getAsString();
}
if (videoDimensions != null && !videoDimensions.isJsonNull()) {
this.videoDimensions = videoDimensions.getAsString();
} }
this.typeOfVideo = (String) typeOfVideo;
this.videoDimensions = (String) videoDimensions;
} }
/** /**
@ -130,17 +139,16 @@ public class Publisher {
return this.videoDimensions; return this.videoDimensions;
} }
@SuppressWarnings("unchecked") protected JsonObject toJson() {
protected JSONObject toJson() { JsonObject json = new JsonObject();
JSONObject json = new JSONObject(); json.addProperty("streamId", this.streamId);
json.put("streamId", this.streamId); json.addProperty("hasAudio", this.hasAudio());
json.put("hasAudio", this.hasAudio()); json.addProperty("hasVideo", this.hasVideo());
json.put("hasVideo", this.hasVideo()); json.addProperty("audioActive", this.isAudioActive());
json.put("audioActive", this.isAudioActive()); json.addProperty("videoActive", this.isVideoActive());
json.put("videoActive", this.isVideoActive()); json.addProperty("frameRate", this.getFrameRate());
json.put("frameRate", this.getFrameRate()); json.addProperty("typeOfVideo", this.getTypeOfVideo());
json.put("typeOfVideo", this.getTypeOfVideo()); json.addProperty("videoDimensions", this.getVideoDimensions());
json.put("videoDimensions", this.getVideoDimensions());
return json; return json;
} }

View File

@ -17,7 +17,8 @@
package io.openvidu.java.client; package io.openvidu.java.client;
import org.json.simple.JSONObject; import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
/** /**
* See {@link io.openvidu.java.client.OpenVidu#startRecording(String)} * See {@link io.openvidu.java.client.OpenVidu#startRecording(String)}
@ -86,27 +87,30 @@ public class Recording {
private String url; private String url;
private RecordingProperties recordingProperties; private RecordingProperties recordingProperties;
protected Recording(JSONObject json) { protected Recording(JsonObject json) {
this.id = (String) json.get("id"); this.id = json.get("id").getAsString();
this.sessionId = (String) json.get("sessionId"); this.sessionId = json.get("sessionId").getAsString();
this.createdAt = (long) json.get("createdAt"); this.createdAt = json.get("createdAt").getAsLong();
this.size = (long) json.get("size"); this.size = json.get("size").getAsLong();
this.duration = (double) json.get("duration"); this.duration = json.get("duration").getAsDouble();
this.url = (String) json.get("url"); JsonElement urlElement = json.get("url");
this.status = Recording.Status.valueOf((String) json.get("status")); if (!urlElement.isJsonNull()) {
this.url = urlElement.getAsString();
}
this.status = Recording.Status.valueOf(json.get("status").getAsString());
boolean hasAudio = (boolean) json.get("hasAudio"); boolean hasAudio = json.get("hasAudio").getAsBoolean();
boolean hasVideo = (boolean) json.get("hasVideo"); boolean hasVideo = json.get("hasVideo").getAsBoolean();
OutputMode outputMode = OutputMode.valueOf((String) json.get("outputMode")); OutputMode outputMode = OutputMode.valueOf(json.get("outputMode").getAsString());
RecordingProperties.Builder builder = new RecordingProperties.Builder().name((String) json.get("name")) RecordingProperties.Builder builder = new RecordingProperties.Builder().name(json.get("name").getAsString())
.outputMode(outputMode).hasAudio(hasAudio).hasVideo(hasVideo); .outputMode(outputMode).hasAudio(hasAudio).hasVideo(hasVideo);
if (OutputMode.COMPOSED.equals(outputMode) && hasVideo) { if (OutputMode.COMPOSED.equals(outputMode) && hasVideo) {
builder.resolution((String) json.get("resolution")); builder.resolution(json.get("resolution").getAsString());
builder.recordingLayout(RecordingLayout.valueOf((String) json.get("recordingLayout"))); builder.recordingLayout(RecordingLayout.valueOf(json.get("recordingLayout").getAsString()));
String customLayout = (String) json.get("customLayout"); JsonElement customLayout = json.get("customLayout");
if (customLayout != null) { if (customLayout != null) {
builder.customLayout(customLayout); builder.customLayout(customLayout.getAsString());
} }
} }
this.recordingProperties = builder.build(); this.recordingProperties = builder.build();

View File

@ -27,18 +27,20 @@ import java.util.stream.Collectors;
import org.apache.http.HttpHeaders; import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
public class Session { public class Session {
private static final Logger log = LoggerFactory.getLogger(Session.class); private static final Logger log = LoggerFactory.getLogger(Session.class);
@ -63,7 +65,7 @@ public class Session {
this.getSessionIdHttp(); this.getSessionIdHttp();
} }
protected Session(OpenVidu openVidu, JSONObject json) { protected Session(OpenVidu openVidu, JsonObject json) {
this.openVidu = openVidu; this.openVidu = openVidu;
this.resetSessionWithJson(json); this.resetSessionWithJson(json);
} }
@ -109,7 +111,6 @@ public class Session {
* @throws OpenViduJavaClientException * @throws OpenViduJavaClientException
* @throws OpenViduHttpException * @throws OpenViduHttpException
*/ */
@SuppressWarnings("unchecked")
public String generateToken(TokenOptions tokenOptions) throws OpenViduJavaClientException, OpenViduHttpException { public String generateToken(TokenOptions tokenOptions) throws OpenViduJavaClientException, OpenViduHttpException {
if (!this.hasSessionId()) { if (!this.hasSessionId()) {
@ -118,36 +119,36 @@ public class Session {
HttpPost request = new HttpPost(this.openVidu.hostname + OpenVidu.API_TOKENS); HttpPost request = new HttpPost(this.openVidu.hostname + OpenVidu.API_TOKENS);
JSONObject json = new JSONObject(); JsonObject json = new JsonObject();
json.put("session", this.sessionId); json.addProperty("session", this.sessionId);
json.put("role", tokenOptions.getRole().name()); json.addProperty("role", tokenOptions.getRole().name());
json.put("data", tokenOptions.getData()); json.addProperty("data", tokenOptions.getData());
if (tokenOptions.getKurentoOptions() != null) { if (tokenOptions.getKurentoOptions() != null) {
JSONObject kurentoOptions = new JSONObject(); JsonObject kurentoOptions = new JsonObject();
if (tokenOptions.getKurentoOptions().getVideoMaxRecvBandwidth() != null) { if (tokenOptions.getKurentoOptions().getVideoMaxRecvBandwidth() != null) {
kurentoOptions.put("videoMaxRecvBandwidth", kurentoOptions.addProperty("videoMaxRecvBandwidth",
tokenOptions.getKurentoOptions().getVideoMaxRecvBandwidth()); tokenOptions.getKurentoOptions().getVideoMaxRecvBandwidth());
} }
if (tokenOptions.getKurentoOptions().getVideoMinRecvBandwidth() != null) { if (tokenOptions.getKurentoOptions().getVideoMinRecvBandwidth() != null) {
kurentoOptions.put("videoMinRecvBandwidth", kurentoOptions.addProperty("videoMinRecvBandwidth",
tokenOptions.getKurentoOptions().getVideoMinRecvBandwidth()); tokenOptions.getKurentoOptions().getVideoMinRecvBandwidth());
} }
if (tokenOptions.getKurentoOptions().getVideoMaxSendBandwidth() != null) { if (tokenOptions.getKurentoOptions().getVideoMaxSendBandwidth() != null) {
kurentoOptions.put("videoMaxSendBandwidth", kurentoOptions.addProperty("videoMaxSendBandwidth",
tokenOptions.getKurentoOptions().getVideoMaxSendBandwidth()); tokenOptions.getKurentoOptions().getVideoMaxSendBandwidth());
} }
if (tokenOptions.getKurentoOptions().getVideoMinSendBandwidth() != null) { if (tokenOptions.getKurentoOptions().getVideoMinSendBandwidth() != null) {
kurentoOptions.put("videoMinSendBandwidth", kurentoOptions.addProperty("videoMinSendBandwidth",
tokenOptions.getKurentoOptions().getVideoMinSendBandwidth()); tokenOptions.getKurentoOptions().getVideoMinSendBandwidth());
} }
if (tokenOptions.getKurentoOptions().getAllowedFilters().length > 0) { if (tokenOptions.getKurentoOptions().getAllowedFilters().length > 0) {
JSONArray allowedFilters = new JSONArray(); JsonArray allowedFilters = new JsonArray();
for (String filter : tokenOptions.getKurentoOptions().getAllowedFilters()) { for (String filter : tokenOptions.getKurentoOptions().getAllowedFilters()) {
allowedFilters.add(filter); allowedFilters.add(filter);
} }
kurentoOptions.put("allowedFilters", allowedFilters); kurentoOptions.add("allowedFilters", allowedFilters);
} }
json.put("kurentoOptions", kurentoOptions); json.add("kurentoOptions", kurentoOptions);
} }
StringEntity params; StringEntity params;
try { try {
@ -169,7 +170,7 @@ public class Session {
try { try {
int statusCode = response.getStatusLine().getStatusCode(); int statusCode = response.getStatusLine().getStatusCode();
if ((statusCode == org.apache.http.HttpStatus.SC_OK)) { if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
String token = (String) httpResponseToJson(response).get("id"); String token = httpResponseToJson(response).get("id").getAsString();
log.info("Returning a TOKEN: {}", token); log.info("Returning a TOKEN: {}", token);
return token; return token;
} else { } else {
@ -444,7 +445,6 @@ public class Session {
return (this.sessionId != null && !this.sessionId.isEmpty()); return (this.sessionId != null && !this.sessionId.isEmpty());
} }
@SuppressWarnings("unchecked")
private void getSessionIdHttp() throws OpenViduJavaClientException, OpenViduHttpException { private void getSessionIdHttp() throws OpenViduJavaClientException, OpenViduHttpException {
if (this.hasSessionId()) { if (this.hasSessionId()) {
return; return;
@ -452,13 +452,13 @@ public class Session {
HttpPost request = new HttpPost(this.openVidu.hostname + OpenVidu.API_SESSIONS); HttpPost request = new HttpPost(this.openVidu.hostname + OpenVidu.API_SESSIONS);
JSONObject json = new JSONObject(); JsonObject json = new JsonObject();
json.put("mediaMode", properties.mediaMode().name()); json.addProperty("mediaMode", properties.mediaMode().name());
json.put("recordingMode", properties.recordingMode().name()); json.addProperty("recordingMode", properties.recordingMode().name());
json.put("defaultOutputMode", properties.defaultOutputMode().name()); json.addProperty("defaultOutputMode", properties.defaultOutputMode().name());
json.put("defaultRecordingLayout", properties.defaultRecordingLayout().name()); json.addProperty("defaultRecordingLayout", properties.defaultRecordingLayout().name());
json.put("defaultCustomLayout", properties.defaultCustomLayout()); json.addProperty("defaultCustomLayout", properties.defaultCustomLayout());
json.put("customSessionId", properties.customSessionId()); json.addProperty("customSessionId", properties.customSessionId());
StringEntity params = null; StringEntity params = null;
try { try {
params = new StringEntity(json.toString()); params = new StringEntity(json.toString());
@ -478,9 +478,9 @@ public class Session {
try { try {
int statusCode = response.getStatusLine().getStatusCode(); int statusCode = response.getStatusLine().getStatusCode();
if ((statusCode == org.apache.http.HttpStatus.SC_OK)) { if ((statusCode == org.apache.http.HttpStatus.SC_OK)) {
JSONObject responseJson = httpResponseToJson(response); JsonObject responseJson = httpResponseToJson(response);
this.sessionId = (String) responseJson.get("id"); this.sessionId = responseJson.get("id").getAsString();
this.createdAt = (long) responseJson.get("createdAt"); this.createdAt = responseJson.get("createdAt").getAsLong();
log.info("Session '{}' created", this.sessionId); log.info("Session '{}' created", this.sessionId);
} else if (statusCode == org.apache.http.HttpStatus.SC_CONFLICT) { } else if (statusCode == org.apache.http.HttpStatus.SC_CONFLICT) {
// 'customSessionId' already existed // 'customSessionId' already existed
@ -493,12 +493,11 @@ public class Session {
} }
} }
private JSONObject httpResponseToJson(HttpResponse response) throws OpenViduJavaClientException { private JsonObject httpResponseToJson(HttpResponse response) throws OpenViduJavaClientException {
JSONParser parser = new JSONParser(); JsonObject json;
JSONObject json;
try { try {
json = (JSONObject) parser.parse(EntityUtils.toString(response.getEntity())); json = JsonParser.parseString(EntityUtils.toString(response.getEntity())).getAsJsonObject();
} catch (org.apache.http.ParseException | ParseException | IOException e) { } catch (JsonSyntaxException | ParseException | IOException e) {
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); throw new OpenViduJavaClientException(e.getMessage(), e.getCause());
} }
return json; return json;
@ -508,96 +507,96 @@ public class Session {
this.recording = recording; this.recording = recording;
} }
@SuppressWarnings("unchecked") protected Session resetSessionWithJson(JsonObject json) {
protected Session resetSessionWithJson(JSONObject json) { this.sessionId = json.get("sessionId").getAsString();
this.sessionId = (String) json.get("sessionId"); this.createdAt = json.get("createdAt").getAsLong();
this.createdAt = (long) json.get("createdAt"); this.recording = json.get("recording").getAsBoolean();
this.recording = (boolean) json.get("recording");
SessionProperties.Builder builder = new SessionProperties.Builder() SessionProperties.Builder builder = new SessionProperties.Builder()
.mediaMode(MediaMode.valueOf((String) json.get("mediaMode"))) .mediaMode(MediaMode.valueOf(json.get("mediaMode").getAsString()))
.recordingMode(RecordingMode.valueOf((String) json.get("recordingMode"))) .recordingMode(RecordingMode.valueOf(json.get("recordingMode").getAsString()))
.defaultOutputMode(Recording.OutputMode.valueOf((String) json.get("defaultOutputMode"))); .defaultOutputMode(Recording.OutputMode.valueOf(json.get("defaultOutputMode").getAsString()));
if (json.containsKey("defaultRecordingLayout")) { if (json.has("defaultRecordingLayout")) {
builder.defaultRecordingLayout(RecordingLayout.valueOf((String) json.get("defaultRecordingLayout"))); builder.defaultRecordingLayout(RecordingLayout.valueOf(json.get("defaultRecordingLayout").getAsString()));
} }
if (json.containsKey("defaultCustomLayout")) { if (json.has("defaultCustomLayout")) {
builder.defaultCustomLayout((String) json.get("defaultCustomLayout")); builder.defaultCustomLayout(json.get("defaultCustomLayout").getAsString());
} }
if (this.properties != null && this.properties.customSessionId() != null) { if (this.properties != null && this.properties.customSessionId() != null) {
builder.customSessionId(this.properties.customSessionId()); builder.customSessionId(this.properties.customSessionId());
} else if (json.containsKey("customSessionId")) { } else if (json.has("customSessionId")) {
builder.customSessionId((String) json.get("customSessionId")); builder.customSessionId(json.get("customSessionId").getAsString());
} }
this.properties = builder.build(); this.properties = builder.build();
JSONArray jsonArrayConnections = (JSONArray) ((JSONObject) json.get("connections")).get("content"); JsonArray jsonArrayConnections = (json.get("connections").getAsJsonObject()).get("content").getAsJsonArray();
this.activeConnections.clear(); this.activeConnections.clear();
jsonArrayConnections.forEach(connection -> { jsonArrayConnections.forEach(connection -> {
JSONObject con = (JSONObject) connection; JsonObject con = connection.getAsJsonObject();
Map<String, Publisher> publishers = new ConcurrentHashMap<>(); Map<String, Publisher> publishers = new ConcurrentHashMap<>();
JSONArray jsonArrayPublishers = (JSONArray) con.get("publishers"); JsonArray jsonArrayPublishers = con.get("publishers").getAsJsonArray();
jsonArrayPublishers.forEach(publisher -> { jsonArrayPublishers.forEach(publisher -> {
JSONObject pubJson = (JSONObject) publisher; JsonObject pubJson = publisher.getAsJsonObject();
JSONObject mediaOptions = (JSONObject) pubJson.get("mediaOptions"); JsonObject mediaOptions = pubJson.get("mediaOptions").getAsJsonObject();
Publisher pub = new Publisher((String) pubJson.get("streamId"), (long) pubJson.get("createdAt"), Publisher pub = new Publisher(pubJson.get("streamId").getAsString(),
(boolean) mediaOptions.get("hasAudio"), (boolean) mediaOptions.get("hasVideo"), pubJson.get("createdAt").getAsLong(), mediaOptions.get("hasAudio").getAsBoolean(),
mediaOptions.get("audioActive"), mediaOptions.get("videoActive"), mediaOptions.get("frameRate"), mediaOptions.get("hasVideo").getAsBoolean(), mediaOptions.get("audioActive"),
mediaOptions.get("typeOfVideo"), mediaOptions.get("videoDimensions")); mediaOptions.get("videoActive"), mediaOptions.get("frameRate"), mediaOptions.get("typeOfVideo"),
mediaOptions.get("videoDimensions"));
publishers.put(pub.getStreamId(), pub); publishers.put(pub.getStreamId(), pub);
}); });
List<String> subscribers = new ArrayList<>(); List<String> subscribers = new ArrayList<>();
JSONArray jsonArraySubscribers = (JSONArray) con.get("subscribers"); JsonArray jsonArraySubscribers = con.get("subscribers").getAsJsonArray();
jsonArraySubscribers.forEach(subscriber -> { jsonArraySubscribers.forEach(subscriber -> {
subscribers.add((String) ((JSONObject) subscriber).get("streamId")); subscribers.add((subscriber.getAsJsonObject()).get("streamId").getAsString());
}); });
this.activeConnections.put((String) con.get("connectionId"), this.activeConnections.put(con.get("connectionId").getAsString(),
new Connection((String) con.get("connectionId"), (long) con.get("createdAt"), new Connection(con.get("connectionId").getAsString(), con.get("createdAt").getAsLong(),
OpenViduRole.valueOf((String) con.get("role")), (String) con.get("token"), OpenViduRole.valueOf(con.get("role").getAsString()), con.get("token").getAsString(),
(String) con.get("location"), (String) con.get("platform"), (String) con.get("serverData"), con.get("location").getAsString(), con.get("platform").getAsString(),
(String) con.get("clientData"), publishers, subscribers)); con.get("serverData").getAsString(), con.get("clientData").getAsString(), publishers,
subscribers));
}); });
return this; return this;
} }
@SuppressWarnings("unchecked")
protected String toJson() { protected String toJson() {
JSONObject json = new JSONObject(); JsonObject json = new JsonObject();
json.put("sessionId", this.sessionId); json.addProperty("sessionId", this.sessionId);
json.put("createdAt", this.createdAt); json.addProperty("createdAt", this.createdAt);
json.put("customSessionId", this.properties.customSessionId()); json.addProperty("customSessionId", this.properties.customSessionId());
json.put("recording", this.recording); json.addProperty("recording", this.recording);
json.put("mediaMode", this.properties.mediaMode().name()); json.addProperty("mediaMode", this.properties.mediaMode().name());
json.put("recordingMode", this.properties.recordingMode().name()); json.addProperty("recordingMode", this.properties.recordingMode().name());
json.put("defaultOutputMode", this.properties.defaultOutputMode().name()); json.addProperty("defaultOutputMode", this.properties.defaultOutputMode().name());
json.put("defaultRecordingLayout", this.properties.defaultRecordingLayout().name()); json.addProperty("defaultRecordingLayout", this.properties.defaultRecordingLayout().name());
json.put("defaultCustomLayout", this.properties.defaultCustomLayout()); json.addProperty("defaultCustomLayout", this.properties.defaultCustomLayout());
JSONObject connections = new JSONObject(); JsonObject connections = new JsonObject();
connections.put("numberOfElements", this.getActiveConnections().size()); connections.addProperty("numberOfElements", this.getActiveConnections().size());
JSONArray jsonArrayConnections = new JSONArray(); JsonArray jsonArrayConnections = new JsonArray();
this.getActiveConnections().forEach(con -> { this.getActiveConnections().forEach(con -> {
JSONObject c = new JSONObject(); JsonObject c = new JsonObject();
c.put("connectionId", con.getConnectionId()); c.addProperty("connectionId", con.getConnectionId());
c.put("role", con.getRole().name()); c.addProperty("role", con.getRole().name());
c.put("token", con.getToken()); c.addProperty("token", con.getToken());
c.put("clientData", con.getClientData()); c.addProperty("clientData", con.getClientData());
c.put("serverData", con.getServerData()); c.addProperty("serverData", con.getServerData());
JSONArray pubs = new JSONArray(); JsonArray pubs = new JsonArray();
con.getPublishers().forEach(p -> { con.getPublishers().forEach(p -> {
pubs.add(p.toJson()); pubs.add(p.toJson());
}); });
JSONArray subs = new JSONArray(); JsonArray subs = new JsonArray();
con.getSubscribers().forEach(s -> { con.getSubscribers().forEach(s -> {
subs.add(s); subs.add(s);
}); });
c.put("publishers", pubs); c.add("publishers", pubs);
c.put("subscribers", subs); c.add("subscribers", subs);
jsonArrayConnections.add(c); jsonArrayConnections.add(c);
}); });
connections.put("content", jsonArrayConnections); connections.add("content", jsonArrayConnections);
json.put("connections", connections); json.add("connections", connections);
return json.toJSONString(); return json.toString();
} }
} }

View File

@ -182,6 +182,11 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</exclusion> </exclusion>
<exclusion>
<!-- Until kurento-java spring-boot dependency is updated to 2.2.4.RELEASE -->
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
</exclusion>
<exclusion> <exclusion>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
@ -279,11 +284,22 @@
<artifactId>commons-lang3</artifactId> <artifactId>commons-lang3</artifactId>
<version>${version.commonslang}</version> <version>${version.commonslang}</version>
</dependency> </dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${version.gson}</version>
</dependency>
<dependency> <dependency>
<groupId>io.openvidu</groupId> <groupId>io.openvidu</groupId>
<artifactId>openvidu-java-client</artifactId> <artifactId>openvidu-java-client</artifactId>
<version>${version.openvidu.java.client}</version> <version>${version.openvidu.java.client}</version>
</dependency> </dependency>
<dependency>
<!-- Until kurento-java spring-boot dependency is updated to 2.2.4.RELEASE -->
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>5.2.3.RELEASE</version>
</dependency>
<!-- Test dependencies --> <!-- Test dependencies -->

View File

@ -57,11 +57,6 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${version.spring-boot}</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
@ -75,7 +70,7 @@
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId> <artifactId>slf4j-api</artifactId>
<version>1.7.26</version> <version>${version.slf4j}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.seleniumhq.selenium</groupId> <groupId>org.seleniumhq.selenium</groupId>
@ -95,12 +90,12 @@
<dependency> <dependency>
<groupId>com.google.code.gson</groupId> <groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId> <artifactId>gson</artifactId>
<version>2.8.5</version> <version>${version.gson}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.mashape.unirest</groupId> <groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId> <artifactId>unirest-java</artifactId>
<version>1.4.9</version> <version>${version.unirest}</version>
</dependency> </dependency>
</dependencies> </dependencies>

View File

@ -34,11 +34,14 @@ import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.SSLContextBuilder;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.mashape.unirest.http.HttpMethod; import com.mashape.unirest.http.HttpMethod;
import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.JsonNode;
@ -78,27 +81,27 @@ public class CustomHttpClient {
return Unirest.get(path).header("Authorization", credentials).asJson().getStatus(); return Unirest.get(path).header("Authorization", credentials).asJson().getStatus();
} }
public JSONObject rest(HttpMethod method, String path, int status) throws Exception { public JsonObject rest(HttpMethod method, String path, int status) throws Exception {
return this.commonRest(method, path, null, status); return this.commonRest(method, path, null, status);
} }
public JSONObject rest(HttpMethod method, String path, String body, int status) throws Exception { public JsonObject rest(HttpMethod method, String path, String body, int status) throws Exception {
return this.commonRest(method, path, body, status); return this.commonRest(method, path, body, status);
} }
public JSONObject rest(HttpMethod method, String path, String body, int status, boolean exactReturnedFields, public JsonObject rest(HttpMethod method, String path, String body, int status, boolean exactReturnedFields,
String jsonReturnedValue) throws Exception { String jsonReturnedValue) throws Exception {
JSONObject json = this.commonRest(method, path, body, status); JsonObject json = this.commonRest(method, path, body, status);
JSONObject jsonObjExpected = null; JsonObject jsonObjExpected = null;
jsonReturnedValue.replaceAll("'", "\""); jsonReturnedValue.replaceAll("'", "\"");
try { try {
jsonObjExpected = new JSONObject(jsonReturnedValue); jsonObjExpected = JsonParser.parseString(jsonReturnedValue).getAsJsonObject();
} catch (JSONException e1) { } catch (JsonSyntaxException e1) {
throw new Exception("Expected json element is a string without a JSON format: " + jsonReturnedValue); throw new Exception("Expected json element is a string without a JSON format: " + jsonReturnedValue);
} }
if (exactReturnedFields) { if (exactReturnedFields) {
if (jsonObjExpected.length() != json.length()) { if (jsonObjExpected.size() != json.size()) {
throw new Exception( throw new Exception(
"Error in number of keys in JSON response to POST (" + json.toString() + ")" + path); "Error in number of keys in JSON response to POST (" + json.toString() + ")" + path);
} }
@ -117,12 +120,12 @@ public class CustomHttpClient {
return json; return json;
} }
public JSONObject rest(HttpMethod method, String path, String body, int status, boolean exactReturnedFields, public JsonObject rest(HttpMethod method, String path, String body, int status, boolean exactReturnedFields,
Map<String, ?> jsonResponse) throws Exception { Map<String, ?> jsonResponse) throws Exception {
org.json.JSONObject json = this.commonRest(method, path, body, status); JsonObject json = this.commonRest(method, path, body, status);
if (exactReturnedFields) { if (exactReturnedFields) {
if (jsonResponse.size() != json.length()) if (jsonResponse.size() != json.size())
throw new Exception("Error in number of keys in JSON response to POST " + path); throw new Exception("Error in number of keys in JSON response to POST " + path);
} }
@ -131,47 +134,47 @@ public class CustomHttpClient {
if (value instanceof String) { if (value instanceof String) {
try { try {
JSONObject jsonObjExpected = new JSONObject((String) value); JsonObject jsonObjExpected = JsonParser.parseString((String) value).getAsJsonObject();
JSONObject jsonObjActual = json.getJSONObject(entry.getKey()); JsonObject jsonObjActual = json.get(entry.getKey()).getAsJsonObject();
// COMPARE // COMPARE
} catch (JSONException e1) { } catch (JsonSyntaxException e1) {
try { try {
JSONArray jsonArrayExpected = new JSONArray((String) value); JsonArray jsonArrayExpected = JsonParser.parseString((String) value).getAsJsonArray();
JSONArray jsonArrayActual = json.getJSONArray(entry.getKey()); JsonArray jsonArrayActual = json.get(entry.getKey()).getAsJsonArray();
// COMPARE // COMPARE
} catch (JSONException e2) { } catch (JsonSyntaxException e2) {
if (((String) value) != json.getString(entry.getKey())) { if (((String) value) != json.get(entry.getKey()).getAsString()) {
throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: "
+ value + ". Actual: " + json.getString(entry.getKey())); + value + ". Actual: " + json.get(entry.getKey()).getAsString());
} }
} }
} }
} else if (value instanceof Integer) { } else if (value instanceof Integer) {
if (((int) value) != json.getInt(entry.getKey())) { if (((int) value) != json.get(entry.getKey()).getAsInt()) {
throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value
+ ". Actual: " + json.getInt(entry.getKey())); + ". Actual: " + json.get(entry.getKey()).getAsInt());
} }
} else if (value instanceof Long) { } else if (value instanceof Long) {
if (((long) value) != json.getLong(entry.getKey())) { if (((long) value) != json.get(entry.getKey()).getAsLong()) {
throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value
+ ". Actual: " + json.getLong(entry.getKey())); + ". Actual: " + json.get(entry.getKey()).getAsLong());
} }
} else if (value instanceof Double) { } else if (value instanceof Double) {
if (((double) value) != json.getDouble(entry.getKey())) { if (((double) value) != json.get(entry.getKey()).getAsDouble()) {
throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value
+ ". Actual: " + json.getDouble(entry.getKey())); + ". Actual: " + json.get(entry.getKey()).getAsDouble());
} }
} else if (value instanceof Boolean) { } else if (value instanceof Boolean) {
if (((boolean) value) != json.getBoolean(entry.getKey())) { if (((boolean) value) != json.get(entry.getKey()).getAsBoolean()) {
throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value throw new Exception("JSON field " + entry.getKey() + " has not expected value. Expected: " + value
+ ". Actual: " + json.getBoolean(entry.getKey())); + ". Actual: " + json.get(entry.getKey()).getAsBoolean());
} }
} else if (value instanceof JSONArray) { } else if (value instanceof JSONArray || value instanceof JsonArray) {
json.getJSONArray(entry.getKey()); JsonParser.parseString(entry.getValue().toString()).getAsJsonArray();
} else if (value instanceof JSONObject) { } else if (value instanceof JSONObject || value instanceof JsonObject) {
json.getJSONObject(entry.getKey()); JsonParser.parseString(entry.getValue().toString()).getAsJsonObject();
} else { } else {
throw new Exception("JSON response field cannot be parsed: " + entry.toString()); throw new Exception("JSON response field cannot be parsed: " + entry.toString());
} }
@ -183,9 +186,9 @@ public class CustomHttpClient {
Unirest.shutdown(); Unirest.shutdown();
} }
private org.json.JSONObject commonRest(HttpMethod method, String path, String body, int status) throws Exception { private JsonObject commonRest(HttpMethod method, String path, String body, int status) throws Exception {
HttpResponse<?> jsonResponse = null; HttpResponse<?> jsonResponse = null;
org.json.JSONObject json = null; JsonObject json = null;
path = openviduUrl + (path.startsWith("/") ? path : ("/" + path)); path = openviduUrl + (path.startsWith("/") ? path : ("/" + path));
HttpRequest request = null; HttpRequest request = null;
@ -227,7 +230,9 @@ public class CustomHttpClient {
try { try {
jsonResponse = request.asJson(); jsonResponse = request.asJson();
if (jsonResponse.getBody() != null) { if (jsonResponse.getBody() != null) {
json = ((JsonNode) jsonResponse.getBody()).getObject(); jsonResponse.getBody();
json = JsonParser.parseString(((JsonNode) jsonResponse.getBody()).getObject().toString())
.getAsJsonObject();
} }
} catch (UnirestException e) { } catch (UnirestException e) {
try { try {

View File

@ -72,24 +72,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<version>${version.spring-boot}</version> <version>${version.spring-boot}</version>
<scope>test</scope> <scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${version.junit.jupiter}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>selenium-jupiter</artifactId>
<version>${version.selenium.jupiter}</version>
<scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.github.bonigarcia</groupId> <groupId>io.github.bonigarcia</groupId>
@ -128,28 +110,9 @@
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.junit.platform</groupId> <groupId>com.google.code.gson</groupId>
<artifactId>junit-platform-runner</artifactId> <artifactId>gson</artifactId>
<version>${version.junit.platform}</version> <version>${version.gson}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>${version.json-simple}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jcodec</groupId>
<artifactId>jcodec</artifactId>
<version>0.2.3</version>
<scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.jcodec</groupId> <groupId>org.jcodec</groupId>
@ -160,7 +123,7 @@
<dependency> <dependency>
<groupId>com.mashape.unirest</groupId> <groupId>com.mashape.unirest</groupId>
<artifactId>unirest-java</artifactId> <artifactId>unirest-java</artifactId>
<version>1.4.9</version> <version>${version.unirest}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency> <dependency>
@ -175,11 +138,6 @@
<version>${version.openvidu.java.client}</version> <version>${version.openvidu.java.client}</version>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${version.spring-boot}</version>
</dependency>
</dependencies> </dependencies>
</project> </project>

View File

@ -50,9 +50,6 @@ import org.jcodec.api.FrameGrab;
import org.jcodec.api.JCodecException; import org.jcodec.api.JCodecException;
import org.jcodec.common.model.Picture; import org.jcodec.common.model.Picture;
import org.jcodec.scale.AWTUtil; import org.jcodec.scale.AWTUtil;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.junit.Assert; import org.junit.Assert;
import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
@ -77,6 +74,7 @@ import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonArray; import com.google.gson.JsonArray;
import com.google.gson.JsonObject; import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonReader;
import com.mashape.unirest.http.HttpMethod; import com.mashape.unirest.http.HttpMethod;
@ -999,12 +997,12 @@ public class OpenViduTestAppE2eTest {
user.getDriver().manage().window().setSize(new Dimension(newWidth, newHeight)); user.getDriver().manage().window().setSize(new Dimension(newWidth, newHeight));
String widthAndHeight = user.getEventManager().getDimensionOfViewport(); String widthAndHeight = user.getEventManager().getDimensionOfViewport();
JSONObject obj = (JSONObject) new JSONParser().parse(widthAndHeight); JsonObject obj = JsonParser.parseString(widthAndHeight).getAsJsonObject();
expectedWidthHeight[0] = (long) obj.get("width"); expectedWidthHeight[0] = obj.get("width").getAsLong();
expectedWidthHeight[1] = (long) obj.get("height"); expectedWidthHeight[1] = obj.get("height").getAsLong();
System.out.println("New viewport dimension: " + obj.toJSONString()); System.out.println("New viewport dimension: " + obj.toString());
user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 6); user.getEventManager().waitUntilEventReaches("streamPropertyChanged", 6);
@ -1631,9 +1629,10 @@ public class OpenViduTestAppE2eTest {
// Store connectionId and streamId // Store connectionId and streamId
String response = user.getDriver().findElement(By.id("api-response-text-area")).getAttribute("value"); String response = user.getDriver().findElement(By.id("api-response-text-area")).getAttribute("value");
JSONObject json = (JSONObject) ((JSONArray) new JSONParser().parse(response.split("%")[1])).get(0); JsonObject json = JsonParser.parseString(response.split("%")[1]).getAsJsonArray().get(0).getAsJsonObject();
String connectionId = (String) json.keySet().iterator().next(); String connectionId = json.keySet().iterator().next();
String streamId = (String) ((JSONObject) ((JSONArray) json.get(connectionId)).get(0)).get("streamId"); String streamId = json.get(connectionId).getAsJsonArray().get(0).getAsJsonObject().get("streamId")
.getAsString();
// Fetch all sessions (no change) // Fetch all sessions (no change)
user.getDriver().findElement(By.id("list-sessions-btn")).click(); user.getDriver().findElement(By.id("list-sessions-btn")).click();
@ -2154,8 +2153,9 @@ public class OpenViduTestAppE2eTest {
pub = connectionModerator.getPublishers().get(0); pub = connectionModerator.getPublishers().get(0);
String widthAndHeight = user.getEventManager().getDimensionOfViewport(); String widthAndHeight = user.getEventManager().getDimensionOfViewport();
JSONObject obj = (JSONObject) new JSONParser().parse(widthAndHeight); JsonObject obj = JsonParser.parseString(widthAndHeight).getAsJsonObject();
Assert.assertEquals("{\"width\":" + (long) obj.get("width") + ",\"height\":" + ((long) obj.get("height")) + "}", Assert.assertEquals(
"{\"width\":" + obj.get("width").getAsLong() + ",\"height\":" + (obj.get("height").getAsLong()) + "}",
pub.getVideoDimensions()); pub.getVideoDimensions());
Assert.assertEquals(new Integer(30), pub.getFrameRate()); Assert.assertEquals(new Integer(30), pub.getFrameRate());
Assert.assertEquals("SCREEN", pub.getTypeOfVideo()); Assert.assertEquals("SCREEN", pub.getTypeOfVideo());
@ -2405,9 +2405,9 @@ public class OpenViduTestAppE2eTest {
restClient.rest(HttpMethod.POST, "/api/sessions", body, HttpStatus.SC_OK, true, restClient.rest(HttpMethod.POST, "/api/sessions", body, HttpStatus.SC_OK, true,
"{'id': 'STR', 'createdAt': 0}"); "{'id': 'STR', 'createdAt': 0}");
// Default values // Default values
org.json.JSONObject res = restClient.rest(HttpMethod.POST, "/api/sessions", "{}", HttpStatus.SC_OK, true, JsonObject res = restClient.rest(HttpMethod.POST, "/api/sessions", "{}", HttpStatus.SC_OK, true,
"{'id': 'STR', 'createdAt': 0}"); "{'id': 'STR', 'createdAt': 0}");
restClient.rest(HttpMethod.DELETE, "/api/sessions/" + res.getString("id"), HttpStatus.SC_NO_CONTENT); restClient.rest(HttpMethod.DELETE, "/api/sessions/" + res.get("id").getAsString(), HttpStatus.SC_NO_CONTENT);
// 409 // 409
body = "{'customSessionId': 'CUSTOM_SESSION_ID'}"; body = "{'customSessionId': 'CUSTOM_SESSION_ID'}";
@ -2438,16 +2438,16 @@ public class OpenViduTestAppE2eTest {
body = "{'session': 'CUSTOM_SESSION_ID', 'role': 'MODERATOR', 'data': 'SERVER_DATA', 'kurentoOptions': {'allowedFilters': ['GStreamerFilter']}}"; body = "{'session': 'CUSTOM_SESSION_ID', 'role': 'MODERATOR', 'data': 'SERVER_DATA', 'kurentoOptions': {'allowedFilters': ['GStreamerFilter']}}";
res = restClient.rest(HttpMethod.POST, "/api/tokens", body, HttpStatus.SC_OK, true, res = restClient.rest(HttpMethod.POST, "/api/tokens", body, HttpStatus.SC_OK, true,
"{'id':'STR','session':'STR','role':'STR','data':'STR','token':'STR','kurentoOptions':{'allowedFilters':['STR']}}"); "{'id':'STR','session':'STR','role':'STR','data':'STR','token':'STR','kurentoOptions':{'allowedFilters':['STR']}}");
final String token1 = res.getString("token"); final String token1 = res.get("token").getAsString();
Assert.assertEquals("JSON return value from /api/tokens should have equal srtings in 'id' and 'token'", Assert.assertEquals("JSON return value from /api/tokens should have equal srtings in 'id' and 'token'",
res.getString("id"), token1); res.get("id").getAsString(), token1);
Assert.assertEquals("Wrong session parameter", "CUSTOM_SESSION_ID", res.getString("session")); Assert.assertEquals("Wrong session parameter", "CUSTOM_SESSION_ID", res.get("session").getAsString());
// Default values // Default values
body = "{'session': 'CUSTOM_SESSION_ID'}"; body = "{'session': 'CUSTOM_SESSION_ID'}";
res = restClient.rest(HttpMethod.POST, "/api/tokens", body, HttpStatus.SC_OK, true, res = restClient.rest(HttpMethod.POST, "/api/tokens", body, HttpStatus.SC_OK, true,
"{'id':'STR','session':'STR','role':'STR','data':'STR','token':'STR'}"); "{'id':'STR','session':'STR','role':'STR','data':'STR','token':'STR'}");
final String token2 = res.getString("id"); final String token2 = res.get("id").getAsString();
/** POST /api/signal (NOT ACTIVE SESSION) **/ /** POST /api/signal (NOT ACTIVE SESSION) **/
body = "{}"; body = "{}";
@ -2495,9 +2495,9 @@ public class OpenViduTestAppE2eTest {
// 409 (RELAYED media mode) // 409 (RELAYED media mode)
res = restClient.rest(HttpMethod.POST, "/api/sessions", "{'mediaMode':'RELAYED'}", HttpStatus.SC_OK, true, res = restClient.rest(HttpMethod.POST, "/api/sessions", "{'mediaMode':'RELAYED'}", HttpStatus.SC_OK, true,
"{'id': 'STR', 'createdAt': 0}"); "{'id': 'STR', 'createdAt': 0}");
body = "{'session':'" + res.getString("id") + "'}"; body = "{'session':'" + res.get("id").getAsString() + "'}";
restClient.rest(HttpMethod.POST, "/api/recordings/start", body, HttpStatus.SC_CONFLICT); restClient.rest(HttpMethod.POST, "/api/recordings/start", body, HttpStatus.SC_CONFLICT);
restClient.rest(HttpMethod.DELETE, "/api/sessions/" + res.getString("id"), HttpStatus.SC_NO_CONTENT); restClient.rest(HttpMethod.DELETE, "/api/sessions/" + res.get("id").getAsString(), HttpStatus.SC_NO_CONTENT);
// Start session // Start session
setupBrowser("chrome"); setupBrowser("chrome");
@ -2591,13 +2591,14 @@ public class OpenViduTestAppE2eTest {
+ "'videoDimensions':'STR','filter':{}}}],'subscribers':[{'createdAt':0,'streamId':'STR','publisher':'STR'}]},{'connectionId':'STR','createdAt':0,'location':'STR'," + "'videoDimensions':'STR','filter':{}}}],'subscribers':[{'createdAt':0,'streamId':'STR','publisher':'STR'}]},{'connectionId':'STR','createdAt':0,'location':'STR',"
+ "'platform':'STR','token':'STR','role':'STR','serverData':'STR','clientData':'STR','publishers':[{'createdAt':0,'streamId':'STR','mediaOptions':{'hasAudio':false," + "'platform':'STR','token':'STR','role':'STR','serverData':'STR','clientData':'STR','publishers':[{'createdAt':0,'streamId':'STR','mediaOptions':{'hasAudio':false,"
+ "'audioActive':false,'hasVideo':false,'videoActive':false,'typeOfVideo':'STR','frameRate':0,'videoDimensions':'STR','filter':{}}}],'subscribers':[{'createdAt':0,'streamId':'STR','publisher':'STR'}]}]},'recording':false}"); + "'audioActive':false,'hasVideo':false,'videoActive':false,'typeOfVideo':'STR','frameRate':0,'videoDimensions':'STR','filter':{}}}],'subscribers':[{'createdAt':0,'streamId':'STR','publisher':'STR'}]}]},'recording':false}");
String streamId = ((org.json.JSONObject) ((org.json.JSONObject) res.getJSONObject("connections") String streamId = res.get("connections").getAsJsonObject().get("content").getAsJsonArray().get(0)
.getJSONArray("content").get(0)).getJSONArray("publishers").get(0)).getString("streamId"); .getAsJsonObject().get("publishers").getAsJsonArray().get(0).getAsJsonObject().get("streamId")
.getAsString();
restClient.rest(HttpMethod.DELETE, "/api/sessions/CUSTOM_SESSION_ID/stream/" + streamId, restClient.rest(HttpMethod.DELETE, "/api/sessions/CUSTOM_SESSION_ID/stream/" + streamId,
HttpStatus.SC_NO_CONTENT); HttpStatus.SC_NO_CONTENT);
final String connectionId = ((org.json.JSONObject) res.getJSONObject("connections").getJSONArray("content") final String connectionId = res.get("connections").getAsJsonObject().get("content").getAsJsonArray().get(0)
.get(0)).getString("connectionId"); .getAsJsonObject().get("connectionId").getAsString();
/** POST /api/signal (ACTIVE SESSION) **/ /** POST /api/signal (ACTIVE SESSION) **/
body = "{'session':'CUSTOM_SESSION_ID','to':['wrongConnectionId']}"; body = "{'session':'CUSTOM_SESSION_ID','to':['wrongConnectionId']}";
@ -2981,37 +2982,37 @@ public class OpenViduTestAppE2eTest {
// Publish IP camera. Dummy URL because no user will subscribe to it [200] // Publish IP camera. Dummy URL because no user will subscribe to it [200]
String ipCamBody = "{'type':'IPCAM','rtspUri':'rtsp://dummyurl.com','adaptativeBitrate':true,'onlyPlayWithSubscribers':true,'data':'MY_IP_CAMERA'}"; String ipCamBody = "{'type':'IPCAM','rtspUri':'rtsp://dummyurl.com','adaptativeBitrate':true,'onlyPlayWithSubscribers':true,'data':'MY_IP_CAMERA'}";
org.json.JSONObject response = restClient.rest(HttpMethod.POST, "/api/sessions/IP_CAM_SESSION/connection", JsonObject response = restClient.rest(HttpMethod.POST, "/api/sessions/IP_CAM_SESSION/connection", ipCamBody,
ipCamBody, HttpStatus.SC_OK, true, HttpStatus.SC_OK, true,
"{'connectionId':'STR','createdAt':0,'location':'STR','platform':'STR','token':'STR','role':'STR','serverData':'STR','clientData':'STR','publishers':[],'subscribers':[]}"); "{'connectionId':'STR','createdAt':0,'location':'STR','platform':'STR','token':'STR','role':'STR','serverData':'STR','clientData':'STR','publishers':[],'subscribers':[]}");
CustomWebhook.waitForEvent("sessionCreated", 1); CustomWebhook.waitForEvent("sessionCreated", 1);
CustomWebhook.waitForEvent("participantJoined", 1); CustomWebhook.waitForEvent("participantJoined", 1);
CustomWebhook.waitForEvent("webrtcConnectionCreated", 1); CustomWebhook.waitForEvent("webrtcConnectionCreated", 1);
Assert.assertEquals("Wrong serverData property", "MY_IP_CAMERA", response.get("serverData")); Assert.assertEquals("Wrong serverData property", "MY_IP_CAMERA", response.get("serverData").getAsString());
Assert.assertEquals("Wrong platform property", "IPCAM", response.get("platform")); Assert.assertEquals("Wrong platform property", "IPCAM", response.get("platform").getAsString());
Assert.assertEquals("Wrong role property", "PUBLISHER", response.get("role")); Assert.assertEquals("Wrong role property", "PUBLISHER", response.get("role").getAsString());
Assert.assertEquals("Wrong number of publishers in IPCAM participant", 1, Assert.assertEquals("Wrong number of publishers in IPCAM participant", 1,
response.getJSONArray("publishers").length()); response.get("publishers").getAsJsonArray().size());
org.json.JSONObject ipCamPublisher = response.getJSONArray("publishers").getJSONObject(0); JsonObject ipCamPublisher = response.get("publishers").getAsJsonArray().get(0).getAsJsonObject();
Assert.assertEquals("Wrong number of properties in IPCAM publisher", 4, ipCamPublisher.length()); Assert.assertEquals("Wrong number of properties in IPCAM publisher", 4, ipCamPublisher.size());
Assert.assertEquals("Wrong rtspUri property", "rtsp://dummyurl.com", ipCamPublisher.get("rtspUri")); Assert.assertEquals("Wrong rtspUri property", "rtsp://dummyurl.com", ipCamPublisher.get("rtspUri").getAsString());
org.json.JSONObject mediaOptions = ipCamPublisher.getJSONObject("mediaOptions"); JsonObject mediaOptions = ipCamPublisher.get("mediaOptions").getAsJsonObject();
Assert.assertEquals("Wrong number of properties in MediaOptions", 10, mediaOptions.length()); Assert.assertEquals("Wrong number of properties in MediaOptions", 10, mediaOptions.size());
Assert.assertTrue("Wrong adaptativeBitrate property", mediaOptions.getBoolean("adaptativeBitrate")); Assert.assertTrue("Wrong adaptativeBitrate property", mediaOptions.get("adaptativeBitrate").getAsBoolean());
Assert.assertTrue("Wrong onlyPlayWithSubscribers property", Assert.assertTrue("Wrong onlyPlayWithSubscribers property",
mediaOptions.getBoolean("onlyPlayWithSubscribers")); mediaOptions.get("onlyPlayWithSubscribers").getAsBoolean());
// Can't delete the stream [405] // Can't delete the stream [405]
restClient.rest(HttpMethod.DELETE, restClient.rest(HttpMethod.DELETE,
"/api/sessions/IP_CAM_SESSION/stream/" + ipCamPublisher.getString("streamId"), "/api/sessions/IP_CAM_SESSION/stream/" + ipCamPublisher.get("streamId").getAsString(),
HttpStatus.SC_METHOD_NOT_ALLOWED); HttpStatus.SC_METHOD_NOT_ALLOWED);
// Can delete the connection [204] // Can delete the connection [204]
restClient.rest(HttpMethod.DELETE, restClient.rest(HttpMethod.DELETE,
"/api/sessions/IP_CAM_SESSION/connection/" + response.getString("connectionId"), "/api/sessions/IP_CAM_SESSION/connection/" + response.get("connectionId").getAsString(),
HttpStatus.SC_NO_CONTENT); HttpStatus.SC_NO_CONTENT);
CustomWebhook.waitForEvent("webrtcConnectionDestroyed", 1); CustomWebhook.waitForEvent("webrtcConnectionDestroyed", 1);
@ -3046,8 +3047,8 @@ public class OpenViduTestAppE2eTest {
CustomWebhook.waitForEvent("recordingStatusChanged", 1); // Stopped CustomWebhook.waitForEvent("recordingStatusChanged", 1); // Stopped
CustomWebhook.waitForEvent("recordingStatusChanged", 1); // Ready CustomWebhook.waitForEvent("recordingStatusChanged", 1); // Ready
String recPath = restClient.rest(HttpMethod.GET, "/config", HttpStatus.SC_OK) String recPath = restClient.rest(HttpMethod.GET, "/config", HttpStatus.SC_OK).get("openviduRecordingPath")
.getString("openviduRecordingPath"); .getAsString();
recPath = recPath.endsWith("/") ? recPath : (recPath + "/"); recPath = recPath.endsWith("/") ? recPath : (recPath + "/");
String fullRecordingPath = "file://" + recPath + "TestSession/TestSession.mp4"; String fullRecordingPath = "file://" + recPath + "TestSession/TestSession.mp4";
ipCamBody = "{'type':'IPCAM','rtspUri':'" + fullRecordingPath ipCamBody = "{'type':'IPCAM','rtspUri':'" + fullRecordingPath

View File

@ -43,24 +43,25 @@
<properties> <properties>
<version.kurento>6.13.0</version.kurento> <version.kurento>6.13.0</version.kurento>
<version.spring-boot>2.1.7.RELEASE</version.spring-boot> <version.spring-boot>2.2.4.RELEASE</version.spring-boot>
<version.junit>4.12</version.junit> <version.junit>4.12</version.junit>
<version.junit.jupiter>5.6.0</version.junit.jupiter> <version.junit.jupiter>5.6.0</version.junit.jupiter>
<version.junit.platform>1.6.0</version.junit.platform> <version.junit.platform>1.6.0</version.junit.platform>
<version.selenium>3.141.59</version.selenium> <version.selenium>3.141.59</version.selenium>
<version.mockito.core>3.2.4</version.mockito.core> <version.mockito.core>2.23.4</version.mockito.core>
<version.powermock>2.0.5</version.powermock> <version.powermock>2.0.5</version.powermock>
<version.hamcrest>2.2</version.hamcrest> <version.hamcrest>2.2</version.hamcrest>
<version.json-simple>1.1.1</version.json-simple>
<version.httpclient>4.5.11</version.httpclient> <version.httpclient>4.5.11</version.httpclient>
<version.janino>3.1.0</version.janino> <version.janino>3.1.0</version.janino>
<version.commonslang>3.9</version.commonslang> <version.commonslang>3.9</version.commonslang>
<version.dockerjava>3.1.5</version.dockerjava> <version.dockerjava>3.1.5</version.dockerjava>
<version.slf4j>1.7.30</version.slf4j>
<version.gson>2.8.6</version.gson>
<version.unirest>1.4.9</version.unirest>
<version.thymeleaf>3.0.11.RELEASE</version.thymeleaf> <version.thymeleaf>3.0.11.RELEASE</version.thymeleaf>
<version.thymeleaflayout>2.4.1</version.thymeleaflayout> <version.thymeleaflayout>2.4.1</version.thymeleaflayout>
<version.webdrivermanager>3.8.1</version.webdrivermanager> <version.webdrivermanager>3.8.1</version.webdrivermanager>
<version.selenium.jupiter>3.2.1</version.selenium.jupiter>
<version.openvidu.java.client>2.11.0</version.openvidu.java.client> <version.openvidu.java.client>2.11.0</version.openvidu.java.client>
<version.openvidu.client>1.1.0</version.openvidu.client> <version.openvidu.client>1.1.0</version.openvidu.client>