Lamdba Integration

Test Lamdbas with full pipeline of client through database
This commit is contained in:
NMerz 2020-10-03 23:00:19 -04:00
parent 1f361cf401
commit 81b4673766
18 changed files with 386 additions and 124 deletions

View File

@ -3,11 +3,13 @@ import java.sql.SQLException;
import java.time.LocalDateTime; import java.time.LocalDateTime;
public class ItemEntry { public class ItemEntry {
Integer listID;
Integer productID; Integer productID;
Integer quantity; Integer quantity;
LocalDateTime addedDate; LocalDateTime addedDate;
Boolean purchased; Boolean purchased;
public ItemEntry(ResultSet listRow) throws SQLException { public ItemEntry(Integer listID, ResultSet listRow) throws SQLException {
this.listID = listID;
productID = listRow.getInt(1); productID = listRow.getInt(1);
quantity = listRow.getInt(2); quantity = listRow.getInt(2);
addedDate = listRow.getObject(3, LocalDateTime.class); addedDate = listRow.getObject(3, LocalDateTime.class);

View File

@ -1,5 +1,6 @@
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
@ -7,14 +8,14 @@ public class List {
Integer itemID; Integer itemID;
String name; String name;
String owner; String owner;
LocalDateTime lastUpdated; long lastUpdated;
ArrayList<ItemEntry> entries; ArrayList<ItemEntry> entries;
public List(ResultSet listRow) throws SQLException { public List(ResultSet listRow) throws SQLException {
itemID = listRow.getInt(1); itemID = listRow.getInt("listID");
name = listRow.getString(2); name = listRow.getString("name");
owner = listRow.getString(3); owner = listRow.getString("owner");
lastUpdated = listRow.getObject(4, LocalDateTime.class); lastUpdated = listRow.getTimestamp("lastUpdated").toInstant().toEpochMilli();
entries = new ArrayList<>(); entries = new ArrayList<>();
} }
@ -22,6 +23,17 @@ public class List {
entries.add(entry); entries.add(entry);
} }
@Override
public String toString() {
return "List{" +
"itemID=" + itemID +
", name='" + name + '\'' +
", owner='" + owner + '\'' +
", lastUpdated=" + lastUpdated +
", entries=" + entries +
'}';
}
public ItemEntry[] getEntries() { public ItemEntry[] getEntries() {
return entries.toArray(new ItemEntry[entries.size()]); return entries.toArray(new ItemEntry[entries.size()]);
} }
@ -50,11 +62,11 @@ public class List {
this.owner = owner; this.owner = owner;
} }
public LocalDateTime getLastUpdated() { public long getLastUpdated() {
return lastUpdated; return lastUpdated;
} }
public void setLastUpdated(LocalDateTime lastUpdated) { public void setLastUpdated(long lastUpdated) {
this.lastUpdated = lastUpdated; this.lastUpdated = lastUpdated;
} }
} }

View File

@ -1,6 +1,4 @@
import java.sql.Connection; import java.sql.*;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.Instant; import java.time.Instant;
import java.time.ZoneOffset; import java.time.ZoneOffset;
import java.util.HashMap; import java.util.HashMap;
@ -20,13 +18,16 @@ public class ListAdder implements CallHandler {
public Object conductAction(Map<String, Object> bodyMap, HashMap<String, String> queryString, String cognitoID) throws SQLException { public Object conductAction(Map<String, Object> bodyMap, HashMap<String, String> queryString, String cognitoID) throws SQLException {
Connection connection = connector.getConnection(); Connection connection = connector.getConnection();
PreparedStatement statement = connection.prepareStatement(LIST_CREATE); PreparedStatement statement = connection.prepareStatement(LIST_CREATE, Statement.RETURN_GENERATED_KEYS);
statement.setString(1, bodyMap.get("name").toString());//Needs safe checking statement.setString(1, bodyMap.get("name").toString());//Needs safe checking
statement.setString(2, cognitoID); statement.setString(2, cognitoID);
statement.setObject(3, Instant.now().atZone(ZoneOffset.UTC).toLocalDateTime()); statement.setTimestamp(3, Timestamp.from(Instant.now()));
System.out.println(statement); System.out.println(statement);
statement.executeUpdate(); statement.executeUpdate();
ResultSet newIDRS = statement.getGeneratedKeys();
newIDRS.first();
Integer newID = newIDRS.getInt(1);
connection.commit(); connection.commit();
return null; return newID;
} }
} }

View File

@ -23,13 +23,14 @@ public class ListGetter implements CallHandler{
@Override @Override
public Object conductAction(Map<String, Object> bodyMap, HashMap<String, String> queryMap, String cognitoID) throws SQLException { public Object conductAction(Map<String, Object> bodyMap, HashMap<String, String> queryMap, String cognitoID) throws SQLException {
Connection connection = connector.getConnection(); try (Connection connection = connector.getConnection()) {
Integer id = Integer.parseInt(queryMap.get("id")); Integer id = Integer.parseInt(queryMap.get("id"));
try {
if (id == -1) { if (id == -1) {
PreparedStatement getLists = connection.prepareStatement(GET_LISTS); PreparedStatement getLists = connection.prepareStatement(GET_LISTS);
getLists.setString(1, cognitoID); getLists.setString(1, cognitoID);
System.out.println(getLists);
ResultSet getListsResults = getLists.executeQuery(); ResultSet getListsResults = getLists.executeQuery();
System.out.println(getListsResults);
ArrayList<Integer> listIds = new ArrayList<>(); ArrayList<Integer> listIds = new ArrayList<>();
while (getListsResults.next()) { while (getListsResults.next()) {
listIds.add(getListsResults.getInt(1)); listIds.add(getListsResults.getInt(1));
@ -48,11 +49,10 @@ public class ListGetter implements CallHandler{
getListEntries.setInt(1, id); getListEntries.setInt(1, id);
ResultSet getEntryResults = getListEntries.executeQuery(); ResultSet getEntryResults = getListEntries.executeQuery();
while (getEntryResults.next()) { while (getEntryResults.next()) {
retrievedList.addItemEntry(new ItemEntry(getEntryResults)); retrievedList.addItemEntry(new ItemEntry(id, getEntryResults));
} }
System.out.println(retrievedList);
return retrievedList; return retrievedList;
} finally {
connection.close();
} }
} }
} }

View File

@ -6,14 +6,14 @@ import java.time.ZoneOffset;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class ItemAdder implements CallHandler { public class ListEntryAdder implements CallHandler {
private DBConnector connector; private DBConnector connector;
private String cognitoID; private String cognitoID;
private final String ITEM_TO_LIST = "INSERT INTO ListProduct (productID, listID, quantity, addedDate, purchased) VALUES (?, ?, ?, ?, ?)"; private final String ITEM_TO_LIST = "INSERT INTO ListProduct (productID, listID, quantity, addedDate, purchased) VALUES (?, ?, ?, ?, ?)";
public ItemAdder(DBConnector connector, String cognitoID) { public ListEntryAdder(DBConnector connector, String cognitoID) {
this.connector = connector; this.connector = connector;
this.cognitoID = cognitoID; this.cognitoID = cognitoID;
} }
@ -22,7 +22,7 @@ public class ItemAdder implements CallHandler {
Connection connection = connector.getConnection(); Connection connection = connector.getConnection();
try { try {
PreparedStatement statement = connection.prepareStatement(ITEM_TO_LIST); PreparedStatement statement = connection.prepareStatement(ITEM_TO_LIST);
statement.setInt(1, (Integer) bodyMap.get("itemID")); statement.setInt(1, (Integer) bodyMap.get("productID"));
statement.setInt(2, (Integer) bodyMap.get("listID")); statement.setInt(2, (Integer) bodyMap.get("listID"));
statement.setInt(3, (Integer) bodyMap.get("quantity")); statement.setInt(3, (Integer) bodyMap.get("quantity"));
statement.setObject(4, Instant.now().atZone(ZoneOffset.UTC).toLocalDateTime()); statement.setObject(4, Instant.now().atZone(ZoneOffset.UTC).toLocalDateTime());

View File

@ -3,9 +3,9 @@ import com.amazonaws.services.lambda.runtime.RequestHandler;
import java.util.Map; import java.util.Map;
public class ItemDELETE implements RequestHandler<Map<String,Object>, Object> { public class ListEntryDELETE implements RequestHandler<Map<String,Object>, Object> {
public Object handleRequest(Map<String, Object> inputMap, Context unfilled) { public Object handleRequest(Map<String, Object> inputMap, Context unfilled) {
return BasicHandler.handleRequest(inputMap, unfilled, ItemGetter.class); return BasicHandler.handleRequest(inputMap, unfilled, ListEntryDeleter.class);
} }
} }

View File

@ -4,14 +4,14 @@ import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class ItemDeleter implements CallHandler { public class ListEntryDeleter implements CallHandler {
private DBConnector connector; private DBConnector connector;
private String cognitoID; private String cognitoID;
private final String REMOVE_FROM_LIST = "DELETE FROM ListProduct WHERE (ProductID = ? AND ListID = ?);"; private final String REMOVE_FROM_LIST = "DELETE FROM ListProduct WHERE (ProductID = ? AND ListID = ?);";
public ItemDeleter(DBConnector connector, String cognitoID) { public ListEntryDeleter(DBConnector connector, String cognitoID) {
this.connector = connector; this.connector = connector;
this.cognitoID = cognitoID; this.cognitoID = cognitoID;
} }

View File

@ -3,9 +3,9 @@ import com.amazonaws.services.lambda.runtime.RequestHandler;
import java.util.Map; import java.util.Map;
public class ItemPOST implements RequestHandler<Map<String,Object>, Object> { public class ListEntryPOST implements RequestHandler<Map<String,Object>, Object> {
public Object handleRequest(Map<String, Object> inputMap, Context unfilled) { public Object handleRequest(Map<String, Object> inputMap, Context unfilled) {
return BasicHandler.handleRequest(inputMap, unfilled, ItemAdder.class); return BasicHandler.handleRequest(inputMap, unfilled, ListEntryAdder.class);
} }
} }

View File

@ -24,7 +24,7 @@ public class BasicHandler {
} }
} catch (IOException |SQLException|ClassNotFoundException e) { } catch (IOException |SQLException|ClassNotFoundException e) {
e.printStackTrace(); e.printStackTrace();
throw new RuntimeException(e.getMessage()); throw new RuntimeException(e.getLocalizedMessage());
} }
return null; return null;
} }

View File

@ -44,6 +44,13 @@ public class AuthManager {
} }
public String getUserToken() { public String getUserToken() {
if (authSession == null) {
try {
fetchAuthSession();
} catch (AuthException e) {
e.printStackTrace();
}
}
return authSession.getUserPoolTokens().getValue().getIdToken(); return authSession.getUserPoolTokens().getValue().getIdToken();
} }

View File

@ -1,44 +0,0 @@
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

@ -1,8 +0,0 @@
package com.example.listify;
public class List {
String name;
List(String name) {
this.name = name;
}
}

View File

@ -13,11 +13,18 @@ import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI; import androidx.navigation.ui.NavigationUI;
import com.amplifyframework.auth.AuthException; import com.amplifyframework.auth.AuthException;
import com.example.listify.data.Item;
import com.example.listify.data.ListEntry;
import com.example.listify.data.List;
import com.google.android.material.navigation.NavigationView; import com.google.android.material.navigation.NavigationView;
import org.json.JSONException; import org.json.JSONException;
import java.io.IOException; import java.io.IOException;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.Properties; import java.util.Properties;
import java.util.Random;
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration; private AppBarConfiguration mAppBarConfiguration;
@ -29,6 +36,10 @@ public class MainActivity extends AppCompatActivity {
//------------------------------Auth Testing---------------------------------------------// //------------------------------Auth Testing---------------------------------------------//
boolean testAuth = false;
if (testAuth) {
AuthManager authManager = new AuthManager(); AuthManager authManager = new AuthManager();
try { try {
authManager.signIn("merzn@purdue.edu", "Password123"); authManager.signIn("merzn@purdue.edu", "Password123");
@ -43,13 +54,20 @@ public class MainActivity extends AppCompatActivity {
Log.e("Authentication", "SignUp error: " + signUpError.getMessage()); Log.e("Authentication", "SignUp error: " + signUpError.getMessage());
} }
} }
}
//------------------------------------------------------------------------------------------// //------------------------------------------------------------------------------------------//
boolean testAPI = true;
//----------------------------------API Testing---------------------------------------------// //----------------------------------API Testing---------------------------------------------//
if (testAPI) {
AuthManager authManager = new AuthManager();
try {
authManager.signIn("merzn@purdue.edu", "Password123");
} catch (AuthException e) {
e.printStackTrace();
}
Properties configs = new Properties(); Properties configs = new Properties();
try { try {
configs = AuthManager.loadProperties(this, "android.resource://" + getPackageName() + "/raw/auths.json"); configs = AuthManager.loadProperties(this, "android.resource://" + getPackageName() + "/raw/auths.json");
@ -58,22 +76,33 @@ public class MainActivity extends AppCompatActivity {
} }
Requestor requestor = new Requestor(authManager, configs.getProperty("apiKey")); Requestor requestor = new Requestor(authManager, configs.getProperty("apiKey"));
List testList = new List("IAmATestList"); //The name is the only part of this that is used, the rest is generated by the Lambda.
List testList = new List(-1, "New List", "user filled by lambda", Instant.now().toEpochMilli());
//Everything except addedDate is used for ItemEntry
ListEntry entry = new ListEntry(1, 1, new Random().nextInt(), Instant.now().atZone(ZoneOffset.UTC).toLocalDateTime(),false);
SynchronousReceiver<Integer> idReceiver = new SynchronousReceiver<>();
try { try {
requestor.postObject(testList); requestor.postObject(testList, idReceiver, idReceiver);
} catch (JSONException e) { System.out.println(idReceiver.await());
requestor.postObject(entry);
} catch (JSONException | IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
SynchronousReceiver<Item> receiver = new SynchronousReceiver<Item>(); SynchronousReceiver<Item> itemReceiver = new SynchronousReceiver<>();
requestor.getObject("1", Item.class, receiver, receiver); requestor.getObject("1", Item.class, itemReceiver, itemReceiver);
SynchronousReceiver<List> listReceiver = new SynchronousReceiver<>();
requestor.getObject("39", List.class, listReceiver, listReceiver);
SynchronousReceiver<Integer[]> listIdsReceiver = new SynchronousReceiver<>();
requestor.getListOfIds(List.class, listIdsReceiver, listIdsReceiver);
try { try {
System.out.println(receiver.await()); System.out.println(itemReceiver.await());
System.out.println(listReceiver.await());
System.out.println(Arrays.toString(listIdsReceiver.await()));
} catch (IOException receiverError) { } catch (IOException receiverError) {
receiverError.printStackTrace(); receiverError.printStackTrace();
} }
}
//------------------------------------------------------------------------------------------// //------------------------------------------------------------------------------------------//

View File

@ -29,7 +29,7 @@ public class Requestor {
} }
public <T> void getListOfIds(Class<T> ofType, Receiver<Integer[]> successHandler, RequestErrorHandler failureHandler) { public <T> void getListOfIds(Class<T> ofType, Receiver<Integer[]> successHandler, RequestErrorHandler failureHandler) {
String getURL = DEV_BASEURL + "/" + ofType.getSimpleName() + "?list=-1"; String getURL = DEV_BASEURL + "/" + ofType.getSimpleName() + "?id=-1";
Request postRequest = buildBaseRequest(getURL, "GET", null); Request postRequest = buildBaseRequest(getURL, "GET", null);
launchCall(postRequest, successHandler, Integer[].class, failureHandler); launchCall(postRequest, successHandler, Integer[].class, failureHandler);
} }
@ -41,15 +41,22 @@ public class Requestor {
} }
public void postObject(Object toPost) throws JSONException { public void postObject(Object toPost) throws JSONException {
postObject(toPost, null); postObject(toPost, (RequestErrorHandler) null);
} }
public void postObject(Object toPost, RequestErrorHandler failureHandler) throws JSONException { public void postObject(Object toPost, RequestErrorHandler failureHandler) throws JSONException {
String postURL = DEV_BASEURL + "/" + toPost.getClass().getSimpleName(); postObject(toPost, null, failureHandler);
Request postRequest = buildBaseRequest(postURL, "POST", new Gson().toJson(toPost));
launchCall(postRequest, null, null, failureHandler);
} }
public void postObject(Object toPost, Receiver<Integer> idReceiver) throws JSONException {
postObject(toPost, idReceiver, null);
}
public void postObject(Object toPost, Receiver<Integer> idReceiver, RequestErrorHandler failureHandler) throws JSONException {
String postURL = DEV_BASEURL + "/" + toPost.getClass().getSimpleName();
Request postRequest = buildBaseRequest(postURL, "POST", new Gson().toJson(toPost));
launchCall(postRequest, idReceiver, Integer.class, failureHandler);
}
private void launchCall(Request toLaunch, Receiver receiver, Class classType, RequestErrorHandler failureHandler) { private void launchCall(Request toLaunch, Receiver receiver, Class classType, RequestErrorHandler failureHandler) {
client.newCall(toLaunch).enqueue(new Callback() { client.newCall(toLaunch).enqueue(new Callback() {

View File

@ -0,0 +1,116 @@
package com.example.listify.data;
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 == null ? null : retrievedDate) +
", fetchCounts=" + fetchCounts +
'}';
}
public Integer getProductID() {
return productID;
}
public void setProductID(Integer productID) {
this.productID = productID;
}
public Integer getChainID() {
return chainID;
}
public void setChainID(Integer chainID) {
this.chainID = chainID;
}
public String getUpc() {
return upc;
}
public void setUpc(String upc) {
this.upc = upc;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public LocalDateTime getRetrievedDate() {
return retrievedDate;
}
public void setRetrievedDate(LocalDateTime retrievedDate) {
this.retrievedDate = retrievedDate;
}
public Integer getFetchCounts() {
return fetchCounts;
}
public void setFetchCounts(Integer fetchCounts) {
this.fetchCounts = fetchCounts;
}
}

View File

@ -0,0 +1,70 @@
package com.example.listify.data;
import java.util.Arrays;
public class List {
Integer itemID;
String name;
String owner;
long lastUpdated;
final ListEntry[] entries;
public List(Integer itemID, String name, String owner, long lastUpdated, ListEntry[] entries) {
this.itemID = itemID;
this.name = name;
this.owner = owner;
this.lastUpdated = lastUpdated;
this.entries = entries;
}
public List(Integer itemID, String name, String owner, long lastUpdated) {
this(itemID, name, owner, lastUpdated, null);
}
@Override
public String toString() {
return "List{" +
"itemID=" + itemID +
", name='" + name + '\'' +
", owner='" + owner + '\'' +
", lastUpdated=" + lastUpdated +
", entries=" + Arrays.toString(entries) +
'}';
}
public Integer getItemID() {
return itemID;
}
public void setItemID(Integer itemID) {
this.itemID = itemID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public long getLastUpdated() {
return lastUpdated;
}
public void setLastUpdated(long lastUpdated) {
this.lastUpdated = lastUpdated;
}
public ListEntry[] getEntries() {
return entries;
}
}

View File

@ -0,0 +1,70 @@
package com.example.listify.data;
import java.time.LocalDateTime;
public class ListEntry {
Integer listID;
Integer productID;
Integer quantity;
LocalDateTime addedDate;
Boolean purchased;
public ListEntry(Integer listID, Integer productID, Integer quantity, LocalDateTime addedDate, Boolean purchased) {
this.listID = listID;
this.productID = productID;
this.quantity = quantity;
this.addedDate = addedDate;
this.purchased = purchased;
}
@Override
public String toString() {
return "ListEntry{" +
"listID=" + listID +
", productID=" + productID +
", quantity=" + quantity +
", addedDate=" + addedDate +
", purchased=" + purchased +
'}';
}
public Integer getListID() {
return listID;
}
public void setListID(Integer listID) {
this.listID = listID;
}
public Integer getProductID() {
return productID;
}
public void setProductID(Integer productID) {
this.productID = productID;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public LocalDateTime getAddedDate() {
return addedDate;
}
public void setAddedDate(LocalDateTime addedDate) {
this.addedDate = addedDate;
}
public Boolean getPurchased() {
return purchased;
}
public void setPurchased(Boolean purchased) {
this.purchased = purchased;
}
}

View File

@ -11,7 +11,7 @@ REL_SCRIPT_DIR=$(dirname "${BASH_SOURCE[0]}")
source ${REL_SCRIPT_DIR}/VarSetup.sh source ${REL_SCRIPT_DIR}/VarSetup.sh
RAWLAMBDA=$(aws lambda create-function --function-name ${functionName}${method} --zip-file fileb://${jarPath} --runtime ${LANGUAGE} --role ${LAMBDAROLE} --handler ${functionName}${method} 2>${DEBUGFILE}) RAWLAMBDA=$(aws lambda create-function --function-name ${functionName}${method} --zip-file fileb://${jarPath} --runtime ${LANGUAGE} --role ${LAMBDAROLE} --handler ${functionName}${method} --memory-size 512 2>${DEBUGFILE})
if [[ $? -ne 0 ]]; then if [[ $? -ne 0 ]]; then