Merge branch 'master' into connect-to-db

This commit is contained in:
Clayton Wilson 2020-10-08 19:29:11 -04:00 committed by GitHub
commit e16fafeaa0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
31 changed files with 2370 additions and 145 deletions

2
.gitignore vendored
View File

@ -88,3 +88,5 @@ Lambdas/Lists/src/main/resources/dbProperties.json
Lambdas/Lists/target/classes/dbProperties.json Lambdas/Lists/target/classes/dbProperties.json
Lambdas/Lists/target/classes/META-INF/Lists.kotlin_module Lambdas/Lists/target/classes/META-INF/Lists.kotlin_module
Listify/app/src/main/res/raw/auths.json Listify/app/src/main/res/raw/auths.json
Lambdas/Lists/target/surefire-reports/TestInputUtils.txt
Lambdas/Lists/target/surefire-reports/TEST-TestInputUtils.xml

View File

@ -1,5 +1,3 @@
import com.google.gson.Gson;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -7,30 +5,25 @@ import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class ItemGetter implements CallHandler{ public class ItemGetter implements CallHandler {
private final DBConnector connector; private final Connection connection;
private final String GET_ITEM = "SELECT * FROM Product WHERE productID = ?;"; private final String GET_ITEM = "SELECT * FROM Product WHERE productID = ?;";
public ItemGetter(DBConnector connector, String cognitoID) { public ItemGetter(Connection connection, String cognitoID) {
this.connector = connector; this.connection = connection;
} }
@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(); PreparedStatement statement = connection.prepareStatement(GET_ITEM);
try { statement.setInt(1, Integer.parseInt(queryMap.get("id")));
PreparedStatement statement = connection.prepareStatement(GET_ITEM); System.out.println(statement);
statement.setInt(1, Integer.parseInt(queryMap.get("id"))); ResultSet queryResults = statement.executeQuery();
System.out.println(statement); queryResults.first();
ResultSet queryResults = statement.executeQuery(); System.out.println(queryResults);
queryResults.first(); Item retrievedItem = new Item(queryResults);
System.out.println(queryResults); System.out.println(retrievedItem);
Item retrievedItem = new Item(queryResults); return retrievedItem;
System.out.println(retrievedItem);
return retrievedItem;
} finally {
connection.close();
}
} }
} }

View File

