8
8
package com .opentok .util ;
9
9
10
10
import java .io .IOException ;
11
+ import java .net .InetSocketAddress ;
12
+ import java .net .Proxy ;
13
+ import java .net .SocketAddress ;
11
14
import java .util .Collection ;
12
15
import java .util .Map ;
13
16
import java .util .concurrent .ExecutionException ;
@@ -285,6 +288,7 @@ public String deleteArchive(String archiveId) throws RequestException {
285
288
public static class Builder {
286
289
private final int apiKey ;
287
290
private final String apiSecret ;
291
+ private Proxy proxy ;
288
292
private String apiUrl ;
289
293
private AsyncHttpClientConfig config ;
290
294
@@ -298,15 +302,48 @@ public Builder apiUrl(String apiUrl) {
298
302
return this ;
299
303
}
300
304
305
+ public Builder proxy (Proxy proxy ) {
306
+ this .proxy = proxy ;
307
+ return this ;
308
+ }
309
+
301
310
public HttpClient build () {
302
- this . config = new AsyncHttpClientConfig .Builder ()
311
+ AsyncHttpClientConfig . Builder configBuilder = new AsyncHttpClientConfig .Builder ()
303
312
.setUserAgent ("Opentok-Java-SDK/" + Version .VERSION + " JRE/" + System .getProperty ("java.version" ))
304
- .addRequestFilter (new PartnerAuthRequestFilter (this .apiKey , this .apiSecret ))
305
- .build ();
313
+ .addRequestFilter (new PartnerAuthRequestFilter (this .apiKey , this .apiSecret ));
314
+ if (this .proxy != null ) {
315
+ configBuilder .setProxyServer (createProxyServer (this .proxy ));
316
+ }
317
+ this .config = configBuilder .build ();
306
318
// NOTE: not thread-safe, config could be modified by another thread here?
307
319
HttpClient client = new HttpClient (this );
308
320
return client ;
309
321
}
322
+
323
+ // credit: https://github.com/AsyncHttpClient/async-http-client/blob/b52a8de5d6a862b5d1652d62f87ce774cbcff156/src/main/java/com/ning/http/client/ProxyServer.java#L99-L127
324
+ static ProxyServer createProxyServer (final Proxy proxy ) {
325
+ if (proxy .type ().equals (Proxy .Type .DIRECT )) {
326
+ return null ;
327
+ }
328
+
329
+ if (!proxy .type ().equals (Proxy .Type .HTTP )) {
330
+ throw new IllegalArgumentException ("Only DIRECT and HTTP Proxies are supported!" );
331
+ }
332
+
333
+ final SocketAddress sa = proxy .address ();
334
+
335
+ if (!(sa instanceof InetSocketAddress )) {
336
+ throw new IllegalArgumentException ("Only Internet Address sockets are supported!" );
337
+ }
338
+
339
+ InetSocketAddress isa = (InetSocketAddress ) sa ;
340
+
341
+ if (isa .isUnresolved ()) {
342
+ return new ProxyServer (isa .getHostName (), isa .getPort ());
343
+ } else {
344
+ return new ProxyServer (isa .getAddress ().getHostAddress (), isa .getPort ());
345
+ }
346
+ }
310
347
}
311
348
312
349
static class PartnerAuthRequestFilter implements RequestFilter {
0 commit comments