openvidu-server REST API returns JSON instead of plain/text

pull/20/head
pabloFuente 2017-05-11 12:07:49 +02:00
parent 8537dde6ad
commit 7ab71f998f
9 changed files with 85 additions and 46 deletions

View File

@ -10,7 +10,6 @@ import java.security.NoSuchAlgorithmException;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
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.ClientProtocolException;
import org.apache.http.client.CredentialsProvider; import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpGet;
@ -22,6 +21,8 @@ import org.apache.http.impl.client.BasicCredentialsProvider;
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.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.openvidu.client.OpenViduException.Code; import org.openvidu.client.OpenViduException.Code;
public class OpenVidu { public class OpenVidu {
@ -59,23 +60,20 @@ public class OpenVidu {
} }
} }
public String createSession() throws OpenViduException, ClientProtocolException, IOException { public JSONObject createSession() throws IOException, ParseException {
HttpResponse response = myHttpClient.execute(new HttpGet(this.urlOpenViduServer + "getSessionId")); HttpResponse response = myHttpClient.execute(new HttpGet(this.urlOpenViduServer + "getSessionId"));
int statusCode = response.getStatusLine().getStatusCode(); int statusCode = response.getStatusLine().getStatusCode();
if ((statusCode == org.apache.http.HttpStatus.SC_OK) && (response.getEntity().getContentLength() > 0)){ if ((statusCode == org.apache.http.HttpStatus.SC_OK)){
System.out.println("Returning a SESSIONID"); System.out.println("Returning a SESSIONID");
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); return this.httpResponseToJsonObject(response);
String sessionId = br.readLine();
return sessionId;
} else { } else {
throw new OpenViduException(Code.TRANSPORT_REQUEST_ERROR_CODE, "Unable to generate a sessionID"); throw new OpenViduException(Code.SESSIONID_CANNOT_BE_CREATED_ERROR_CODE, "Unable to generate a sessionID");
} }
} }
public String generateToken(String sessionId, String role) throws OpenViduException, ClientProtocolException, IOException { public JSONObject generateToken(String sessionId, String role) throws IOException, ParseException {
JSONObject json = new JSONObject(); JSONObject json = new JSONObject();
json.put(0, sessionId); json.put(0, sessionId);
json.put(1, role); json.put(1, role);
@ -88,14 +86,22 @@ public class OpenVidu {
HttpResponse response = myHttpClient.execute(request); HttpResponse response = myHttpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode(); int statusCode = response.getStatusLine().getStatusCode();
if ((statusCode == org.apache.http.HttpStatus.SC_OK) && (response.getEntity().getContentLength() > 0)){ if ((statusCode == org.apache.http.HttpStatus.SC_OK)){
System.out.println("Returning a TOKEN"); System.out.println("Returning a TOKEN");
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); return this.httpResponseToJsonObject(response);
String token = br.readLine();
return token;
} else { } else {
throw new OpenViduException(Code.TRANSPORT_REQUEST_ERROR_CODE, "Unable to generate a token"); throw new OpenViduException(Code.TOKEN_CANNOT_BE_CREATED_ERROR_CODE, "Unable to generate a token");
} }
} }
private JSONObject httpResponseToJsonObject(HttpResponse response) throws ParseException, UnsupportedOperationException, IOException{
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer buf = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
buf.append(line);
}
JSONParser parser = new JSONParser();
return ((JSONObject) parser.parse(buf.toString()));
}
} }

View File

@ -38,7 +38,8 @@ public class OpenViduException extends RuntimeException {
104), USER_CLOSED_ERROR_CODE( 104), USER_CLOSED_ERROR_CODE(
103), USER_NOT_FOUND_ERROR_CODE(102), USER_GENERIC_ERROR_CODE(101), 103), USER_NOT_FOUND_ERROR_CODE(102), USER_GENERIC_ERROR_CODE(101),
USER_UNAUTHORIZED(401); USER_UNAUTHORIZED_ERROR_CODE(401), ROLE_NOT_FOUND_ERROR_CODE(402),
SESSIONID_CANNOT_BE_CREATED_ERROR_CODE(403), TOKEN_CANNOT_BE_CREATED_ERROR_CODE(404);
private int value; private int value;

