Skip to content

Erika solution#23

Open
eafalkens wants to merge 3 commits intomainfrom
erika-solution
Open

Erika solution#23
eafalkens wants to merge 3 commits intomainfrom
erika-solution

Conversation

@eafalkens
Copy link

@eafalkens eafalkens commented Dec 14, 2025

Summary by CodeRabbit

  • New Features

    • Introduced login authentication system with credentials validation
    • Added interactive menu with options to view missions, count by year, and manage user accounts
  • Documentation

    • Added Review Assignment Due Date badge to README

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Dec 14, 2025

Walkthrough

Added a cosmetic badge to README.md and implemented an interactive login system with a text-based menu in Main.java that enables users to authenticate, view moon missions, manage accounts, and perform JDBC operations on mission and account data.

Changes

Cohort / File(s) Summary
Documentation
README.md
Added Review Assignment Due Date badge link for cosmetic purposes.
Core Application Logic
src/main/java/com/example/Main.java
Replaced explicit java.sql imports with wildcard; added java.util.Scanner. Introduced interactive login flow with validateLogin method. Implemented text-based menu with options to list missions, fetch by ID, count by year, manage accounts (create/update/delete). Added helper methods for JDBC operations and user interaction control (pause, exit).

Sequence Diagram

sequenceDiagram
    participant User as User
    participant App as Application (Main)
    participant DB as Database

    User->>App: Start application
    App->>User: Prompt for username & password
    User->>App: Enter credentials
    App->>DB: validateLogin(username, password)
    DB-->>App: Account found/valid
    alt Login success
        App->>User: Display main menu
        User->>App: Select operation
        alt List Missions
            App->>DB: Query moon_mission table
            DB-->>App: Return missions
            App->>User: Display missions
        else Fetch Mission by ID
            App->>User: Prompt for mission_id
            User->>App: Provide mission_id
            App->>DB: Query mission details
            DB-->>App: Return mission data
            App->>User: Display mission details
        else Count Missions by Year
            App->>User: Prompt for year
            User->>App: Provide year
            App->>DB: Count missions by year
            DB-->>App: Return count
            App->>User: Display count
        else Manage Accounts
            App->>DB: Create/Update/Delete account
            DB-->>App: Operation result
            App->>User: Display result
        end
        App->>User: Pause for acknowledgment
        User->>App: Continue or exit
    else Login fail
        App->>User: Display error
        App->>App: Exit application
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

  • Primary focus areas:
    • JDBC operations and database connectivity logic across multiple methods (validateLogin, listMoonMissions, getMissionById, countMissionsByYear, createAccount, updateAccountPassword, deleteAccount)
    • Login flow and authentication mechanism correctness
    • Interactive menu logic and user input handling with Scanner
    • Username generation logic in cap3 utility method
    • Proper resource management and database connection handling throughout the interactive session

Poem

🐰 A login prompt appears with flourish and care,
Menus bloom where missions dance in the air,
Accounts created, updated, and freed,
The database hops with each user need!
Interactive magic, from queries to screens,
The finest Java adventure we've seen!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Title check ❓ Inconclusive The title 'Erika solution' is vague and generic, providing no meaningful information about the changeset's content or purpose. Use a descriptive title that summarizes the main change, such as 'Add interactive login and mission management menu' or 'Implement user authentication and JDBC operations'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (3)
src/main/java/com/example/Main.java (3)

3-5: Wildcard java.sql.* is OK, but explicit imports are usually clearer.


142-166: Close ResultSet via try-with-resources for consistency.

ResultSet rs = stmt.executeQuery(); (Line 148) isn’t in try-with-resources. Suggest:

@@
-            ResultSet rs = stmt.executeQuery();
-
-            if (rs.next()) {
+            try (ResultSet rs = stmt.executeQuery()) {
+              if (rs.next()) {
                 System.out.println("\n=== Mission Details ===");
                 System.out.println("Mission ID: " + rs.getInt("mission_id"));
                 System.out.println("Spacecraft: " + rs.getString("spacecraft"));
                 System.out.println("Launch Date: " + rs.getDate("launch_date"));
                 System.out.println("Carrier Rocket: " + rs.getString("carrier_rocket"));
                 System.out.println("Operator: " + rs.getString("operator"));
                 System.out.println("Mission Type: " + rs.getString("mission_type"));
                 System.out.println("Outcome: " + rs.getString("outcome"));
-            } else {
+              } else {
                 System.out.println("Mission not found");
-            }
+              }
+            }