@ -0,0 +1,55 @@
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class TestItemGetter {
@Test
public void testItemGetterValid() {
conductItemGetterTest(false);
}
@Test
public void testItemGetterError() {
conductItemGetterTest(true);
}
public void conductItemGetterTest(boolean shouldThrow) {
ArrayList<Object> rsReturns = new ArrayList<>();
rsReturns.add(1);//ProductID
rsReturns.add(2);//chainID
rsReturns.add("aupc");
rsReturns.add("adescription");
rsReturns.add(BigDecimal.valueOf(.03));//Price
rsReturns.add("animageurl");
rsReturns.add("adepartment");
rsReturns.add(Timestamp.from(Instant.ofEpochMilli(1602192528688L)));//retrievedDate
rsReturns.add(5); // fetchCounts
StatementInjector injector = null;
try {
injector = new StatementInjector(null, rsReturns, shouldThrow);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
ItemGetter getter = new ItemGetter(injector, "id");
Map<String, Object> ignore = new HashMap<>();
HashMap<String, String> queryParams = TestInputUtils.addQueryParams(ignore);
queryParams.put("id", "1");
try {
Object conductReturn = getter.conductAction(TestInputUtils.addBody(ignore), queryParams, "cognitoID");
assert !shouldThrow;
assert (conductReturn.getClass() == Item.class);
Item itemReturn = (Item) conductReturn;
assert (itemReturn.toString().equals("Item{productID=1, chainID=2, upc='aupc', description='adescription', price=0.03, imageURL='animageurl', department='adepartment', retrievedDate=1602192528688, fetchCounts=5}"));
} catch (SQLException throwables) {
throwables.printStackTrace();
assert shouldThrow;
}
}
}

View File

@ -1,6 +1,5 @@
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.LocalDateTime;
public class ItemEntry { public class ItemEntry {
Integer listID; Integer listID;
@ -10,10 +9,40 @@ public class ItemEntry {
Boolean purchased; Boolean purchased;
public ItemEntry(Integer listID, ResultSet listRow) throws SQLException { public ItemEntry(Integer listID, ResultSet listRow) throws SQLException {
this.listID = listID; this.listID = listID;
productID = listRow.getInt(1); productID = listRow.getInt(2);
quantity = listRow.getInt(2); quantity = listRow.getInt(3);
addedDate = listRow.getTimestamp(3).toInstant().toEpochMilli(); addedDate = listRow.getTimestamp(4).toInstant().toEpochMilli();
purchased = listRow.getBoolean(4); purchased = listRow.getBoolean(5);
}
@Override
public String toString() {
return "ItemEntry{" +
"listID=" + listID +
", productID=" + productID +
", quantity=" + quantity +
", addedDate=" + addedDate +
", purchased=" + purchased +
'}';
}
public Integer getListID() {
return listID;
}
public void setListID(Integer listID) {
this.listID = listID;
}
@Override
public String toString() {
return "ItemEntry{" +
"listID=" + listID +
", productID=" + productID +
", quantity=" + quantity +
", addedDate=" + addedDate +
", purchased=" + purchased +
'}';
} }
public Integer getProductID() { public Integer getProductID() {

View File

@ -1,7 +1,5 @@
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.util.ArrayList; import java.util.ArrayList;
public class List { public class List {

View File

@ -1,23 +1,21 @@
import java.sql.*; import java.sql.*;
import java.time.Instant; import java.time.Instant;
import java.time.ZoneOffset;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class ListAdder implements CallHandler { public class ListAdder implements CallHandler {
private DBConnector connector; private Connection connection;
private String cognitoID; private String cognitoID;
private final String LIST_CREATE = "INSERT INTO List (name, owner, lastUpdated) VALUES (?, ?, ?)"; private final String LIST_CREATE = "INSERT INTO List (name, owner, lastUpdated) VALUES (?, ?, ?)";
public ListAdder(DBConnector connector, String cognitoID) { public ListAdder(Connection connection, String cognitoID) {
this.connector = connector; this.connection = connection;
this.cognitoID = cognitoID; this.cognitoID = cognitoID;
} }
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();
PreparedStatement statement = connection.prepareStatement(LIST_CREATE, Statement.RETURN_GENERATED_KEYS); 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);

View File

@ -1,5 +1,3 @@
import com.google.gson.Gson;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
@ -9,50 +7,48 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class ListGetter implements CallHandler{ public class ListGetter implements CallHandler{
private final DBConnector connector; private final Connection connection;
private final String cognitoID; private final String cognitoID;
private final String GET_LIST = "SELECT * FROM List WHERE listID = ?;"; private final String GET_LIST = "SELECT * FROM List WHERE listID = ?;";
private final String GET_LISTS = "SELECT listID FROM List WHERE owner = ?;"; private final String GET_LISTS = "SELECT listID FROM List WHERE owner = ?;";
private final String GET_ENTRIES = "SELECT * FROM ListProduct WHERE listID = ?;"; private final String GET_ENTRIES = "SELECT * FROM ListProduct WHERE listID = ?;";
public ListGetter(DBConnector connector, String cognitoID) { public ListGetter(Connection connection, String cognitoID) {
this.connector = connector; this.connection = connection;
this.cognitoID = cognitoID; this.cognitoID = cognitoID;
} }
@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 {
try (Connection connection = connector.getConnection()) { Integer id = Integer.parseInt(queryMap.get("id"));
Integer id = Integer.parseInt(queryMap.get("id")); 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);
System.out.println(getLists); ResultSet getListsResults = getLists.executeQuery();
ResultSet getListsResults = getLists.executeQuery(); System.out.println(getListsResults);
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));
}
return listIds;
} }
PreparedStatement getList = connection.prepareStatement(GET_LIST); return listIds;
getList.setInt(1, id);
System.out.println(getList);
ResultSet getListResults = getList.executeQuery();
getListResults.first();
System.out.println(getListResults);
List retrievedList = new List(getListResults);
System.out.println(retrievedList);
PreparedStatement getListEntries = connection.prepareStatement(GET_ENTRIES);
getListEntries.setInt(1, id);
ResultSet getEntryResults = getListEntries.executeQuery();
while (getEntryResults.next()) {
retrievedList.addItemEntry(new ItemEntry(id, getEntryResults));
}
System.out.println(retrievedList);
return retrievedList;
} }
PreparedStatement getList = connection.prepareStatement(GET_LIST);
getList.setInt(1, id);
System.out.println(getList);
ResultSet getListResults = getList.executeQuery();
getListResults.first();
System.out.println(getListResults);
List retrievedList = new List(getListResults);
System.out.println(retrievedList);
PreparedStatement getListEntries = connection.prepareStatement(GET_ENTRIES);
getListEntries.setInt(1, id);
ResultSet getEntryResults = getListEntries.executeQuery();
while (getEntryResults.next()) {
retrievedList.addItemEntry(new ItemEntry(id, getEntryResults));
}
System.out.println(retrievedList);
return retrievedList;
} }
} }

View File

@ -0,0 +1,49 @@
import org.junit.Test;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class TestListAdder {
@Test
public void testListAdderValid() {
testListAdderCore(false);
}
@Test
public void testListAdderError() {
testListAdderCore(true);
}
public void testListAdderCore(boolean shouldThrow) {
StatementInjector injector;
ArrayList<Object> rsReturns = new ArrayList<>();
rsReturns.add(1); //new listID
try {
injector = new StatementInjector(null, rsReturns, shouldThrow);
} catch (SQLException throwables) {
throwables.printStackTrace();
assert false; //Error in test infrastructure
return;
}
ListAdder listAdder = new ListAdder(injector, "cognitoID");
Map<String, Object> ignore = new HashMap<>();
Map<String, Object> body = TestInputUtils.addBody(ignore);
body.put("name", "aname");
try {
Object rawIDReturn = listAdder.conductAction(body, TestInputUtils.addQueryParams(ignore), "cognitoID");
assert !shouldThrow;
if (!(rawIDReturn.getClass() == Integer.class)) {
assert false;
return;
}
assert (((Integer) rawIDReturn) == 1);
assert (injector.getStatementString().contains("INSERT INTO List (name, owner, lastUpdated) VALUES (?, ?, ?)[aname, cognitoID,"));
} catch (SQLException throwables) {
assert shouldThrow;
throwables.printStackTrace();
}
}
}

View File

@ -0,0 +1,105 @@
import org.junit.Test;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class TestListGetter {
@Test
public void testListGetterValid() {
conductListGetterTest(false);
}
@Test
public void testListIDGetterValid() {
conductListIDGetterTest(false);
}
@Test
public void testListIDGetterError() {
conductListIDGetterTest(false);
}
@Test
public void testListGetterError() {
conductListGetterTest(true);
}
public void conductListGetterTest(boolean shouldThrow) {
Integer listID = 1;
String name = "aname";
String owner = "anowner";
Timestamp lastUpdated = Timestamp.from(Instant.ofEpochMilli(1602192528688L));
Integer productID = 2;
Integer quantity = 3;
Timestamp addedDate = Timestamp.from(Instant.ofEpochMilli(1602192528689L));;
Boolean purchased = false;
ArrayList<Object> rsReturns = new ArrayList<>();
rsReturns.add(listID);
rsReturns.add(name);
rsReturns.add(owner);
rsReturns.add(lastUpdated);
rsReturns.add(productID);
rsReturns.add(quantity);
rsReturns.add(addedDate);
rsReturns.add(purchased);
StatementInjector injector = null;
try {
injector = new StatementInjector(null, rsReturns, shouldThrow);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
ListGetter getter = new ListGetter(injector, "id");
Map<String, Object> ignore = new HashMap<>();
HashMap<String, String> queryParams = TestInputUtils.addQueryParams(ignore);
queryParams.put("id", "1");
try {
Object conductReturn = getter.conductAction(TestInputUtils.addBody(ignore), queryParams, "cognitoID");
assert !shouldThrow;
assert (conductReturn.getClass() == List.class);
List listReturn = (List) conductReturn;
assert (listReturn.toString().equals("List{itemID=1, name='aname', owner='anowner', lastUpdated=1602192528688, entries=[ItemEntry{listID=1, productID=2, quantity=3, addedDate=1602192528689, purchased=false}]}"));
} catch (SQLException throwables) {
throwables.printStackTrace();
assert shouldThrow;
}
}
public void conductListIDGetterTest(boolean shouldThrow) {
ArrayList<Object> rsReturns = new ArrayList<>();
rsReturns.add(1);
rsReturns.add(2);
rsReturns.add(3);
rsReturns.add(4);
StatementInjector injector = null;
try {
injector = new StatementInjector(null, rsReturns, shouldThrow);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
ListGetter getter = new ListGetter(injector, "id");
Map<String, Object> ignore = new HashMap<>();
HashMap<String, String> queryParams = TestInputUtils.addQueryParams(ignore);
queryParams.put("id", "-1");
try {
Object conductReturn = getter.conductAction(TestInputUtils.addBody(ignore), queryParams, "cognitoID");
assert !shouldThrow;
assert (conductReturn.getClass() == ArrayList.class);
ArrayList<Integer> listIDsReturn = (ArrayList<Integer>) conductReturn;
System.out.println(listIDsReturn.toString());
assert (listIDsReturn.toString().equals("[1, 2, 3, 4]"));
} catch (SQLException throwables) {
throwables.printStackTrace();
assert shouldThrow;
}
}
}

View File

@ -9,31 +9,26 @@ import java.util.Map;
public class ListEntryAdder implements CallHandler { public class ListEntryAdder implements CallHandler {
private DBConnector connector; private Connection connection;
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 ListEntryAdder(DBConnector connector, String cognitoID) { public ListEntryAdder(Connection connection, String cognitoID) {
this.connector = connector; this.connection = connection;
this.cognitoID = cognitoID; this.cognitoID = cognitoID;
} }
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(); PreparedStatement statement = connection.prepareStatement(ITEM_TO_LIST);
try { statement.setInt(1, (Integer) bodyMap.get("productID"));
PreparedStatement statement = connection.prepareStatement(ITEM_TO_LIST); statement.setInt(2, (Integer) bodyMap.get("listID"));
statement.setInt(1, (Integer) bodyMap.get("productID")); statement.setInt(3, (Integer) bodyMap.get("quantity"));
statement.setInt(2, (Integer) bodyMap.get("listID")); statement.setTimestamp(4, Timestamp.from(Instant.now()));
statement.setInt(3, (Integer) bodyMap.get("quantity")); statement.setBoolean(5, (Boolean) bodyMap.get("purchased"));
statement.setTimestamp(4, Timestamp.from(Instant.now())); System.out.println(statement);
statement.setBoolean(5, (Boolean) bodyMap.get("purchased")); statement.executeUpdate();
System.out.println(statement); connection.commit();
statement.executeUpdate();
connection.commit();
} finally {
connection.close();
}
return null; return null;
} }
} }

View File

@ -6,28 +6,23 @@ import java.util.Map;
public class ListEntryDeleter implements CallHandler { public class ListEntryDeleter implements CallHandler {
private DBConnector connector; private Connection connection;
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 ListEntryDeleter(DBConnector connector, String cognitoID) { public ListEntryDeleter(Connection connection, String cognitoID) {
this.connector = connector; this.connection = connection;
this.cognitoID = cognitoID; this.cognitoID = cognitoID;
} }
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(); PreparedStatement statement = connection.prepareStatement(REMOVE_FROM_LIST);
try { statement.setInt(1, (Integer) bodyMap.get("productID"));
PreparedStatement statement = connection.prepareStatement(REMOVE_FROM_LIST); statement.setInt(2, (Integer) bodyMap.get("listID"));
statement.setInt(1, (Integer) bodyMap.get("ProductID")); System.out.println(statement);
statement.setInt(2, (Integer) bodyMap.get("ListID")); statement.executeUpdate();
System.out.println(statement); connection.commit();
statement.executeUpdate();
connection.commit();
} finally {
connection.close();
}
return null; return null;
} }
} }

