mirror of
https://github.com/ClaytonWWilson/Listify.git
synced 2025-12-15 18:28:47 +00:00
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:
parent
69572b3a1f
commit
f107ab023d
52
Lambdas/Lists/Item/src/Item.java
Normal file
52
Lambdas/Lists/Item/src/Item.java
Normal file
@ -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 +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@ -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<String, Object> bodyMap, String queryString) throws SQLException {
|
||||
public Object conductAction(Map<String, Object> bodyMap, HashMap<String, String> 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;
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,9 +3,9 @@ import com.amazonaws.services.lambda.runtime.RequestHandler;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class ItemGET implements RequestHandler<Map<String,Object>, String> {
|
||||
public class ItemGET implements RequestHandler<Map<String,Object>, Object> {
|
||||
|
||||
public String handleRequest(Map<String, Object> inputMap, Context unfilled) {
|
||||
public Object handleRequest(Map<String, Object> inputMap, Context unfilled) {
|
||||
return BasicHandler.handleRequest(inputMap, unfilled, ItemGetter.class);
|
||||
}
|
||||
}
|
||||
|
||||
@ -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<String, Object> bodyMap, String cognitoID) throws SQLException {
|
||||
return null;
|
||||
public Object conductAction(Map<String, Object> bodyMap, HashMap<String, String> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,9 +3,9 @@ import com.amazonaws.services.lambda.runtime.RequestHandler;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public class ItemPOST implements RequestHandler<Map<String,Object>, String>{
|
||||
public class ItemPOST implements RequestHandler<Map<String,Object>, Object> {
|
||||
|
||||
public String handleRequest(Map<String, Object> inputMap, Context unfilled) {
|
||||
public Object handleRequest(Map<String, Object> inputMap, Context unfilled) {
|
||||
return BasicHandler.handleRequest(inputMap, unfilled, ItemAdder.class);
|
||||
}
|
||||
}
|
||||
|
||||
16
Lambdas/Lists/List/src/ItemEntry.java
Normal file
16
Lambdas/Lists/List/src/ItemEntry.java
Normal file
@ -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);
|
||||
}
|
||||
}
|
||||
18
Lambdas/Lists/List/src/List.java
Normal file
18
Lambdas/Lists/List/src/List.java
Normal file
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@ -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<String, Object> bodyMap, String queryString) throws SQLException {
|
||||
public Object conductAction(Map<String, Object> bodyMap, HashMap<String, String> 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();
|
||||
|
||||
12
Lambdas/Lists/List/src/ListGET.java
Normal file
12
Lambdas/Lists/List/src/ListGET.java
Normal file
@ -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<Map<String,Object>, Object> {
|
||||
|
||||
public Object handleRequest(Map<String, Object> inputMap, Context unfilled) {
|
||||
return BasicHandler.handleRequest(inputMap, unfilled, ListGetter.class);
|
||||
}
|
||||
|
||||
}
|
||||
39
Lambdas/Lists/List/src/ListGetter.java
Normal file
39
Lambdas/Lists/List/src/ListGetter.java
Normal file
@ -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<String, Object> bodyMap, HashMap<String, String> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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<Map<String,Object>, String>{
|
||||
public class ListPOST implements RequestHandler<Map<String,Object>, Object>{
|
||||
|
||||
public String handleRequest(Map<String, Object> inputMap, Context unfilled) {
|
||||
public Object handleRequest(Map<String, Object> inputMap, Context unfilled) {
|
||||
return BasicHandler.handleRequest(inputMap, unfilled, ListAdder.class);
|
||||
}
|
||||
}
|
||||
|
||||
@ -39,6 +39,16 @@
|
||||
<artifactId>mariadb-java-client</artifactId>
|
||||
<version>2.7.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpclient</artifactId>
|
||||
<version>4.5</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.code.gson</groupId>
|
||||
<artifactId>gson</artifactId>
|
||||
<version>2.8.6</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<properties>
|
||||
<maven.compiler.source>1.11</maven.compiler.source>
|
||||
|
||||
@ -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 <T extends CallHandler> String handleRequest(Map<String, Object> inputMap, Context unfilled, Class<T> toCall) {
|
||||
public static <T extends CallHandler> Object handleRequest(Map<String, Object> inputMap, Context unfilled, Class<T> toCall) {
|
||||
String cognitoID = InputUtils.getCognitoIDFromBody(inputMap);
|
||||
HashMap<String, String> queryMap = InputUtils.getQueryParams(inputMap);
|
||||
try {
|
||||
DBConnector connector = new DBConnector();
|
||||
try {
|
||||
Constructor<T> 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 {
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public interface CallHandler {
|
||||
String conductAction(Map<String, Object> bodyMap, String cognitoID) throws SQLException;
|
||||
Object conductAction(Map<String, Object> bodyMap, HashMap<String, String> queryString, String cognitoID) throws SQLException;
|
||||
}
|
||||
|
||||
@ -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<String, Object> inputMap) {
|
||||
private static String getQueryString(Map<String, Object> inputMap) {
|
||||
return (String) (getMap(inputMap, "params").get("querystring"));
|
||||
}
|
||||
|
||||
public static HashMap<String, String> getQueryParams(Map<String, Object> inputMap) {
|
||||
return (HashMap<String, String>) (getMap(inputMap, "params").get("querystring"));
|
||||
|
||||
// String queryString = getQueryString(inputMap);
|
||||
// List<NameValuePair> queryparams = URLEncodedUtils.parse(queryString, StandardCharsets.UTF_8);
|
||||
// HashMap<String, String> mappedParams = new HashMap<>();
|
||||
// for (NameValuePair param : queryparams) {
|
||||
// mappedParams.put(param.getName(), param.getValue());
|
||||
// }
|
||||
// return mappedParams;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static Map<String, Object> getMap(Map<String, Object> parentMap, String childKey) {
|
||||
if ((parentMap.get(childKey) != null) && (parentMap.get(childKey) instanceof Map<?, ?>)) {
|
||||
return ((Map<String, Object>) parentMap.get(childKey));
|
||||
|
||||
@ -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">
|
||||
|
||||
@ -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'
|
||||
|
||||
}
|
||||
44
Listify/app/src/main/java/com/example/listify/Item.java
Normal file
44
Listify/app/src/main/java/com/example/listify/Item.java
Normal 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 +
|
||||
'}';
|
||||
}
|
||||
}
|
||||
@ -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();
|
||||
}
|
||||
|
||||
|
||||
//------------------------------------------------------------------------------------------//
|
||||
|
||||
|
||||
|
||||
@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@ -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
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user