168-184: Same ResultSet lifecycle improvement as above.

@@
-            ResultSet rs = stmt.executeQuery();
-
-            if (rs.next()) {
-                int count = rs.getInt("count");
-                System.out.println("Number of missions in " + year + ": " + count);
-            }
+            try (ResultSet rs = stmt.executeQuery()) {
+                if (rs.next()) {
+                    int count = rs.getInt("count");
+                    System.out.println("Number of missions in " + year + ": " + count);
+                }
+            }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e629e94 and 1ee0491.

📒 Files selected for processing (2)
  • README.md (1 hunks)
  • src/main/java/com/example/Main.java (3 hunks)
🔇 Additional comments (5)
README.md (1)

1-1: Badge addition looks fine (cosmetic-only).

src/main/java/com/example/Main.java (4)

225-250: Update flow OK; consider confirming when 0 rows updated is an error vs normal.

This likely matches assignment needs, but verify output strings match tests (Line 242-245).


252-273: Delete flow OK; same note on expected output strings.

Verify output phrasing matches integration test assertions (Line 265-268).


302-310: cap3 is safe for short/blank strings; looks good.


16-105: and

Comment on lines +107 to +124
private boolean validateLogin(String username, String password,
String jdbcUrl, String dbUser, String dbPass) {
String sql = "SELECT 1 FROM account WHERE name = ? AND password = ?";
try (Connection conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPass);
PreparedStatement stmt = conn.prepareStatement(sql)) {

stmt.setString(1, username);
stmt.setString(2, password);

try (ResultSet rs = stmt.executeQuery()) {
return rs.next();
}

} catch (SQLException e) {
System.err.println("Login error: " + e.getMessage());
return false;
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Login query is parameterized (good), but don’t mask DB errors as “invalid login”.

Right now any SQLException returns false (Line 120-123), which makes “DB down / wrong config” look like bad credentials. Consider rethrowing (or failing fast) so misconfig is obvious during runs/tests.

@@
         } catch (SQLException e) {
-            System.err.println("Login error: " + e.getMessage());
-            return false;
+            throw new RuntimeException("Login query failed", e);
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private boolean validateLogin(String username, String password,
String jdbcUrl, String dbUser, String dbPass) {
String sql = "SELECT 1 FROM account WHERE name = ? AND password = ?";
try (Connection conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPass);
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, username);
stmt.setString(2, password);
try (ResultSet rs = stmt.executeQuery()) {
return rs.next();
}
} catch (SQLException e) {
System.err.println("Login error: " + e.getMessage());
return false;
}
}
private boolean validateLogin(String username, String password,
String jdbcUrl, String dbUser, String dbPass) {
String sql = "SELECT 1 FROM account WHERE name = ? AND password = ?";
try (Connection conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPass);
PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, username);
stmt.setString(2, password);
try (ResultSet rs = stmt.executeQuery()) {
return rs.next();
}
} catch (SQLException e) {
throw new RuntimeException("Login query failed", e);
}
}
🤖 Prompt for AI Agents
In src/main/java/com/example/Main.java around lines 107-124 the validateLogin
method currently catches SQLException and returns false, masking configuration
or DB availability errors as “invalid login”; change the method to stop
swallowing SQLExceptions — either declare throws SQLException on validateLogin
and let callers handle it, or catch SQLException and rethrow a runtime exception
(e.g., IllegalStateException) with the original exception as the cause so DB
failures surface clearly; remove the System.err swallow and ensure callers/tests
can detect and fail fast on misconfiguration or connectivity issues.