View File

@ -0,0 +1,47 @@
import org.junit.Test;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class TestListEntryAdder {
@Test
public void testListEntryAdderValid() {
testListEntryAdderCore(false);
}
@Test
public void testListEntryAdderError() {
testListEntryAdderCore(true);
}
public void testListEntryAdderCore(boolean shouldThrow) {
StatementInjector injector;
try {
injector = new StatementInjector(null, null, shouldThrow);
} catch (SQLException throwables) {
throwables.printStackTrace();
assert false; //Error in test infrastructure
return;
}
ListEntryAdder listEntryAdder = new ListEntryAdder(injector, "cognitoID");
Map<String, Object> ignore = new HashMap<>();
Map<String, Object> body = TestInputUtils.addBody(ignore);
body.put("productID", 16);
body.put("listID", 15);
body.put("quantity", 14);
body.put("purchased", false);
try {
Object rawIDReturn = listEntryAdder.conductAction(body, TestInputUtils.addQueryParams(ignore), "cognitoID");
assert !shouldThrow;
assert (rawIDReturn == null);
assert (injector.getStatementString().contains("INSERT INTO ListProduct (productID, listID, quantity, addedDate, purchased) VALUES (?, ?, ?, ?, ?)[16, 15, 14, "));
assert (injector.getStatementString().contains(", false]"));
} catch (SQLException throwables) {
assert shouldThrow;
throwables.printStackTrace();
}
}
}

