From c106688549b494519aa8c6ec5162beb34740fa06 Mon Sep 17 00:00:00 2001 From: "github-classroom[bot]" <66690702+github-classroom[bot]@users.noreply.github.com> Date: Mon, 8 Dec 2025 09:55:05 +0000 Subject: [PATCH 1/8] add deadline --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index d20aaf9..7071577 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,4 @@ +[![Review Assignment Due Date](https://classroom.github.com/assets/deadline-readme-button-22041afd0340ce965d47ae6ef1cefeee28c7c493a6346c4f15d667ab976d596c.svg)](https://classroom.github.com/a/339Lr3BJ) ### How the tests work (and Docker requirement) This project ships with an end‑to‑end CLI integration test suite that uses Testcontainers to spin up a temporary MySQL database. From afbae1f2df6a0a57ccf6cbe31ee281fef059b305 Mon Sep 17 00:00:00 2001 From: Anna Ziafar Date: Thu, 11 Dec 2025 13:57:57 +0100 Subject: [PATCH 2/8] =?UTF-8?q?Datasource=20-=20klar=20Validering=20av=20a?= =?UTF-8?q?nv=C3=A4ndare=20-=20klar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 10 ++++ src/main/java/com/example/DataSource.java | 49 ++++++++++++++++ src/main/java/com/example/Main.java | 68 +++++++++++++++-------- 3 files changed, 103 insertions(+), 24 deletions(-) create mode 100644 src/main/java/com/example/DataSource.java diff --git a/pom.xml b/pom.xml index 002ff66..02e44d0 100644 --- a/pom.xml +++ b/pom.xml @@ -51,6 +51,16 @@ mysql 1.21.3 + + org.apache.commons + commons-dbcp2 + 2.13.0 + + + org.slf4j + slf4j-nop + 2.0.17 + diff --git a/src/main/java/com/example/DataSource.java b/src/main/java/com/example/DataSource.java new file mode 100644 index 0000000..e8d1b72 --- /dev/null +++ b/src/main/java/com/example/DataSource.java @@ -0,0 +1,49 @@ +package com.example; + +import org.apache.commons.dbcp2.BasicDataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class DataSource { + + private static BasicDataSource source = new BasicDataSource(); + private final static String jdbcUrl = resolveConfig("APP_JDBC_URL", "APP_JDBC_URL"); + private final static String dbUser = resolveConfig("APP_DB_USER", "APP_DB_USER"); + private final static String dbPass = resolveConfig("APP_DB_PASS", "APP_DB_PASS"); + + static { + source.setUrl(jdbcUrl); + source.setUsername(dbUser); + source.setPassword(dbPass); + source.addConnectionProperty("hibernate.hbm2ddl.auto", "update"); + } + + public static Connection getConnection() throws SQLException { + return source.getConnection(); + } + + public static String getJdbcUrl(){ + return jdbcUrl; + } + + public static String getDbUser(){ + return dbUser; + } + + public static String getDbPass(){ + return dbPass; + } + + + /** + * Reads configuration with precedence: Java system property first, then environment variable. + * Returns trimmed value or null if neither source provides a non-empty value. + */ + private static String resolveConfig(String propertyKey, String envKey) { + String v = System.getProperty(propertyKey); + if (v == null || v.trim().isEmpty()) { + v = System.getenv(envKey); + } + return (v == null || v.trim().isEmpty()) ? null : v.trim(); + } +} diff --git a/src/main/java/com/example/Main.java b/src/main/java/com/example/Main.java index 6dc6fbd..04e00e5 100644 --- a/src/main/java/com/example/Main.java +++ b/src/main/java/com/example/Main.java @@ -1,36 +1,34 @@ package com.example; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; +import java.sql.*; import java.util.Arrays; +import java.util.Objects; public class Main { + private static String userQuery = "SELECT * FROM account WHERE name = ?"; - static void main(String[] args) { + static void main(String[] args) throws SQLException { if (isDevMode(args)) { DevDatabaseInitializer.start(); } new Main().run(); + } public void run() { - // Resolve DB settings with precedence: System properties -> Environment variables - String jdbcUrl = resolveConfig("APP_JDBC_URL", "APP_JDBC_URL"); - String dbUser = resolveConfig("APP_DB_USER", "APP_DB_USER"); - String dbPass = resolveConfig("APP_DB_PASS", "APP_DB_PASS"); - - if (jdbcUrl == null || dbUser == null || dbPass == null) { + if (DataSource.getJdbcUrl() == null || DataSource.getDbUser() == null || DataSource.getDbPass() == null) { throw new IllegalStateException( "Missing DB configuration. Provide APP_JDBC_URL, APP_DB_USER, APP_DB_PASS " + "as system properties (-Dkey=value) or environment variables."); } - try (Connection connection = DriverManager.getConnection(jdbcUrl, dbUser, dbPass)) { - } catch (SQLException e) { - throw new RuntimeException(e); + + if(validateSignIn() == false){ + System.out.println("Invalid username or password"); + } else { + System.out.println("YAY"); } - //Todo: Starting point for your code + } /** @@ -48,15 +46,37 @@ private static boolean isDevMode(String[] args) { return Arrays.asList(args).contains("--dev"); //Argument --dev } - /** - * Reads configuration with precedence: Java system property first, then environment variable. - * Returns trimmed value or null if neither source provides a non-empty value. - */ - private static String resolveConfig(String propertyKey, String envKey) { - String v = System.getProperty(propertyKey); - if (v == null || v.trim().isEmpty()) { - v = System.getenv(envKey); + + private static boolean validateSignIn(){ + String userName = IO.readln("Enter the username: "); + String password = IO.readln("Enter the password: "); + + try(Connection con = DataSource.getConnection(); PreparedStatement ps = con.prepareStatement(userQuery)){ + ps.setString(1, userName); + ResultSet result = ps.executeQuery(); + if(result.next() == false){ + return false; + } + + String inputPassword = result.getString(3); + return Objects.equals(inputPassword, password); + + } catch (SQLException e) { + throw new RuntimeException(e); } - return (v == null || v.trim().isEmpty()) ? null : v.trim(); } -} + + + private static void printMenu(){ + System.out.println(" MENU\n" + + "=====================================================================\n" + + "\n" + + "1) List moon missions (prints spacecraft names from `moon_mission`).\n" + + "2) Get a moon mission by mission_id (prints details for that mission).\n" + + "3) Count missions for a given year (prompts: year; prints the number of missions launched that year).\n" + + "4) Create an account (prompts: first name, last name, ssn, password; prints confirmation).\n" + + "5) Update an account password (prompts: user_id, new password; prints confirmation).\n" + + "6) Delete an account (prompts: user_id; prints confirmation).\n" + + "0) Exit."); + } +} \ No newline at end of file From 2d9f527953ee88a6845cb21c2d1f3dbc5dd7ba6f Mon Sep 17 00:00:00 2001 From: Anna Ziafar Date: Thu, 11 Dec 2025 20:30:35 +0100 Subject: [PATCH 3/8] =?UTF-8?q?Uppdaterad=20logik=20f=C3=B6r=20inloggning.?= =?UTF-8?q?=20Ny=20metod:=20initialize()?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/example/Main.java | 44 ++++++++++++++++++----------- 1 file changed, 28 insertions(+), 16 deletions(-) diff --git a/src/main/java/com/example/Main.java b/src/main/java/com/example/Main.java index 04e00e5..9251c8c 100644 --- a/src/main/java/com/example/Main.java +++ b/src/main/java/com/example/Main.java @@ -22,13 +22,14 @@ public void run() { "as system properties (-Dkey=value) or environment variables."); } - - if(validateSignIn() == false){ - System.out.println("Invalid username or password"); - } else { - System.out.println("YAY"); + boolean execute = initialize(); + while(execute){ + printMenu(); + String choice = IO.readln("Please enter your choice: "); } + System.out.println("hejhej"); + } /** @@ -46,27 +47,37 @@ private static boolean isDevMode(String[] args) { return Arrays.asList(args).contains("--dev"); //Argument --dev } + private static boolean initialize(){ + while (true){ + String userName = IO.readln("Enter the username: "); + String password = IO.readln("Enter the password: "); + System.out.println(); - private static boolean validateSignIn(){ - String userName = IO.readln("Enter the username: "); - String password = IO.readln("Enter the password: "); + if(validateSignIn(userName, password)) + return true; - try(Connection con = DataSource.getConnection(); PreparedStatement ps = con.prepareStatement(userQuery)){ - ps.setString(1, userName); - ResultSet result = ps.executeQuery(); - if(result.next() == false){ + String choice = IO.readln("Invalid username or password. Press 0 to exit or any other key to return to sign in: "); + if(choice.trim().equals("0")) return false; + } + } + + private static boolean validateSignIn(String username, String password){ + try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(userQuery)) { + pS.setString(1, username); + ResultSet result = pS.executeQuery(); + if(result.next()){ + String inputPassword = result.getString(3); + return Objects.equals(inputPassword, password); } - String inputPassword = result.getString(3); - return Objects.equals(inputPassword, password); + return false; } catch (SQLException e) { throw new RuntimeException(e); } } - private static void printMenu(){ System.out.println(" MENU\n" + "=====================================================================\n" + @@ -77,6 +88,7 @@ private static void printMenu(){ "4) Create an account (prompts: first name, last name, ssn, password; prints confirmation).\n" + "5) Update an account password (prompts: user_id, new password; prints confirmation).\n" + "6) Delete an account (prompts: user_id; prints confirmation).\n" + - "0) Exit."); + "0) Exit." + + " "); } } \ No newline at end of file From 0924a272b7f8c33fd3f9390e244489e6d003e361 Mon Sep 17 00:00:00 2001 From: Anna Ziafar Date: Thu, 11 Dec 2025 21:08:55 +0100 Subject: [PATCH 4/8] Uppdaterade metod + variabelnamn. Ny metod - handleMenuOptions --- src/main/java/com/example/Main.java | 52 +++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/example/Main.java b/src/main/java/com/example/Main.java index 9251c8c..44216b2 100644 --- a/src/main/java/com/example/Main.java +++ b/src/main/java/com/example/Main.java @@ -5,7 +5,7 @@ import java.util.Objects; public class Main { - private static String userQuery = "SELECT * FROM account WHERE name = ?"; + private static final String userQuery = "SELECT * FROM account WHERE name = ?"; static void main(String[] args) throws SQLException { if (isDevMode(args)) { @@ -22,14 +22,40 @@ public void run() { "as system properties (-Dkey=value) or environment variables."); } - boolean execute = initialize(); - while(execute){ - printMenu(); - String choice = IO.readln("Please enter your choice: "); + boolean executeProgram = authenticateUser(); + while(executeProgram){ + displayMenu(); + String choice = IO.readln("Your choice: "); + executeProgram = handleMenuOptions(choice); } + } - System.out.println("hejhej"); - + private boolean handleMenuOptions(String choice){ + switch (choice) { + case "0": + return false; + case "1": + System.out.println("Case 1"); + return true; + case "2": + System.out.println("Case 2"); + return true; + case "3": + System.out.println("Case 3"); + return true; + case "4": + System.out.println("Case 4"); + return true; + case "5": + System.out.println("Case 5"); + return true; + case "6": + System.out.println("Case 6"); + return true; + default: + System.out.println("Invalid entry, please try again."); + return true; + } } /** @@ -47,13 +73,13 @@ private static boolean isDevMode(String[] args) { return Arrays.asList(args).contains("--dev"); //Argument --dev } - private static boolean initialize(){ + private static boolean authenticateUser(){ while (true){ - String userName = IO.readln("Enter the username: "); - String password = IO.readln("Enter the password: "); + String username = IO.readln("Enter your username: "); + String password = IO.readln("Enter your password: "); System.out.println(); - if(validateSignIn(userName, password)) + if(validateSignIn(username, password)) return true; String choice = IO.readln("Invalid username or password. Press 0 to exit or any other key to return to sign in: "); @@ -78,7 +104,7 @@ private static boolean validateSignIn(String username, String password){ } } - private static void printMenu(){ + private static void displayMenu(){ System.out.println(" MENU\n" + "=====================================================================\n" + "\n" + @@ -88,7 +114,7 @@ private static void printMenu(){ "4) Create an account (prompts: first name, last name, ssn, password; prints confirmation).\n" + "5) Update an account password (prompts: user_id, new password; prints confirmation).\n" + "6) Delete an account (prompts: user_id; prints confirmation).\n" + - "0) Exit." + + "0) Exit.\n" + " "); } } \ No newline at end of file From 03ed5b851a6838e0ba93cd8591c543f815433fc0 Mon Sep 17 00:00:00 2001 From: Anna Ziafar Date: Sun, 14 Dec 2025 11:10:43 +0100 Subject: [PATCH 5/8] Allt funkar utom displayMissionsForAYear --- src/main/java/com/example/DataSource.java | 1 + src/main/java/com/example/Main.java | 207 ++++++++++++++++++---- 2 files changed, 176 insertions(+), 32 deletions(-) diff --git a/src/main/java/com/example/DataSource.java b/src/main/java/com/example/DataSource.java index e8d1b72..5715e22 100644 --- a/src/main/java/com/example/DataSource.java +++ b/src/main/java/com/example/DataSource.java @@ -16,6 +16,7 @@ public class DataSource { source.setUsername(dbUser); source.setPassword(dbPass); source.addConnectionProperty("hibernate.hbm2ddl.auto", "update"); + source.setDefaultAutoCommit(true); } public static Connection getConnection() throws SQLException { diff --git a/src/main/java/com/example/Main.java b/src/main/java/com/example/Main.java index 44216b2..7c71b4e 100644 --- a/src/main/java/com/example/Main.java +++ b/src/main/java/com/example/Main.java @@ -1,11 +1,19 @@ package com.example; import java.sql.*; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Objects; +import java.util.Scanner; public class Main { private static final String userQuery = "SELECT * FROM account WHERE name = ?"; + private static String missionQuery = "SELECT * FROM moon_mission"; + private static final String COUNT_MISSIONS_QUERY = "SELECT COUNT(*) FROM moon_mission WHERE launch_date LIKE ?"; + + private static final int columnsMoonMissions = 7; + private Scanner scanner = new Scanner(System.in); static void main(String[] args) throws SQLException { if (isDevMode(args)) { @@ -24,37 +32,169 @@ public void run() { boolean executeProgram = authenticateUser(); while(executeProgram){ + displayMenu(); - String choice = IO.readln("Your choice: "); - executeProgram = handleMenuOptions(choice); + System.out.println("Your choice: "); + String choice = scanner.nextLine(); + + switch (choice) { + case "0": + executeProgram = false; + break; + case "1": + displayAllMoonMissions(); + break; + case "2": + getMissionFromID(); + break; + case "3": + displayMissionsForAYear(); + break; + case "4": + createAccount(); + break; + case "5": + updatePassword(); + break; + case "6": + deleteAccount(); + break; + default: + System.out.println("Invalid entry, please try again."); + break; + + } } } - private boolean handleMenuOptions(String choice){ - switch (choice) { - case "0": - return false; - case "1": - System.out.println("Case 1"); - return true; - case "2": - System.out.println("Case 2"); - return true; - case "3": - System.out.println("Case 3"); - return true; - case "4": - System.out.println("Case 4"); - return true; - case "5": - System.out.println("Case 5"); - return true; - case "6": - System.out.println("Case 6"); - return true; - default: - System.out.println("Invalid entry, please try again."); - return true; + public void createAccount(){ + String addUser = "insert into account (name, password, first_name, last_name, ssn)" + + "values (?, ?, ?, ?, ?)"; + + try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(addUser)) { + System.out.println("Enter your firstname: "); + String firstname = scanner.nextLine(); + System.out.println("Enter your lastname: "); + String lastname = scanner.nextLine(); + System.out.println("Choose a password: "); + String password = scanner.nextLine(); + System.out.println("Enter your social security number (nnnnnn-nnnn): "); + String ssn = scanner.nextLine(); + String username = firstname.substring(0, 3) + lastname.substring(0, 3); + + pS.setString(1, username); + pS.setString(2, password); + pS.setString(3, firstname); + pS.setString(4, lastname); + pS.setString(5, ssn); + pS.executeUpdate(); + + System.out.println("User " + username + " succesfully created"); + + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + private void deleteAccount(){ + String delete = "delete from account where user_id = ?"; + try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(delete)) { + System.out.println("Enter user_id for the account that you would like to delete: "); + int id = Integer.parseInt(scanner.nextLine()); + + pS.setInt(1, id); + int rowsDeleted = pS.executeUpdate(); + + if (rowsDeleted > 0) + System.out.println("Account with id " + id + " successfully deleted"); + else + System.out.println("Error! Something went wrong when deleting the account."); + + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + private void updatePassword(){ + String findId = "update account set password = ? where user_id = ?"; + try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(findId)) { + System.out.print("Enter user-id: "); + int id = Integer.parseInt(scanner.nextLine()); + System.out.print("New password: "); + String password = scanner.nextLine(); + + pS.setString(1, password); + pS.setInt(2, id); + int rowsUpdated = pS.executeUpdate(); + + if (rowsUpdated > 0) + System.out.println("Password successfully updated."); + else + System.out.println("Error! Something went wrong when updating the password."); + + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + private void displayMissionsForAYear() { + try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(COUNT_MISSIONS_QUERY)) { + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + String inputYear = IO.readln("Select a year: "); + LocalDate year = LocalDate.parse(inputYear.trim() + "-01-01", formatter); + + pS.setDate(1, Date.valueOf(year)); + ResultSet result = pS.executeQuery(); + + if(result.next()){ + int numOfMissions = result.getInt("mission_count"); + System.out.println("During " + year + "there were " + numOfMissions + " missions in total."); + } else + System.out.println("There were no moon missions registered during " + year); + + + } catch (SQLException e) { + throw new RuntimeException(); + } + } + + private void getMissionFromID(){ + try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(missionQuery + " where mission_id = ?")) { + System.out.println("Enter a mission-id: "); + int missionId = Integer.parseInt(scanner.nextLine()); + pS.setInt(1, missionId); + ResultSet result = pS.executeQuery(); + + if(result.next()){ + ResultSetMetaData meta = result.getMetaData(); + int columns = meta.getColumnCount(); + + System.out.println("\n-------- Mission Details --------\n"); + for(int i = 1; i <= columns; i++){ + System.out.println(meta.getColumnName(i) + ": " + result.getString(i)); + } + + } else { + System.out.println("Could not find mission with id: " + missionId); + } + + } catch (SQLException e) { + throw new RuntimeException(e); + } + + } + + private void displayAllMoonMissions(){ + try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(missionQuery)) { + ResultSet result = pS.executeQuery(); + System.out.println("\nList of all spacecrafts: \n "); + while (result.next()){ + String name = result.getString("spacecraft"); + System.out.println(name); + } + + } catch (SQLException e) { + throw new RuntimeException(e); } } @@ -73,17 +213,20 @@ private static boolean isDevMode(String[] args) { return Arrays.asList(args).contains("--dev"); //Argument --dev } - private static boolean authenticateUser(){ + private boolean authenticateUser(){ while (true){ - String username = IO.readln("Enter your username: "); - String password = IO.readln("Enter your password: "); + System.out.println("Username: "); + String username = scanner.nextLine(); + System.out.println("Password: "); + String password = scanner.nextLine(); System.out.println(); if(validateSignIn(username, password)) return true; - String choice = IO.readln("Invalid username or password. Press 0 to exit or any other key to return to sign in: "); - if(choice.trim().equals("0")) + System.out.println("Invalid username or password. Press 0 to exit or any other key to return to sign in: "); + String choice = scanner.nextLine(); + if(choice != null && choice.trim().equals("0")) return false; } } From ca205f63b930ccb0e7e5abcc074fb0d45aca3b02 Mon Sep 17 00:00:00 2001 From: Anna Ziafar Date: Sun, 14 Dec 2025 18:44:09 +0100 Subject: [PATCH 6/8] Allt klart! --- pom.xml | 5 + src/main/java/com/example/DataSource.java | 8 +- src/main/java/com/example/Main.java | 275 ++++++------------ src/main/java/repositories/AccountInter.java | 42 +++ src/main/java/repositories/AccountRepo.java | 96 ++++++ .../java/repositories/MoonMissionInter.java | 23 ++ .../java/repositories/MoonMissionRepo.java | 80 +++++ 7 files changed, 346 insertions(+), 183 deletions(-) create mode 100644 src/main/java/repositories/AccountInter.java create mode 100644 src/main/java/repositories/AccountRepo.java create mode 100644 src/main/java/repositories/MoonMissionInter.java create mode 100644 src/main/java/repositories/MoonMissionRepo.java diff --git a/pom.xml b/pom.xml index 02e44d0..ecefccc 100644 --- a/pom.xml +++ b/pom.xml @@ -61,6 +61,11 @@ slf4j-nop 2.0.17 + + org.hibernate.orm + hibernate-core + 7.1.11.Final + diff --git a/src/main/java/com/example/DataSource.java b/src/main/java/com/example/DataSource.java index 5715e22..1c27cd1 100644 --- a/src/main/java/com/example/DataSource.java +++ b/src/main/java/com/example/DataSource.java @@ -6,10 +6,10 @@ public class DataSource { - private static BasicDataSource source = new BasicDataSource(); - private final static String jdbcUrl = resolveConfig("APP_JDBC_URL", "APP_JDBC_URL"); - private final static String dbUser = resolveConfig("APP_DB_USER", "APP_DB_USER"); - private final static String dbPass = resolveConfig("APP_DB_PASS", "APP_DB_PASS"); + private static final BasicDataSource source = new BasicDataSource(); + private static final String jdbcUrl = resolveConfig("APP_JDBC_URL", "APP_JDBC_URL"); + private static final String dbUser = resolveConfig("APP_DB_USER", "APP_DB_USER"); + private static final String dbPass = resolveConfig("APP_DB_PASS", "APP_DB_PASS"); static { source.setUrl(jdbcUrl); diff --git a/src/main/java/com/example/Main.java b/src/main/java/com/example/Main.java index 7c71b4e..74d53df 100644 --- a/src/main/java/com/example/Main.java +++ b/src/main/java/com/example/Main.java @@ -1,19 +1,15 @@ package com.example; +import repositories.AccountRepo; +import repositories.MoonMissionRepo; + import java.sql.*; -import java.time.LocalDate; -import java.time.format.DateTimeFormatter; import java.util.Arrays; -import java.util.Objects; import java.util.Scanner; public class Main { - private static final String userQuery = "SELECT * FROM account WHERE name = ?"; - private static String missionQuery = "SELECT * FROM moon_mission"; - private static final String COUNT_MISSIONS_QUERY = "SELECT COUNT(*) FROM moon_mission WHERE launch_date LIKE ?"; - private static final int columnsMoonMissions = 7; - private Scanner scanner = new Scanner(System.in); + private final Scanner scanner = new Scanner(System.in); static void main(String[] args) throws SQLException { if (isDevMode(args)) { @@ -30,172 +26,110 @@ public void run() { "as system properties (-Dkey=value) or environment variables."); } - boolean executeProgram = authenticateUser(); - while(executeProgram){ + AccountRepo accountRepo = new AccountRepo(); + MoonMissionRepo moonMissionRepo = new MoonMissionRepo(); + + //Only run program if sign-in is valid + boolean executeProgram = validateSignIn(accountRepo); + while (executeProgram) { displayMenu(); - System.out.println("Your choice: "); - String choice = scanner.nextLine(); + System.out.print("Your choice: "); + String choice = scanner.nextLine().trim(); switch (choice) { - case "0": - executeProgram = false; - break; - case "1": - displayAllMoonMissions(); - break; - case "2": - getMissionFromID(); - break; - case "3": - displayMissionsForAYear(); - break; - case "4": - createAccount(); - break; - case "5": - updatePassword(); - break; - case "6": - deleteAccount(); - break; - default: - System.out.println("Invalid entry, please try again."); - break; - + case "0" -> executeProgram = false; + case "1" -> displayAllMoonMissions(moonMissionRepo); + case "2" -> getMissionFromID(moonMissionRepo); + case "3" -> displayMissionsForAYear(moonMissionRepo); + case "4" -> createAccount(accountRepo); + case "5" -> updatePassword(accountRepo); + case "6" -> deleteAccount(accountRepo); + default -> System.out.println("Invalid entry, please try again."); } } } - public void createAccount(){ - String addUser = "insert into account (name, password, first_name, last_name, ssn)" + - "values (?, ?, ?, ?, ?)"; - - try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(addUser)) { - System.out.println("Enter your firstname: "); - String firstname = scanner.nextLine(); - System.out.println("Enter your lastname: "); - String lastname = scanner.nextLine(); - System.out.println("Choose a password: "); - String password = scanner.nextLine(); - System.out.println("Enter your social security number (nnnnnn-nnnn): "); - String ssn = scanner.nextLine(); - String username = firstname.substring(0, 3) + lastname.substring(0, 3); - - pS.setString(1, username); - pS.setString(2, password); - pS.setString(3, firstname); - pS.setString(4, lastname); - pS.setString(5, ssn); - pS.executeUpdate(); - - System.out.println("User " + username + " succesfully created"); - - } catch (SQLException e) { - throw new RuntimeException(e); + public void createAccount(AccountRepo accountRepo) { + System.out.print("Enter your first name: "); + String firstName = scanner.nextLine().trim(); + if(firstName.isBlank() || firstName.length() < 3){ + System.out.println("Error. First name must be at least 3 characters."); + return; } - } - - private void deleteAccount(){ - String delete = "delete from account where user_id = ?"; - try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(delete)) { - System.out.println("Enter user_id for the account that you would like to delete: "); - int id = Integer.parseInt(scanner.nextLine()); - - pS.setInt(1, id); - int rowsDeleted = pS.executeUpdate(); - - if (rowsDeleted > 0) - System.out.println("Account with id " + id + " successfully deleted"); - else - System.out.println("Error! Something went wrong when deleting the account."); - } catch (SQLException e) { - throw new RuntimeException(e); + System.out.print("Enter your lastname: "); + String lastName = scanner.nextLine().trim(); + if(lastName.isBlank() || lastName.length() < 3){ + System.out.println("Error. Lastname must be at least 3 characters."); + return; } - } - private void updatePassword(){ - String findId = "update account set password = ? where user_id = ?"; - try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(findId)) { - System.out.print("Enter user-id: "); - int id = Integer.parseInt(scanner.nextLine()); - System.out.print("New password: "); - String password = scanner.nextLine(); - - pS.setString(1, password); - pS.setInt(2, id); - int rowsUpdated = pS.executeUpdate(); - - if (rowsUpdated > 0) - System.out.println("Password successfully updated."); - else - System.out.println("Error! Something went wrong when updating the password."); - - } catch (SQLException e) { - throw new RuntimeException(e); + System.out.print("Enter your social security number (yymmdd-nnnn): "); + String ssn = scanner.nextLine().trim(); + if(!ssn.matches("^\\d{6}-\\d{4}")){ + System.out.println("Error! Must be in format yymmdd-xxxx"); + return; } - } - private void displayMissionsForAYear() { - try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(COUNT_MISSIONS_QUERY)) { - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); - String inputYear = IO.readln("Select a year: "); - LocalDate year = LocalDate.parse(inputYear.trim() + "-01-01", formatter); + System.out.print("Choose a password: "); + String password = scanner.nextLine().trim(); + if(!validPassword(password)){ + return; + } - pS.setDate(1, Date.valueOf(year)); - ResultSet result = pS.executeQuery(); + accountRepo.createAccount(firstName, lastName, password, ssn); + } - if(result.next()){ - int numOfMissions = result.getInt("mission_count"); - System.out.println("During " + year + "there were " + numOfMissions + " missions in total."); - } else - System.out.println("There were no moon missions registered during " + year); + private void deleteAccount(AccountRepo accountRepo) { + System.out.print("Enter userId for the account that you would like to delete: "); + int userId = Integer.parseInt(scanner.nextLine().trim()); + accountRepo.deleteAccount(userId); + } - } catch (SQLException e) { - throw new RuntimeException(); + private boolean validPassword(String password){ + if(password.isBlank() || password.length() < 6){ + System.out.println("Error. Password must be at least 8 characters long."); + return false; } + return true; } - private void getMissionFromID(){ - try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(missionQuery + " where mission_id = ?")) { - System.out.println("Enter a mission-id: "); - int missionId = Integer.parseInt(scanner.nextLine()); - pS.setInt(1, missionId); - ResultSet result = pS.executeQuery(); - - if(result.next()){ - ResultSetMetaData meta = result.getMetaData(); - int columns = meta.getColumnCount(); + private void updatePassword(AccountRepo accountRepo) { + System.out.print("Enter user id: "); + int userId = Integer.parseInt(scanner.nextLine().trim()); - System.out.println("\n-------- Mission Details --------\n"); - for(int i = 1; i <= columns; i++){ - System.out.println(meta.getColumnName(i) + ": " + result.getString(i)); - } + System.out.print("Choose a new password: "); + String password = scanner.nextLine().trim(); + if(!validPassword(password)){ + return; + } - } else { - System.out.println("Could not find mission with id: " + missionId); - } + accountRepo.updatePassword(userId, password); + } - } catch (SQLException e) { - throw new RuntimeException(e); + private void displayMissionsForAYear(MoonMissionRepo moonMissionRepo) { + System.out.print("Enter a year: "); + String year = scanner.nextLine().trim(); + if(!year.matches("^[1-2][09]\\d{2}")){ + System.out.println("Invalid year"); + return; } + moonMissionRepo.allMissionsConductedInYear(year); } - private void displayAllMoonMissions(){ - try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(missionQuery)) { - ResultSet result = pS.executeQuery(); - System.out.println("\nList of all spacecrafts: \n "); - while (result.next()){ - String name = result.getString("spacecraft"); - System.out.println(name); - } + private void getMissionFromID(MoonMissionRepo moonMissionRepo) { + System.out.print("Enter the mission-id: "); + int id = Integer.parseInt(scanner.nextLine().trim()); - } catch (SQLException e) { - throw new RuntimeException(e); - } + moonMissionRepo.getMissionFromID(id); + } + + private void displayAllMoonMissions(MoonMissionRepo moonMissionRepo) { + String column = "spacecraft"; + moonMissionRepo.displayColumn(column); } /** @@ -213,50 +147,33 @@ private static boolean isDevMode(String[] args) { return Arrays.asList(args).contains("--dev"); //Argument --dev } - private boolean authenticateUser(){ - while (true){ - System.out.println("Username: "); - String username = scanner.nextLine(); - System.out.println("Password: "); - String password = scanner.nextLine(); - System.out.println(); + private boolean validateSignIn(AccountRepo accountRepo){ + while (true) { + System.out.print("Username: "); + String username = scanner.nextLine().trim(); + System.out.print("Password: "); + String password = scanner.nextLine().trim(); - if(validateSignIn(username, password)) + if(accountRepo.validateLogIn(username, password)) return true; System.out.println("Invalid username or password. Press 0 to exit or any other key to return to sign in: "); String choice = scanner.nextLine(); - if(choice != null && choice.trim().equals("0")) + if (choice != null && choice.trim().equals("0")) return false; } } - private static boolean validateSignIn(String username, String password){ - try(Connection con = DataSource.getConnection(); PreparedStatement pS = con.prepareStatement(userQuery)) { - pS.setString(1, username); - ResultSet result = pS.executeQuery(); - if(result.next()){ - String inputPassword = result.getString(3); - return Objects.equals(inputPassword, password); - } - - return false; - - } catch (SQLException e) { - throw new RuntimeException(e); - } - } - - private static void displayMenu(){ - System.out.println(" MENU\n" + - "=====================================================================\n" + + private static void displayMenu() { + System.out.println(" MENU\n" + + "=======================================\n" + "\n" + - "1) List moon missions (prints spacecraft names from `moon_mission`).\n" + - "2) Get a moon mission by mission_id (prints details for that mission).\n" + - "3) Count missions for a given year (prompts: year; prints the number of missions launched that year).\n" + - "4) Create an account (prompts: first name, last name, ssn, password; prints confirmation).\n" + - "5) Update an account password (prompts: user_id, new password; prints confirmation).\n" + - "6) Delete an account (prompts: user_id; prints confirmation).\n" + + "1) List moon missions.\n" + + "2) Get a moon mission by mission_id.\n" + + "3) Count missions for a given year.\n" + + "4) Create an account.\n" + + "5) Update an account password.\n" + + "6) Delete an account.\n" + "0) Exit.\n" + " "); } diff --git a/src/main/java/repositories/AccountInter.java b/src/main/java/repositories/AccountInter.java new file mode 100644 index 0000000..9ea1eb4 --- /dev/null +++ b/src/main/java/repositories/AccountInter.java @@ -0,0 +1,42 @@ +package repositories; + +public interface AccountInter { + + /** + * Validates username and password. + * @param password connected to username. + * @param username of account that will be validated. + * @return true if user exists in database, otherwise return false. + */ + boolean validateLogIn(String username, String password); + + /** + * Creates an account + * + * @param firstName users first name. + * @param lastName users last name. + * @param password user chooses a password. + * @param ssn users social security number. + * Print confirmation if account was successfully created, otherwise print error-message + */ + void createAccount(String firstName, String lastName, String password, String ssn); + + + /** + * Deletes an existing account. + * @param userId primary key used to find account. + * If account is not found print error message, + * otherwise print confirmation + */ + void deleteAccount(int userId); + + /** + * Updates password of existing account + * @param userID unique key used to find account + * @param password new password + * Prints confirmation when password successfully changed, + * otherwise print error-message + */ + void updatePassword(int userID, String password); + +} diff --git a/src/main/java/repositories/AccountRepo.java b/src/main/java/repositories/AccountRepo.java new file mode 100644 index 0000000..8e5d1be --- /dev/null +++ b/src/main/java/repositories/AccountRepo.java @@ -0,0 +1,96 @@ +package repositories; + +import com.example.DataSource; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +public class AccountRepo implements AccountInter{ + + @Override + public boolean validateLogIn(String username, String password) { + String userQuery = "select * from account where name = ? and password = ?"; + + try (Connection con = DataSource.getConnection(); + PreparedStatement pS = con.prepareStatement(userQuery)) { + + pS.setString(1, username); + pS.setString(2, password); + ResultSet result = pS.executeQuery(); + return result.next(); + + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Override + public void createAccount(String firstName, String lastName, String password, String ssn) { + String addUser = "insert into account (name, password, first_name, last_name, ssn)" + + "values (?, ?, ?, ?, ?)"; + + try (Connection con = DataSource.getConnection(); + PreparedStatement pS = con.prepareStatement(addUser)) { + + String username = firstName.substring(0, 3) + lastName.substring(0, 3); + pS.setString(1, username); + pS.setString(2, password); + pS.setString(3, firstName); + pS.setString(4, lastName); + pS.setString(5, ssn); + int rowsAffected = pS.executeUpdate(); + + if(rowsAffected == 0) + System.out.println("Error. Something went wrong when creating the account."); + else + System.out.println("Account with username " + username + " successfully created."); + + + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Override + public void deleteAccount(int userId) { + String deleteUser = "delete from account where user_id = ?"; + + try (Connection con = DataSource.getConnection(); + PreparedStatement pS = con.prepareStatement(deleteUser)) { + + pS.setInt(1, userId); + int rowsDeleted = pS.executeUpdate(); + + if (rowsDeleted > 0) + System.out.println("Account with id " + userId + " successfully deleted"); + else + System.out.println("Error! No account found with id: " + userId); + + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Override + public void updatePassword(int userID, String password) { + String updatePassword = "update account set password = ? where user_id = ?"; + + try (Connection con = DataSource.getConnection(); + PreparedStatement pS = con.prepareStatement(updatePassword)) { + + pS.setString(1, password); + pS.setInt(2, userID); + int rowsUpdated = pS.executeUpdate(); + + if (rowsUpdated > 0) + System.out.println("Password successfully updated."); + else + System.out.println("Error! Something went wrong when updating the password."); + + } catch (SQLException e) { + throw new RuntimeException(e); + } + } +} diff --git a/src/main/java/repositories/MoonMissionInter.java b/src/main/java/repositories/MoonMissionInter.java new file mode 100644 index 0000000..e1781d5 --- /dev/null +++ b/src/main/java/repositories/MoonMissionInter.java @@ -0,0 +1,23 @@ +package repositories; + +public interface MoonMissionInter { + /** + * Display all information from chosen column, if * then show all columns + * @param columnName the column that you would like to display + */ + void displayColumn(String columnName); + + /** + * Retrieves all information about a mission when you enter an ID + * @param missionID unique for each mission + */ + void getMissionFromID(int missionID); + + /** + * Counts how many missions have been conducted in a year + * @param year the chosen year + * Prints number of missions even if they were 0 + */ + void allMissionsConductedInYear(String year); + +} diff --git a/src/main/java/repositories/MoonMissionRepo.java b/src/main/java/repositories/MoonMissionRepo.java new file mode 100644 index 0000000..ad134e3 --- /dev/null +++ b/src/main/java/repositories/MoonMissionRepo.java @@ -0,0 +1,80 @@ +package repositories; + +import com.example.DataSource; + +import java.sql.*; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +public class MoonMissionRepo implements MoonMissionInter{ + @Override + public void displayColumn(String columnName) { + String query = "select * from moon_mission"; + + try (Connection con = DataSource.getConnection(); + PreparedStatement pS = con.prepareStatement(query)) { + + ResultSet result = pS.executeQuery(); + while (result.next()) { + String name = result.getString(columnName); + System.out.println(name); + } + + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + @Override + public void getMissionFromID(int missionId) { + String query = "select * from moon_mission where mission_id = ?"; + + try (Connection con = DataSource.getConnection(); + PreparedStatement pS = con.prepareStatement(query)) { + + pS.setInt(1, missionId); + ResultSet result = pS.executeQuery(); + + if (result.next()) { + ResultSetMetaData meta = result.getMetaData(); + int columns = meta.getColumnCount(); + + System.out.println("\n-------- Mission Details --------\n"); + for (int i = 1; i <= columns; i++) { + System.out.println(meta.getColumnName(i) + ": " + result.getString(i)); + } + + } else { + System.out.println("Could not find mission with id: " + missionId); + } + + } catch (SQLException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + @Override + public void allMissionsConductedInYear(String year) { + String query = "select count(*) from moon_mission where launch_date like ?"; + + try (Connection con = DataSource.getConnection(); + PreparedStatement pS = con.prepareStatement(query)) { + + int numMissions = 0; + pS.setString(1, year.trim() + "%"); + ResultSet result = pS.executeQuery(); + if (result.next()){ + numMissions = result.getInt(1); + } + + System.out.println("There were " + numMissions + " moon missions registered during " + year + "."); + + } catch (SQLException e) { + e.printStackTrace(); + throw new RuntimeException(); + } + } + + +} From c36f9480d4f5b8827c75bd533b7c3f59b43c5cc2 Mon Sep 17 00:00:00 2001 From: Anna Ziafar Date: Sun, 14 Dec 2025 18:58:22 +0100 Subject: [PATCH 7/8] Snyggare layout --- src/main/java/com/example/Main.java | 28 +++++++++++-------- .../java/repositories/MoonMissionRepo.java | 2 +- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/src/main/java/com/example/Main.java b/src/main/java/com/example/Main.java index 74d53df..879552e 100644 --- a/src/main/java/com/example/Main.java +++ b/src/main/java/com/example/Main.java @@ -121,15 +121,18 @@ private void displayMissionsForAYear(MoonMissionRepo moonMissionRepo) { } private void getMissionFromID(MoonMissionRepo moonMissionRepo) { - System.out.print("Enter the mission-id: "); + System.out.print("Enter mission-id: "); int id = Integer.parseInt(scanner.nextLine().trim()); moonMissionRepo.getMissionFromID(id); + System.out.println(); } private void displayAllMoonMissions(MoonMissionRepo moonMissionRepo) { String column = "spacecraft"; + System.out.println("-----Spacecrafts-----\n"); moonMissionRepo.displayColumn(column); + System.out.println(); } /** @@ -157,24 +160,25 @@ private boolean validateSignIn(AccountRepo accountRepo){ if(accountRepo.validateLogIn(username, password)) return true; - System.out.println("Invalid username or password. Press 0 to exit or any other key to return to sign in: "); - String choice = scanner.nextLine(); + System.out.print("Invalid username or password. Press 0 to exit or any other key to return to sign in: "); + String choice = scanner.nextLine().trim(); + System.out.println(); if (choice != null && choice.trim().equals("0")) return false; } } private static void displayMenu() { - System.out.println(" MENU\n" + - "=======================================\n" + + System.out.println(" MENU\n" + + "==================================\n" + "\n" + - "1) List moon missions.\n" + - "2) Get a moon mission by mission_id.\n" + - "3) Count missions for a given year.\n" + - "4) Create an account.\n" + - "5) Update an account password.\n" + - "6) Delete an account.\n" + - "0) Exit.\n" + + "1) List moon missions\n" + + "2) Get a moon mission by mission_id\n" + + "3) Count missions for a given year\n" + + "4) Create an account\n" + + "5) Update an account password\n" + + "6) Delete an account\n" + + "0) Exit\n" + " "); } } \ No newline at end of file diff --git a/src/main/java/repositories/MoonMissionRepo.java b/src/main/java/repositories/MoonMissionRepo.java index ad134e3..417994c 100644 --- a/src/main/java/repositories/MoonMissionRepo.java +++ b/src/main/java/repositories/MoonMissionRepo.java @@ -68,7 +68,7 @@ public void allMissionsConductedInYear(String year) { numMissions = result.getInt(1); } - System.out.println("There were " + numMissions + " moon missions registered during " + year + "."); + System.out.println("There were " + numMissions + " moon missions registered during " + year + ".\n"); } catch (SQLException e) { e.printStackTrace(); From 9389593ed06b10704930b47d98884a6bd9d904d0 Mon Sep 17 00:00:00 2001 From: Anna Ziafar Date: Mon, 15 Dec 2025 11:06:52 +0100 Subject: [PATCH 8/8] =?UTF-8?q?=C3=84ndringar,=20sm=C3=A5fel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/main/java/com/example/Main.java | 4 ++-- src/main/java/repositories/AccountRepo.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/example/Main.java b/src/main/java/com/example/Main.java index 879552e..ef2e841 100644 --- a/src/main/java/com/example/Main.java +++ b/src/main/java/com/example/Main.java @@ -90,7 +90,7 @@ private void deleteAccount(AccountRepo accountRepo) { private boolean validPassword(String password){ if(password.isBlank() || password.length() < 6){ - System.out.println("Error. Password must be at least 8 characters long."); + System.out.println("Error. Password must be at least 6 characters long."); return false; } return true; @@ -112,7 +112,7 @@ private void updatePassword(AccountRepo accountRepo) { private void displayMissionsForAYear(MoonMissionRepo moonMissionRepo) { System.out.print("Enter a year: "); String year = scanner.nextLine().trim(); - if(!year.matches("^[1-2][09]\\d{2}")){ + if(!year.matches("^(19|20)\\d{2}$")){ System.out.println("Invalid year"); return; } diff --git a/src/main/java/repositories/AccountRepo.java b/src/main/java/repositories/AccountRepo.java index 8e5d1be..d40abe5 100644 --- a/src/main/java/repositories/AccountRepo.java +++ b/src/main/java/repositories/AccountRepo.java @@ -28,7 +28,7 @@ public boolean validateLogIn(String username, String password) { @Override public void createAccount(String firstName, String lastName, String password, String ssn) { - String addUser = "insert into account (name, password, first_name, last_name, ssn)" + + String addUser = "insert into account (name, password, first_name, last_name, ssn) " + "values (?, ?, ?, ?, ?)"; try (Connection con = DataSource.getConnection();