Comment on lines +126 to +140
private void listMoonMissions(String jdbcUrl, String dbUser, String dbPass) {
String sql = "SELECT spacecraft FROM moon_mission ORDER BY mission_id";
try (Connection conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPass);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {

System.out.println("\n=== Moon Missions ===");
while (rs.next()) {
System.out.println(rs.getString("spacecraft"));
}

} catch (SQLException e) {
System.err.println("Error listing missions: " + e.getMessage());
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

git ls-files | head -20

Repository: ithsjava25/ithsjava25-java-databas-jdbc-javafx-classrom

Length of output: 483


🏁 Script executed:

find . -maxdepth 2 -name "README*" -o -name "readme*" | head -10

Repository: ithsjava25/ithsjava25-java-databas-jdbc-javafx-classrom

Length of output: 110


🏁 Script executed:

find . -name "Main.java" | head -5

Repository: ithsjava25/ithsjava25-java-databas-jdbc-javafx-classrom

Length of output: 136


🏁 Script executed:

cat README.md

Repository: ithsjava25/ithsjava25-java-databas-jdbc-javafx-classrom

Length of output: 6058


🏁 Script executed:

wc -l src/main/java/com/example/Main.java

Repository: ithsjava25/ithsjava25-java-databas-jdbc-javafx-classrom

Length of output: 138


🏁 Script executed:

sed -n '126,140p' src/main/java/com/example/Main.java

Repository: ithsjava25/ithsjava25-java-databas-jdbc-javafx-classrom

Length of output: 752


🏁 Script executed:

cat src/test/java/com/example/CliAppIT.java

Repository: ithsjava25/ithsjava25-java-databas-jdbc-javafx-classrom

Length of output: 13365


Output may not strictly match specification. README requirement states "prints spacecraft names" without mentioning a header. The === Moon Missions === line (132) adds content beyond what is specified. While the integration tests use flexible substring matching and won't fail, consider removing the header to align exactly with the stated requirement.

-            System.out.println("\n=== Moon Missions ===");
             while (rs.next()) {
                 System.out.println(rs.getString("spacecraft"));
             }
🤖 Prompt for AI Agents
In src/main/java/com/example/Main.java around lines 126-140, remove the extra
header print so output matches the README spec; delete the
System.out.println("\n=== Moon Missions ==="); (and the leading newline) so the
method prints only spacecraft names one per line from the ResultSet and leaves
error handling unchanged.

Comment on lines +186 to +223
private void createAccount(String jdbcUrl, String dbUser, String dbPass, Scanner scanner) {
System.out.print("First name: ");
String firstName = scanner.nextLine();

System.out.print("Last name: ");
String lastName = scanner.nextLine();

System.out.print("SSN: ");
String ssn = scanner.nextLine();

System.out.print("Password: ");
String password = scanner.nextLine();

// Skapa username från förnamn + första 3 bokstäver av efternamn
String username = cap3(firstName) + cap3(lastName);

String sql = "INSERT INTO account (first_name, last_name, ssn, name, password) " +
"VALUES (?, ?, ?, ?, ?)";

try (Connection conn = DriverManager.getConnection(jdbcUrl, dbUser, dbPass);
PreparedStatement stmt = conn.prepareStatement(sql)) {

stmt.setString(1, firstName);
stmt.setString(2, lastName);
stmt.setString(3, ssn);
stmt.setString(4, username);
stmt.setString(5, password);

int rows = stmt.executeUpdate();
if (rows > 0) {
System.out.println("Account created successfully!");
System.out.println("Username: " + username);
}

} catch (SQLException e) {
System.err.println("Error creating account: " + e.getMessage());
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

find . -type f \( -name "*init*.sql" -o -name "*schema*.sql" -o -name "*.sql" \) | head -20

Repository: ithsjava25/ithsjava25-java-databas-jdbc-javafx-classrom

Length of output: 128


🏁 Script executed:

cat ./src/main/resources/init.sql

Repository: ithsjava25/ithsjava25-java-databas-jdbc-javafx-classrom

Length of output: 4853


Username generation may allow duplicates; consider enforcing uniqueness or collision handling.

The account.name column has no UNIQUE constraint in the schema, so cap3(firstName) + cap3(lastName) collisions will not cause INSERT failures. However, the method can still generate identical usernames for different people (e.g., "Bob Brown" and "Bobby Browner" both → "BobBro"), leading to silent duplicates. Consider either adding a UNIQUE constraint on account.name, detecting duplicates before insertion, or appending a suffix/counter to ensure uniqueness.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant