|
|
@@ -4,6 +4,7 @@ import com.google.gson.Gson;
|
|
|
import com.google.gson.JsonElement;
|
|
|
import com.ning.http.client.AsyncCompletionHandler;
|
|
|
import com.ning.http.client.AsyncHttpClient;
|
|
|
+import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
|
|
|
import com.ning.http.client.Realm;
|
|
|
import com.ning.http.client.Response;
|
|
|
import uk.ac.ic.wlgitbridge.writelatex.api.request.exception.FailedConnectionException;
|
|
|
@@ -27,13 +28,51 @@ public abstract class Request<T extends Result> {
|
|
|
error = false;
|
|
|
}
|
|
|
|
|
|
+ public void request() {
|
|
|
+ switch (httpMethod()) {
|
|
|
+ case GET:
|
|
|
+ performGetRequest();
|
|
|
+ break;
|
|
|
+ case POST:
|
|
|
+ performPostRequest();
|
|
|
+ break;
|
|
|
+ default:
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ public T getResult() throws FailedConnectionException {
|
|
|
+ if (error) {
|
|
|
+ throw new FailedConnectionException();
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ return future.get();
|
|
|
+ } catch (InterruptedException e) {
|
|
|
+ throw new FailedConnectionException();
|
|
|
+ } catch (ExecutionException e) {
|
|
|
+ throw new FailedConnectionException();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ protected abstract HTTPMethod httpMethod();
|
|
|
protected abstract Realm buildRequestRealm();
|
|
|
protected abstract T parseResponse(JsonElement json) throws FailedConnectionException;
|
|
|
|
|
|
- public void request() {
|
|
|
- AsyncHttpClient client = new AsyncHttpClient();
|
|
|
+ protected String getPostBody() {
|
|
|
+ return "";
|
|
|
+ }
|
|
|
+
|
|
|
+ private void performGetRequest() {
|
|
|
+ request(new AsyncHttpClient().prepareGet(url));
|
|
|
+ }
|
|
|
+
|
|
|
+ private void performPostRequest() {
|
|
|
+ request(new AsyncHttpClient().preparePost(url).setBody(getPostBody()));
|
|
|
+ }
|
|
|
+
|
|
|
+ private void request(BoundRequestBuilder boundRequestBuilder) {
|
|
|
try {
|
|
|
- future = client.prepareGet(url).setRealm(buildRequestRealm()).execute(new AsyncCompletionHandler<T>() {
|
|
|
+ future = boundRequestBuilder.setRealm(buildRequestRealm()).execute(new AsyncCompletionHandler<T>() {
|
|
|
|
|
|
@Override
|
|
|
public T onCompleted(Response response) throws Exception {
|
|
|
@@ -51,17 +90,4 @@ public abstract class Request<T extends Result> {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
- public T getResult() throws FailedConnectionException {
|
|
|
- if (error) {
|
|
|
- throw new FailedConnectionException();
|
|
|
- }
|
|
|
- try {
|
|
|
- return future.get();
|
|
|
- } catch (InterruptedException e) {
|
|
|
- throw new FailedConnectionException();
|
|
|
- } catch (ExecutionException e) {
|
|
|
- throw new FailedConnectionException();
|
|
|
- }
|
|
|
- }
|
|
|
-
|
|
|
}
|