-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathAsync.java
More file actions
518 lines (432 loc) · 20.5 KB
/
Async.java
File metadata and controls
518 lines (432 loc) · 20.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
package com.klippa.NativeScriptHTTP;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Stack;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.CertificatePinner;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
public class Async {
static final String TAG = "Async";
static ThreadPoolExecutor executor = null;
static ThreadPoolExecutor threadPoolExecutor() {
if (executor == null) {
int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
ThreadFactory backgroundPriorityThreadFactory = new PriorityThreadFactory(android.os.Process.THREAD_PRIORITY_BACKGROUND);
executor = new ThreadPoolExecutor(
NUMBER_OF_CORES * 2,
NUMBER_OF_CORES * 2,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
backgroundPriorityThreadFactory
);
}
return executor;
}
public interface CompleteCallback {
void onComplete(Object result, Object tag);
void onError(String error, Object tag);
}
static class PriorityThreadFactory implements ThreadFactory {
private final int mThreadPriority;
public PriorityThreadFactory(int threadPriority) {
mThreadPriority = threadPriority;
}
@Override
public Thread newThread(final Runnable runnable) {
Runnable wrapperRunnable = new Runnable() {
@Override
public void run() {
try {
android.os.Process.setThreadPriority(mThreadPriority);
} catch (Throwable t) {
}
runnable.run();
}
};
return new Thread(wrapperRunnable);
}
}
public static class Http {
private static final String GET_METHOD = "GET";
private static final String HEAD_METHOD = "HEAD";
private static OkHttpClient client;
private static MemoryCookieJar cookieJar;
private static CertificatePinner.Builder certificatePinnerBuilder;
private static ImageParseMethod imageParseMethod = ImageParseMethod.CONTENTTYPE;
private static boolean disableSslValidation = false;
public static void InitClient() {
if (cookieJar == null) {
cookieJar = new MemoryCookieJar();
}
if (client == null) {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.cookieJar(cookieJar);
if (disableSslValidation) {
// Disable ssl validations
try {
javax.net.ssl.TrustManager TRUST_ALL_CERTS = new javax.net.ssl.X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[] {};
}
};
javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContext.getInstance("SSL");
sslContext.init(null, new javax.net.ssl.TrustManager[] { TRUST_ALL_CERTS }, new java.security.SecureRandom());
builder.sslSocketFactory(sslContext.getSocketFactory(), (javax.net.ssl.X509TrustManager) TRUST_ALL_CERTS)
.hostnameVerifier(new javax.net.ssl.HostnameVerifier() {
@Override
public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
return true;
}
});
} catch (java.security.KeyManagementException e) {
e.printStackTrace();
} catch (java.security.NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
client = builder.build();
}
}
public static void MakeRequest(final RequestOptions options, final CompleteCallback callback, final Object context) {
InitClient();
final android.os.Handler mHandler = new android.os.Handler();
threadPoolExecutor().execute(new Runnable() {
@Override
public void run() {
final HttpRequestTask task = new HttpRequestTask(callback, context);
try {
final OkHttpClient client = task.buildClient(options);
final Request request = task.buildRequest(options);
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
final RequestResult result = new RequestResult();
result.error = e;
mHandler.post(new Runnable() {
@Override
public void run() {
task.onPostExecute(result);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final RequestResult result = task.parseResponse(response, options);
mHandler.post(new Runnable() {
@Override
public void run() {
task.onPostExecute(result);
}
});
}
});
} catch(Exception e) {
final RequestResult result = new RequestResult();
result.error = e;
mHandler.post(new Runnable() {
@Override
public void run() {
task.onPostExecute(result);
}
});
}
}
});
}
public static WebSocket GetWebSocketConnection(final RequestOptions options, final WebSocketListener listener) {
InitClient();
OkHttpClient.Builder clientBuilder = client.newBuilder();
// don't follow redirect (30x) responses; by default, HttpURLConnection follows them.
if (options.dontFollowRedirects) {
clientBuilder.followRedirects(false);
}
OkHttpClient client = clientBuilder.build();
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url(options.url);
if (options.headers != null) {
for (KeyValuePair pair : options.headers) {
String key = pair.key.toString();
requestBuilder.addHeader(key, pair.value.toString());
}
}
Request request = requestBuilder.build();
return client.newWebSocket(request, listener);
}
public static void ClearCookies() {
if (cookieJar != null) {
cookieJar.clear();
}
}
public static void DisableSSLValidation(boolean disable) {
client = null;
disableSslValidation = disable;
InitClient();
}
public static void SetImageParseMethod(ImageParseMethod newImageParseMethod) {
imageParseMethod = newImageParseMethod;
}
public static void SetConcurrencyLimits(int maxRequests, int maxRequestsPerHost) {
// Make sure we have a client.
InitClient();
client.dispatcher().setMaxRequests(maxRequests);
client.dispatcher().setMaxRequestsPerHost(maxRequestsPerHost);
}
public static void PinCertificate(String pattern, String[] hashes) {
// Make sure we have a client.
InitClient();
// Make sure we have a pinner.
if (certificatePinnerBuilder == null) {
certificatePinnerBuilder = new CertificatePinner.Builder();
}
// Add the pin.
certificatePinnerBuilder.add(pattern, hashes);
// Override the certificate pinner of the client.
client = client.newBuilder().certificatePinner(certificatePinnerBuilder.build()).build();
}
public static void RemoveCertificatePins() {
certificatePinnerBuilder = null;
// If we had a client, reset the pinner to the default.
if (client != null) {
client = client.newBuilder().certificatePinner(CertificatePinner.DEFAULT).build();
}
}
public enum ImageParseMethod {
NEVER,
CONTENTTYPE,
ALWAYS
}
public static class KeyValuePair {
public String key;
public String value;
public KeyValuePair(String key, String value) {
this.key = key;
this.value = value;
}
}
public static class RequestOptions {
public String url;
public String method;
public ArrayList<KeyValuePair> headers;
public RequestBody content;
public int timeout = -1;
public int screenWidth = -1;
public int screenHeight = -1;
public boolean dontFollowRedirects = false;
public boolean forceImageParsing = false;
public void addHeaders(Request.Builder requestBuilder) {
if (this.headers == null) {
return;
}
for (KeyValuePair pair : this.headers) {
String key = pair.key.toString();
requestBuilder.addHeader(key, pair.value.toString());
}
}
}
public static class RequestResult {
public ByteArrayOutputStream raw;
public ArrayList<KeyValuePair> headers = new ArrayList<KeyValuePair>();
public int statusCode;
public String responseAsString;
public Bitmap responseAsImage;
public Exception error;
public String url;
public String statusText;
public void getHeaders(Response response) {
Headers headers = response.headers();
if (headers == null) {
// no headers, this may happen if there is no internet connection currently available
return;
}
int size = headers.size();
if (size == 0) {
return;
}
for (int i = 0; i < headers.size(); i++) {
this.headers.add(new KeyValuePair(headers.name(i), headers.value(i)));
}
}
public void readResponseStream(Response response, Stack<Closeable> openedStreams, RequestOptions options) throws IOException {
ResponseBody responseBody = response.body();
if (responseBody == null) {
// responseBody can be null in case of no body.
return;
}
int contentLength = ((int) responseBody.contentLength());
InputStream inStream = responseBody.byteStream();
openedStreams.push(inStream);
BufferedInputStream buffer = new BufferedInputStream(inStream, 4096);
openedStreams.push(buffer);
ByteArrayOutputStream2 responseStream = contentLength != -1 ? new ByteArrayOutputStream2(contentLength) : new ByteArrayOutputStream2();
openedStreams.push(responseStream);
byte[] buff = new byte[4096];
int read = -1;
while ((read = buffer.read(buff, 0, buff.length)) != -1) {
responseStream.write(buff, 0, read);
}
this.raw = responseStream;
buff = null;
MediaType contentType = responseBody.contentType();
if (options.forceImageParsing || imageParseMethod == ImageParseMethod.ALWAYS || (imageParseMethod == ImageParseMethod.CONTENTTYPE && contentType != null && contentType.toString().startsWith("image/"))) {
// make the byte array conversion here, not in the JavaScript
// world for better performance
try {
// TODO: Generally this approach will not work for very
// large files
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inJustDecodeBounds = true;
// check the size of the bitmap first
BitmapFactory.decodeByteArray(responseStream.buf(), 0, responseStream.size(), bitmapOptions);
if (bitmapOptions.outWidth > 0 && bitmapOptions.outHeight > 0) {
int scale = 1;
final int height = bitmapOptions.outHeight;
final int width = bitmapOptions.outWidth;
if ((options.screenWidth > 0 && bitmapOptions.outWidth > options.screenWidth) ||
(options.screenHeight > 0 && bitmapOptions.outHeight > options.screenHeight)) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// scale down the image since it is larger than the
// screen resolution
while ((halfWidth / scale) > options.screenWidth && (halfHeight / scale) > options.screenHeight) {
scale *= 2;
}
}
bitmapOptions.inJustDecodeBounds = false;
bitmapOptions.inSampleSize = scale;
this.responseAsImage = BitmapFactory.decodeByteArray(responseStream.buf(), 0, responseStream.size(), bitmapOptions);
}
} catch (Exception e) {
Log.e(TAG, "Failed to decode byte array, Exception: " + e.getMessage());
}
}
if (this.responseAsImage == null) {
// convert to string
this.responseAsString = responseStream.toString();
}
}
public static final class ByteArrayOutputStream2 extends ByteArrayOutputStream {
public ByteArrayOutputStream2() {
super();
}
public ByteArrayOutputStream2(int size) {
super(size);
}
/**
* Returns the internal buffer of this ByteArrayOutputStream, without copying.
*/
public synchronized byte[] buf() {
return this.buf;
}
}
}
static class HttpRequestTask {
private CompleteCallback callback;
private Object context;
public HttpRequestTask(CompleteCallback callback, Object context) {
this.callback = callback;
this.context = context;
}
protected OkHttpClient buildClient(RequestOptions... params) {
RequestOptions options = params[0];
OkHttpClient.Builder clientBuilder = client.newBuilder();
// apply timeout
if (options.timeout > 0) {
clientBuilder.writeTimeout(options.timeout, TimeUnit.MILLISECONDS);
clientBuilder.readTimeout(options.timeout, TimeUnit.MILLISECONDS);
clientBuilder.connectTimeout(options.timeout, TimeUnit.MILLISECONDS);
}
// don't follow redirect (30x) responses; by default, HttpURLConnection follows them.
if (options.dontFollowRedirects) {
clientBuilder.followRedirects(false);
}
return clientBuilder.build();
}
protected Request buildRequest(RequestOptions... params) {
RequestOptions options = params[0];
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.url(options.url);
// set the request method
String requestMethod = options.method != null ? options.method.toUpperCase(Locale.ENGLISH) : GET_METHOD;
requestBuilder.method(requestMethod, options.content);
// add the headers
options.addHeaders(requestBuilder);
return requestBuilder.build();
}
protected RequestResult parseResponse(Response response, RequestOptions... params) {
RequestResult result = new RequestResult();
Stack<Closeable> openedStreams = new Stack<Closeable>();
try {
RequestOptions options = params[0];
String requestMethod = options.method != null ? options.method.toUpperCase(Locale.ENGLISH) : GET_METHOD;
// build the result
result.getHeaders(response);
result.url = options.url;
result.statusCode = response.code();
result.statusText = response.message();
if (!requestMethod.equals(HEAD_METHOD)) {
result.readResponseStream(response, openedStreams, options);
}
// close the opened streams (saves copy-paste implementation
// in each method that throws IOException)
this.closeOpenedStreams(openedStreams);
return result;
} catch (Exception e) // TODO: Catch all exceptions?
{
result.error = e;
return result;
} finally {
try {
this.closeOpenedStreams(openedStreams);
} catch (IOException e) {
Log.e(TAG, "Failed to close opened streams, IOException: " + e.getMessage());
}
}
}
protected void onPostExecute(final RequestResult result) {
if (result != null) {
this.callback.onComplete(result, this.context);
} else {
this.callback.onError("HttpRequestTask returns no result.", this.context);
}
}
private void closeOpenedStreams(Stack<Closeable> streams) throws IOException {
while (streams.size() > 0) {
Closeable stream = streams.pop();
stream.close();
}
}
}
}
}