Datasets:
ArXiv:
License:
File size: 2,329 Bytes
c574d3a |
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 |
package httpcli;
import httpcli.adapter.RespBodyAdapter;
import java.util.concurrent.Future;
public class AsyncHttpCall<T>
implements HttpCall<T>, HttpCallback<T>, Runnable {
final RequestDispatcher dispatcher;
HttpCallback<T> callback;
Future future;
boolean cancel;
boolean running = false;
final HttpCli cli;
final HttpRequest request;
final RespBodyAdapter<T> adapter;
public AsyncHttpCall(HttpCli cli, HttpRequest request, RespBodyAdapter<T> adapter) {
this.cli = cli;
this.request = request;
this.adapter = adapter;
this.dispatcher = cli.dispatcher();
}
public AsyncHttpCall(HttpRequest request, RespBodyAdapter<T> adapter) {
this(request.cli, request, adapter);
}
@Override public HttpRequest request() {
return this.request;
}
@Override public HttpCallback<T> callback() {
return this.callback;
}
@Override public RespBodyAdapter<T> adapter() {
return this.adapter;
}
@Override public boolean isCancelled() {
return (this.future != null) ? this.future.isCancelled() : this.cancel;
}
@Override public boolean isDone() {
return (this.future != null) ? this.future.isDone() : false;
}
public boolean isRunning() {
return this.running;
}
@Override public void execute(HttpCallback<T> callback) {
this.callback = callback;
this.running = this.dispatcher.execute(this);
}
@Override public T execute() throws Exception {
return this.cli.execute(request(), adapter());
}
@Override public boolean cancel(boolean mayInterruptIfRunning) {
this.running = false;
if (this.future != null) {
return this.future.cancel(mayInterruptIfRunning);
} else {
this.cancel = true;
return false;
}
}
@Override public void onResponse(T result) throws Exception {
if (this.callback != null) this.callback.onResponse(result);
}
@Override public void onFailure(Exception e) {
if (this.callback != null) this.callback.onFailure(e);
}
@Override public void run() {
try {
T result = this.execute();
this.dispatcher.onResponse(this, result);
} catch (Exception e) {
this.dispatcher.onFailure(this, e);
}
this.running = false;
}
public void delivery(Runnable run) {
this.dispatcher.delivery(run);
}
}
|