GET strcuture

Build out infrastructure for get requests (along with the first couple).

This includes changing the request engine from Volley to OKHTTP due to issues get Volley's callbacks to call back.
This commit is contained in:
NMerz
2020-10-03 17:37:46 -04:00
parent 69572b3a1f
commit f107ab023d
21 changed files with 398 additions and 52 deletions

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="false" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" default="true" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" />
</component>
<component name="ProjectType">

View File

@@ -50,5 +50,6 @@ dependencies {
implementation 'org.json:json:20200518'
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
implementation 'com.squareup.okhttp3:okhttp:4.8.1'
}

View File

@@ -0,0 +1,44 @@
package com.example.listify;
import java.math.BigDecimal;
import java.time.LocalDateTime;
public class Item {
Integer productID;
Integer chainID;
String upc;
String description;
BigDecimal price;
String imageURL;
String department;
LocalDateTime retrievedDate;
Integer fetchCounts;
public Item(Integer productID, Integer chainID, String upc, String description, BigDecimal price,
String imageURL, String department, LocalDateTime retrievedDate, Integer fetchCounts) {
this.productID = productID;
this.chainID = chainID;
this.upc = upc;
this.description = description;
this.price = price;
this.imageURL = imageURL;
this.department = department;
this.retrievedDate = retrievedDate;
this.fetchCounts = fetchCounts;
}
@Override
public String toString() {
return "Item{" +
"productID=" + productID +
", chainID=" + chainID +
", upc='" + upc + '\'' +
", description='" + description + '\'' +
", price=" + price +
", imageURL='" + imageURL + '\'' +
", department='" + department + '\'' +
", retrievedDate=" + retrievedDate +
", fetchCounts=" + fetchCounts +
'}';
}
}

View File

