Advertisement
Guest User

Untitled

a guest
May 23rd, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 25.74 KB | None | 0 0
  1. public class DBModel {
  2.  
  3. private String mDBName;
  4. private String mTableName;
  5. private String[] mFieldNames;
  6. private String[] mFieldTypes;
  7. public DBModel(String dbName, String tableName, String[] fieldNames, String[] fieldTypes)
  8. throws SQLException {
  9. super();
  10. mDBName = dbName;
  11. mTableName = tableName;
  12. mFieldNames = fieldNames;
  13. mFieldTypes = fieldTypes;
  14. if (mFieldNames == null || mFieldTypes == null || mFieldNames.length == 0 || mFieldNames.length != mFieldTypes.length)
  15. throw new SQLException("Database field names and types must exist and have the same number of elements.");
  16. createTable();
  17. }
  18.  
  19. private void createTable() throws SQLException
  20. {
  21. try (Connection connection = connectToDB();
  22. Statement stmt = connection.createStatement();) {
  23. StringBuilder createSQL = new StringBuilder("CREATE TABLE IF NOT EXISTS ");
  24. createSQL.append(mTableName).append("(");
  25. for (int i = 0; i < mFieldNames.length; i++)
  26. createSQL.append(mFieldNames[i]).append(" ").append(mFieldTypes[i]).append((i < mFieldNames.length -1) ? "," : ")");
  27. stmt.executeUpdate(createSQL.toString());
  28. }
  29.  
  30. }
  31.  
  32. public ArrayList<ArrayList<String>> getAllRecords() throws SQLException {
  33. try (Connection connection = connectToDB();
  34. Statement stmt = connection.createStatement();
  35. ResultSet rs = stmt.executeQuery("SELECT * FROM " + mTableName);) {
  36. ArrayList<ArrayList<String>> resultsList = new ArrayList<>();
  37. while (rs.next()) {
  38. // Let's loop through each of the fields and add each value to the ArrayList
  39. ArrayList<String> values = new ArrayList<>(mFieldNames.length);
  40. for (String fieldName : mFieldNames)
  41. values.add(rs.getString(fieldName));
  42. // Now add the values to the 2D ArrayList
  43. resultsList.add(values);
  44. }
  45. return resultsList;
  46. }
  47. }
  48.  
  49. public ArrayList<ArrayList<String>> getRecord(String key) throws SQLException
  50. {
  51. try (Connection connection = connectToDB();
  52. Statement stmt = connection.createStatement();
  53. ResultSet rs = stmt.executeQuery("SELECT * FROM " + mTableName + " WHERE " + mFieldNames[0] + " = " + key);) {
  54. ArrayList<ArrayList<String>> resultsList = new ArrayList<>();
  55. while (rs.next()) {
  56. // Let's loop through each of the fields and add each value to the ArrayList
  57. ArrayList<String> values = new ArrayList<>(mFieldNames.length);
  58. for (String fieldName : mFieldNames)
  59. values.add(rs.getString(fieldName));
  60. // Now add the values to the 2D ArrayList
  61. resultsList.add(values);
  62. }
  63. return resultsList;
  64. }
  65. }
  66.  
  67. public int getRecordCount() throws SQLException {
  68. return getAllRecords().size();
  69. }
  70.  
  71. public int createRecord(String[] fields, String[] values) throws SQLException {
  72. try (Connection connection = connectToDB();
  73. Statement stmt = connection.createStatement();) {
  74. if(fields == null || values == null || fields.length == 0 || fields.length != values.length)
  75. return -1;
  76.  
  77. StringBuilder insertSQL = new StringBuilder("INSERT INTO ");
  78. insertSQL.append(mTableName).append("(");
  79. for(int i = 0; i < fields.length; i++)
  80. insertSQL.append(fields[i]).append((i < fields.length - 1) ? "," : ") VALUES(");
  81. for(int i = 0; i < values.length; i++)
  82. insertSQL.append(convertToSQLText(fields[i], values[i])).append((i < values.length - 1) ? "," : ")");
  83.  
  84. stmt.executeUpdate(insertSQL.toString());
  85. return stmt.getGeneratedKeys().getInt(1);
  86. }
  87. }
  88.  
  89. public boolean updateRecord(String key, String[] fields, String[] values) throws SQLException
  90. {
  91.  
  92. if (fields == null || values == null || fields.length == 0 || fields.length != values.length)
  93. return false;
  94. StringBuilder updateSQL = new StringBuilder("UPDATE ");
  95. updateSQL.append(mTableName).append(" SET ");
  96. for (int i = 0; i < fields.length; i++)
  97. updateSQL.append(fields[i]).append("=").append(convertToSQLText(fields[i], values[i])).append((i < fields.length - 1) ? ", " : " ");
  98. try (Connection connection = connectToDB();
  99. Statement stmt = connection.createStatement();) {
  100. updateSQL.append("WHERE ").append(mFieldNames[0]).append("=").append(key);
  101. stmt.executeUpdate(updateSQL.toString());
  102. return true;
  103. }
  104. }
  105.  
  106. public void deleteAllRecords() throws SQLException {
  107. try (Connection connection = connectToDB();
  108. Statement stmt = connection.createStatement();) {
  109. stmt.executeUpdate("DELETE FROM " + mTableName);
  110. }
  111. }
  112.  
  113. public void deleteRecord(String key) throws SQLException
  114. {
  115. try (Connection connection = connectToDB();
  116. Statement stmt = connection.createStatement();) {
  117. stmt.executeUpdate("DELETE FROM " + mTableName + " WHERE " + mFieldNames[0] + " = " + key);
  118. }
  119. }
  120.  
  121. private String convertToSQLText(String field, String value) {
  122. // Lookup the field in field names, if found, check to see if the type is TEXT (if so, append ' ' around value)
  123. for (int i = 0; i < mFieldNames.length; i++) {
  124. if (mFieldNames[i].equals(field)) {
  125. if (mFieldTypes[i].toUpperCase().startsWith("TEXT"))
  126. return "'" + value + "'";
  127. break;
  128. }
  129. }
  130. return value;
  131. }
  132.  
  133. private Connection connectToDB() throws SQLException {
  134. // Load SQLite database classes
  135. try {
  136. Class.forName("org.sqlite.JDBC");
  137. } catch (ClassNotFoundException e) {
  138. e.printStackTrace();
  139. }
  140. // Establish a connection to the database and return that connection
  141. Connection connection = DriverManager.getConnection("jdbc:sqlite:" + mDBName);
  142. return connection;
  143. }
  144. }
  145.  
  146. public class Controller {
  147.  
  148. private static Controller theOne;
  149.  
  150. private static final String DB_NAME = "vg_inventory.db";
  151.  
  152. private static final String USER_TABLE_NAME = "user";
  153. private static final String[] USER_FIELD_NAMES = { "id", "name", "email", "role", "password"};
  154. private static final String[] USER_FIELD_TYPES = { "INTEGER PRIMARY KEY", "TEXT", "TEXT", "TEXT", "TEXT"};
  155.  
  156. private static final String VIDEO_GAME_TABLE_NAME = "video_game";
  157. private static final String[] VIDEO_GAME_FIELD_NAMES = { "id", "name", "platform", "year", "genre", "publisher"};
  158. private static final String[] VIDEO_GAME_FIELD_TYPES = { "INTEGER PRIMARY KEY", "TEXT", "TEXT", "INTEGER", "TEXT", "TEXT"};
  159. private static final String VIDEO_GAME_DATA_FILE = "videogames_lite.csv";
  160.  
  161. private static final String USER_GAMES_TABLE_NAME = "user_games";
  162. private static final String[] USER_GAMES_FIELD_NAMES = { "user_id", "game_id"};
  163. private static final String[] USER_GAMES_FIELD_TYPES = { "INTEGER", "INTEGER"};
  164.  
  165. private User mCurrentUser;
  166. private DBModel mUserDB;
  167. private DBModel mVideoGameDB;
  168. private DBModel mUserGamesDB;
  169.  
  170. private ObservableList<User> mAllUsersList;
  171. private ObservableList<VideoGame> mAllGamesList;
  172.  
  173. private Controller() {
  174. }
  175.  
  176. public static Controller getInstance() {
  177. if (theOne == null) {
  178. theOne = new Controller();
  179. theOne.mAllUsersList = FXCollections.observableArrayList();
  180. theOne.mAllGamesList = FXCollections.observableArrayList();
  181.  
  182. try {
  183. theOne.mUserDB = new DBModel(DB_NAME, USER_TABLE_NAME, USER_FIELD_NAMES, USER_FIELD_TYPES);
  184.  
  185. ArrayList<ArrayList<String>> resultsList = theOne.mUserDB.getAllRecords();
  186.  
  187. for (ArrayList<String> values : resultsList) {
  188. int id = Integer.parseInt(values.get(0));
  189. String name = values.get(1);
  190. String email = values.get(2);
  191. String role = values.get(3);
  192. theOne.mAllUsersList.add(new User(id, name, email, role));
  193. }
  194.  
  195. theOne.mVideoGameDB = new DBModel(DB_NAME, VIDEO_GAME_TABLE_NAME, VIDEO_GAME_FIELD_NAMES, VIDEO_GAME_FIELD_TYPES);
  196. theOne.initializeVideoGameDBFromFile();
  197. resultsList = theOne.mVideoGameDB.getAllRecords();
  198. for (ArrayList<String> values : resultsList)
  199. {
  200. int id = Integer.parseInt(values.get(0));
  201. String name = values.get(1);
  202. String platform = values.get(2);
  203. int year = Integer.parseInt(values.get(3));
  204. String genre = values.get(4);
  205. String publisher = values.get(5);
  206. theOne.mAllGamesList.add(new VideoGame(id, name, platform, year, genre, publisher));
  207. }
  208.  
  209. theOne.mUserGamesDB= new DBModel(DB_NAME, USER_GAMES_TABLE_NAME, USER_GAMES_FIELD_NAMES, USER_GAMES_FIELD_TYPES);
  210.  
  211. } catch (SQLException e) {
  212. e.printStackTrace();
  213. }
  214. }
  215. return theOne;
  216. }
  217.  
  218. public boolean isValidPassword(String password)
  219. {
  220. // Valid password must contain (see regex below):
  221. // At least one lower case letter
  222. // At least one digit
  223. // At least one special character (@, #, $, %, !)
  224. // At least one upper case letter
  225. // At least 8 characters long, but no more than 16
  226. return password.matches("((?=.*[a-z])(?=.*d)(?=.*[@#$%!])(?=.*[A-Z]).{8,16})");
  227. }
  228.  
  229. public boolean isValidEmail(String email)
  230. {
  231. return email.matches(
  232. "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
  233. + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
  234. }
  235.  
  236. public String signUpUser(String name, String email, String password)
  237. {
  238. if (!isValidEmail(email))
  239. return "Email address is not valid. Please use different address.";
  240.  
  241. for (User u : theOne.mAllUsersList)
  242. if (u.getEmail().equalsIgnoreCase(email))
  243. return "Email address already used. Please sign in or use different email.";
  244.  
  245. if (!isValidPassword(password))
  246. return "Password must be at least 8 characters, including 1 upper case letter, 1 lower case letter, 1 digit and one symbol.";
  247.  
  248. try {
  249. // In practice, passwords should always be encrypted before storing in database:
  250. // See http://www.jasypt.org/howtoencryptuserpasswords.html for a useful tutorial
  251. String[] values = {name, email, "STANDARD", password};
  252. int id = theOne.mUserDB.createRecord(Arrays.copyOfRange(USER_FIELD_NAMES, 1, USER_FIELD_NAMES.length), values);
  253. mCurrentUser = new User(id, name, email, "STANDARD");
  254. theOne.mAllUsersList.add(mCurrentUser);
  255. } catch (Exception e) {
  256. e.printStackTrace();
  257. return "Error creating user, please try again.";
  258. }
  259. return "SUCCESS";
  260. }
  261.  
  262. public String signInUser(String email, String password) {
  263. for (User u : theOne.mAllUsersList)
  264. if (u.getEmail().equalsIgnoreCase(email))
  265. {
  266. try {
  267. ArrayList<ArrayList<String>> resultsList = theOne.mUserDB.getRecord(String.valueOf(u.getId()));
  268. String storedPassword = resultsList.get(0).get(4);
  269. if (password.equals(storedPassword))
  270. {
  271. mCurrentUser = u;
  272. return "SUCCESS";
  273. }
  274.  
  275.  
  276. } catch (Exception e) {}
  277. return "Incorrect password. Please try again.";
  278. }
  279. return "Email address not found. Please try again.";
  280. }
  281.  
  282. public User getCurrentUser()
  283. {
  284. return mCurrentUser;
  285. }
  286.  
  287. public ObservableList<User> getAllUsers() {
  288. return theOne.mAllUsersList;
  289. }
  290.  
  291. public ObservableList<VideoGame> getAllVideoGames() {
  292. return theOne.mAllGamesList;
  293. }
  294.  
  295. public ObservableList<String> getDistinctPlatforms() {
  296. ObservableList<String> platforms = FXCollections.observableArrayList();
  297. platforms.add("");
  298. for (VideoGame vg : theOne.mAllGamesList)
  299. if (!platforms.contains(vg.getPlatform()))
  300. platforms.add(vg.getPlatform());
  301. FXCollections.sort(platforms);
  302. return platforms;
  303. }
  304.  
  305. public ObservableList<String> getDistinctPublishers() {
  306. ObservableList<String> publishers = FXCollections.observableArrayList();
  307. publishers.add("");
  308. for (VideoGame vg : theOne.mAllGamesList)
  309. if (!publishers.contains(vg.getPublisher()))
  310. publishers.add(vg.getPublisher());
  311. FXCollections.sort(publishers);
  312. return publishers;
  313. }
  314.  
  315. public ObservableList<VideoGame> getGamesForCurrentUser()
  316. {
  317. ObservableList<VideoGame> userGamesList = FXCollections.observableArrayList();
  318. if (mCurrentUser != null)
  319. {
  320. try {
  321. ArrayList<ArrayList<String>> resultsList= theOne.mUserGamesDB.getRecord(String.valueOf(mCurrentUser.getId()));
  322. for (ArrayList<String> values : resultsList)
  323. {
  324. int gameId = Integer.parseInt(values.get(1));
  325. for (VideoGame vg : theOne.mAllGamesList)
  326. if (vg.getId() == gameId)
  327. userGamesList.add(vg);
  328. }
  329.  
  330. } catch (SQLException e) {
  331. e.printStackTrace();
  332. }
  333.  
  334. }
  335.  
  336. return userGamesList;
  337. }
  338.  
  339. public boolean addGameToInventory(VideoGame selectedGame) {
  340. ObservableList<VideoGame> userGamesList = theOne.getGamesForCurrentUser();
  341. if (userGamesList.contains(selectedGame))
  342. return false;
  343. String[] values = {String.valueOf(mCurrentUser.getId()), String.valueOf(selectedGame.getId())};
  344. try {
  345. this.mUserGamesDB.createRecord(USER_GAMES_FIELD_NAMES, values);
  346. } catch (SQLException e) {
  347. e.printStackTrace();
  348. return false;
  349. }
  350. return true;
  351. }
  352.  
  353. private int initializeVideoGameDBFromFile() throws SQLException {
  354. int recordsCreated = 0;
  355.  
  356. // If the result set contains results, database table already has
  357. // records, no need to populate from file (so return false)
  358. if (theOne.mUserDB.getRecordCount() > 0)
  359. return 0;
  360.  
  361. try {
  362. // Otherwise, open the file (CSV file) and insert user data
  363. // into database
  364. Scanner fileScanner = new Scanner(new File(VIDEO_GAME_DATA_FILE));
  365. // First read is for headings:
  366. fileScanner.nextLine();
  367. // All subsequent reads are for user data
  368. while (fileScanner.hasNextLine()) {
  369. String[] data = fileScanner.nextLine().split(",");
  370. // Length of values is one less than field names because values
  371. // does not have id (DB will assign one)
  372. String[] values = new String[VIDEO_GAME_FIELD_NAMES.length - 1];
  373. values[0] = data[1].replaceAll("'", "''");
  374. values[1] = data[2];
  375. values[2] = data[3];
  376. values[3] = data[4];
  377. values[4] = data[5];
  378. theOne.mVideoGameDB.createRecord(Arrays.copyOfRange(VIDEO_GAME_FIELD_NAMES, 1, VIDEO_GAME_FIELD_NAMES.length), values);
  379. recordsCreated++;
  380. }
  381.  
  382. // All done with the CSV file, close the connection
  383. fileScanner.close();
  384. } catch (FileNotFoundException e) {
  385. return 0;
  386. }
  387. return recordsCreated;
  388. }
  389.  
  390. public ObservableList<VideoGame> filter(String publisher, String platform, double year) {
  391. ObservableList<VideoGame> filteredVideoGamesList = FXCollections.observableArrayList();
  392. for (VideoGame vg : theOne.mAllGamesList) {
  393. if ((publisher == null || vg.getPublisher().equals(publisher) || publisher.isEmpty()) && (platform == null || vg.getPlatform().equals(platform) || platform.isEmpty())
  394. && (vg.getYear() >= year))
  395. filteredVideoGamesList.add(vg);
  396. }
  397. return filteredVideoGamesList;
  398. }
  399.  
  400. }
  401.  
  402. public class ViewNavigator {
  403.  
  404. public static final String SIGN_UP_SCENE = "SignUpScene.fxml";
  405.  
  406.  
  407. public static final String SIGN_IN_SCENE = "SignInScene.fxml";
  408.  
  409. public static final String VIDEO_GAME_LIST_SCENE = "VideoGamesListScene.fxml";
  410.  
  411. public static final String VIEW_INVENTORY_SCENE = "ViewInventoryScene.fxml";
  412.  
  413. public static Stage mainStage;
  414.  
  415. public static void setStage(Stage stage) {
  416. mainStage = stage;
  417. }
  418.  
  419. public static void loadScene(String title, String sceneFXML) {
  420.  
  421. try {
  422. mainStage.setTitle(title);
  423. Scene scene = new Scene(FXMLLoader.load(ViewNavigator.class.getResource(sceneFXML)));
  424. mainStage.setScene(scene);
  425. mainStage.show();
  426. } catch (IOException e) {
  427. System.err.println("Error loading: " + sceneFXML + "\n" + e.getMessage());
  428. e.printStackTrace();
  429. }
  430. }
  431.  
  432. }
  433. public class MainView extends Application {
  434.  
  435. @Override
  436. public void start(Stage primaryStage) throws Exception {
  437. // Set stage only needs to be called once for the view navigator
  438. ViewNavigator.setStage(primaryStage);
  439. ViewNavigator.loadScene("Welcome to VG in.vent.ory", ViewNavigator.SIGN_IN_SCENE);
  440. }
  441.  
  442. public static void main(String[] args) {
  443. launch(args);
  444. }
  445.  
  446. }
  447. public class VideoGamesListScene implements Initializable {
  448.  
  449. private static Controller controller = Controller.getInstance();
  450.  
  451. @FXML
  452. private ListView<VideoGame> allVideoGamesLV;
  453. @FXML
  454. private ComboBox<String> publishersCB;
  455. @FXML
  456. private ComboBox<String> platformsCB;
  457. @FXML
  458. private Slider yearSlider;
  459.  
  460. @Override
  461. public void initialize(URL location, ResourceBundle resources) {
  462. allVideoGamesLV.setItems(controller.getAllVideoGames());
  463. platformsCB.setItems(controller.getDistinctPlatforms());
  464. publishersCB.setItems(controller.getDistinctPublishers());
  465. }
  466.  
  467. @FXML
  468. public Object addGameToInventory()
  469. {
  470. VideoGame selectedGame = allVideoGamesLV.getSelectionModel().getSelectedItem();
  471. if (controller.addGameToInventory(selectedGame))
  472. System.out.println("SUCCESS");
  473. else
  474. System.out.println("Could not add game.");
  475. return this;
  476. }
  477.  
  478. @FXML
  479. public Object viewInventory()
  480. {
  481. ViewNavigator.loadScene("User's Video Games", ViewNavigator.VIEW_INVENTORY_SCENE);
  482. return this;
  483. }
  484.  
  485. @FXML
  486. private void filter() {
  487. ObservableList<VideoGame> gamesList;
  488. gamesList = controller.filter(publishersCB.getSelectionModel().getSelectedItem(), platformsCB.getSelectionModel().getSelectedItem(), yearSlider.getValue());
  489. allVideoGamesLV.setItems(gamesList);
  490. }
  491. }
  492. <?xml version="1.0" encoding="UTF-8"?>
  493.  
  494. <?import javafx.geometry.Insets?>
  495. <?import javafx.scene.control.Button?>
  496. <?import javafx.scene.control.ComboBox?>
  497. <?import javafx.scene.control.Label?>
  498. <?import javafx.scene.control.ListView?>
  499. <?import javafx.scene.control.Slider?>
  500. <?import javafx.scene.layout.BorderPane?>
  501. <?import javafx.scene.layout.ColumnConstraints?>
  502. <?import javafx.scene.layout.GridPane?>
  503. <?import javafx.scene.layout.HBox?>
  504. <?import javafx.scene.layout.RowConstraints?>
  505.  
  506. <BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="480.0" prefWidth="640.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="edu.orangecoastcollege.cs272.ic14.view.VideoGamesListScene">
  507. <top>
  508. <GridPane vgap="10.0" BorderPane.alignment="CENTER">
  509. <columnConstraints>
  510. <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
  511. <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
  512. </columnConstraints>
  513. <rowConstraints>
  514. <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
  515. <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
  516. <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
  517. </rowConstraints>
  518. <children>
  519. <Label text="Select Platform:" />
  520. <Label text="Select Publisher:" GridPane.rowIndex="1" />
  521. <Label text="Filter Year:" GridPane.rowIndex="2" />
  522. <Slider fx:id="yearSlider" blockIncrement="5.0" majorTickUnit="11.0" max="2015.0" min="1982.0" minorTickCount="2" onMouseDragged="#filter" showTickLabels="true" showTickMarks="true" GridPane.columnIndex="1" GridPane.rowIndex="2" />
  523. <ComboBox fx:id="platformsCB" onAction="#filter" prefWidth="200.0" GridPane.columnIndex="1" />
  524. <ComboBox fx:id="publishersCB" onAction="#filter" prefWidth="200.0" GridPane.columnIndex="1" GridPane.rowIndex="1" />
  525. </children>
  526. <BorderPane.margin>
  527. <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" />
  528. </BorderPane.margin>
  529. </GridPane>
  530. </top>
  531. <center>
  532. <ListView fx:id="allVideoGamesLV" prefHeight="200.0" prefWidth="200.0" BorderPane.alignment="CENTER" />
  533. </center>
  534. <bottom>
  535. <HBox alignment="CENTER" prefHeight="40.0" prefWidth="200.0" spacing="50.0" BorderPane.alignment="CENTER">
  536. <children>
  537. <Button mnemonicParsing="false" onAction="#addGameToInventory" text="Add Game to Inventory" />
  538. <Button mnemonicParsing="false" onAction="#viewInventory" text="View Inventory" />
  539. </children>
  540. </HBox>
  541. </bottom>
  542. </BorderPane>
  543. public class TestDBModel
  544. {
  545.  
  546. private static final String DB_NAME = "cs272_test.db";
  547. private static final String TABLE_NAME = "car";
  548. private static final String[] FIELD_NAMES = { "id", "make", "description", "horsepower", "fuelType", "cityMPG", "hwyMPG", "hybrid" };
  549. private static final String[] FIELD_TYPES = { "INTEGER PRIMARY KEY", "TEXT", "TEXT", "INTEGER", "TEXT", "INTEGER", "INTEGER", "INTEGER" };
  550.  
  551. private static DBModel db;
  552.  
  553. private String[] values;
  554.  
  555. // Set up before class defines variables, resources, etc
  556. // Static method, so only executes once before all testing begins
  557. // Anything you need to setup before testing, do it here
  558. @BeforeClass
  559. public static void setUpBeforeClass() throws Exception
  560. {
  561. // Instantiate our database
  562. db = new DBModel(DB_NAME, TABLE_NAME, FIELD_NAMES, FIELD_TYPES);
  563. }
  564.  
  565. // Tear down after class cleans up any open resources
  566. // Static method, only executes once at the end of all testing
  567. @AfterClass
  568. public static void tearDownAfterClass() throws Exception
  569. {
  570. db.close();
  571. }
  572.  
  573. // set up is executed before each individual test
  574. @Before
  575. public void setUp() throws Exception
  576. {
  577. values = new String[] { "1", "BMW", "2018 M3 Manual", "300", "Gas", "25", "45", "0" };
  578.  
  579. }
  580.  
  581. // tear down is executed after each individual test
  582. @After
  583. public void tearDown() throws Exception
  584. {
  585. db.deleteAllRecords();
  586. }
  587.  
  588. @Test
  589. public void testGetAllRecords()
  590. {
  591. try
  592. {
  593. db.getAllRecords();
  594. }
  595. catch (SQLException e)
  596. {
  597. fail("Getting all records on empty database should not generate SQLException");
  598. }
  599. }
  600.  
  601. @Test
  602. public void testGetRecord()
  603. {
  604. try
  605. {
  606. db.createRecord(Arrays.copyOfRange(FIELD_NAMES, 1, FIELD_NAMES.length), Arrays.copyOfRange(values, 1, values.length));
  607. assertTrue("Before deletion, count should be positive", db.getRecordCount() > 0);
  608. db.getRecord(FIELD_NAMES[1]);
  609. }
  610. catch (SQLException e)
  611. {
  612. fail("Getting record on empty database should not generate SQLException");
  613. }
  614. }
  615.  
  616. @Test
  617. public void testGetRecordCount()
  618. {
  619. try
  620. {
  621. db.createRecord(Arrays.copyOfRange(FIELD_NAMES, 1, FIELD_NAMES.length), Arrays.copyOfRange(values, 1, values.length));
  622. assertEquals("Testing to see if record count is 1 after creating a record.", 1, db.getRecordCount());
  623. db.createRecord(Arrays.copyOfRange(FIELD_NAMES, 1, FIELD_NAMES.length), Arrays.copyOfRange(values, 1, values.length));
  624. assertEquals("Testing to see if record count is 2 after creating a record.", 2, db.getRecordCount());
  625. db.deleteRecord("1");
  626. assertEquals("Testing to see if record count is 1 after deleting a record.", 1, db.getRecordCount());
  627. db.deleteRecord("2");
  628. assertEquals("Testing to see if record count is 0 after deleting a record.", 0, db.getRecordCount());
  629. }
  630. catch(SQLException e)
  631. {
  632. fail("Getting record count should not generate SQLException");
  633. }
  634. }
  635.  
  636. @Test
  637. public void testCreateRecord()
  638. {
  639. try
  640. {
  641. assertEquals("Testing creation of car with id provided", 1, db.createRecord(FIELD_NAMES, values));
  642. assertEquals("Testing the count of records", 1, db.getRecordCount());
  643. assertEquals("Testing creation of car, no id provided", 2, db.createRecord(Arrays.copyOfRange(FIELD_NAMES, 1, FIELD_NAMES.length), Arrays.copyOfRange(values, 1, values.length)));
  644. assertEquals("Testing the count of records", 2, db.getRecordCount());
  645. }
  646. catch (SQLException e)
  647. {
  648. e.printStackTrace();
  649. fail("Creation of records should not generate SQLException");
  650. }
  651.  
  652. try
  653. {
  654. db.createRecord(FIELD_NAMES, values);
  655. fail("Creating a record with a duplicate id should generate a SQLException.");
  656. }
  657. catch (SQLException e)
  658. {
  659. // Expected
  660. }
  661. }
  662.  
  663. @Test
  664. public void testUpdateRecord()
  665. {
  666. try
  667. {
  668. db.createRecord(Arrays.copyOfRange(FIELD_NAMES, 1, FIELD_NAMES.length), Arrays.copyOfRange(values, 1, values.length));
  669. assertTrue("Update should be successful", db.updateRecord("1", Arrays.copyOfRange(FIELD_NAMES, 1, FIELD_NAMES.length), Arrays.copyOfRange(values, 1, values.length)));
  670. assertFalse("Update should be successful", db.updateRecord("1", FIELD_NAMES, Arrays.copyOfRange(values, 1, values.length)));
  671. assertTrue("Update of id that does not exist should return true", db.updateRecord("10", Arrays.copyOfRange(FIELD_NAMES, 1, FIELD_NAMES.length), Arrays.copyOfRange(values, 1, values.length)));
  672. }
  673. catch (SQLException e)
  674. {
  675. fail("Update of records should not generate SQLException");
  676. }
  677. }
  678.  
  679. @Test
  680. public void testDeleteAllRecords()
  681. {
  682. try
  683. {
  684. db.createRecord(Arrays.copyOfRange(FIELD_NAMES, 1, FIELD_NAMES.length), Arrays.copyOfRange(values, 1, values.length));
  685. assertTrue("Before deletion, count should be positive", db.getRecordCount() > 0);
  686. db.deleteAllRecords();
  687. assertEquals("Count after deletion should be 0.", 0, db.getRecordCount());
  688. }
  689. catch (SQLException e)
  690. {
  691. fail("Deletion should not generate an SQLException.");
  692. }
  693. }
  694.  
  695. @Test
  696. public void testDeleteRecord()
  697. {
  698. try
  699. {
  700. db.createRecord(Arrays.copyOfRange(FIELD_NAMES, 1, FIELD_NAMES.length), Arrays.copyOfRange(values, 1, values.length));
  701. assertTrue("Before deletion, count should be positive", db.getRecordCount() > 0);
  702. db.deleteRecord("1");
  703. assertEquals("Count after deletion should be 0.", 0, db.getRecordCount());
  704. }
  705. catch (SQLException e)
  706. {
  707. fail("Deletion should not generate an SQLException.");
  708. }
  709. }
  710.  
  711. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement