openvidu-java-client: rollback to Apache HttpClient. Upgrade it to version 5

pull/789/head
pabloFuente 2023-01-31 20:35:33 +01:00
parent 047a23137a
commit 66bbe9f41f
6 changed files with 793 additions and 650 deletions

View File

@ -63,6 +63,11 @@
</distributionManagement> </distributionManagement>
<dependencies> <dependencies>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
<dependency> <dependency>
<groupId>com.google.code.gson</groupId> <groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId> <artifactId>gson</artifactId>

View File

@ -18,49 +18,66 @@
package io.openvidu.java.client; package io.openvidu.java.client;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL; import java.net.URL;
import java.net.http.HttpClient; import java.nio.charset.StandardCharsets;
import java.net.http.HttpClient.Builder;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.time.Duration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Base64;
import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509ExtendedTrustManager;
import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
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.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);
protected String hostname; protected String hostname;
protected HttpClient httpClient; protected CloseableHttpClient httpClient;
protected Map<String, Session> activeSessions = new ConcurrentHashMap<>(); protected Map<String, Session> activeSessions = new ConcurrentHashMap<>();
protected long requestTimeout = 30000;
protected Map<String, String> headers = new HashMap<>();
protected final static String API_PATH = "openvidu/api"; protected final static String API_PATH = "openvidu/api";
protected final static String API_SESSIONS = API_PATH + "/sessions"; protected final static String API_SESSIONS = API_PATH + "/sessions";
@ -69,8 +86,6 @@ public class OpenVidu {
protected final static String API_RECORDINGS_START = API_RECORDINGS + "/start"; protected final static String API_RECORDINGS_START = API_RECORDINGS + "/start";
protected final static String API_RECORDINGS_STOP = API_RECORDINGS + "/stop"; protected final static String API_RECORDINGS_STOP = API_RECORDINGS + "/stop";
private String defaultBasicAuth;
/** /**
* @param hostname URL where your OpenVidu deployment is up an running. It must * @param hostname URL where your OpenVidu deployment is up an running. It must
* be the full URL (e.g. <code>https://12.34.56.78:1234/</code>) * be the full URL (e.g. <code>https://12.34.56.78:1234/</code>)
@ -80,138 +95,115 @@ public class OpenVidu {
public OpenVidu(String hostname, String secret) { public OpenVidu(String hostname, String secret) {
testHostname(hostname); testHostname(hostname);
setDefaultBasicAuth(secret);
this.hostname = hostname; this.hostname = hostname;
if (!this.hostname.endsWith("/")) { if (!this.hostname.endsWith("/")) {
this.hostname += "/"; this.hostname += "/";
} }
TrustStrategy trustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
};
final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(null, -1),
new UsernamePasswordCredentials("OPENVIDUAPP", secret.toCharArray()));
SSLContext sslContext; SSLContext sslContext;
try { try {
sslContext = SSLContext.getInstance("TLS"); sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build();
sslContext.init(null, new TrustManager[] { new X509ExtendedTrustManager() { } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(final X509Certificate[] a_certificates, final String a_auth_type) {
}
public void checkServerTrusted(final X509Certificate[] a_certificates, final String a_auth_type) {
}
public void checkClientTrusted(final X509Certificate[] a_certificates, final String a_auth_type,
final Socket a_socket) {
}
public void checkServerTrusted(final X509Certificate[] a_certificates, final String a_auth_type,
final Socket a_socket) {
}
public void checkClientTrusted(final X509Certificate[] a_certificates, final String a_auth_type,
final SSLEngine a_engine) {
}
public void checkServerTrusted(final X509Certificate[] a_certificates, final String a_auth_type,
final SSLEngine a_engine) {
}
} }, null);
} catch (KeyManagementException | NoSuchAlgorithmException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create()
.setSslContext(sslContext).build();
Builder b = HttpClient.newBuilder(); ConnectionConfig.Builder connectionConfigBuilder = ConnectionConfig.custom()
b.sslContext(sslContext); .setConnectTimeout(30, TimeUnit.SECONDS).setSocketTimeout(30, TimeUnit.SECONDS)
b.connectTimeout(Duration.ofSeconds(30)); .setTimeToLive(30, TimeUnit.SECONDS);
this.httpClient = b.build();
final HttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslSocketFactory).setDefaultConnectionConfig(connectionConfigBuilder.build())
.build();
RequestConfig requestBuilder = RequestConfig.custom().setConnectionRequestTimeout(30, TimeUnit.SECONDS).build();
this.httpClient = HttpClients.custom().setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestBuilder).setDefaultCredentialsProvider(credentialsProvider).build();
} }
/** /**
* @param hostname URL where your OpenVidu deployment is up an running. It * @param hostname URL where your OpenVidu deployment is up an running. It must
* must be the full URL (e.g. * be the full URL (e.g. <code>https://12.34.56.78:1234/</code>)
* <code>https://12.34.56.78:1234/</code>) *
* @param httpClient Object of class <a target="_blank" href= * @param secret Secret configured in your OpenVidu deployment
* "https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpClient.html">java.net.http.HttpClient</a>. *
* @param builder An instance of <a href=
* "https://hc.apache.org/httpcomponents-client-5.2.x/current/httpclient5/apidocs/org/apache/hc/client5/http/impl/classic/HttpClientBuilder.html"
* target=
* "_blank">org.apache.hc.client5.http.impl.classic.HttpClientBuilder</a>.
* This overrides the internal HTTP client in use. This method * This overrides the internal HTTP client in use. This method
* allows you to custom configure the HTTP client to your * allows you to custom configure the HTTP client to your needs.
* needs. This may be interesting for many reasons, including: * This may be interesting for many reasons, including:
* <ul> * <ul>
* <li>Adding custom HTTP headers</li>
* <li>Adding proxy configuration</li> * <li>Adding proxy configuration</li>
* <li>Customizing the SSLContext</li> * <li>Customizing the SSLContext</li>
* <li>Modifying the connection timeout</li> * <li>Modifying the connection timeouts</li>
* <li>Adding a cookie handler</li> * <li>Setting up a cookie store</li>
* </ul> * </ul>
* This method will override any <a href=
* "https://hc.apache.org/httpcomponents-client-5.2.x/current/httpclient5/apidocs/org/apache/hc/client5/http/auth/CredentialsProvider.html"
* target="_blank">CredentialsProvider</a> of the
* {@code builder} with a <a href=
* "https://hc.apache.org/httpcomponents-client-5.2.x/current/httpclient5/apidocs/org/apache/hc/client5/http/impl/auth/BasicCredentialsProvider.html"
* target="_blank">BasicCredentialsProvider</a> built with the
* param {@code secret}, which is the default configuration.
*/ */
public OpenVidu(String hostname, String secret, HttpClient httpClient) { public OpenVidu(String hostname, String secret, HttpClientBuilder builder) {
testHostname(hostname); testHostname(hostname);
setDefaultBasicAuth(secret);
this.hostname = hostname; this.hostname = hostname;
if (!this.hostname.endsWith("/")) { if (!this.hostname.endsWith("/")) {
this.hostname += "/"; this.hostname += "/";
} }
Builder b = HttpClient.newBuilder(); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
if (httpClient.authenticator().isPresent()) { credentialsProvider.setCredentials(new AuthScope(null, -1),
log.warn( new UsernamePasswordCredentials("OPENVIDUAPP", secret.toCharArray()));
"The provided HttpClient contains a custom java.net.Authenticator. OpenVidu deployments require all HTTP requests to have an Authorization header with Basic Auth, with username \"OPENVIDUAPP\" and password your OpenVidu deployment's secret (configuration parameter OPENVIDU_SECRET). The default Authenticator adds this header. Make sure that your custom Authenticator does so as well or that you add it explicitly via OpenVidu#setRequestHeaders, or you will receive 401 responses"); this.httpClient = builder.setDefaultCredentialsProvider(credentialsProvider).build();
b.authenticator(httpClient.authenticator().get());
}
if (httpClient.connectTimeout().isPresent()) {
b.connectTimeout(httpClient.connectTimeout().get());
}
if (httpClient.cookieHandler().isPresent()) {
b.cookieHandler(httpClient.cookieHandler().get());
}
if (httpClient.executor().isPresent()) {
b.executor(httpClient.executor().get());
}
if (httpClient.proxy().isPresent()) {
b.proxy(httpClient.proxy().get());
}
b.followRedirects(httpClient.followRedirects());
b.sslContext(httpClient.sslContext());
b.sslParameters(httpClient.sslParameters());
b.version(httpClient.version());
this.httpClient = b.build();
} }
/** /**
* Returns the current request timeout configured for all requests. * @param hostname URL where your OpenVidu deployment is up an running. It must
*/ * be the full URL (e.g. <code>https://12.34.56.78:1234/</code>)
public long getRequestTimeout() {
return this.requestTimeout;
}
/**
* Sets the request timeout for all HTTP requests. This is the same as setting
* the <a target="_blank" href=
* "https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpRequest.html#timeout()">HttpRequest.timeout()</a>
* property for all requests. The default value is 30000 ms.
* *
* @param requestTimeout Timeout in milliseconds * @param builder An instance of <a href=
* "https://hc.apache.org/httpcomponents-client-5.2.x/current/httpclient5/apidocs/org/apache/hc/client5/http/impl/classic/HttpClientBuilder.html"
* target=
* "_blank">org.apache.hc.client5.http.impl.classic.HttpClientBuilder</a>.
* This overrides the internal HTTP client in use. This method
* allows you to custom configure the HTTP client to your needs.
* This may be interesting for many reasons, including:
* <ul>
* <li>Adding custom HTTP headers</li>
* <li>Adding proxy configuration</li>
* <li>Customizing the SSLContext</li>
* <li>Modifying the connection timeouts</li>
* <li>Setting up a cookie store</li>
* </ul>
*/ */
public void setRequestTimeout(long requestTimeout) { public OpenVidu(String hostname, HttpClientBuilder builder) {
this.requestTimeout = requestTimeout;
testHostname(hostname);
this.hostname = hostname;
if (!this.hostname.endsWith("/")) {
this.hostname += "/";
} }
/** this.httpClient = builder.build();
* Returns the current collection of custom headers configured for all requests.
*/
public Map<String, String> getRequestHeaders() {
return this.headers;
}
/**
* Sets custom HTTP headers for all requests. Will override any previous value.
*
* @param headers Header names and values
*/
public void setRequestHeaders(Map<String, String> headers) {
this.headers = headers;
} }
/** /**
@ -275,23 +267,15 @@ public class OpenVidu {
* API</a>) * API</a>)
*/ */
public Recording startRecording(String sessionId, RecordingProperties properties) public Recording startRecording(String sessionId, RecordingProperties properties)
throws OpenViduJavaClientException, OpenViduHttpException { throws OpenViduHttpException, OpenViduJavaClientException {
try { final HttpClientResponseHandler<Recording> responseHandler = new HttpClientResponseHandler<Recording>() {
JsonObject json = properties.toJson(); @Override
json.addProperty("session", sessionId); public Recording handleResponse(final ClassicHttpResponse response) throws IOException, HttpException {
final int status = response.getCode();
HttpRequest request = addHeaders( if (status == HttpStatus.SC_OK) {
HttpRequest.newBuilder().POST(HttpRequest.BodyPublishers.ofString(json.toString())) Recording r = new Recording(httpResponseEntityToJson(response.getEntity()));
.uri(new URI(this.hostname + API_RECORDINGS_START)) Session activeSession = activeSessions.get(r.getSessionId());
.setHeader("Content-Type", "application/json").timeout(Duration.ofMillis(requestTimeout)))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if ((response.statusCode() == HttpURLConnection.HTTP_OK)) {
Recording r = new Recording(Utils.httpResponseToJson(response));
Session activeSession = this.activeSessions.get(r.getSessionId());
if (activeSession != null) { if (activeSession != null) {
activeSession.setIsBeingRecorded(true); activeSession.setIsBeingRecorded(true);
} else { } else {
@ -301,11 +285,23 @@ public class OpenVidu {
} }
return r; return r;
} else { } else {
throw new OpenViduHttpException(response.statusCode()); throw openViduHttpException(status);
} }
}
};
} catch (URISyntaxException | IOException | InterruptedException e) { JsonObject json = properties.toJson();
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); json.addProperty("session", sessionId);
StringEntity params = new StringEntity(json.toString(), StandardCharsets.UTF_8);
HttpPost request = new HttpPost(this.hostname + API_RECORDINGS_START);
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
request.setEntity(params);
try {
return this.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw ioExceptionToOpenViduHttpException(e);
} }
} }
@ -376,16 +372,13 @@ public class OpenVidu {
*/ */
public Recording stopRecording(String recordingId) throws OpenViduJavaClientException, OpenViduHttpException { public Recording stopRecording(String recordingId) throws OpenViduJavaClientException, OpenViduHttpException {
try { final HttpClientResponseHandler<Recording> responseHandler = new HttpClientResponseHandler<Recording>() {
HttpRequest request = addHeaders(HttpRequest.newBuilder().POST(HttpRequest.BodyPublishers.noBody()) @Override
.uri(new URI(this.hostname + API_RECORDINGS_STOP + "/" + recordingId)) public Recording handleResponse(final ClassicHttpResponse response) throws IOException, HttpException {
.timeout(Duration.ofMillis(requestTimeout))).build(); final int status = response.getCode();
if (status == HttpStatus.SC_OK) {
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); Recording r = new Recording(httpResponseEntityToJson(response.getEntity()));
Session activeSession = activeSessions.get(r.getSessionId());
if (response.statusCode() == HttpURLConnection.HTTP_OK) {
Recording r = new Recording(Utils.httpResponseToJson(response));
Session activeSession = this.activeSessions.get(r.getSessionId());
if (activeSession != null) { if (activeSession != null) {
activeSession.setIsBeingRecorded(false); activeSession.setIsBeingRecorded(false);
} else { } else {
@ -395,10 +388,17 @@ public class OpenVidu {
} }
return r; return r;
} else { } else {
throw new OpenViduHttpException(response.statusCode()); throw openViduHttpException(status);
} }
} catch (URISyntaxException | IOException | InterruptedException e) { }
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); };
HttpPost request = new HttpPost(this.hostname + API_RECORDINGS_STOP + "/" + recordingId);
try {
return this.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw ioExceptionToOpenViduHttpException(e);
} }
} }
@ -417,21 +417,24 @@ public class OpenVidu {
*/ */
public Recording getRecording(String recordingId) throws OpenViduJavaClientException, OpenViduHttpException { public Recording getRecording(String recordingId) throws OpenViduJavaClientException, OpenViduHttpException {
try { final HttpClientResponseHandler<Recording> responseHandler = new HttpClientResponseHandler<Recording>() {
HttpRequest request = addHeaders( @Override
HttpRequest.newBuilder().GET().uri(new URI(this.hostname + API_RECORDINGS + "/" + recordingId)) public Recording handleResponse(final ClassicHttpResponse response) throws IOException, HttpException {
.timeout(Duration.ofMillis(requestTimeout))) final int status = response.getCode();
.build(); if (status == HttpStatus.SC_OK) {
return new Recording(httpResponseEntityToJson(response.getEntity()));
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == HttpURLConnection.HTTP_OK) {
return new Recording(Utils.httpResponseToJson(response));
} else { } else {
throw new OpenViduHttpException(response.statusCode()); throw openViduHttpException(status);
} }
} catch (URISyntaxException | IOException | InterruptedException e) { }
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); };
HttpGet request = new HttpGet(this.hostname + API_RECORDINGS + "/" + recordingId);
try {
return this.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw ioExceptionToOpenViduHttpException(e);
} }
} }
@ -445,25 +448,31 @@ public class OpenVidu {
*/ */
public List<Recording> listRecordings() throws OpenViduJavaClientException, OpenViduHttpException { public List<Recording> listRecordings() throws OpenViduJavaClientException, OpenViduHttpException {
try { final HttpClientResponseHandler<List<Recording>> responseHandler = new HttpClientResponseHandler<List<Recording>>() {
HttpRequest request = addHeaders(HttpRequest.newBuilder().GET().uri(new URI(this.hostname + API_RECORDINGS)) @Override
.timeout(Duration.ofMillis(requestTimeout))).build(); public List<Recording> handleResponse(final ClassicHttpResponse response)
throws IOException, HttpException {
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); final int status = response.getCode();
if (status == HttpStatus.SC_OK) {
if (response.statusCode() == HttpURLConnection.HTTP_OK) {
List<Recording> recordings = new ArrayList<>(); List<Recording> recordings = new ArrayList<>();
JsonObject json = Utils.httpResponseToJson(response); JsonObject json = httpResponseEntityToJson(response.getEntity());
JsonArray array = json.get("items").getAsJsonArray(); JsonArray array = json.get("items").getAsJsonArray();
array.forEach(item -> { array.forEach(item -> {
recordings.add(new Recording(item.getAsJsonObject())); recordings.add(new Recording(item.getAsJsonObject()));
}); });
return recordings; return recordings;
} else { } else {
throw new OpenViduHttpException(response.statusCode()); throw openViduHttpException(status);
} }
} catch (URISyntaxException | IOException | InterruptedException e) { }
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); };
HttpGet request = new HttpGet(this.hostname + API_RECORDINGS);
try {
return this.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw ioExceptionToOpenViduHttpException(e);
} }
} }
@ -485,19 +494,23 @@ public class OpenVidu {
*/ */
public void deleteRecording(String recordingId) throws OpenViduJavaClientException, OpenViduHttpException { public void deleteRecording(String recordingId) throws OpenViduJavaClientException, OpenViduHttpException {
try { final HttpClientResponseHandler<Void> responseHandler = new HttpClientResponseHandler<Void>() {
HttpRequest request = addHeaders( @Override
HttpRequest.newBuilder().DELETE().uri(new URI(this.hostname + API_RECORDINGS + "/" + recordingId)) public Void handleResponse(final ClassicHttpResponse response) throws IOException, HttpException {
.timeout(Duration.ofMillis(requestTimeout))) final int status = response.getCode();
.build(); if (status != HttpStatus.SC_NO_CONTENT) {
throw openViduHttpException(status);
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != HttpURLConnection.HTTP_NO_CONTENT) {
throw new OpenViduHttpException(response.statusCode());
} }
} catch (URISyntaxException | IOException | InterruptedException e) { return null;
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); }
};
HttpDelete request = new HttpDelete(this.hostname + API_RECORDINGS + "/" + recordingId);
try {
this.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw ioExceptionToOpenViduHttpException(e);
} }
} }
@ -566,16 +579,14 @@ public class OpenVidu {
*/ */
public boolean fetch() throws OpenViduJavaClientException, OpenViduHttpException { public boolean fetch() throws OpenViduJavaClientException, OpenViduHttpException {
try { final OpenVidu thisOV = this;
HttpRequest request = addHeaders(HttpRequest.newBuilder().GET() final HttpClientResponseHandler<Boolean> responseHandler = new HttpClientResponseHandler<Boolean>() {
.uri(new URI(this.hostname + API_SESSIONS + "?pendingConnections=true")) @Override
.timeout(Duration.ofMillis(requestTimeout))).build(); public Boolean handleResponse(final ClassicHttpResponse response) throws IOException, HttpException {
final int status = response.getCode();
if (status == HttpStatus.SC_OK) {
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); JsonObject jsonSessions = httpResponseEntityToJson(response.getEntity());
if (response.statusCode() == HttpURLConnection.HTTP_OK) {
JsonObject jsonSessions = Utils.httpResponseToJson(response);
JsonArray jsonArraySessions = jsonSessions.get("content").getAsJsonArray(); JsonArray jsonArraySessions = jsonSessions.get("content").getAsJsonArray();
// Boolean to store if any Session has changed // Boolean to store if any Session has changed
@ -586,12 +597,12 @@ public class OpenVidu {
jsonArraySessions.forEach(sessionJsonElement -> { jsonArraySessions.forEach(sessionJsonElement -> {
JsonObject sessionJson = sessionJsonElement.getAsJsonObject(); JsonObject sessionJson = sessionJsonElement.getAsJsonObject();
final Session sessionObj = new Session(this, sessionJson); final Session sessionObj = new Session(thisOV, sessionJson);
String id = sessionObj.getSessionId(); String id = sessionObj.getSessionId();
fetchedSessionIds.add(id); fetchedSessionIds.add(id);
// 2. Update existing Session // 2. Update existing Session
this.activeSessions.computeIfPresent(id, (sId, s) -> { activeSessions.computeIfPresent(id, (sId, s) -> {
String beforeJSON = s.toJson(); String beforeJSON = s.toJson();
s = s.resetWithJson(sessionJson); s = s.resetWithJson(sessionJson);
String afterJSON = s.toJson(); String afterJSON = s.toJson();
@ -602,7 +613,7 @@ public class OpenVidu {
}); });
// 3. Add new Session // 3. Add new Session
this.activeSessions.computeIfAbsent(id, sId -> { activeSessions.computeIfAbsent(id, sId -> {
log.info("New session '{}' fetched", id); log.info("New session '{}' fetched", id);
hasChanged[0] = true; hasChanged[0] = true;
return sessionObj; return sessionObj;
@ -610,7 +621,7 @@ public class OpenVidu {
}); });
// 4. Remove closed sessions from local collection // 4. Remove closed sessions from local collection
this.activeSessions.entrySet().removeIf(entry -> { activeSessions.entrySet().removeIf(entry -> {
if (fetchedSessionIds.contains(entry.getKey())) { if (fetchedSessionIds.contains(entry.getKey())) {
return false; return false;
} else { } else {
@ -620,28 +631,73 @@ public class OpenVidu {
} }
}); });
log.info("Active sessions info fetched: {}", this.activeSessions.keySet()); log.info("Active sessions info fetched: {}", activeSessions.keySet());
return hasChanged[0]; return hasChanged[0];
} else { } else {
throw new OpenViduHttpException(response.statusCode()); throw openViduHttpException(status);
} }
}
};
} catch (URISyntaxException | IOException | InterruptedException e) { HttpGet request = new HttpGet(this.hostname + API_SESSIONS + "?pendingConnections=true");
throw new OpenViduJavaClientException(e.getMessage(), e.getCause());
try {
return this.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw ioExceptionToOpenViduHttpException(e);
} }
} }
protected HttpRequest.Builder addHeaders(HttpRequest.Builder builder) { protected static JsonObject httpResponseEntityToJson(HttpEntity responseEntity) throws IOException {
// HTTP header names are case insensitive try {
Map<String, String> headersLowerCase = new HashMap<>(); JsonObject json = new Gson().fromJson(EntityUtils.toString(responseEntity, StandardCharsets.UTF_8),
this.headers.forEach((k, v) -> headersLowerCase.put(k.toLowerCase(), v)); JsonObject.class);
if (!headersLowerCase.containsKey("authorization")) { return json;
// There is no custom Authorization header. Add default Basic Auth for OpenVidu } catch (JsonSyntaxException | ParseException | IOException e) {
headersLowerCase.put("authorization", this.defaultBasicAuth); JsonObject json = new JsonObject();
json.addProperty("openviduExceptionType", OpenViduJavaClientException.class.getSimpleName());
json.addProperty("openviduExceptionMessage", e.getMessage());
throw new IOException(json.toString(), e.getCause());
}
}
protected static IOException openViduHttpException(int status) {
JsonObject json = new JsonObject();
json.addProperty("openviduExceptionType", OpenViduHttpException.class.getSimpleName());
json.addProperty("openviduExceptionMessage", status);
return new IOException(json.toString());
}
protected static IOException openViduException(OpenViduException exception) {
JsonObject json = new JsonObject();
json.addProperty("openviduExceptionType", exception.getClass().getSimpleName());
json.addProperty("openviduExceptionMessage", exception.getMessage());
return new IOException(json.toString());
}
protected static OpenViduHttpException ioExceptionToOpenViduHttpException(IOException exception)
throws OpenViduJavaClientException {
JsonObject json;
try {
String message = exception.getMessage();
json = JsonParser.parseString(message).getAsJsonObject();
} catch (Exception e) {
throw new OpenViduJavaClientException(exception.getMessage(), exception.getCause());
}
if (json.has("openviduExceptionType")) {
String openviduExceptionType = json.get("openviduExceptionType").getAsString();
if (OpenViduJavaClientException.class.getSimpleName().equals(openviduExceptionType)) {
throw new OpenViduJavaClientException(json.get("openviduExceptionMessage").getAsString());
} else if (OpenViduHttpException.class.getSimpleName().equals(openviduExceptionType)) {
return new OpenViduHttpException(json.get("openviduExceptionMessage").getAsInt());
} else {
log.error("Unknown OpenVidu Exception: " + openviduExceptionType);
throw new OpenViduJavaClientException(exception.getMessage(), exception.getCause());
}
} else {
// Unlikely case when an unknown exception has a JSON format message
throw new OpenViduJavaClientException(exception.getMessage(), exception.getCause());
} }
headersLowerCase.forEach((k, v) -> builder.setHeader(k, v));
return builder;
} }
private void testHostname(String hostnameStr) { private void testHostname(String hostnameStr) {
@ -652,7 +708,4 @@ public class OpenVidu {
} }
} }
private void setDefaultBasicAuth(String secret) {
this.defaultBasicAuth = "Basic " + Base64.getEncoder().encodeToString(("OPENVIDUAPP:" + secret).getBytes());
}
} }

View File

@ -18,12 +18,7 @@
package io.openvidu.java.client; package io.openvidu.java.client;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -31,6 +26,16 @@ import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPatch;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -113,34 +118,35 @@ public class Session {
*/ */
@Deprecated @Deprecated
public String generateToken(TokenOptions tokenOptions) throws OpenViduJavaClientException, OpenViduHttpException { public String generateToken(TokenOptions tokenOptions) throws OpenViduJavaClientException, OpenViduHttpException {
if (!this.hasSessionId()) { if (!this.hasSessionId()) {
this.getSessionId(); this.getSessionId();
} }
try { final HttpClientResponseHandler<String> responseHandler = new HttpClientResponseHandler<String>() {
JsonObject json = tokenOptions.toJsonObject(sessionId); @Override
public String handleResponse(final ClassicHttpResponse response) throws IOException, HttpException {
HttpRequest request = this.openVidu final int status = response.getCode();
.addHeaders(HttpRequest.newBuilder().POST(HttpRequest.BodyPublishers.ofString(json.toString())) if (status == HttpStatus.SC_OK) {
.uri(new URI(this.openVidu.hostname + OpenVidu.API_TOKENS)) String token = OpenVidu.httpResponseEntityToJson(response.getEntity()).get("id").getAsString();
.setHeader("Content-Type", "application/json")
.timeout(Duration.ofMillis(this.openVidu.requestTimeout)))
.build();
HttpResponse<String> response = this.openVidu.httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == HttpURLConnection.HTTP_OK) {
String token = Utils.httpResponseToJson(response).get("id").getAsString();
log.info("Returning a TOKEN: {}", token); log.info("Returning a TOKEN: {}", token);
return token; return token;
} else { } else {
throw new OpenViduHttpException(response.statusCode()); throw OpenVidu.openViduHttpException(status);
} }
}
};
} catch (URISyntaxException | IOException | InterruptedException e) { JsonObject json = tokenOptions.toJsonObject(sessionId);
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); StringEntity params = new StringEntity(json.toString(), StandardCharsets.UTF_8);
HttpPost request = new HttpPost(this.openVidu.hostname + OpenVidu.API_TOKENS);
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
request.setEntity(params);
try {
return this.openVidu.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw OpenVidu.ioExceptionToOpenViduHttpException(e);
} }
} }
@ -175,33 +181,36 @@ public class Session {
*/ */
public Connection createConnection(ConnectionProperties connectionProperties) public Connection createConnection(ConnectionProperties connectionProperties)
throws OpenViduJavaClientException, OpenViduHttpException { throws OpenViduJavaClientException, OpenViduHttpException {
if (!this.hasSessionId()) { if (!this.hasSessionId()) {
this.getSessionId(); this.getSessionId();
} }
try { final HttpClientResponseHandler<Connection> responseHandler = new HttpClientResponseHandler<Connection>() {
JsonObject json = connectionProperties.toJson(sessionId); @Override
public Connection handleResponse(final ClassicHttpResponse response) throws IOException, HttpException {
HttpRequest request = this.openVidu.addHeaders(HttpRequest.newBuilder() final int status = response.getCode();
.POST(HttpRequest.BodyPublishers.ofString(json.toString())) if (status == HttpStatus.SC_OK) {
.uri(new URI(this.openVidu.hostname + OpenVidu.API_SESSIONS + "/" + this.sessionId + "/connection")) Connection connection = new Connection(OpenVidu.httpResponseEntityToJson(response.getEntity()));
.setHeader("Content-Type", "application/json") connections.put(connection.getConnectionId(), connection);
.timeout(Duration.ofMillis(this.openVidu.requestTimeout))).build();
HttpResponse<String> response = this.openVidu.httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == HttpURLConnection.HTTP_OK) {
Connection connection = new Connection(Utils.httpResponseToJson(response));
this.connections.put(connection.getConnectionId(), connection);
return connection; return connection;
} else { } else {
throw new OpenViduHttpException(response.statusCode()); throw OpenVidu.openViduHttpException(status);
} }
}
};
} catch (URISyntaxException | IOException | InterruptedException e) { JsonObject json = connectionProperties.toJson(sessionId);
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); StringEntity params = new StringEntity(json.toString(), StandardCharsets.UTF_8);
HttpPost request = new HttpPost(
this.openVidu.hostname + OpenVidu.API_SESSIONS + "/" + this.sessionId + "/connection");
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
request.setEntity(params);
try {
return this.openVidu.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw OpenVidu.ioExceptionToOpenViduHttpException(e);
} }
} }
@ -214,23 +223,26 @@ public class Session {
*/ */
public void close() throws OpenViduJavaClientException, OpenViduHttpException { public void close() throws OpenViduJavaClientException, OpenViduHttpException {
try { final HttpClientResponseHandler<Void> responseHandler = new HttpClientResponseHandler<Void>() {
HttpRequest request = this.openVidu.addHeaders(HttpRequest.newBuilder().DELETE() @Override
.uri(new URI(this.openVidu.hostname + OpenVidu.API_SESSIONS + "/" + this.sessionId)) public Void handleResponse(final ClassicHttpResponse response) throws IOException, HttpException {
.timeout(Duration.ofMillis(this.openVidu.requestTimeout))).build(); final int status = response.getCode();
if (status == HttpStatus.SC_NO_CONTENT) {
HttpResponse<String> response = this.openVidu.httpClient.send(request, openVidu.activeSessions.remove(sessionId);
HttpResponse.BodyHandlers.ofString()); log.info("Session {} closed", sessionId);
if (response.statusCode() == HttpURLConnection.HTTP_NO_CONTENT) {
this.openVidu.activeSessions.remove(this.sessionId);
log.info("Session {} closed", this.sessionId);
} else { } else {
throw new OpenViduHttpException(response.statusCode()); throw OpenVidu.openViduHttpException(status);
} }
return null;
}
};
} catch (URISyntaxException | IOException | InterruptedException e) { HttpDelete request = new HttpDelete(this.openVidu.hostname + OpenVidu.API_SESSIONS + "/" + this.sessionId);
throw new OpenViduJavaClientException(e.getMessage(), e.getCause());
try {
this.openVidu.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw OpenVidu.ioExceptionToOpenViduHttpException(e);
} }
} }
@ -257,29 +269,31 @@ public class Session {
*/ */
public boolean fetch() throws OpenViduJavaClientException, OpenViduHttpException { public boolean fetch() throws OpenViduJavaClientException, OpenViduHttpException {
try {
final String beforeJSON = this.toJson(); final String beforeJSON = this.toJson();
HttpRequest request = this.openVidu.addHeaders(HttpRequest.newBuilder().GET() final HttpClientResponseHandler<Boolean> responseHandler = new HttpClientResponseHandler<Boolean>() {
.uri(new URI(this.openVidu.hostname + OpenVidu.API_SESSIONS + "/" + this.sessionId @Override
+ "?pendingConnections=true")) public Boolean handleResponse(final ClassicHttpResponse response) throws IOException, HttpException {
.timeout(Duration.ofMillis(this.openVidu.requestTimeout))).build(); final int status = response.getCode();
if (status == HttpStatus.SC_OK) {
HttpResponse<String> response = this.openVidu.httpClient.send(request, resetWithJson(OpenVidu.httpResponseEntityToJson(response.getEntity()));
HttpResponse.BodyHandlers.ofString()); final String afterJSON = toJson();
if (response.statusCode() == HttpURLConnection.HTTP_OK) {
this.resetWithJson(Utils.httpResponseToJson(response));
final String afterJSON = this.toJson();
boolean hasChanged = !beforeJSON.equals(afterJSON); boolean hasChanged = !beforeJSON.equals(afterJSON);
log.info("Session info fetched for session '{}'. Any change: {}", this.sessionId, hasChanged); log.info("Session info fetched for session '{}'. Any change: {}", sessionId, hasChanged);
return hasChanged; return hasChanged;
} else { } else {
throw new OpenViduHttpException(response.statusCode()); throw OpenVidu.openViduHttpException(status);
} }
}
};
} catch (URISyntaxException | IOException | InterruptedException e) { HttpGet request = new HttpGet(
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); this.openVidu.hostname + OpenVidu.API_SESSIONS + "/" + this.sessionId + "?pendingConnections=true");
try {
return this.openVidu.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw OpenVidu.ioExceptionToOpenViduHttpException(e);
} }
} }
@ -329,27 +343,22 @@ public class Session {
*/ */
public void forceDisconnect(String connectionId) throws OpenViduJavaClientException, OpenViduHttpException { public void forceDisconnect(String connectionId) throws OpenViduJavaClientException, OpenViduHttpException {
try { final HttpClientResponseHandler<Void> responseHandler = new HttpClientResponseHandler<Void>() {
@Override
HttpRequest request = this.openVidu.addHeaders(HttpRequest public Void handleResponse(final ClassicHttpResponse response) throws IOException, HttpException {
.newBuilder().DELETE().uri(new URI(this.openVidu.hostname + OpenVidu.API_SESSIONS + "/" final int status = response.getCode();
+ this.sessionId + "/connection/" + connectionId)) if (status == HttpStatus.SC_NO_CONTENT) {
.timeout(Duration.ofMillis(this.openVidu.requestTimeout))).build();
HttpResponse<String> response = this.openVidu.httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == HttpURLConnection.HTTP_NO_CONTENT) {
// Remove connection from activeConnections map // Remove connection from activeConnections map
Connection connectionClosed = this.connections.remove(connectionId); Connection connectionClosed = connections.remove(connectionId);
// Remove every Publisher of the closed connection from every subscriber list of // Remove every Publisher of the closed connection from every subscriber list of
// other connections // other connections
if (connectionClosed != null) { if (connectionClosed != null) {
for (Publisher publisher : connectionClosed.getPublishers()) { for (Publisher publisher : connectionClosed.getPublishers()) {
String streamId = publisher.getStreamId(); String streamId = publisher.getStreamId();
for (Connection connection : this.connections.values()) { for (Connection connection : connections.values()) {
connection.setSubscribers(connection.getSubscribers().stream() connection.setSubscribers(connection.getSubscribers().stream()
.filter(subscriber -> !streamId.equals(subscriber)).collect(Collectors.toList())); .filter(subscriber -> !streamId.equals(subscriber))
.collect(Collectors.toList()));
} }
} }
} else { } else {
@ -358,11 +367,19 @@ public class Session {
} }
log.info("Connection {} closed", connectionId); log.info("Connection {} closed", connectionId);
} else { } else {
throw new OpenViduHttpException(response.statusCode()); throw OpenVidu.openViduHttpException(status);
} }
return null;
}
};
} catch (URISyntaxException | IOException | InterruptedException e) { HttpDelete request = new HttpDelete(
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); this.openVidu.hostname + OpenVidu.API_SESSIONS + "/" + this.sessionId + "/connection/" + connectionId);
try {
this.openVidu.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw OpenVidu.ioExceptionToOpenViduHttpException(e);
} }
} }
@ -409,20 +426,12 @@ public class Session {
*/ */
public void forceUnpublish(String streamId) throws OpenViduJavaClientException, OpenViduHttpException { public void forceUnpublish(String streamId) throws OpenViduJavaClientException, OpenViduHttpException {
try { final HttpClientResponseHandler<Void> responseHandler = new HttpClientResponseHandler<Void>() {
@Override
HttpRequest request = this.openVidu public Void handleResponse(final ClassicHttpResponse response) throws IOException, HttpException {
.addHeaders(HttpRequest.newBuilder().DELETE() final int status = response.getCode();
.uri(new URI(this.openVidu.hostname + OpenVidu.API_SESSIONS + "/" + this.sessionId if (status == HttpStatus.SC_NO_CONTENT) {
+ "/stream/" + streamId)) for (Connection connection : connections.values()) {
.timeout(Duration.ofMillis(this.openVidu.requestTimeout)))
.build();
HttpResponse<String> response = this.openVidu.httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == HttpURLConnection.HTTP_NO_CONTENT) {
for (Connection connection : this.connections.values()) {
// Try to remove the Publisher from the Connection publishers collection // Try to remove the Publisher from the Connection publishers collection
if (connection.publishers.remove(streamId) != null) { if (connection.publishers.remove(streamId) != null) {
continue; continue;
@ -432,11 +441,19 @@ public class Session {
} }
log.info("Stream {} unpublished", streamId); log.info("Stream {} unpublished", streamId);
} else { } else {
throw new OpenViduHttpException(response.statusCode()); throw OpenVidu.openViduHttpException(status);
} }
return null;
}
};
} catch (URISyntaxException | IOException | InterruptedException e) { HttpDelete request = new HttpDelete(
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); this.openVidu.hostname + OpenVidu.API_SESSIONS + "/" + this.sessionId + "/stream/" + streamId);
try {
this.openVidu.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw OpenVidu.ioExceptionToOpenViduHttpException(e);
} }
} }
@ -481,45 +498,47 @@ public class Session {
public Connection updateConnection(String connectionId, ConnectionProperties connectionProperties) public Connection updateConnection(String connectionId, ConnectionProperties connectionProperties)
throws OpenViduJavaClientException, OpenViduHttpException { throws OpenViduJavaClientException, OpenViduHttpException {
try { final HttpClientResponseHandler<Connection> responseHandler = new HttpClientResponseHandler<Connection>() {
@Override
JsonObject jsonPayload = connectionProperties.toJson(this.sessionId); public Connection handleResponse(final ClassicHttpResponse response) throws IOException, HttpException {
final int status = response.getCode();
HttpRequest request = this.openVidu.addHeaders(HttpRequest.newBuilder() if (status == HttpStatus.SC_OK) {
.method("PATCH", HttpRequest.BodyPublishers.ofString(jsonPayload.toString()))
.uri(new URI(this.openVidu.hostname + OpenVidu.API_SESSIONS + "/" + this.sessionId + "/connection/"
+ connectionId))
.setHeader("Content-Type", "application/json")
.timeout(Duration.ofMillis(this.openVidu.requestTimeout))).build();
HttpResponse<String> response = this.openVidu.httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == HttpURLConnection.HTTP_OK) {
log.info("Connection {} updated", connectionId); log.info("Connection {} updated", connectionId);
} else if (response.statusCode() == HttpURLConnection.HTTP_NO_CONTENT) { } else if (status == HttpStatus.SC_NO_CONTENT) {
log.info("Properties of Connection {} remain the same", connectionId); log.info("Properties of Connection {} remain the same", connectionId);
} else { } else {
throw new OpenViduHttpException(response.statusCode()); throw OpenVidu.openViduHttpException(status);
} }
JsonObject json = Utils.httpResponseToJson(response); JsonObject json = OpenVidu.httpResponseEntityToJson(response.getEntity());
// Update the actual Connection object with the new options // Update the actual Connection object with the new options
Connection existingConnection = this.connections.get(connectionId); Connection existingConnection = connections.get(connectionId);
if (existingConnection == null) { if (existingConnection == null) {
// The updated Connection is not available in local map // The updated Connection is not available in local map
Connection newConnection = new Connection(json); Connection newConnection = new Connection(json);
this.connections.put(connectionId, newConnection); connections.put(connectionId, newConnection);
return newConnection; return newConnection;
} else { } else {
// The updated Connection was available in local map // The updated Connection was available in local map
existingConnection.overrideConnectionProperties(connectionProperties); existingConnection.overrideConnectionProperties(connectionProperties);
return existingConnection; return existingConnection;
} }
}
};
} catch (URISyntaxException | IOException | InterruptedException e) { JsonObject json = connectionProperties.toJson(this.sessionId);
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); StringEntity params = new StringEntity(json.toString(), StandardCharsets.UTF_8);
HttpPatch request = new HttpPatch(
this.openVidu.hostname + OpenVidu.API_SESSIONS + "/" + this.sessionId + "/connection/" + connectionId);
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
request.setEntity(params);
try {
return this.openVidu.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw OpenVidu.ioExceptionToOpenViduHttpException(e);
} }
} }
@ -626,53 +645,59 @@ public class Session {
} }
private void getSessionHttp() throws OpenViduJavaClientException, OpenViduHttpException { private void getSessionHttp() throws OpenViduJavaClientException, OpenViduHttpException {
if (this.hasSessionId()) { if (this.hasSessionId()) {
return; return;
} }
try { final HttpClientResponseHandler<Void> responseHandler = new HttpClientResponseHandler<Void>() {
@Override
JsonObject json = properties.toJson(); public Void handleResponse(final ClassicHttpResponse response) throws IOException, HttpException {
final int status = response.getCode();
HttpRequest request = this.openVidu if (status == HttpStatus.SC_OK) {
.addHeaders(HttpRequest.newBuilder().POST(HttpRequest.BodyPublishers.ofString(json.toString())) JsonObject responseJson = OpenVidu.httpResponseEntityToJson(response.getEntity());
.uri(new URI(this.openVidu.hostname + OpenVidu.API_SESSIONS)) sessionId = responseJson.get("id").getAsString();
.setHeader("Content-Type", "application/json") createdAt = responseJson.get("createdAt").getAsLong();
.timeout(Duration.ofMillis(this.openVidu.requestTimeout)))
.build();
HttpResponse<String> response = this.openVidu.httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == HttpURLConnection.HTTP_OK) {
JsonObject responseJson = Utils.httpResponseToJson(response);
this.sessionId = responseJson.get("id").getAsString();
this.createdAt = responseJson.get("createdAt").getAsLong();
// Values that get filled by OpenVidu Server from its global or per-session // Values that get filled by OpenVidu Server from its global or per-session
// configuration // configuration
VideoCodec forcedVideoCodec = VideoCodec.valueOf(responseJson.get("forcedVideoCodec").getAsString()); VideoCodec forcedVideoCodec = VideoCodec
.valueOf(responseJson.get("forcedVideoCodec").getAsString());
Boolean allowTranscoding = responseJson.get("allowTranscoding").getAsBoolean(); Boolean allowTranscoding = responseJson.get("allowTranscoding").getAsBoolean();
SessionProperties responseProperties = new SessionProperties.Builder().mediaMode(properties.mediaMode()) SessionProperties responseProperties = new SessionProperties.Builder()
.recordingMode(properties.recordingMode()) .mediaMode(properties.mediaMode()).recordingMode(properties.recordingMode())
.defaultRecordingProperties(properties.defaultRecordingProperties()) .defaultRecordingProperties(properties.defaultRecordingProperties())
.customSessionId(properties.customSessionId()).mediaNode(properties.mediaNode()) .customSessionId(properties.customSessionId()).mediaNode(properties.mediaNode())
.forcedVideoCodec(forcedVideoCodec).allowTranscoding(allowTranscoding).build(); .forcedVideoCodec(forcedVideoCodec).allowTranscoding(allowTranscoding).build();
this.properties = responseProperties; properties = responseProperties;
log.info("Session '{}' created", this.sessionId); log.info("Session '{}' created", sessionId);
} else if (response.statusCode() == HttpURLConnection.HTTP_CONFLICT) { } else if (status == HttpStatus.SC_CONFLICT) {
// 'customSessionId' already existed // 'customSessionId' already existed
this.sessionId = properties.customSessionId(); sessionId = properties.customSessionId();
this.fetch(); try {
} else { fetch();
throw new OpenViduHttpException(response.statusCode()); } catch (OpenViduJavaClientException | OpenViduHttpException e) {
throw OpenVidu.openViduException(e);
} }
} else {
throw OpenVidu.openViduHttpException(status);
}
return null;
}
};
} catch (URISyntaxException | IOException | InterruptedException e) { JsonObject json = properties.toJson();
throw new OpenViduJavaClientException(e.getMessage(), e.getCause()); StringEntity params = new StringEntity(json.toString(), StandardCharsets.UTF_8);
HttpPost request = new HttpPost(this.openVidu.hostname + OpenVidu.API_SESSIONS);
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
request.setEntity(params);
try {
this.openVidu.httpClient.execute(request, responseHandler);
} catch (IOException e) {
throw OpenVidu.ioExceptionToOpenViduHttpException(e);
} }
} }

View File

@ -1,25 +1,10 @@
package io.openvidu.java.client; package io.openvidu.java.client;
import java.net.http.HttpResponse;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
/** /**
* @hidden * @hidden
*/ */
public class Utils { public class Utils {
public static JsonObject httpResponseToJson(HttpResponse<String> response) throws OpenViduJavaClientException {
try {
JsonObject json = new Gson().fromJson(response.body(), JsonObject.class);
return json;
} catch (JsonSyntaxException e) {
throw new OpenViduJavaClientException(e.getMessage(), e.getCause());
}
}
public static boolean isAcceptableRecordingResolution(String stringResolution) { public static boolean isAcceptableRecordingResolution(String stringResolution) {
// Matches every string with format "AxB", being A and B any number not starting // Matches every string with format "AxB", being A and B any number not starting
// with 0 and 3 digits long or 4 digits long if they start with 1 // with 0 and 3 digits long or 4 digits long if they start with 1

View File

@ -1,19 +1,28 @@
package io.openvidu.java.client.test; package io.openvidu.java.client.test;
import java.net.Authenticator; import java.util.List;
import java.net.CookieManager; import java.util.concurrent.TimeUnit;
import java.net.CookiePolicy;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.ProxySelector;
import java.net.http.HttpClient;
import java.net.http.HttpClient.Redirect;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.Executors;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import org.apache.hc.client5.http.auth.AuthCache;
import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.auth.BasicAuthCache;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.client5.http.impl.auth.BasicScheme;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.message.BasicHeader;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
@ -31,40 +40,57 @@ public class OpenViduConstructorTest {
} }
@Test @Test
public void buildWithHttpClientWithoutAuthenticator() { public void buildWithCustomHttpClient() {
HttpClient.Builder builder = HttpClient.newBuilder();
builder.connectTimeout(Duration.ofMillis(10000)); HttpClientBuilder builder = HttpClients.custom();
ProxySelector proxy = ProxySelector.of(new InetSocketAddress("https://my.proxy.hostname/", 4444));
builder.proxy(proxy); // Custom header
builder.followRedirects(Redirect.ALWAYS); BasicHeader header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
builder.setDefaultHeaders(List.of(header));
// Custom request timeout
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5, TimeUnit.SECONDS).build();
builder.setDefaultRequestConfig(requestConfig);
// Custom proxy to authenticate
HttpHost proxy = new HttpHost("https://localhost/", 8090);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(proxy),
new UsernamePasswordCredentials("username_admin", "secret_password".toCharArray()));
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(proxy, basicAuth);
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
context.setAuthCache(authCache);
builder.setRoutePlanner(routePlanner);
// Custom SSLContext
SSLContext sslContext = null; SSLContext sslContext = null;
try { try {
sslContext = SSLContext.getInstance("TLSv1.2"); sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, null); sslContext.init(null, null, null);
} catch (Exception e) { } catch (Exception e) {
} }
builder.sslContext(sslContext); final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create()
builder.executor(Executors.newFixedThreadPool(1)); .setSslContext(sslContext).build();
builder.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)); final HttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
OpenVidu OV = new OpenVidu("https://localhost:4443/", "MY_SECRET", builder.build()); .setSSLSocketFactory(sslSocketFactory).build();
Assertions.assertEquals(30000, OV.getRequestTimeout()); builder.setConnectionManager(connectionManager);
Assertions.assertTrue(OV.getRequestHeaders().isEmpty());
OV.setRequestTimeout(5000);
OV.setRequestHeaders(Map.of("header1", "value1", "header2", "value2"));
Assertions.assertEquals(5000, OV.getRequestTimeout());
Assertions.assertEquals(2, OV.getRequestHeaders().size());
}
@Test // Custom CredentialsProvider
public void buildWithHttpClientWithAuthenticator() { final BasicCredentialsProvider customCredentialsProvider = new BasicCredentialsProvider();
Authenticator authenticator = new Authenticator() { customCredentialsProvider.setCredentials(new AuthScope(null, -1),
@Override new UsernamePasswordCredentials("OPENVIDUAPP", "MY_SECRET".toCharArray()));
protected PasswordAuthentication getPasswordAuthentication() { builder.setDefaultCredentialsProvider(customCredentialsProvider);
return new PasswordAuthentication("OPENVIDUAPP", "secret".toCharArray());
} new OpenVidu("https://localhost", "MY_SECRET");
}; new OpenVidu("https://localhost", "MY_SECRET", builder);
HttpClient.Builder builder = HttpClient.newBuilder().authenticator(authenticator); new OpenVidu("https://localhost", builder);
new OpenVidu("https://localhost:4443/", "MY_SECRET", builder.build());
} }
} }