View File

@ -0,0 +1,44 @@
import org.junit.Test;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class TestListEntryDeleter {
@Test
public void testListEntryDeleterValid() {
testListEntryDeleterCore(false);
}
@Test
public void testListEntryDeleterError() {
testListEntryDeleterCore(true);
}
public void testListEntryDeleterCore(boolean shouldThrow) {
StatementInjector injector;
try {
injector = new StatementInjector(null, null, shouldThrow);
} catch (SQLException throwables) {
throwables.printStackTrace();
assert false; //Error in test infrastructure
return;
}
ListEntryDeleter listEntryDeleter = new ListEntryDeleter(injector, "cognitoID");
Map<String, Object> ignore = new HashMap<>();
Map<String, Object> body = TestInputUtils.addBody(ignore);
body.put("productID", 16);
body.put("listID", 15);
try {
Object rawIDReturn = listEntryDeleter.conductAction(body, TestInputUtils.addQueryParams(ignore), "cognitoID");
assert !shouldThrow;
assert (rawIDReturn == null);
assert (injector.getStatementString().equals("DELETE FROM ListProduct WHERE (ProductID = ? AND ListID = ?);[16, 15]"));
} catch (SQLException throwables) {
assert shouldThrow;
throwables.printStackTrace();
}
}
}