View File

@ -38,7 +38,8 @@ public class OpenViduException extends RuntimeException {
104), USER_CLOSED_ERROR_CODE( 104), USER_CLOSED_ERROR_CODE(
103), USER_NOT_FOUND_ERROR_CODE(102), USER_GENERIC_ERROR_CODE(101), 103), USER_NOT_FOUND_ERROR_CODE(102), USER_GENERIC_ERROR_CODE(101),
USER_UNAUTHORIZED(401); USER_UNAUTHORIZED_ERROR_CODE(401), ROLE_NOT_FOUND_ERROR_CODE(402),
SESSIONID_CANNOT_BE_CREATED_ERROR_CODE(403), TOKEN_CANNOT_BE_CREATED_ERROR_CODE(404);
private int value; private int value;

View File

@ -5,9 +5,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.apache.http.client.HttpClient;
import org.json.simple.JSONObject; import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.openvidu.client.OpenVidu; import org.openvidu.client.OpenVidu;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
@ -48,7 +46,7 @@ public class SessionController {
} }
@RequestMapping(value = "/create-session", method = RequestMethod.POST) @RequestMapping(value = "/create-session", method = RequestMethod.POST)
public ResponseEntity<String> createSession(@RequestBody String lessonId) { public ResponseEntity<JSONObject> createSession(@RequestBody String lessonId) {
if (!this.userIsLogged()) { if (!this.userIsLogged()) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
@ -71,27 +69,33 @@ public class SessionController {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
} }
JSONObject responseJson = new JSONObject();
if(this.lessonIdSessionId.get(id_lesson) != null) { if(this.lessonIdSessionId.get(id_lesson) != null) {
// If there's already a valid sessionId for this lesson, not necessary to ask for a new one // If there's already a valid sessionId for this lesson, not necessary to ask for a new one
return new ResponseEntity<>(this.lessonIdSessionId.get(id_lesson), HttpStatus.OK); responseJson.put(0, this.lessonIdSessionId.get(id_lesson));
return new ResponseEntity<>(responseJson, HttpStatus.OK);
} }
else { else {
try { try {
String sessionId = this.openVidu.createSession(); JSONObject json = this.openVidu.createSession();
String sessionId = (String) json.get("0");
this.lessonIdSessionId.put(id_lesson, sessionId); this.lessonIdSessionId.put(id_lesson, sessionId);
this.sessionIdUserIdToken.put(sessionId, new HashMap<>()); this.sessionIdUserIdToken.put(sessionId, new HashMap<>());
showMap(); showMap();
return new ResponseEntity<>(sessionId, HttpStatus.OK); responseJson.put(0, sessionId);
return new ResponseEntity<>(responseJson, HttpStatus.OK);
} catch (Exception e) { } catch (Exception e) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR); return getErrorResponse(e);
} }
} }
} }
@RequestMapping(value = "/generate-token", method = RequestMethod.POST) @RequestMapping(value = "/generate-token", method = RequestMethod.POST)
public ResponseEntity<JSONObject> generateToken(@RequestBody String lessonId) throws Exception { public ResponseEntity<JSONObject> generateToken(@RequestBody String lessonId) {
if (!this.userIsLogged()) { if (!this.userIsLogged()) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED); return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
@ -119,12 +123,12 @@ public class SessionController {
String sessionId = this.lessonIdSessionId.get(id_lesson); String sessionId = this.lessonIdSessionId.get(id_lesson);
String role = user.hasRoleTeacher() ? "PUBLISHER" : "SUBSCRIBER"; String role = user.hasRoleTeacher() ? "PUBLISHER" : "SUBSCRIBER";
try { JSONObject responseJson = new JSONObject();
String token = this.openVidu.generateToken(sessionId, role); try {
String token = (String) this.openVidu.generateToken(sessionId, role).get("0");
this.sessionIdUserIdToken.get(sessionId).put(this.user.getLoggedUser().getId(), token); this.sessionIdUserIdToken.get(sessionId).put(this.user.getLoggedUser().getId(), token);
JSONObject responseJson = new JSONObject();
responseJson.put(0, sessionId); responseJson.put(0, sessionId);
responseJson.put(1, token); responseJson.put(1, token);
@ -132,9 +136,7 @@ public class SessionController {
return new ResponseEntity<>(responseJson, HttpStatus.OK); return new ResponseEntity<>(responseJson, HttpStatus.OK);
} catch (Exception e) { } catch (Exception e) {
JSONParser parser = new JSONParser(); return getErrorResponse(e);
JSONObject json = (JSONObject) parser.parse(e.getMessage());
return new ResponseEntity<>(json, HttpStatus.INTERNAL_SERVER_ERROR);
} }
} }
@ -198,6 +200,14 @@ public class SessionController {
return true; return true;
} }
private ResponseEntity<JSONObject> getErrorResponse(Exception e){
JSONObject json = new JSONObject();
json.put("cause", e.getCause());
json.put("error", e.getMessage());
json.put("exception", e.getClass());
return new ResponseEntity<>(json, HttpStatus.INTERNAL_SERVER_ERROR);
}
// Authorization checking for creating or joining a certain lesson // Authorization checking for creating or joining a certain lesson
private boolean checkAuthorization(Object o, User u){ private boolean checkAuthorization(Object o, User u){
return !(o == null || !this.user.getLoggedUser().equals(u)); return !(o == null || !this.user.getLoggedUser().equals(u));

View File

@ -84,10 +84,12 @@ export class VideoSessionComponent implements OnInit {
// If the user is the teacher: creates the session and gets a token (with PUBLISHER role) // If the user is the teacher: creates the session and gets a token (with PUBLISHER role)
this.videoSessionService.createSession(this.lesson.id).subscribe( this.videoSessionService.createSession(this.lesson.id).subscribe(
sessionId => { sessionId => { // {0: sessionId}
this.sessionId = sessionId; console.warn(sessionId);
this.sessionId = sessionId[0];
this.videoSessionService.generateToken(this.lesson.id).subscribe( this.videoSessionService.generateToken(this.lesson.id).subscribe(
sessionIdAndToken => { sessionIdAndToken => {
console.warn(sessionIdAndToken);
this.token = sessionIdAndToken[1]; this.token = sessionIdAndToken[1];
console.warn("Token: " + this.token); console.warn("Token: " + this.token);
console.warn("SessionId: " + this.sessionId); console.warn("SessionId: " + this.sessionId);
@ -106,7 +108,7 @@ export class VideoSessionComponent implements OnInit {
// If the user is a student: gets a token (with SUBSCRIBER role) // If the user is a student: gets a token (with SUBSCRIBER role)
this.videoSessionService.generateToken(this.lesson.id).subscribe( this.videoSessionService.generateToken(this.lesson.id).subscribe(
sessionIdAndToken => { sessionIdAndToken => { // {0: sessionId, 1: token}
this.sessionId = sessionIdAndToken[0]; this.sessionId = sessionIdAndToken[0];
this.token = sessionIdAndToken[1]; this.token = sessionIdAndToken[1];
console.warn("Token: " + this.token); console.warn("Token: " + this.token);

View File

@ -14,13 +14,13 @@ export class VideoSessionService {
constructor(private http: Http, private authenticationService: AuthenticationService) { } constructor(private http: Http, private authenticationService: AuthenticationService) { }
// Returns "sessionId" // Returns {0: sessionId}
createSession(lessonId: number) { createSession(lessonId: number) {
let body = JSON.stringify(lessonId); let body = JSON.stringify(lessonId);
let headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + this.authenticationService.token }); let headers = new Headers({ 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + this.authenticationService.token });
let options = new RequestOptions({ headers }); let options = new RequestOptions({ headers });
return this.http.post('/api-sessions/create-session', body, options) return this.http.post('/api-sessions/create-session', body, options)
.map(response => response.text()) .map(response => response.json())
.catch(error => this.handleError(error)); .catch(error => this.handleError(error));
} }

View File

@ -155,6 +155,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId> <artifactId>spring-boot-starter-security</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
</dependency>
</dependencies> </dependencies>
<!-- <profiles> <profile> <id>default</id> <activation> <property> <name>default</name> <!-- <profiles> <profile> <id>default</id> <activation> <property> <name>default</name>

View File

@ -20,7 +20,7 @@ import static org.kurento.commons.PropertiesManager.getProperty;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.json.simple.JSONObject;
import org.openvidu.server.core.NotificationRoomManager; import org.openvidu.server.core.NotificationRoomManager;
import org.openvidu.server.security.ParticipantRole; import org.openvidu.server.security.ParticipantRole;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -60,14 +60,29 @@ public class RoomController {
} }
@RequestMapping(value = "/getSessionId", method = RequestMethod.GET) @RequestMapping(value = "/getSessionId", method = RequestMethod.GET)
public ResponseEntity<String> getSessionId() { public ResponseEntity<JSONObject> getSessionId() {
String sessionId = roomManager.newSessionId(); String sessionId = roomManager.newSessionId();
return new ResponseEntity<String>(sessionId, HttpStatus.OK); JSONObject responseJson = new JSONObject();
responseJson.put(0, sessionId);
return new ResponseEntity<JSONObject>(responseJson, HttpStatus.OK);
} }
@RequestMapping(value = "/newToken", method = RequestMethod.POST) @RequestMapping(value = "/newToken", method = RequestMethod.POST)
public ResponseEntity<String> getToken(@RequestBody Map sessionIdAndRole) { public ResponseEntity<JSONObject> getToken(@RequestBody Map sessionIdAndRole) {
String token = roomManager.newToken((String) sessionIdAndRole.get("0"), ParticipantRole.valueOf((String) sessionIdAndRole.get("1"))); JSONObject responseJson = new JSONObject();
return new ResponseEntity<String>(token, HttpStatus.OK); try {
ParticipantRole role = ParticipantRole.valueOf((String) sessionIdAndRole.get("1"));
String token = roomManager.newToken((String) sessionIdAndRole.get("0"), role);
responseJson.put(0, token);
return new ResponseEntity<JSONObject>(responseJson, HttpStatus.OK);
}
catch (IllegalArgumentException e){
responseJson.put("timestamp", System.currentTimeMillis());
responseJson.put("status", HttpStatus.BAD_REQUEST.value());
responseJson.put("error", HttpStatus.BAD_REQUEST.getReasonPhrase());
responseJson.put("message", "Role " + sessionIdAndRole.get("1") + " is not defined");
responseJson.put("path", "/newToken");
return new ResponseEntity<JSONObject>(responseJson, HttpStatus.BAD_REQUEST);
}
} }
} }

View File

@ -72,7 +72,7 @@ public class JsonRpcUserControl {
} }
else { else {
System.out.println("Error: sessionId or token not valid"); System.out.println("Error: sessionId or token not valid");
throw new OpenViduException(Code.USER_UNAUTHORIZED, throw new OpenViduException(Code.USER_UNAUTHORIZED_ERROR_CODE,
"Unable to join room. The user does not have a valid token"); "Unable to join room. The user does not have a valid token");
} }
} }
@ -93,7 +93,7 @@ public class JsonRpcUserControl {
} }
else { else {
System.out.println("Error: user is not a publisher"); System.out.println("Error: user is not a publisher");
throw new OpenViduException(Code.USER_UNAUTHORIZED, throw new OpenViduException(Code.USER_UNAUTHORIZED_ERROR_CODE,
"Unable to publish video. The user does not have a valid token"); "Unable to publish video. The user does not have a valid token");
} }
} }