View File

@ -20,13 +20,11 @@ package io.openvidu.test.e2e;
import static org.junit.jupiter.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.fail;
import java.io.File; import java.io.File;
import java.net.Authenticator;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.Socket;
import java.net.http.HttpClient;
import java.security.KeyManagementException; import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import java.security.cert.X509Certificate;
import java.util.Arrays; import java.util.Arrays;
import java.util.Base64; import java.util.Base64;
@ -43,11 +41,22 @@ import java.util.function.BiFunction;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509ExtendedTrustManager;
import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.RandomStringUtils;
import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.io.HttpClientConnectionManager;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactoryBuilder;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Disabled;
@ -2440,127 +2449,167 @@ public class OpenViduTestAppE2eTest extends AbstractOpenViduTestappE2eTest {
gracefullyLeaveParticipants(user, 2); gracefullyLeaveParticipants(user, 2);
} }
private HttpClientBuilder getHttpClientBuilder() {
HttpClientBuilder builder = HttpClients.custom();
TrustStrategy trustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
};
SSLContext sslContext;
try {
sslContext = new SSLContextBuilder().loadTrustMaterial(null, trustStrategy).build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
throw new RuntimeException(e);
}
final SSLConnectionSocketFactory sslSocketFactory = SSLConnectionSocketFactoryBuilder.create()
.setSslContext(sslContext).build();
final HttpClientConnectionManager connectionManager = PoolingHttpClientConnectionManagerBuilder.create()
.setSSLSocketFactory(sslSocketFactory).build();
builder.setConnectionManager(connectionManager);
return builder;
}
@Test @Test
@DisplayName("openvidu-java-client custom HttpClient test") @DisplayName("openvidu-java-client custom HttpClient test")
void openViduJavaClientCustomHttpClientTest() throws Exception { void openViduJavaClientCustomHttpClientTest() throws Exception {
log.info("openvidu-java-client custom HttpClient test");
// Test all possible combinations: custom Authenticator present and valid, // Test all possible combinations: custom Authenticator present and valid,
// present and wrong and no present; in combination with custom Authorization // present and wrong and no present; in combination with custom Authorization
// header present and valid, present and wrong and no present // header present and valid, present and wrong and no present
HttpClient.Builder builder = HttpClient.newBuilder();
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[] { new X509ExtendedTrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(final X509Certificate[] a_certificates, final String a_auth_type) {
}
public void checkServerTrusted(final X509Certificate[] a_certificates, final String a_auth_type) {
}
public void checkClientTrusted(final X509Certificate[] a_certificates, final String a_auth_type,
final Socket a_socket) {
}
public void checkServerTrusted(final X509Certificate[] a_certificates, final String a_auth_type,
final Socket a_socket) {
}
public void checkClientTrusted(final X509Certificate[] a_certificates, final String a_auth_type,
final SSLEngine a_engine) {
}
public void checkServerTrusted(final X509Certificate[] a_certificates, final String a_auth_type,
final SSLEngine a_engine) {
}
} }, null);
} catch (KeyManagementException | NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
builder.sslContext(sslContext);
final String BASIC_AUTH = "Basic "
+ Base64.getEncoder().encodeToString(("OPENVIDUAPP:" + OPENVIDU_SECRET).getBytes());
final String WRONG_SECRET = "WRONG_SECRET_" + RandomStringUtils.randomAlphanumeric(10); final String WRONG_SECRET = "WRONG_SECRET_" + RandomStringUtils.randomAlphanumeric(10);
// 1. No authenticator, no header, 200 final String VALID_BASIC_AUTH = "Basic "
OpenVidu customHttpClientOV1 = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET, builder.build()); + Base64.getEncoder().encodeToString(("OPENVIDUAPP:" + OPENVIDU_SECRET).getBytes());
customHttpClientOV1.fetch(); final String WRONG_BASIC_AUTH = "Basic "
+ Base64.getEncoder().encodeToString(("OPENVIDUAPP:" + WRONG_SECRET).getBytes());
// 2. No authenticator, wrong header, 401 final Collection<Header> VALID_AUTH_HEADER = List
customHttpClientOV1.setRequestHeaders(Map.of("Authorization", "WRONG_AUTH_HEADER")); .of(new BasicHeader(HttpHeaders.AUTHORIZATION, VALID_BASIC_AUTH));
final Collection<Header> WRONG_AUTH_HEADER = List
.of(new BasicHeader(HttpHeaders.AUTHORIZATION, WRONG_BASIC_AUTH));
// 1. No valid certificate with no forgiving SSLContext
OpenVidu[] customOV = { new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET, HttpClients.custom()) };
Assertions.assertThrows(OpenViduJavaClientException.class, () -> {
customOV[0].fetch();
});
// 2. No CredentialsProvider, no Authorization header, no secret, 401
customOV[0] = new OpenVidu(OPENVIDU_URL, getHttpClientBuilder());
OpenViduHttpException thrown = Assertions.assertThrows(OpenViduHttpException.class, () -> { OpenViduHttpException thrown = Assertions.assertThrows(OpenViduHttpException.class, () -> {
customHttpClientOV1.fetch(); customOV[0].fetch();
}); });
Assertions.assertEquals(401, thrown.getStatus()); Assertions.assertEquals(401, thrown.getStatus());
// 3. No authenticator and valid header, 200 // 3. No CredentialsProvider, no Authorization header, valid secret, 200
customHttpClientOV1.setRequestHeaders(Map.of("Authorization", BASIC_AUTH)); customOV[0] = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET, getHttpClientBuilder());
customHttpClientOV1.fetch(); customOV[0].fetch();
// 4. Wrong authenticator and no header, 401 // 4. No CredentialsProvider, no Authorization header, wrong secret, 401
builder.authenticator(new Authenticator() { customOV[0] = new OpenVidu(OPENVIDU_URL, WRONG_SECRET, getHttpClientBuilder());
@Override thrown = Assertions.assertThrows(OpenViduHttpException.class, () -> {
protected PasswordAuthentication getPasswordAuthentication() { customOV[0].fetch();
return new PasswordAuthentication("OPENVIDUAPP", WRONG_SECRET.toCharArray());
}
}); });
OpenVidu customHttpClientOV2 = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET, builder.build()); Assertions.assertEquals(401, thrown.getStatus());
OpenViduJavaClientException thrown2 = Assertions.assertThrows(OpenViduJavaClientException.class, () -> {
customHttpClientOV2.fetch(); // 5. No CredentialsProvider, wrong Authorization header, no secret, 401
HttpClientBuilder builder = getHttpClientBuilder();
builder.setDefaultHeaders(WRONG_AUTH_HEADER);
customOV[0] = new OpenVidu(OPENVIDU_URL, builder);
thrown = Assertions.assertThrows(OpenViduHttpException.class, () -> {
customOV[0].fetch();
}); });
Assertions.assertTrue(thrown2.getMessage().contains("too many authentication attempts")); Assertions.assertEquals(401, thrown.getStatus());
// 5. Wrong authenticator and wrong header, 401 // 6. No CredentialsProvider, wrong Authorization header, valid secret, 200
customHttpClientOV2.setRequestHeaders(Map.of("Authorization", "WRONG_AUTH_HEADER")); builder = getHttpClientBuilder();
thrown2 = Assertions.assertThrows(OpenViduJavaClientException.class, () -> { builder.setDefaultHeaders(WRONG_AUTH_HEADER);
customHttpClientOV2.fetch(); customOV[0] = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET, builder);
customOV[0].fetch();
// 7. No CredentialsProvider, wrong Authorization header, wrong secret, 401
builder = getHttpClientBuilder();
builder.setDefaultHeaders(WRONG_AUTH_HEADER);
customOV[0] = new OpenVidu(OPENVIDU_URL, WRONG_SECRET, builder);
thrown = Assertions.assertThrows(OpenViduHttpException.class, () -> {
customOV[0].fetch();
}); });
Assertions.assertTrue(thrown2.getMessage().contains("too many authentication attempts")); Assertions.assertEquals(401, thrown.getStatus());
// 6. Wrong authenticator and valid header, 401 // 8. No CredentialsProvider, valid Authorization header, no secret, 200
customHttpClientOV2.setRequestHeaders(Map.of("Authorization", BASIC_AUTH)); builder = getHttpClientBuilder();
thrown2 = Assertions.assertThrows(OpenViduJavaClientException.class, () -> { builder.setDefaultHeaders(VALID_AUTH_HEADER);
customHttpClientOV2.fetch(); customOV[0] = new OpenVidu(OPENVIDU_URL, builder);
customOV[0].fetch();
// 9. No CredentialsProvider, valid Authorization header, valid secret, 200
builder = getHttpClientBuilder();
builder.setDefaultHeaders(VALID_AUTH_HEADER);
customOV[0] = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET, builder);
customOV[0].fetch();
// 10. No CredentialsProvider, valid Authorization header, wrong secret, 200
builder = getHttpClientBuilder();
builder.setDefaultHeaders(VALID_AUTH_HEADER);
customOV[0] = new OpenVidu(OPENVIDU_URL, WRONG_SECRET, builder);
customOV[0].fetch();
// 11. Valid CredentialsProvider, no Authorization header, no secret, 200
final BasicCredentialsProvider validCredentialsProvider = new BasicCredentialsProvider();
validCredentialsProvider.setCredentials(new AuthScope(null, -1),
new UsernamePasswordCredentials("OPENVIDUAPP", OPENVIDU_SECRET.toCharArray()));
builder = getHttpClientBuilder();
builder.setDefaultCredentialsProvider(validCredentialsProvider);
customOV[0] = new OpenVidu(OPENVIDU_URL, builder);
customOV[0].fetch();
// 12. Valid CredentialsProvider, valid Authorization header, no secret, 200
builder = getHttpClientBuilder();
builder.setDefaultCredentialsProvider(validCredentialsProvider);
builder.setDefaultHeaders(VALID_AUTH_HEADER);
customOV[0] = new OpenVidu(OPENVIDU_URL, builder);
customOV[0].fetch();
// 13. Valid CredentialsProvider, wrong Authorization header, no secret, 200
builder = getHttpClientBuilder();
builder.setDefaultCredentialsProvider(validCredentialsProvider);
builder.setDefaultHeaders(WRONG_AUTH_HEADER);
customOV[0] = new OpenVidu(OPENVIDU_URL, builder);
customOV[0].fetch();
// 14. Wrong CredentialsProvider, no Authorization header, no secret, 401
final BasicCredentialsProvider wrongCredentialsProvider = new BasicCredentialsProvider();
validCredentialsProvider.setCredentials(new AuthScope(null, -1),
new UsernamePasswordCredentials("OPENVIDUAPP", WRONG_SECRET.toCharArray()));
builder = getHttpClientBuilder();
builder.setDefaultCredentialsProvider(wrongCredentialsProvider);
customOV[0] = new OpenVidu(OPENVIDU_URL, builder);
thrown = Assertions.assertThrows(OpenViduHttpException.class, () -> {
customOV[0].fetch();
}); });
Assertions.assertTrue(thrown2.getMessage().contains("too many authentication attempts")); Assertions.assertEquals(401, thrown.getStatus());
// 7. Valid authenticator and no header, 200 // 15. Wrong CredentialsProvider, valid Authorization header, no secret, 200
builder.authenticator(new Authenticator() { builder = getHttpClientBuilder();
@Override builder.setDefaultCredentialsProvider(wrongCredentialsProvider);
protected PasswordAuthentication getPasswordAuthentication() { builder.setDefaultHeaders(VALID_AUTH_HEADER);
return new PasswordAuthentication("OPENVIDUAPP", OPENVIDU_SECRET.toCharArray()); customOV[0] = new OpenVidu(OPENVIDU_URL, builder);
} customOV[0].fetch();
// 16. Wrong CredentialsProvider, wrong Authorization header, no secret
builder = getHttpClientBuilder();
builder.setDefaultCredentialsProvider(wrongCredentialsProvider);
builder.setDefaultHeaders(WRONG_AUTH_HEADER);
customOV[0] = new OpenVidu(OPENVIDU_URL, builder);
thrown = Assertions.assertThrows(OpenViduHttpException.class, () -> {
customOV[0].fetch();
}); });
OpenVidu customHttpClientOV3 = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET, builder.build()); Assertions.assertEquals(401, thrown.getStatus());
customHttpClientOV3.fetch();
// 8. Valid authenticator and wrong header, 200
customHttpClientOV3.setRequestHeaders(Map.of("Authorization", "WRONG_AUTH_HEADER"));
customHttpClientOV3.fetch();
// 9. Valid authenticator and valid header, 200
customHttpClientOV3.setRequestHeaders(Map.of("Authorization", BASIC_AUTH));
customHttpClientOV3.fetch();
// 10. Wrong secret, valid authenticator, no header, 200
OpenVidu customHttpClientOV4 = new OpenVidu(OPENVIDU_URL, WRONG_SECRET, builder.build());
customHttpClientOV4.fetch();
// 11. Wrong secret, valid authenticator, wrong header, 200
customHttpClientOV4.setRequestHeaders(Map.of("Authorization", "WRONG_AUTH_HEADER"));
customHttpClientOV4.fetch();
// 12. Wrong secret, no authenticator, valid header, 200
builder = HttpClient.newBuilder().sslContext(sslContext);
customHttpClientOV4 = new OpenVidu(OPENVIDU_URL, WRONG_SECRET, builder.build());
customHttpClientOV4.setRequestHeaders(Map.of("Authorization", BASIC_AUTH));
customHttpClientOV4.fetch();
} }
@Test @Test