View File

@ -89,9 +89,27 @@
<artifactId>jackson-databind</artifactId> <artifactId>jackson-databind</artifactId>
<version>2.11.3</version> <version>2.11.3</version>
</dependency> </dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
</dependencies> </dependencies>
<properties> <properties>
<maven.compiler.source>1.11</maven.compiler.source> <maven.compiler.source>1.11</maven.compiler.source>
<maven.compiler.target>1.11</maven.compiler.target> <maven.compiler.target>1.11</maven.compiler.target>
</properties> </properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
</plugins>
</build>
</project> </project>

View File

@ -3,6 +3,7 @@ import com.amazonaws.services.lambda.runtime.Context;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -13,14 +14,16 @@ public class BasicHandler {
HashMap<String, String> queryMap = InputUtils.getQueryParams(inputMap); HashMap<String, String> queryMap = InputUtils.getQueryParams(inputMap);
try { try {
DBConnector connector = new DBConnector(); DBConnector connector = new DBConnector();
try { try (Connection connection = connector.getConnection()) {
Constructor<T> constructor = toCall.getConstructor(DBConnector.class, String.class); try {
CallHandler callHandler = constructor.newInstance(connector, cognitoID); Constructor<T> constructor = toCall.getConstructor(Connection.class, String.class);
return callHandler.conductAction(InputUtils.getBody(inputMap), queryMap, cognitoID); CallHandler callHandler = constructor.newInstance(connection, cognitoID);
} catch (SQLException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) { return callHandler.conductAction(InputUtils.getBody(inputMap), queryMap, cognitoID);
e.printStackTrace(); } catch (SQLException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
} finally { e.printStackTrace();
connector.close(); } finally {
connector.close();
}
} }
} catch (IOException |SQLException|ClassNotFoundException e) { } catch (IOException |SQLException|ClassNotFoundException e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -13,13 +13,12 @@ public class DBConnector {
Connection connection; Connection connection;
public DBConnector() throws IOException, SQLException, ClassNotFoundException { public DBConnector() throws IOException, SQLException, ClassNotFoundException {
this(loadProperties("dbProperties.json")); this(loadProperties(DBConnector.class.getResource("dbProperties.json").getPath()));
} }
public DBConnector(Properties dbProperties) throws SQLException, ClassNotFoundException { public DBConnector(Properties dbProperties) throws SQLException, ClassNotFoundException {
Class.forName("org.mariadb.jdbc.Driver"); Class.forName("org.mariadb.jdbc.Driver");
System.out.println(dbProperties); System.out.println(dbProperties);
System.out.println(DBConnector.buildURL(dbProperties));
connection = DriverManager.getConnection(dbProperties.get("url").toString(), dbProperties.get("user").toString(), dbProperties.get("password").toString()); connection = DriverManager.getConnection(dbProperties.get("url").toString(), dbProperties.get("user").toString(), dbProperties.get("password").toString());
System.out.println(connection); System.out.println(connection);
} }
@ -43,11 +42,4 @@ public class DBConnector {
propertiesJSON.keys().forEachRemaining(key -> toReturn.setProperty(key, propertiesJSON.get(key).toString())); propertiesJSON.keys().forEachRemaining(key -> toReturn.setProperty(key, propertiesJSON.get(key).toString()));
return toReturn; return toReturn;
} }
public static String buildURL(Properties dbProperties) {
String dbURL = dbProperties.get("url").toString();
dbURL += "?user=" + dbProperties.get("user").toString();
dbURL += "&password=" + dbProperties.get("password").toString();
return dbURL;
}
} }

View File

@ -10,12 +10,7 @@ public class InputUtils {
public static String getCognitoIDFromBody(Map<String, Object> inputMap) { public static String getCognitoIDFromBody(Map<String, Object> inputMap) {
System.out.println(inputMap.keySet()); System.out.println(inputMap.keySet());
System.out.println(inputMap.entrySet()); System.out.println(inputMap.entrySet());
Map<String, Object> contextMap; Map<String, Object> contextMap = getMap(inputMap, "context");
if ((inputMap.get("context") != null) && (inputMap.get("context") instanceof Map<?, ?>)) {
contextMap = ((Map<String, Object>) inputMap.get("context"));
} else {
throw new IllegalArgumentException("The key \"context\" must exist and be a map");
}
System.out.println(inputMap.get("context")); System.out.println(inputMap.get("context"));
System.out.println(contextMap.get("sub")); System.out.println(contextMap.get("sub"));
return contextMap.get("sub").toString(); return contextMap.get("sub").toString();
@ -25,20 +20,8 @@ public class InputUtils {
return getMap(inputMap, "body"); return getMap(inputMap, "body");
} }
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) { public static HashMap<String, String> getQueryParams(Map<String, Object> inputMap) {
return (HashMap<String, String>) (getMap(inputMap, "params").get("querystring")); 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;
} }

View File

@ -0,0 +1,34 @@
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class BadCallListener extends CallListener {
static SQLException toThrowSQL = null;
static RuntimeException toThrowRuntime = null;
public BadCallListener(Connection connection, String cognitoID) {
super(connection, cognitoID);
}
@Override
public Object conductAction(Map<String, Object> bodyMap, HashMap<String, String> queryString, String cognitoID) throws SQLException {
if (toThrowSQL != null) {
throw toThrowSQL;
}
throw toThrowRuntime;
}
public static void setRuntimeException(RuntimeException newException) {
toThrowRuntime = newException;
toThrowSQL = null;
}
public static void setSQLException(SQLException newException) {
toThrowRuntime = null;
toThrowSQL = newException;
}
}

View File

@ -0,0 +1,35 @@
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class CallListener implements CallHandler {
static int calls = 0;
static int creates = 0;
public CallListener(Connection connection, String cognitoID) {
creates++;
}
@Override
public Object conductAction(Map<String, Object> bodyMap, HashMap<String, String> queryString, String cognitoID) throws SQLException {
calls++;
return null;
}
public static int getCalls() {
return calls;
}
public static void clear() {
creates = 0;
calls = 0;
}
public static int getCreates() {
return creates;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,55 @@
import org.junit.Test;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
public class TestBasicHandler {
@Test
public void testClassCreatedAndCalled() {
BasicHandler.handleRequest(buildFullSampleMap(), null, CallListener.class);
assert (CallListener.getCreates() == 1);
assert (CallListener.getCalls() == 1);
CallListener.clear();
}
@Test
public void testBadCalls() {
BadCallListener.setRuntimeException(new RuntimeException());
try {
BasicHandler.handleRequest(buildFullSampleMap(), null, BadCallListener.class);
assert false;
} catch (RuntimeException ignored) {
}
BadCallListener.setSQLException(new SQLException());
Object handlerReturn = BasicHandler.handleRequest(buildFullSampleMap(), null, Hidden.class);
assert (handlerReturn == null);
BadCallListener.clear();
}
@Test
public void testBadClass() {
try {
assert (BasicHandler.handleRequest(buildFullSampleMap(), null, Hidden.class) == null);
} catch (Exception ignored) {
assert false;
}
}
public static Map<String, Object> buildFullSampleMap() {
Map<String, Object> testMap = new HashMap<>();
TestInputUtils.addBody(testMap);
TestInputUtils.addCognitoID(testMap);
TestInputUtils.addQueryParams(testMap);
return testMap;
}
private class Hidden implements CallHandler{
@Override
public Object conductAction(Map<String, Object> bodyMap, HashMap<String, String> queryString, String cognitoID) throws SQLException {
return null;
}
}
}

View File

@ -0,0 +1,25 @@
import org.junit.Test;
import java.io.IOException;
import java.util.Properties;
public class TestDBConnector {
@Test
public void testLoadProperties() {
Properties testProperties;
try {
testProperties = DBConnector.loadProperties(getClass().getResource("testDBProperties.json").getPath());
} catch (IOException e) {
System.out.println(e);
assert false;
return;
}
Properties testPropertiesKey = new Properties();
testPropertiesKey.put("url", "jdbc:mariadb://listify.id.us-east-2.rds.amazonaws.com:3306/ListifySchema");
testPropertiesKey.put("user", "auser");
testPropertiesKey.put("password", "apassword");
assert (testProperties.equals(testPropertiesKey));
}
}

View File

@ -0,0 +1,62 @@
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class TestInputUtils {
@Test
public void testGetBody() {
Map<String, Object> testMap = new HashMap<>();
Map<String, Object> bodyMap = addBody(testMap);
assert (InputUtils.getBody(testMap).equals(bodyMap));
}
@Test
public void testGetQueryParams() {
Map<String, Object> testMap = new HashMap<>();
Map<String, String> queryMap = addQueryParams(testMap);
assert (InputUtils.getQueryParams(testMap).equals(queryMap));
}
@Test
public void testGetCognitoID() {
Map<String, Object> testMap = new HashMap<>();
String cognitoID = addCognitoID(testMap);
assert (InputUtils.getCognitoIDFromBody(testMap).equals(cognitoID));
}
@Test
public void testGetBadMapKey() {
Map<String, Object> testMap = new HashMap<>();
try {
InputUtils.getMap(testMap, "missing");
assert (false);
} catch (IllegalArgumentException e) {
}
}
public static String addCognitoID(Map<String, Object> testMap) {
HashMap<String, String> contextMap = new HashMap<>();
String cognitoID = "Example id";
contextMap.put("sub", cognitoID);
testMap.put("context", contextMap);
return cognitoID;
}
public static HashMap<String, String> addQueryParams(Map<String, Object> testMap) {
HashMap<String, Object> paramsMap = new HashMap<>();
HashMap<String, String> queryMap = new HashMap<>();
paramsMap.put("querystring", queryMap);
testMap.put("params", paramsMap);
return queryMap;
}
public static Map<String, Object> addBody(Map<String, Object> testMap) {
HashMap<String, Object> bodyMap = new HashMap<>();
testMap.put("body", bodyMap);
return bodyMap;
}
}

View File

@ -0,0 +1,5 @@
{
"url": "jdbc:mariadb://listify.id.us-east-2.rds.amazonaws.com:3306/ListifySchema",
"user": "auser",
"password": "apassword"
}

View File

@ -0,0 +1,5 @@
{
"url": "jdbc:mariadb://listify.id.us-east-2.rds.amazonaws.com:3306/ListifySchema",
"user": "auser",
"password": "apassword"
}

View File

@ -40,8 +40,7 @@
<activity android:name="com.example.listify.ui.LoginPage" /> <activity android:name="com.example.listify.ui.LoginPage" />
<activity android:name="com.example.listify.ui.ForgotPasswordPage" /> <activity android:name="com.example.listify.ui.ForgotPasswordPage" />
<activity android:name="com.example.listify.ui.ResetPasswordPage" /> <activity android:name="com.example.listify.ui.ResetPasswordPage" />
<activity android:name="com.example.listify.List" /> <activity android:name="com.example.listify.ListPage" />
</application> </application>
</manifest> </manifest>

View File

@ -13,13 +13,24 @@ import android.widget.EditText;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.ListView; import android.widget.ListView;
import android.widget.TextView; import android.widget.TextView;
import com.example.listify.data.Item;
import com.example.listify.data.List;
import com.example.listify.data.ListEntry;
import com.example.listify.model.Product;
import static com.example.listify.MainActivity.am;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Properties;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
public class List extends AppCompatActivity { public class ListPage extends AppCompatActivity {
ListView listView; ListView listView;
MyAdapter myAdapter; MyAdapter myAdapter;
@ -33,8 +44,51 @@ public class List extends AppCompatActivity {
ArrayList<String> pQuantity = new ArrayList<>(); //String[] pQuantity = {"1"}; ArrayList<String> pQuantity = new ArrayList<>(); //String[] pQuantity = {"1"};
ArrayList<Integer> pImages = new ArrayList<>(); //int[] pImages = {R.drawable.milk}; ArrayList<Integer> pImages = new ArrayList<>(); //int[] pImages = {R.drawable.milk};
Requestor requestor;
@Override @Override
protected void onCreate(@Nullable Bundle savedInstanceState) { protected void onCreate(@Nullable Bundle savedInstanceState) {
Properties configs = new Properties();
try {
configs = AuthManager.loadProperties(this, "android.resource://" + getPackageName() + "/raw/auths.json");
} catch (IOException | JSONException e) {
e.printStackTrace();
}
requestor = new Requestor(am, configs.getProperty("apiKey"));
SynchronousReceiver<List> lr = new SynchronousReceiver<>();
//ListReceiver<List> lr = new ListReceiver<>();
requestor.getObject("39", List.class, lr);
List list;
try {
list = lr.await();
}
catch(Exception e) {
list = null;
}
if(list != null) {
for (ListEntry entry : list.getEntries()) {
int product = entry.getProductID();
SynchronousReceiver<Item> pr = new SynchronousReceiver<>();
requestor.getObject(Integer.toString(product), Item.class, pr, pr);
Item item;
try {
item = pr.await();
} catch (Exception e) {
item = null;
}
if(item != null) {
pNames.add(item.getDescription());
pStores.add("Kroger");
pPrices.add(item.getPrice().toString());
pQuantity.add("1");
pImages.add(R.drawable.placeholder);
}
}
}
pNames.add("Half-gallon organic whole milk"); pNames.add("Half-gallon organic whole milk");
pStores.add("Kroger"); pStores.add("Kroger");
pPrices.add("$5.00"); pPrices.add("$5.00");
@ -53,8 +107,6 @@ public class List extends AppCompatActivity {
pQuantity.add("1"); pQuantity.add("1");
pImages.add(R.drawable.peanutbutter); pImages.add(R.drawable.peanutbutter);
int currSize = pNames.size();
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list); setContentView(R.layout.activity_list);
@ -151,4 +203,27 @@ public class List extends AppCompatActivity {
return listproduct; return listproduct;
} }
} }
class ListReceiver<T> implements Requestor.Receiver<T> {
@Override
public void acceptDelivery(T delivered) {
for(ListEntry entry : ((List) delivered).getEntries()) {
int product = entry.getProductID();
ProductReceiver<Item> pr = new ProductReceiver<>();
requestor.getObject(Integer.toString(product), Item.class, pr);
pQuantity.add("1");
}
}
}
class ProductReceiver<T> implements Requestor.Receiver<T> {
@Override
public void acceptDelivery(T delivered) {
Item i = (Item) delivered;
pNames.add(i.getDescription());
pStores.add("Kroger");
pPrices.add(i.getPrice().toString());
pImages.add(R.drawable.placeholder);
}
}
} }

View File

@ -30,6 +30,8 @@ import java.util.Random;
public class MainActivity extends AppCompatActivity implements CreateListDialogFragment.OnNewListListener { public class MainActivity extends AppCompatActivity implements CreateListDialogFragment.OnNewListListener {
private AppBarConfiguration mAppBarConfiguration; private AppBarConfiguration mAppBarConfiguration;
public static AuthManager am = new AuthManager();
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
@ -86,6 +88,7 @@ public class MainActivity extends AppCompatActivity implements CreateListDialogF
List testList = new List(-1, "New List", "user filled by lambda", Instant.now().toEpochMilli()); List testList = new List(-1, "New List", "user filled by lambda", Instant.now().toEpochMilli());
//Everything except addedDate is used for ItemEntry //Everything except addedDate is used for ItemEntry
ListEntry entry = new ListEntry(1, 4, Math.abs(new Random().nextInt()), Instant.now().toEpochMilli(),false); ListEntry entry = new ListEntry(1, 4, Math.abs(new Random().nextInt()), Instant.now().toEpochMilli(),false);
SynchronousReceiver<Integer> idReceiver = new SynchronousReceiver<>(); SynchronousReceiver<Integer> idReceiver = new SynchronousReceiver<>();
try { try {
requestor.postObject(testList, idReceiver, idReceiver); requestor.postObject(testList, idReceiver, idReceiver);

View File

@ -10,6 +10,7 @@ import android.widget.EditText;
import com.example.listify.R; import com.example.listify.R;
import com.example.listify.AuthManager; import com.example.listify.AuthManager;
import com.example.listify.MainActivity; import com.example.listify.MainActivity;
import static com.example.listify.MainActivity.am;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
@ -51,10 +52,8 @@ public class LoginPage extends AppCompatActivity {
String email = emailText.getText().toString(); String email = emailText.getText().toString();
String password = passwordText.getText().toString(); String password = passwordText.getText().toString();
AuthManager authManager = new AuthManager();
try { try {
authManager.signIn(email, password); am.signIn(email, password);
Intent intent = new Intent(LoginPage.this, MainActivity.class); Intent intent = new Intent(LoginPage.this, MainActivity.class);
startActivity(intent); startActivity(intent);
} }

View File

@ -10,6 +10,7 @@ import android.widget.EditText;
import com.example.listify.R; import com.example.listify.R;
import com.example.listify.AuthManager; import com.example.listify.AuthManager;
import com.example.listify.MainActivity; import com.example.listify.MainActivity;
import static com.example.listify.MainActivity.am;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
@ -17,8 +18,6 @@ public class SignupPage extends AppCompatActivity implements CodePage.CodeDialog
private Button button1; //Log in page button private Button button1; //Log in page button
private Button button2; //Sign up button private Button button2; //Sign up button
AuthManager authManager = new AuthManager();
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
@ -44,7 +43,7 @@ public class SignupPage extends AppCompatActivity implements CodePage.CodeDialog
String password = passwordText.getText().toString(); String password = passwordText.getText().toString();
try { try {
authManager.startSignUp(email, password); am.startSignUp(email, password);
} }
catch(Exception e) { catch(Exception e) {
return; return;
@ -67,7 +66,7 @@ public class SignupPage extends AppCompatActivity implements CodePage.CodeDialog
} }
else { else {
try { try {
authManager.confirmSignUp(code); am.confirmSignUp(code);
Intent intent = new Intent(SignupPage.this, MainActivity.class); Intent intent = new Intent(SignupPage.this, MainActivity.class);
startActivity(intent); startActivity(intent);
} }

View File

@ -32,7 +32,7 @@ public class HomeFragment extends Fragment {
toListPage.setOnClickListener(new View.OnClickListener() { toListPage.setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View v) { public void onClick(View v) {
Intent intent = new Intent(HomeFragment.this.getActivity(), com.example.listify.List.class); Intent intent = new Intent(HomeFragment.this.getActivity(), com.example.listify.ListPage.class);
startActivity(intent); startActivity(intent);
} }
}); });