diff --git a/Lambdas/Lists/Item/src/Item.java b/Lambdas/Lists/Item/src/Item.java new file mode 100644 index 0000000..53ef341 --- /dev/null +++ b/Lambdas/Lists/Item/src/Item.java @@ -0,0 +1,52 @@ +import java.math.BigDecimal; +import java.sql.ResultSet; +import java.sql.SQLException; +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; + + Item(ResultSet itemRow) throws SQLException { + this.productID = itemRow.getInt(1); + System.out.println(this.productID); + this.chainID = itemRow.getInt(2); + System.out.println(this.chainID); + this.upc = itemRow.getString(3); + System.out.println(this.upc); + this.description = itemRow.getString(4); + System.out.println(this.description); + this.price = itemRow.getBigDecimal(5); + System.out.println(this.price); + this.imageURL = itemRow.getString(6); + System.out.println(imageURL); + this.department = itemRow.getString(7); + System.out.println(department); + this.retrievedDate = itemRow.getObject(8, LocalDateTime.class); + System.out.println(retrievedDate); + this.fetchCounts = itemRow.getInt(9); + System.out.println(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 + + '}'; + } +} diff --git a/Lambdas/Lists/Item/src/ItemAdder.java b/Lambdas/Lists/Item/src/ItemAdder.java index bea8cfa..c698a04 100644 --- a/Lambdas/Lists/Item/src/ItemAdder.java +++ b/Lambdas/Lists/Item/src/ItemAdder.java @@ -1,6 +1,9 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.HashMap; import java.util.Map; public class ItemAdder implements CallHandler { @@ -8,20 +11,28 @@ public class ItemAdder implements CallHandler { private DBConnector connector; private String cognitoID; - private final String LIST_CREATE = "INSERT INTO Items (Name) VALUES (?)"; + private final String ITEM_TO_LIST = "INSERT INTO ListProduct (productID, listID, quantity, addedDate, purchased) VALUES (?, ?, ?, ?, ?)"; public ItemAdder(DBConnector connector, String cognitoID) { this.connector = connector; this.cognitoID = cognitoID; } - public String conductAction(Map bodyMap, String queryString) throws SQLException { + public Object conductAction(Map bodyMap, HashMap queryString, String cognitoID) throws SQLException { Connection connection = connector.getConnection(); - PreparedStatement statement = connection.prepareStatement(LIST_CREATE); - statement.setString(1, bodyMap.get("name").toString());//Needs safe checking - System.out.println(statement); - statement.executeUpdate(); - connection.commit(); + try { + PreparedStatement statement = connection.prepareStatement(ITEM_TO_LIST); + statement.setInt(1, (Integer) bodyMap.get("itemID")); + statement.setInt(2, (Integer) bodyMap.get("listID")); + statement.setInt(3, (Integer) bodyMap.get("quantity")); + statement.setObject(4, Instant.now().atZone(ZoneOffset.UTC).toLocalDateTime()); + statement.setBoolean(5, (Boolean) bodyMap.get("purchased")); + System.out.println(statement); + statement.executeUpdate(); + connection.commit(); + } finally { + connection.close(); + } return null; } } diff --git a/Lambdas/Lists/Item/src/ItemGET.java b/Lambdas/Lists/Item/src/ItemGET.java index 3794b51..71c0804 100644 --- a/Lambdas/Lists/Item/src/ItemGET.java +++ b/Lambdas/Lists/Item/src/ItemGET.java @@ -3,9 +3,9 @@ import com.amazonaws.services.lambda.runtime.RequestHandler; import java.util.Map; -public class ItemGET implements RequestHandler, String> { +public class ItemGET implements RequestHandler, Object> { - public String handleRequest(Map inputMap, Context unfilled) { + public Object handleRequest(Map inputMap, Context unfilled) { return BasicHandler.handleRequest(inputMap, unfilled, ItemGetter.class); } } diff --git a/Lambdas/Lists/Item/src/ItemGetter.java b/Lambdas/Lists/Item/src/ItemGetter.java index 57a350c..2414e3a 100644 --- a/Lambdas/Lists/Item/src/ItemGetter.java +++ b/Lambdas/Lists/Item/src/ItemGetter.java @@ -1,9 +1,36 @@ +import com.google.gson.Gson; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; import java.sql.SQLException; +import java.util.HashMap; import java.util.Map; public class ItemGetter implements CallHandler{ + private final DBConnector connector; + + private final String GET_ITEM = "SELECT * FROM Product WHERE productID = ?;"; + + public ItemGetter(DBConnector connector, String cognitoID) { + this.connector = connector; + } + @Override - public String conductAction(Map bodyMap, String cognitoID) throws SQLException { - return null; + public Object conductAction(Map bodyMap, HashMap queryMap, String cognitoID) throws SQLException { + Connection connection = connector.getConnection(); + try { + PreparedStatement statement = connection.prepareStatement(GET_ITEM); + statement.setInt(1, Integer.parseInt(queryMap.get("id"))); + System.out.println(statement); + ResultSet queryResults = statement.executeQuery(); + queryResults.first(); + System.out.println(queryResults); + Item retrievedItem = new Item(queryResults); + System.out.println(retrievedItem); + return retrievedItem; + } finally { + connection.close(); + } } } diff --git a/Lambdas/Lists/Item/src/ItemPOST.java b/Lambdas/Lists/Item/src/ItemPOST.java index f2279c4..51d107f 100644 --- a/Lambdas/Lists/Item/src/ItemPOST.java +++ b/Lambdas/Lists/Item/src/ItemPOST.java @@ -3,9 +3,9 @@ import com.amazonaws.services.lambda.runtime.RequestHandler; import java.util.Map; -public class ItemPOST implements RequestHandler, String>{ +public class ItemPOST implements RequestHandler, Object> { - public String handleRequest(Map inputMap, Context unfilled) { + public Object handleRequest(Map inputMap, Context unfilled) { return BasicHandler.handleRequest(inputMap, unfilled, ItemAdder.class); } } diff --git a/Lambdas/Lists/List/src/ItemEntry.java b/Lambdas/Lists/List/src/ItemEntry.java new file mode 100644 index 0000000..b05ddc7 --- /dev/null +++ b/Lambdas/Lists/List/src/ItemEntry.java @@ -0,0 +1,16 @@ +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDateTime; + +public class ItemEntry { + Integer productID; + Integer quantity; + LocalDateTime addedDate; + Boolean purchased; + public ItemEntry(ResultSet listRow) throws SQLException { + productID = listRow.getInt(1); + quantity = listRow.getInt(2); + addedDate = listRow.getObject(3, LocalDateTime.class); + purchased = listRow.getBoolean(4); + } +} diff --git a/Lambdas/Lists/List/src/List.java b/Lambdas/Lists/List/src/List.java new file mode 100644 index 0000000..c2ac9c6 --- /dev/null +++ b/Lambdas/Lists/List/src/List.java @@ -0,0 +1,18 @@ +import java.sql.ResultSet; +import java.sql.SQLException; +import java.time.LocalDateTime; + +public class List { + Integer itemID; + String name; + String owner; + LocalDateTime lastUpdated; + + public List(ResultSet listRow) throws SQLException { + itemID = listRow.getInt(1); + name = listRow.getString(2); + owner = listRow.getString(3); + lastUpdated = listRow.getObject(8, LocalDateTime.class); + } + +} diff --git a/Lambdas/Lists/List/src/ListAdder.java b/Lambdas/Lists/List/src/ListAdder.java index d7f4982..eb56e36 100644 --- a/Lambdas/Lists/List/src/ListAdder.java +++ b/Lambdas/Lists/List/src/ListAdder.java @@ -1,6 +1,9 @@ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.HashMap; import java.util.Map; public class ListAdder implements CallHandler { @@ -8,18 +11,19 @@ public class ListAdder implements CallHandler { private DBConnector connector; private String cognitoID; - private final String LIST_CREATE = "INSERT INTO Lists (Name, Owner) VALUES (?, ?)"; + private final String LIST_CREATE = "INSERT INTO List (name, owner, lastUpdated) VALUES (?, ?, ?)"; public ListAdder(DBConnector connector, String cognitoID) { this.connector = connector; this.cognitoID = cognitoID; } - public String conductAction(Map bodyMap, String queryString) throws SQLException { + public Object conductAction(Map bodyMap, HashMap queryString, String cognitoID) throws SQLException { Connection connection = connector.getConnection(); PreparedStatement statement = connection.prepareStatement(LIST_CREATE); statement.setString(1, bodyMap.get("name").toString());//Needs safe checking statement.setString(2, cognitoID); + statement.setObject(3, Instant.now().atZone(ZoneOffset.UTC).toLocalDateTime()); System.out.println(statement); statement.executeUpdate(); connection.commit(); diff --git a/Lambdas/Lists/List/src/ListGET.java b/Lambdas/Lists/List/src/ListGET.java new file mode 100644 index 0000000..12a0889 --- /dev/null +++ b/Lambdas/Lists/List/src/ListGET.java @@ -0,0 +1,12 @@ +import com.amazonaws.services.lambda.runtime.Context; +import com.amazonaws.services.lambda.runtime.RequestHandler; + +import java.util.Map; + +public class ListGET implements RequestHandler, Object> { + + public Object handleRequest(Map inputMap, Context unfilled) { + return BasicHandler.handleRequest(inputMap, unfilled, ListGetter.class); + } + +} \ No newline at end of file diff --git a/Lambdas/Lists/List/src/ListGetter.java b/Lambdas/Lists/List/src/ListGetter.java new file mode 100644 index 0000000..9e8596a --- /dev/null +++ b/Lambdas/Lists/List/src/ListGetter.java @@ -0,0 +1,39 @@ +import com.google.gson.Gson; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.Map; + +public class ListGetter implements CallHandler{ + private final DBConnector connector; + private final String cognitoID; + + private final String GET_LIST = "SELECT * FROM List WHERE listID = ?;"; + + public ListGetter(DBConnector connector, String cognitoID) { + this.connector = connector; + this.cognitoID = cognitoID; + } + + @Override + public Object conductAction(Map bodyMap, HashMap queryMap, String cognitoID) throws SQLException { + Connection connection = connector.getConnection(); + try { + PreparedStatement statement = connection.prepareStatement(GET_LIST); + statement.setInt(1, Integer.parseInt(queryMap.get("id"))); + System.out.println(statement); + ResultSet queryResults = statement.executeQuery(); + queryResults.first(); + System.out.println(queryResults); + String returnValue; + List retrievedItem = new List(queryResults); + System.out.println(retrievedItem); + return retrievedItem; + } finally { + connection.close(); + } + } +} diff --git a/Lambdas/Lists/List/src/ListPOST.java b/Lambdas/Lists/List/src/ListPOST.java index 13c2785..4d47863 100644 --- a/Lambdas/Lists/List/src/ListPOST.java +++ b/Lambdas/Lists/List/src/ListPOST.java @@ -3,9 +3,9 @@ import java.util.Map; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; -public class ListPOST implements RequestHandler, String>{ +public class ListPOST implements RequestHandler, Object>{ - public String handleRequest(Map inputMap, Context unfilled) { + public Object handleRequest(Map inputMap, Context unfilled) { return BasicHandler.handleRequest(inputMap, unfilled, ListAdder.class); } } diff --git a/Lambdas/Lists/pom.xml b/Lambdas/Lists/pom.xml index 8d77579..1984615 100644 --- a/Lambdas/Lists/pom.xml +++ b/Lambdas/Lists/pom.xml @@ -39,6 +39,16 @@ mariadb-java-client 2.7.0 + + org.apache.httpcomponents + httpclient + 4.5 + + + com.google.code.gson + gson + 2.8.6 + 1.11 diff --git a/Lambdas/Lists/src/main/java/BasicHandler.java b/Lambdas/Lists/src/main/java/BasicHandler.java index 8b642eb..2a7ec6e 100644 --- a/Lambdas/Lists/src/main/java/BasicHandler.java +++ b/Lambdas/Lists/src/main/java/BasicHandler.java @@ -4,17 +4,19 @@ import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.sql.SQLException; +import java.util.HashMap; import java.util.Map; public class BasicHandler { - public static String handleRequest(Map inputMap, Context unfilled, Class toCall) { + public static Object handleRequest(Map inputMap, Context unfilled, Class toCall) { String cognitoID = InputUtils.getCognitoIDFromBody(inputMap); + HashMap queryMap = InputUtils.getQueryParams(inputMap); try { DBConnector connector = new DBConnector(); try { Constructor constructor = toCall.getConstructor(DBConnector.class, String.class); CallHandler callHandler = constructor.newInstance(connector, cognitoID); - callHandler.conductAction(InputUtils.getBody(inputMap), ""); + return callHandler.conductAction(InputUtils.getBody(inputMap), queryMap, cognitoID); } catch (SQLException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } finally { diff --git a/Lambdas/Lists/src/main/java/CallHandler.java b/Lambdas/Lists/src/main/java/CallHandler.java index ac5aa2a..a637412 100644 --- a/Lambdas/Lists/src/main/java/CallHandler.java +++ b/Lambdas/Lists/src/main/java/CallHandler.java @@ -1,6 +1,7 @@ import java.sql.SQLException; +import java.util.HashMap; import java.util.Map; public interface CallHandler { - String conductAction(Map bodyMap, String cognitoID) throws SQLException; + Object conductAction(Map bodyMap, HashMap queryString, String cognitoID) throws SQLException; } diff --git a/Lambdas/Lists/src/main/java/InputUtils.java b/Lambdas/Lists/src/main/java/InputUtils.java index b10781d..2a4e8bc 100644 --- a/Lambdas/Lists/src/main/java/InputUtils.java +++ b/Lambdas/Lists/src/main/java/InputUtils.java @@ -1,3 +1,9 @@ +import org.apache.http.NameValuePair; +import org.apache.http.client.utils.URLEncodedUtils; + +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; import java.util.Map; public class InputUtils { @@ -19,10 +25,24 @@ public class InputUtils { return getMap(inputMap, "body"); } - public static String getQueryString(Map inputMap) { + private static String getQueryString(Map inputMap) { return (String) (getMap(inputMap, "params").get("querystring")); } + public static HashMap getQueryParams(Map inputMap) { + return (HashMap) (getMap(inputMap, "params").get("querystring")); + +// String queryString = getQueryString(inputMap); +// List queryparams = URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8); +// HashMap mappedParams = new HashMap<>(); +// for (NameValuePair param : queryparams) { +// mappedParams.put(param.getName(), param.getValue()); +// } +// return mappedParams; + } + + + public static Map getMap(Map parentMap, String childKey) { if ((parentMap.get(childKey) != null) && (parentMap.get(childKey) instanceof Map)) { return ((Map) parentMap.get(childKey)); diff --git a/Listify/.idea/misc.xml b/Listify/.idea/misc.xml index fdae1d0..d5d35ec 100644 --- a/Listify/.idea/misc.xml +++ b/Listify/.idea/misc.xml @@ -1,6 +1,6 @@ - + diff --git a/Listify/app/build.gradle b/Listify/app/build.gradle index 099077a..0ad5dc3 100644 --- a/Listify/app/build.gradle +++ b/Listify/app/build.gradle @@ -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' } \ No newline at end of file diff --git a/Listify/app/src/main/java/com/example/listify/Item.java b/Listify/app/src/main/java/com/example/listify/Item.java new file mode 100644 index 0000000..f66f8ec --- /dev/null +++ b/Listify/app/src/main/java/com/example/listify/Item.java @@ -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 + + '}'; + } +} diff --git a/Listify/app/src/main/java/com/example/listify/MainActivity.java b/Listify/app/src/main/java/com/example/listify/MainActivity.java index 8260ed5..59c63d4 100644 --- a/Listify/app/src/main/java/com/example/listify/MainActivity.java +++ b/Listify/app/src/main/java/com/example/listify/MainActivity.java @@ -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 receiver = new SynchronousReceiver(); + requestor.getObject("1", Item.class, receiver, receiver); + try { + System.out.println(receiver.await()); + } catch (IOException receiverError) { + receiverError.printStackTrace(); + } + + //------------------------------------------------------------------------------------------// diff --git a/Listify/app/src/main/java/com/example/listify/Requestor.java b/Listify/app/src/main/java/com/example/listify/Requestor.java index 0c7b48d..3032c0d 100644 --- a/Listify/app/src/main/java/com/example/listify/Requestor.java +++ b/Listify/app/src/main/java/com/example/listify/Requestor.java @@ -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 void getObject(String id, Class classType, Receiver 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 void getObject(String id, Class classType, Receiver 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 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 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 getHeaders() { - HashMap 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 { - 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 { + void acceptDelivery(T delivered); + } + + public interface RequestErrorHandler { + void acceptError(IOException error); } } diff --git a/Listify/app/src/main/java/com/example/listify/SynchronousReceiver.java b/Listify/app/src/main/java/com/example/listify/SynchronousReceiver.java new file mode 100644 index 0000000..7272a3e --- /dev/null +++ b/Listify/app/src/main/java/com/example/listify/SynchronousReceiver.java @@ -0,0 +1,39 @@ +package com.example.listify; + +import java.io.IOException; + +public class SynchronousReceiver implements Requestor.Receiver, 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 + } +}