@@ -25,6 +25,8 @@ public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//------------------------------Auth Testing---------------------------------------------//
AuthManager authManager = new AuthManager();
@@ -46,6 +48,7 @@ public class MainActivity extends AppCompatActivity {
//------------------------------------------------------------------------------------------//
//----------------------------------API Testing---------------------------------------------//
Properties configs = new Properties();
try {
@@ -54,7 +57,7 @@ public class MainActivity extends AppCompatActivity {
e.printStackTrace();
}
Requestor requestor = new Requestor(this, authManager,configs.getProperty("apiKey"));
Requestor requestor = new Requestor(authManager,configs.getProperty("apiKey"));
List testList = new List("IAmATestList");
try {
requestor.postObject(testList);
@@ -62,6 +65,15 @@ public class MainActivity extends AppCompatActivity {
e.printStackTrace();
}
SynchronousReceiver<Item> receiver = new SynchronousReceiver<Item>();
requestor.getObject("1", Item.class, receiver, receiver);
try {
System.out.println(receiver.await());
} catch (IOException receiverError) {
receiverError.printStackTrace();
}
//------------------------------------------------------------------------------------------//

View File

@@ -1,66 +1,104 @@
package com.example.listify;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.io.IOException;
public class Requestor {
private final String DEV_BASEURL = "https://datoh7woc9.execute-api.us-east-2.amazonaws.com/Development";
AuthManager authManager;
RequestQueue queue;
String apiKey;
OkHttpClient client;
Requestor(Context context, AuthManager authManager, String apiKey) {
queue = Volley.newRequestQueue(context);
Requestor(AuthManager authManager, String apiKey) {
this.authManager = authManager;
this.apiKey = apiKey;
client = new OkHttpClient();
}
public <T> void getObject(String id, Class<T> classType, Receiver<T> receiver) {
String getURL = DEV_BASEURL + "/" + classType.getSimpleName() + "?id=" + id;
getObject(id, classType, receiver, null);
}
public void postObject(Object toPost, Response.ErrorListener failureHandler) throws JSONException {
String postURL = DEV_BASEURL + "/" + toPost.getClass().getSimpleName();
queue.add(buildRequest(postURL, toPost, null, failureHandler));
public <T> void getObject(String id, Class<T> classType, Receiver<T> successHandler, RequestErrorHandler failureHandler) {
String getURL = DEV_BASEURL + "/" + classType.getSimpleName() + "?id=" + id;
Request postRequest = buildBaseRequest(getURL, "GET", null);
launchCall(postRequest, successHandler, classType, failureHandler);
}
public void postObject(Object toPost) throws JSONException {
postObject(toPost, null);
}
private JsonObjectRequest buildRequest(String url, Object toJSONify, Response.Listener<JSONObject> successHandler, Response.ErrorListener failureHandler) throws JSONException {
return buildRequest(url, new JSONObject(new Gson().toJson(toJSONify)), successHandler, failureHandler);
public void postObject(Object toPost, RequestErrorHandler failureHandler) throws JSONException {
String postURL = DEV_BASEURL + "/" + toPost.getClass().getSimpleName();
Request postRequest = buildBaseRequest(postURL, "POST", new Gson().toJson(toPost));
launchCall(postRequest, null, null, failureHandler);
}
private JsonObjectRequest buildRequest(String url, JSONObject jsonBody, Response.Listener<JSONObject> successHandler, Response.ErrorListener failureHandler) {
return new JsonObjectRequest(url, jsonBody, successHandler, failureHandler) {
private void launchCall(Request toLaunch, Receiver receiver, Class classType, RequestErrorHandler failureHandler) {
client.newCall(toLaunch).enqueue(new Callback() {
@Override
public Map<String, String> getHeaders() {
HashMap<String, String> headers = new HashMap<>();
System.out.println(authManager.getUserToken());
headers.put("Authorization", authManager.getUserToken());
headers.put("Content-Type", "application/json");
headers.put("X-API-Key", apiKey);
return headers;
public void onResponse(@NotNull Call call, @NotNull okhttp3.Response response) throws IOException {
String responseString = response.body().string();
if (receiver != null) {
if (classType == null) {
Log.e("Requestor Contract Error", "classType while receiver populated");
}
try {
receiver.acceptDelivery(new Gson().fromJson(responseString, classType));
} catch (JsonSyntaxException e) {
System.out.println(e);
Log.e("API response was not proper JSON", responseString);
throw new JsonSyntaxException(e);
}
}
Log.d("API Response", responseString);
}
};
@Override
public void onFailure(@NotNull Call call, IOException e) {
if (failureHandler != null) {
failureHandler.acceptError(e);
} else {
Log.e("Network Error", e.getLocalizedMessage());
}
}
});
}
public class Receiver<T> {
public void acceptDelivery(T delivered) {
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
private Request buildBaseRequest(String url, String method, String bodyJSON) {
Request.Builder requestBase = addAuthHeaders(new Request.Builder().url(url));
if (method == "GET") {
requestBase.get();
} else {
requestBase.method(method, RequestBody.create(bodyJSON, JSON));
}
return requestBase.build();
}
private Request.Builder addAuthHeaders(Request.Builder toAuthorize) {
toAuthorize.addHeader("Authorization", authManager.getUserToken());
toAuthorize.addHeader("X-API-Key", apiKey);
return toAuthorize;
}
public interface Receiver<T> {
void acceptDelivery(T delivered);
}
public interface RequestErrorHandler {
void acceptError(IOException error);
}
}

View File

@@ -0,0 +1,39 @@
package com.example.listify;
import java.io.IOException;
public class SynchronousReceiver<T> implements Requestor.Receiver<T>, Requestor.RequestErrorHandler {
private volatile boolean waiting;
private volatile IOException error;
private T toReturn;
public SynchronousReceiver() {
waiting = true;
error = null;
}
public T await() throws IOException {
while (waiting) {
Thread.yield();
}
waiting = true;
if (error != null) {
IOException toThrow = error;
error = null;
throw toThrow;
}
return toReturn;
}
@Override
public void acceptDelivery(Object delivered) {
toReturn = (T) delivered;
waiting = false;
}
@Override
public void acceptError(IOException error) {
waiting = false;
this.error = error
}
}