From 3fd6546fcea7c079679aa86e960be2e8714cb414 Mon Sep 17 00:00:00 2001 From: Aman Gautam Date: Sat, 16 May 2026 22:56:22 +0530 Subject: [PATCH 1/8] fix: use UTC calendar for JDBC timestamp reads --- src/main/java/dbProcs/Getter.java | 5 +++-- src/main/java/utils/DbTime.java | 12 ++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 src/main/java/utils/DbTime.java diff --git a/src/main/java/dbProcs/Getter.java b/src/main/java/dbProcs/Getter.java index 505de1fb6..dfc2e7fc0 100644 --- a/src/main/java/dbProcs/Getter.java +++ b/src/main/java/dbProcs/Getter.java @@ -19,6 +19,7 @@ import org.json.JSONObject; import org.owasp.encoder.Encode; import servlets.Register; +import utils.DbTime; import utils.ModulePlan; import utils.ScoreboardStatus; @@ -166,7 +167,7 @@ public static String[] authUser(String ApplicationRoot, String userName, String badLoginCount = userResult.getInt(5); result[3] = Boolean.toString(userResult.getBoolean(6)); result[4] = userResult.getString(7); // classId - suspendedUntil = userResult.getTimestamp(8); + suspendedUntil = userResult.getTimestamp(8,DbTime.UTC); loginType = userResult.getString(9); result[5] = Boolean.toString(userResult.getBoolean(10)); } catch (SQLException e) { @@ -368,7 +369,7 @@ public static String[] authUserSSO( log.debug("Getting suspension data"); try { - suspendedUntil = userResult.getTimestamp(7); + suspendedUntil = userResult.getTimestamp(7, DbTime.UTC); } catch (SQLException e) { log.fatal( "Could not find suspension information from ssoName: " + ssoName + ": " + e.toString()); diff --git a/src/main/java/utils/DbTime.java b/src/main/java/utils/DbTime.java new file mode 100644 index 000000000..e60529008 --- /dev/null +++ b/src/main/java/utils/DbTime.java @@ -0,0 +1,12 @@ +package utils; + +import java.util.Calendar; +import java.util.TimeZone; + +public class DbTime { + + private DbTime(){}; + + public static final Calendar UTC = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + +} From bdaae39d2dba7e41095e99dc85e01664db9c9754 Mon Sep 17 00:00:00 2001 From: DuggSe01 Date: Sat, 30 May 2026 14:08:59 +0100 Subject: [PATCH 2/8] style: fix Spotless violations (tabs, trailing semicolon, missing space) --- src/main/java/dbProcs/Getter.java | 2 +- src/main/java/utils/DbTime.java | 5 ++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/dbProcs/Getter.java b/src/main/java/dbProcs/Getter.java index dfc2e7fc0..b639e854f 100644 --- a/src/main/java/dbProcs/Getter.java +++ b/src/main/java/dbProcs/Getter.java @@ -167,7 +167,7 @@ public static String[] authUser(String ApplicationRoot, String userName, String badLoginCount = userResult.getInt(5); result[3] = Boolean.toString(userResult.getBoolean(6)); result[4] = userResult.getString(7); // classId - suspendedUntil = userResult.getTimestamp(8,DbTime.UTC); + suspendedUntil = userResult.getTimestamp(8, DbTime.UTC); loginType = userResult.getString(9); result[5] = Boolean.toString(userResult.getBoolean(10)); } catch (SQLException e) { diff --git a/src/main/java/utils/DbTime.java b/src/main/java/utils/DbTime.java index e60529008..1beb2f28b 100644 --- a/src/main/java/utils/DbTime.java +++ b/src/main/java/utils/DbTime.java @@ -5,8 +5,7 @@ public class DbTime { - private DbTime(){}; - - public static final Calendar UTC = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + private DbTime() {} + public static final Calendar UTC = Calendar.getInstance(TimeZone.getTimeZone("UTC")); } From e9f75f6e8219e02202a8b66a0f7446ed8d252d24 Mon Sep 17 00:00:00 2001 From: Aman Gautam Date: Sat, 30 May 2026 20:48:22 +0530 Subject: [PATCH 3/8] test: add regression coverage for UTC timestamp handling --- src/test/java/utils/DbTimeTest.java | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/test/java/utils/DbTimeTest.java diff --git a/src/test/java/utils/DbTimeTest.java b/src/test/java/utils/DbTimeTest.java new file mode 100644 index 000000000..d53f4df70 --- /dev/null +++ b/src/test/java/utils/DbTimeTest.java @@ -0,0 +1,27 @@ +package utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import java.util.TimeZone; + +import org.junit.jupiter.api.Test; + +public class DbTimeTest { + + @Test + void shouldRemainUtcWhenJvmTimezoneIsNotUtc() { + TimeZone original = TimeZone.getDefault(); + + try { + TimeZone.setDefault(TimeZone.getTimeZone("US/Pacific")); + + assertEquals( + "UTC", + DbTime.UTC.getTimeZone().getID() + ); + + } finally { + TimeZone.setDefault(original); + } + } +} \ No newline at end of file From 82adf2984a3cb9ebd653d3848fc824e99cc96812 Mon Sep 17 00:00:00 2001 From: Aman Gautam Date: Sun, 31 May 2026 15:43:15 +0530 Subject: [PATCH 4/8] test: strengthen UTC timestamp regression coverage --- src/test/java/utils/DbTimeTest.java | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/test/java/utils/DbTimeTest.java b/src/test/java/utils/DbTimeTest.java index d53f4df70..133165b60 100644 --- a/src/test/java/utils/DbTimeTest.java +++ b/src/test/java/utils/DbTimeTest.java @@ -1,7 +1,13 @@ package utils; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import java.sql.ResultSet; +import java.sql.Timestamp; +import java.time.Instant; import java.util.TimeZone; import org.junit.jupiter.api.Test; @@ -9,16 +15,25 @@ public class DbTimeTest { @Test - void shouldRemainUtcWhenJvmTimezoneIsNotUtc() { + void shouldReadTimestampCorrectlyInNonUtcJvm() throws Exception { TimeZone original = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("US/Pacific")); + Instant expected = Instant.parse("2025-01-01T12:00:00Z"); + + ResultSet resultSet = mock(ResultSet.class); + + when(resultSet.getTimestamp(eq(7), eq(DbTime.UTC))) + .thenReturn(Timestamp.from(expected)); + + Timestamp suspendedUntil = + resultSet.getTimestamp(7, DbTime.UTC); + assertEquals( - "UTC", - DbTime.UTC.getTimeZone().getID() - ); + expected.toEpochMilli(), + suspendedUntil.toInstant().toEpochMilli()); } finally { TimeZone.setDefault(original); From a77e866c515af80ca0d477e7a7916a43f42e4ca7 Mon Sep 17 00:00:00 2001 From: Aman Gautam Date: Thu, 4 Jun 2026 23:57:24 +0530 Subject: [PATCH 5/8] refactor: make UTC calendar thread-safe --- src/main/java/dbProcs/Getter.java | 2955 ++++++++++++++------------- src/main/java/utils/DbTime.java | 3 +- src/test/java/utils/DbTimeTest.java | 42 - 3 files changed, 1580 insertions(+), 1420 deletions(-) delete mode 100644 src/test/java/utils/DbTimeTest.java diff --git a/src/main/java/dbProcs/Getter.java b/src/main/java/dbProcs/Getter.java index 5d8b878a1..a46e435bf 100644 --- a/src/main/java/dbProcs/Getter.java +++ b/src/main/java/dbProcs/Getter.java @@ -13,8 +13,6 @@ import java.util.ArrayList; import java.util.Locale; import java.util.ResourceBundle; -import javax.sql.rowset.CachedRowSet; -import javax.sql.rowset.RowSetProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONArray; @@ -64,15 +62,6 @@ public class Getter { private static final int admiralCap = 999; // everything above Major is Admiral - /** - * Safety cap on the number of rows materialized by {@link #getClassInfo}, {@link - * #getPlayersByClass}, and {@link #getAdmins}. These methods return a {@link - * javax.sql.rowset.CachedRowSet}, which holds every row in memory. Realistic workloads are well - * under this limit (tens to a few hundred per call); the cap exists to fail fast on a runaway - * query rather than OOM the JVM. Tracked for proper bounded-collection conversion in #839. - */ - private static final int MAX_ROWSET_ROWS = 10_000; - /** * This method hashes the user submitted password and sends it to the database. The database does * the rest of the work, including Brute Force prevention. @@ -83,109 +72,167 @@ public class Getter { * authentication process. */ public static String[] authUser(String ApplicationRoot, String userName, String password) { + String[] result = null; log.debug("$$$ Getter.authUser $$$"); + log.debug("userName = " + userName); - // Phase 1: Fetch user record (short DB hold, ~1-5ms) - String userId; - String dbUserName; - String dbHash; - String userRole; - int badLoginCount; - boolean tempPassword; - String classId; - Timestamp suspendedUntil; - String loginType; - boolean tempUsername; - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement prestmt = - conn.prepareStatement( - "SELECT userId, userName, userPass, userRole, badLoginCount, tempPassword, classId," - + " suspendedUntil, loginType, tempUsername FROM `users` WHERE userName = ?")) { - prestmt.setString(1, userName); - try (ResultSet userResult = prestmt.executeQuery()) { - if (userResult.next()) { - log.debug("User Found"); - userId = userResult.getString(1); - dbUserName = userResult.getString(2); - dbHash = userResult.getString(3); - userRole = userResult.getString(4); - badLoginCount = userResult.getInt(5); - tempPassword = userResult.getBoolean(6); - classId = userResult.getString(7); - suspendedUntil = userResult.getTimestamp(8, DbTime.UTC); - loginType = userResult.getString(9); - tempUsername = userResult.getBoolean(10); - } else { - log.debug("User did not exist"); - log.debug("$$$ End authUser $$$"); - return null; - } - } + boolean userFound = false; + boolean userVerified = false; + + Connection conn; + try { + conn = Database.getCoreConnection(ApplicationRoot); } catch (SQLException e) { - log.fatal("authUser failed: " + e.toString()); + log.fatal("Could create get core connection: " + e.toString()); throw new RuntimeException(e); } - // Connection released — all user data extracted into local variables - // Fail-fast: reject suspended and SSO users before expensive Argon2 work - if (!"login".equals(loginType)) { - log.debug("User is SSO user, can't login with password!"); - return null; + // See if user Exists + PreparedStatement prestmt; + CallableStatement callstmt; + try { + prestmt = + conn.prepareStatement( + "SELECT userId, userName, userPass, userRole, badLoginCount, tempPassword, classId," + + " suspendedUntil, loginType, tempUsername FROM `users` WHERE userName = ?"); + } catch (SQLException e) { + log.fatal("Could create call statement: " + e.toString()); + throw new RuntimeException(e); } - Timestamp currentTime = new Timestamp(System.currentTimeMillis()); - if (suspendedUntil != null && suspendedUntil.after(currentTime)) { - return null; + log.debug("Gathering results from query"); + ResultSet userResult; + try { + prestmt.setString(1, userName); + userResult = prestmt.executeQuery(); + } catch (SQLException e) { + log.fatal("Could not execute db query: " + e.toString()); + throw new RuntimeException(e); } - // Phase 2: Verify password (CPU-bound Argon2, no DB connection held) - log.debug("Verifying hash"); - Argon2 argon2 = Argon2Factory.create(); - boolean userVerified = argon2.verify(dbHash, password.toCharArray()); + log.debug("Opening Result Set from query"); - if (!userVerified) { - log.debug("Hash did not match, authentication failed"); - log.debug("$$$ End authUser $$$"); - return null; + try { + if (userResult.next()) { + log.debug( + "User Found"); // User found if a row is in the database, this line will not work if the + // result + // set is empty + userFound = true; + } else { + log.debug("User did not exist"); + userFound = false; + } + } catch (SQLException e) { + log.debug("User did not exist"); + userFound = false; } - // Phase 3: Post-verification DB updates (short DB hold if needed) - log.debug("Hash matches"); + if (userFound) { + // Authenticate User + Argon2 argon2 = Argon2Factory.create(); - if (!dbUserName.equalsIgnoreCase(userName)) { - log.fatal( - "User Name used (" - + userName - + ") and User Name retrieved (" - + dbUserName - + ") were not the Same. Nulling Result"); - return null; - } + log.debug("Getting password hash"); + String dbHash; + try { + dbHash = userResult.getString(3); + log.debug("Verifying hash"); - log.debug("User '" + userName + "' has logged in"); + userVerified = argon2.verify(dbHash, password.toCharArray()); - if (badLoginCount > 0) { - log.debug("Clearing Bad Login History"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - CallableStatement callstmt = conn.prepareCall("call userBadLoginReset(?)")) { - callstmt.setString(1, userId); - callstmt.execute(); - log.debug("userBadLoginReset executed!"); } catch (SQLException e) { - log.fatal("Could not reset bad login count: " + e.toString()); + log.fatal("Could not retrieve password hash from db: " + e.toString()); + result = null; + userVerified = false; throw new RuntimeException(e); + // TODO: We should throw a checked exception here instead } - } - String[] result = new String[6]; - result[0] = userId; - result[1] = dbUserName; - result[2] = userRole; - result[3] = Boolean.toString(tempPassword); - result[4] = classId; - result[5] = Boolean.toString(tempUsername); + if (userVerified) { + // Hash matches + log.debug("Hash matches"); + + result = new String[6]; + + int badLoginCount; + String loginType = new String(); + + Timestamp suspendedUntil; + + try { + result[0] = userResult.getString(1); + result[1] = userResult.getString(2); // userName + result[2] = userResult.getString(4); // role + badLoginCount = userResult.getInt(5); + result[3] = Boolean.toString(userResult.getBoolean(6)); + result[4] = userResult.getString(7); // classId + suspendedUntil = userResult.getTimestamp(8, DbTime.UTC.get()); + loginType = userResult.getString(9); + result[5] = Boolean.toString(userResult.getBoolean(10)); + } catch (SQLException e) { + + log.fatal("Could not retrieve auth data from db: " + e.toString()); + throw new RuntimeException(e); + } + + if (!loginType.equals("login")) { + // Login type must be "login" and not "saml" if password login is to be allowed + log.debug("User is SSO user, can't login with password!"); + result = null; + return result; + } + + // Get current system time + Timestamp currentTime = new Timestamp(System.currentTimeMillis()); + + if (suspendedUntil.after(currentTime)) { + // User is suspended + result = null; + return result; + } + + if (!result[1].equalsIgnoreCase( + userName)) // If somehow this functionality has been compromised to sign + // in as + // other users, this will limit the expoitability. But the method is + // sql injection safe, so it should be ok + { + log.fatal( + "User Name used (" + + userName + + ") and User Name retrieved (" + + result[1] + + ") were not the Same. Nulling Result"); + result = null; + } else { + log.debug("User '" + userName + "' has logged in"); + // Before finishing, check if user had a badlogin history, if so, Clear it + if (badLoginCount > 0) { + log.debug("Clearing Bad Login History"); + try { + callstmt = conn.prepareCall("call userBadLoginReset(?)"); + callstmt.setString(1, result[0]); + callstmt.execute(); + } catch (SQLException e) { + log.fatal("Could not reset bad login count: " + e.toString()); + throw new RuntimeException(e); + } + + log.debug("userBadLoginReset executed!"); + } + } + // User has logged in, or a Authentication Bypass was detected... You never + // know! Better safe than sorry + // TODO: will this close the db connection if we return here? + return result; + } else { + // Hash did not match + log.debug("Hash did not match, authentication failed"); + } + } + Database.closeConnection(conn); log.debug("$$$ End authUser $$$"); return result; } @@ -220,143 +267,205 @@ public static String[] authUserSSO( boolean isTempUsername = false; + Connection conn; try { - // Phase 1: See if the user already exists, and capture suspension data if so. - // Each phase opens its own pooled connection in try-with-resources so the - // connection is never held across the Setter.userCreateSSO call (Phase 2). - Timestamp suspendedUntil = null; - - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement prestmt = - conn.prepareStatement( - "SELECT suspendedUntil FROM `users` WHERE ssoName = ? AND loginType='saml'")) { - prestmt.setString(1, ssoName); - log.debug("Gathering userFind ResultSet"); - try (ResultSet userResult = prestmt.executeQuery()) { - log.debug("Opening Result Set from userResult"); - if (userResult.next()) { - // User found if a row is in the database - userFound = true; - log.debug("User Found"); - suspendedUntil = userResult.getTimestamp(1, DbTime.UTC); - } else { - userFound = false; - } - } - } + conn = Database.getCoreConnection(ApplicationRoot); + } catch (SQLException e) { + log.fatal("Could create get core connection: " + e.toString()); + throw new RuntimeException(e); + } + // See if user Exists + PreparedStatement prestmt; + try { + prestmt = + conn.prepareStatement( + "SELECT userId, userName, userPass, badLoginCount, tempPassword, classId," + + " suspendedUntil, loginType FROM `users` WHERE ssoName = ? AND" + + " loginType='saml'"); + } catch (SQLException e) { + log.fatal("Could create call statement: " + e.toString()); + throw new RuntimeException(e); + } - if (!userFound) { - // Phase 2: User wasn't found, enroll them in database. No pooled - // connection is held here; Setter.userCreateSSO borrows its own. + log.debug("Gathering userFind ResultSet"); + ResultSet userResult; + try { + prestmt.setString(1, ssoName); + log.debug("Executing query"); + userResult = prestmt.executeQuery(); + } catch (SQLException e) { + log.fatal("Could not execute db query: " + e.toString()); + throw new RuntimeException(e); + } - boolean userCreated = false; + log.debug("Opening Result Set from userResult"); - log.debug("User did not exist, create it from SSO data"); + try { + if (userResult.next()) { + // User found if a row is in the database + userFound = true; + log.debug("User Found"); + } else { + userFound = false; + } - try { + } catch (SQLException e) { + log.debug("User did not exist"); + userFound = false; + } - if (defaultClass.isEmpty()) { - log.debug("Adding player to database, with null classId"); - newUsername = Setter.userCreateSSO(ApplicationRoot, null, userName, ssoName, userRole); - } else // defaultClass is not empty, so It must be set to a class! - { - log.debug("Adding player to database, to class " + defaultClass); - newUsername = - Setter.userCreateSSO(ApplicationRoot, defaultClass, userName, ssoName, userRole); - } + if (!userFound) { + // User wasn't found, enroll them in database - if (newUsername == null) { - userCreated = false; - } else { - userCreated = true; - } + boolean userCreated = false; - userName = newUsername; + log.debug("User did not exist, create it from SSO data"); - } catch (SQLException e) { - String message = - "Could not create user " - + userName - + " with ssoName " - + ssoName - + " via SSO: " - + e.toString(); - log.fatal(message); - throw new RuntimeException(message); + try { + + if (defaultClass.isEmpty()) { + log.debug("Adding player to database, with null classId"); + newUsername = Setter.userCreateSSO(ApplicationRoot, null, userName, ssoName, userRole); + } else // defaultClass is not empty, so It must be set to a class! + { + log.debug("Adding player to database, to class " + defaultClass); + newUsername = + Setter.userCreateSSO(ApplicationRoot, defaultClass, userName, ssoName, userRole); } - if (!userCreated) { - String message = - "Could not create user " + userName + " with ssoName " + ssoName + " via SSO"; - log.fatal(message); - throw new RuntimeException(message); + if (newUsername == null) { + userCreated = false; + } else { + userCreated = true; } - log.debug("User created"); + userName = newUsername; - } else { + } catch (SQLException e) { + String message = + "Could not create user " + + userName + + " with ssoName " + + ssoName + + " via SSO: " + + e.toString(); + log.fatal(message); + throw new RuntimeException(message); + } - log.debug("Getting suspension data"); + if (!userCreated) { + String message = + "Could not create user " + userName + " with ssoName " + ssoName + " via SSO"; + log.fatal(message); + throw new RuntimeException(message); + } - // Get current system time - Timestamp currentTime = new Timestamp(System.currentTimeMillis()); + log.debug("User created"); - if (suspendedUntil.after(currentTime)) { - // User is suspended - log.debug("User is suspended"); + } else { - result = null; - return result; - } + Timestamp suspendedUntil; + + log.debug("Getting suspension data"); + + try { + suspendedUntil = userResult.getTimestamp(7, DbTime.UTC.get()); + } catch (SQLException e) { + log.fatal( + "Could not find suspension information from ssoName: " + ssoName + ": " + e.toString()); + throw new RuntimeException(e); } - // Phase 3: Find the generated userID and username by asking the database. - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement prestmt = - conn.prepareStatement( - "SELECT userId, userName, classID, tempUsername FROM `users` WHERE ssoName = ?" - + " AND loginType='saml'")) { - prestmt.setString(1, ssoName); - log.debug("Gathering userResult ResultSet"); - try (ResultSet userResult = prestmt.executeQuery()) { - log.debug("Opening user list result set"); - if (userResult.next()) { - userFound = true; - log.debug("User Found"); - } else { - userFound = false; - } + // Get current system time + Timestamp currentTime = new Timestamp(System.currentTimeMillis()); - if (!userFound) { - // If user wasn't found at this stage something is quite wrong, so exit - // forcefully - String message = "User wasn't found after being added!"; - log.fatal(message); - throw new RuntimeException(message); - } + if (suspendedUntil.after(currentTime)) { + // User is suspended + log.debug("User is suspended"); - userID = userResult.getString(1); - userName = userResult.getString(2); - classId = userResult.getString(3); // classId - isTempUsername = userResult.getBoolean(4); - } + result = null; + return result; } + } - log.debug("User '" + userName + "' has logged in via SSO" + " with role " + userRole); + // Find the generated userID and username by asking the database + try { + prestmt = + conn.prepareStatement( + "SELECT userId, userName, classID, tempUsername FROM `users` WHERE ssoName = ? AND" + + " loginType='saml'"); - result[0] = userID; - result[1] = userName; // userName - result[2] = userRole; // role - result[5] = "false"; // sso logins can't change password - result[4] = classId; // classId - result[5] = Boolean.toString(isTempUsername); + } catch (SQLException e) { + log.fatal("Could create call statement: " + e.toString()); + throw new RuntimeException(e); + } - log.debug("$$$ End authUser $$$"); - return result; + log.debug("Gathering userResult ResultSet"); + + try { + prestmt.setString(1, ssoName); + log.debug("Executing query"); + userResult = prestmt.executeQuery(); } catch (SQLException e) { - log.fatal("authUserSSO failed: " + e.toString()); + log.fatal("Could not execute db query: " + e.toString()); throw new RuntimeException(e); } + + log.debug("Opening user list result set"); + + try { + if (userResult.next()) { + userFound = true; + log.debug( + "User Found"); // User found if a row is in the database, this line will not work if the + // result + // set is empty + } else { + userFound = false; + } + + } catch (SQLException e) { + log.debug("User did not exist"); + userFound = false; + } + + if (!userFound) { + // If user wasn't found at this stage something is quite wrong, so exit + // forefully + String message = "User wasn't found after being added!"; + log.fatal(message); + throw new RuntimeException(message); + } + + try { + userID = userResult.getString(1); + userName = userResult.getString(2); + classId = userResult.getString(3); // classId + isTempUsername = userResult.getBoolean(4); + } catch (SQLException e) { + String message = + "Could find userID for userName " + + userName + + " with ssoName " + + ssoName + + " via SSO: " + + e.toString(); + log.fatal(message); + throw new RuntimeException(message); + } + + log.debug("User '" + userName + "' has logged in via SSO" + " with role " + userRole); + + result[0] = userID; + result[1] = userName; // userName + result[2] = userRole; // role + result[5] = "false"; // sso logins can't change password + result[4] = classId; // classId + result[5] = Boolean.toString(isTempUsername); + + Database.closeConnection(conn); + log.debug("$$$ End authUser $$$"); + return result; } /** @@ -372,17 +481,19 @@ public static String checkPlayerResult(String ApplicationRoot, String moduleId, log.debug("*** Getter.checkPlayerResult ***"); String result = null; - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - CallableStatement callstmnt = conn.prepareCall("call userCheckResult(?, ?)")) { + try { + Connection conn = Database.getCoreConnection(ApplicationRoot); log.debug("Preparing userCheckResult call"); + CallableStatement callstmnt = conn.prepareCall("call userCheckResult(?, ?)"); callstmnt.setString(1, moduleId); callstmnt.setString(2, userId); log.debug("Executing userCheckResult"); - try (ResultSet resultSet = callstmnt.executeQuery()) { - resultSet.next(); - result = resultSet.getString(1); - } + ResultSet resultSet = callstmnt.executeQuery(); + resultSet.next(); + result = resultSet.getString(1); + Database.closeConnection(conn); + } catch (SQLException e) { log.debug("userCheckResult Failure: " + e.toString()); result = null; @@ -401,19 +512,21 @@ public static boolean findPlayerById(String ApplicationRoot, String userId) { log.debug("*** Getter.findPlayerById ***"); boolean userFound = false; // Get connection - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - CallableStatement callstmt = conn.prepareCall("call playerFindById(?)")) { + try { + Connection conn = Database.getCoreConnection(ApplicationRoot); + CallableStatement callstmt = conn.prepareCall("call playerFindById(?)"); log.debug("Gathering playerFindById ResultSet"); callstmt.setString(1, userId); - try (ResultSet userFind = callstmt.executeQuery()) { - log.debug("Opening Result Set from playerFindById"); - userFind.next(); // This will throw an exception if player not found - log.debug( - "Player Found: " - + userFind.getString(1)); // This line will not execute if player not found - userFound = true; - } + ResultSet userFind = callstmt.executeQuery(); + log.debug("Opening Result Set from playerFindById"); + userFind.next(); // This will throw an exception if player not found + log.debug( + "Player Found: " + + userFind.getString(1)); // This line will not execute if player not found + userFound = true; + Database.closeConnection(conn); + } catch (SQLException e) { log.error("Player did not exist: " + e.toString()); userFound = false; @@ -434,24 +547,26 @@ public static ArrayList getAllModuleInfo(String ApplicationRoot) { log.debug("*** Getter.getAllModuleInfo ***"); ArrayList modules = new ArrayList(); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - CallableStatement callstmt = conn.prepareCall("call moduleGetAll()")) { + try { + Connection conn = Database.getCoreConnection(ApplicationRoot); + CallableStatement callstmt = conn.prepareCall("call moduleGetAll()"); log.debug("Gathering moduleGetAll ResultSet"); - try (ResultSet resultSet = callstmt.executeQuery()) { - log.debug("Opening Result Set from moduleGetAll"); - int i = 0; - while (resultSet.next()) { - String[] result = new String[4]; - i++; - result[0] = resultSet.getString(1); // moduleId - result[1] = resultSet.getString(2); // moduleName - result[2] = resultSet.getString(3); // moduleType - result[3] = resultSet.getString(4); // mdouleCategory - modules.add(result); - } - log.debug("Returning Array list with " + i + " entries."); + ResultSet resultSet = callstmt.executeQuery(); + log.debug("Opening Result Set from moduleGetAll"); + int i = 0; + while (resultSet.next()) { + String[] result = new String[4]; + i++; + result[0] = resultSet.getString(1); // moduleId + result[1] = resultSet.getString(2); // moduleName + result[2] = resultSet.getString(3); // moduleType + result[3] = resultSet.getString(4); // mdouleCategory + modules.add(result); } + log.debug("Returning Array list with " + i + " entries."); + Database.closeConnection(conn); + } catch (SQLException e) { log.error("Could not execute query: " + e.toString()); } @@ -476,64 +591,63 @@ public static String getChallenges(String ApplicationRoot, String userId, Locale // Getting Translated Level Names ResourceBundle bundle = ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", lang); // Encoder to prevent XSS - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - CallableStatement callstmt = conn.prepareCall("call moduleAllInfo(?, ?)")) { - - callstmt.setString(1, "challenge"); - callstmt.setString(2, userId); - log.debug("Gathering moduleAllInfo ResultSet"); - try (ResultSet challenges = callstmt.executeQuery()) { - log.debug("Opening Result Set from moduleAllInfo"); - String challengeCategory = new String(); - int rowNumber = 0; // Identifies the first row, ie the start of the list. This is slightly - // different output to every other row - while (challenges.next()) { - if (!challengeCategory.equalsIgnoreCase(challenges.getString(2))) { - challengeCategory = challenges.getString(2); - // log.debug("New Category Detected: " + challengeCategory); - if (rowNumber > 0) // output prepared for Every row after row 1 - { - output += - "
  • " - + Encode.forHtml(bundle.getString("category." + challengeCategory)) - + "
  • " + + Encode.forHtml(bundle.getString("category." + challengeCategory)) + + "\n"; } - // Prepare entry output - listEntry += - "" - + Encode.forHtml(levelNames.getString(levels.getString(1))) - + "\n"; - listEntry += "
  • "; - // What section does this belong in? Current or Next? - if (getTounnamentSectionFromRankNumber(levels.getInt(5)) > currentSection) { - // This level is not in the same level band as the previous level. So a new - // Level Band Header is required on the master list before we add the entry. - // Do we need to close a previous list? - if (currentSection - != 0) // If a Section Select hasn't been made before, we don't need to close any - // previous sections - { - // We've had a section before, so need to close the previous one before we make - // this new one - levelMasterList += "\n"; - } - // Update the current section to the one we have just added to the list - currentSection = getTounnamentSectionFromRankNumber(levels.getInt(5)); - // Which to Add? - switch (currentSection) { - case 1: // fieldTraining - // log.debug("Starting Field Training List"); - levelMasterList += - "
    " - + bundle.getString("getter.tournamentRank.1") - + "
      \n"; - break; - case 2: // private - // log.debug("Starting Private List"); - levelMasterList += - "
      " - + bundle.getString("getter.tournamentRank.2") - + "
      " - + "
        \n"; - break; - case 3: // corporal - // log.debug("Starting Corporal List"); - levelMasterList += - "
        " - + bundle.getString("getter.tournamentRank.3") - + "
        " - + "
          \n"; - break; - case 4: // sergeant - // log.debug("Starting Sergeant List"); - levelMasterList += - "
          " - + bundle.getString("getter.tournamentRank.4") - + "
          " - + "
            \n"; - break; - case 5: // Lieutenant - // log.debug("Starting Lieutenant List"); - levelMasterList += - "
            " - + bundle.getString("getter.tournamentRank.5") - + "
              \n"; - break; - case 6: // major - // log.debug("Starting Major List"); - levelMasterList += - "
              " - + bundle.getString("getter.tournamentRank.6") - + "
              " - + "
                \n"; - break; - case 7: // admiral - // log.debug("Starting Admiral List"); - levelMasterList += - "
                " - + bundle.getString("getter.tournamentRank.7") - + "
                " - + "
                  \n"; - break; - } + // Update the current section to the one we have just added to the list + currentSection = getTounnamentSectionFromRankNumber(levels.getInt(5)); + // Which to Add? + switch (currentSection) { + case 1: // fieldTraining + // log.debug("Starting Field Training List"); + levelMasterList += + "
                  " + + bundle.getString("getter.tournamentRank.1") + + "
                    \n"; + break; + case 2: // private + // log.debug("Starting Private List"); + levelMasterList += + "
                    " + + bundle.getString("getter.tournamentRank.2") + + "
                    " + + "
                      \n"; + break; + case 3: // corporal + // log.debug("Starting Corporal List"); + levelMasterList += + "
                      " + + bundle.getString("getter.tournamentRank.3") + + "
                      " + + "
                        \n"; + break; + case 4: // sergeant + // log.debug("Starting Sergeant List"); + levelMasterList += + "
                        " + + bundle.getString("getter.tournamentRank.4") + + "
                        " + + "
                          \n"; + break; + case 5: // Lieutenant + // log.debug("Starting Lieutenant List"); + levelMasterList += + "
                          " + + bundle.getString("getter.tournamentRank.5") + + "
                            \n"; + break; + case 6: // major + // log.debug("Starting Major List"); + levelMasterList += + "
                            " + + bundle.getString("getter.tournamentRank.6") + + "
                            " + + "
                              \n"; + break; + case 7: // admiral + // log.debug("Starting Admiral List"); + levelMasterList += + "
                              " + + bundle.getString("getter.tournamentRank.7") + + "
                              " + + "
                                \n"; + break; } - // Now we can add the entry to the level master List and start again - levelMasterList += listEntry; - // log.debug("Put level in category: " + currentSection); - } - // If no output has been found, return an error message - if (levelMasterList.isEmpty()) { - levelMasterList = - ""; - } else { - // List is complete, but we need to close the last list we made, which deinfetly - // exists as the levelmasterList is not empty - levelMasterList += "
                              "; - log.debug("Tournament List returned"); } + // Now we can add the entry to the level master List and start again + levelMasterList += listEntry; + // log.debug("Put level in category: " + currentSection); } + // If no output has been found, return an error message + if (levelMasterList.isEmpty()) { + levelMasterList = + ""; + } else { + // List is complete, but we need to close the last list we made, which deinfetly + // exists as the levelmasterList is not empty + levelMasterList += "
                            "; + log.debug("Tournament List returned"); + } + Database.closeConnection(conn); + } catch (Exception e) { log.error("Tournament List Retrieval: " + e.toString()); } @@ -2036,75 +2209,73 @@ public static JSONArray getModulesJson(String userId, String floor, Locale local log.debug("*** Getter.getModulesJson ***"); JSONArray jsonOutput = new JSONArray(); new String(); - try (Connection conn = Database.getCoreConnection()) { - ResourceBundle.getBundle("i18n.text", locale); - ResourceBundle levelNames = - ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", locale); - try { - JSONObject jsonSection = new JSONObject(); - JSONArray jsonSectionModules = new JSONArray(); - JSONObject jsonObject = new JSONObject(); - jsonSection.put("levelMode", floor); - jsonOutput.put(jsonSection); - jsonSection = new JSONObject(); - - // Get the modules - try (CallableStatement callstmt = conn.prepareCall("call getMyModules(?)")) { - callstmt.setString(1, userId); - log.debug("Gathering getMyModules ResultSet for user " + userId); - try (ResultSet levels = callstmt.executeQuery()) { - boolean thisModuleIsOpen = - true; // If Incremental Mode is enabled, after all the modules that have been - // completed have been added to the JSON Array the next level will be - // labeled as open and the rest as closed - while (levels.next()) { - jsonObject = new JSONObject(); - boolean moduleCompleted = levels.getString(4) != null; - jsonObject.put("moduleCompleted", moduleCompleted); - jsonObject.put("moduleId", levels.getString(3)); - jsonObject.put("moduleType", levels.getString(5)); - jsonObject.put("moduleName", levelNames.getString(levels.getString(1))); - jsonObject.put( - "moduleCategory", levelNames.getString("category." + levels.getString(2))); - jsonObject.put( - "difficultyCategory", getTounnamentSectionFromRankNumber(levels.getInt(7))); - jsonObject.put("moduleScore", levels.getString(6)); - jsonObject.put("moduleRank", levels.getInt(7)); - jsonObject.put("scoredPoints", levels.getString(8)); // Could be null - jsonObject.put("medalEarned", levels.getString(9)); // Could be null - if (ModulePlan.isIncrementalFloor()) { - boolean moduleOpen; - if (moduleCompleted - || (!moduleCompleted && thisModuleIsOpen)) // If its completed or if this is the - // first not completed - { - moduleOpen = true; - if (!moduleCompleted && thisModuleIsOpen) { - log.debug( - levelNames.getString(levels.getString(1)) - + " is the Next Module for user " - + userId); - thisModuleIsOpen = false; // Stop this from being set again - } - } else { - moduleOpen = false; - } - jsonObject.put("moduleOpen", moduleOpen); - } - jsonSectionModules.put(jsonObject); + Connection conn; + try { + conn = Database.getCoreConnection(); + } catch (SQLException | IOException e) { + log.error("Could not connect to core database: " + e.toString()); + throw new RuntimeException(e); + } + ResourceBundle.getBundle("i18n.text", locale); + ResourceBundle levelNames = ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", locale); + try { + JSONObject jsonSection = new JSONObject(); + JSONArray jsonSectionModules = new JSONArray(); + JSONObject jsonObject = new JSONObject(); + jsonSection.put("levelMode", floor); + jsonOutput.put(jsonSection); + jsonSection = new JSONObject(); + + // Get the modules + CallableStatement callstmt = conn.prepareCall("call getMyModules(?)"); + callstmt.setString(1, userId); + log.debug("Gathering getMyModules ResultSet for user " + userId); + ResultSet levels = callstmt.executeQuery(); + boolean thisModuleIsOpen = + true; // If Incremental Mode is enabled, after all the modules that have been + // completed have been added to the JSON Array the next level will be + // labeled as open and the rest as closed + while (levels.next()) { + jsonObject = new JSONObject(); + boolean moduleCompleted = levels.getString(4) != null; + jsonObject.put("moduleCompleted", moduleCompleted); + jsonObject.put("moduleId", levels.getString(3)); + jsonObject.put("moduleType", levels.getString(5)); + jsonObject.put("moduleName", levelNames.getString(levels.getString(1))); + jsonObject.put("moduleCategory", levelNames.getString("category." + levels.getString(2))); + jsonObject.put("difficultyCategory", getTounnamentSectionFromRankNumber(levels.getInt(7))); + jsonObject.put("moduleScore", levels.getString(6)); + jsonObject.put("moduleRank", levels.getInt(7)); + jsonObject.put("scoredPoints", levels.getString(8)); // Could be null + jsonObject.put("medalEarned", levels.getString(9)); // Could be null + if (ModulePlan.isIncrementalFloor()) { + boolean moduleOpen; + if (moduleCompleted + || (!moduleCompleted && thisModuleIsOpen)) // If its completed or if this is the + // first not completed + { + moduleOpen = true; + if (!moduleCompleted && thisModuleIsOpen) { + log.debug( + levelNames.getString(levels.getString(1)) + + " is the Next Module for user " + + userId); + thisModuleIsOpen = false; // Stop this from being set again } - jsonSection.put("modules", jsonSectionModules); - jsonOutput.put(jsonSection); + } else { + moduleOpen = false; } + jsonObject.put("moduleOpen", moduleOpen); } - } catch (Exception e) { - log.error("Module List Retrieval: " + e.toString()); + jsonSectionModules.put(jsonObject); } - return jsonOutput; - } catch (SQLException | IOException e) { - log.error("Could not connect to core database: " + e.toString()); - throw new RuntimeException(e); + jsonSection.put("modules", jsonSectionModules); + jsonOutput.put(jsonSection); + } catch (Exception e) { + log.error("Module List Retrieval: " + e.toString()); } + Database.closeConnection(conn); + return jsonOutput; } /** @@ -2116,16 +2287,19 @@ public static String getUserClassFromName(String ApplicationRoot, String userNam log.debug("*** Getter.getUserClass ***"); String result = new String(); userName = userName.toLowerCase(); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - CallableStatement callstmt = conn.prepareCall("call userClassId(?)")) { + try { + Connection conn = Database.getCoreConnection(ApplicationRoot); + + CallableStatement callstmt = conn.prepareCall("call userClassId(?)"); log.debug("Gathering userClassId ResultSet"); callstmt.setString(1, userName); - try (ResultSet resultSet = callstmt.executeQuery()) { - log.debug("Opening Result Set from userClassId"); - resultSet.next(); - result = resultSet.getString(1); - log.debug("Found " + result); - } + ResultSet resultSet = callstmt.executeQuery(); + log.debug("Opening Result Set from userClassId"); + resultSet.next(); + result = resultSet.getString(1); + log.debug("Found " + result); + Database.closeConnection(conn); + } catch (SQLException e) { log.error("Could not execute userClassId: " + e.toString()); result = new String(); @@ -2145,15 +2319,18 @@ public static String getUserIdFromName(String ApplicationRoot, String userName) userName = userName.toLowerCase(); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - CallableStatement callstmt = conn.prepareCall("call userGetIdByName(?)")) { + try { + Connection conn = Database.getCoreConnection(ApplicationRoot); + + CallableStatement callstmt = conn.prepareCall("call userGetIdByName(?)"); log.debug("Gathering userGetIdByName ResultSet"); callstmt.setString(1, userName); - try (ResultSet resultSet = callstmt.executeQuery()) { - log.debug("Opening Result Set from userGetIdByName"); - resultSet.next(); - result = resultSet.getString(1); - } + ResultSet resultSet = callstmt.executeQuery(); + log.debug("Opening Result Set from userGetIdByName"); + resultSet.next(); + result = resultSet.getString(1); + Database.closeConnection(conn); + } catch (SQLException e) { log.error("Could not execute query: " + e.toString()); result = null; @@ -2170,15 +2347,18 @@ public static String getUserIdFromName(String ApplicationRoot, String userName) public static String getUserName(String ApplicationRoot, String userId) { log.debug("*** Getter.getUserName ***"); String result = new String(); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - CallableStatement callstmt = conn.prepareCall("call userGetNameById(?)")) { + try { + Connection conn = Database.getCoreConnection(ApplicationRoot); + + CallableStatement callstmt = conn.prepareCall("call userGetNameById(?)"); log.debug("Gathering userGetNameById ResultSet"); callstmt.setString(1, userId); - try (ResultSet resultSet = callstmt.executeQuery()) { - log.debug("Opening Result Set from userGetNameById"); - resultSet.next(); - result = resultSet.getString(1); - } + ResultSet resultSet = callstmt.executeQuery(); + log.debug("Opening Result Set from userGetNameById"); + resultSet.next(); + result = resultSet.getString(1); + Database.closeConnection(conn); + } catch (SQLException e) { log.error("Could not execute query: " + e.toString()); result = null; @@ -2203,21 +2383,24 @@ public static boolean isCsrfLevelComplete( boolean result = false; - log.debug("Preparing csrfLevelComplete call"); - try (Connection conn = Database.getCoreConnection(applicationRoot); - PreparedStatement callstmnt = conn.prepareCall("call csrfLevelComplete(?, ?)")) { + try { + Connection conn = Database.getCoreConnection(applicationRoot); + + log.debug("Preparing csrfLevelComplete call"); + PreparedStatement callstmnt = conn.prepareCall("call csrfLevelComplete(?, ?)"); callstmnt.setString(1, moduleId); callstmnt.setString(2, userId); log.debug("moduleId: " + moduleId); log.debug("userId: " + userId); log.debug("Executing csrfLevelComplete"); - try (ResultSet resultSet = callstmnt.executeQuery()) { - resultSet.next(); - result = resultSet.getInt(1) > 0; // If Result is > 0, then the CSRF level is complete - if (result) { - log.debug("CSRF Level is complete"); - } + ResultSet resultSet = callstmnt.executeQuery(); + resultSet.next(); + result = resultSet.getInt(1) > 0; // If Result is > 0, then the CSRF level is complete + if (result) { + log.debug("CSRF Level is complete"); } + Database.closeConnection(conn); + } catch (SQLException e) { log.error("csrfLevelComplete Failure: " + e.toString()); result = false; @@ -2229,18 +2412,22 @@ public static boolean isCsrfLevelComplete( public static boolean isModuleOpen(String ApplicationRoot, String moduleId) { log.debug("*** Getter.isModuleOpen ***"); boolean result = false; - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - // Get the modules - PreparedStatement prepStmt = - conn.prepareStatement("SELECT moduleStatus FROM modules WHERE moduleId = ?")) { + try { + Connection conn = Database.getCoreConnection(ApplicationRoot); + + // Get the modules + PreparedStatement prepStmt = + conn.prepareStatement("SELECT moduleStatus FROM modules WHERE moduleId = ?"); prepStmt.setString(1, moduleId); - try (ResultSet rs = prepStmt.executeQuery()) { - if (rs.next()) { - if (rs.getString(1).equalsIgnoreCase("open")) { - result = true; - } + ResultSet rs = prepStmt.executeQuery(); + if (rs.next()) { + if (rs.getString(1).equalsIgnoreCase("open")) { + result = true; } } + rs.close(); + Database.closeConnection(conn); + } catch (Exception e) { log.error("isModuleOpen Error: " + e.toString()); } @@ -2254,16 +2441,12 @@ public static boolean isModuleOpen(String ApplicationRoot, String moduleId) { public static ResultSet getAdmins(String ApplicationRoot) { ResultSet result = null; log.debug("*** Getter.adminGetAll () ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - CallableStatement callstmt = conn.prepareCall("call adminGetAll()")) { - callstmt.setMaxRows(MAX_ROWSET_ROWS); - try (ResultSet resultSet = callstmt.executeQuery()) { - log.debug("Gathering adminGetAll ResultSet"); - CachedRowSet rowSet = RowSetProvider.newFactory().createCachedRowSet(); - rowSet.populate(resultSet); - rowSet.beforeFirst(); // populate() leaves the cursor after the last row - result = rowSet; - } + try { + Connection conn = Database.getCoreConnection(ApplicationRoot); + + CallableStatement callstmt = conn.prepareCall("call adminGetAll()"); + log.debug("Gathering adminGetAll ResultSet"); + result = callstmt.executeQuery(); log.debug("Returning Result Set from adminGetAll"); } catch (SQLException e) { @@ -2285,18 +2468,20 @@ public static boolean findAdminById(String ApplicationRoot, String userId) { log.debug("*** Getter.findAdminById ***"); boolean userFound = false; // Get connection - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - CallableStatement callstmt = conn.prepareCall("call adminFindById(?)")) { + try { + Connection conn = Database.getCoreConnection(ApplicationRoot); + + CallableStatement callstmt = conn.prepareCall("call adminFindById(?)"); log.debug("Gathering adminFindById ResultSet"); callstmt.setString(1, userId); - try (ResultSet userFind = callstmt.executeQuery()) { - log.debug("Opening Result Set from adminFindById"); - userFind.next(); // This will throw an exception if player not found - log.debug( - "Admin Found: " - + userFind.getString(1)); // This line will not execute if admin not found - userFound = true; - } + ResultSet userFind = callstmt.executeQuery(); + log.debug("Opening Result Set from adminFindById"); + userFind.next(); // This will throw an exception if player not found + log.debug( + "Admin Found: " + userFind.getString(1)); // This line will not execute if admin not found + userFound = true; + Database.closeConnection(conn); + } catch (Exception e) { log.error("Admin does not exist: " + e.toString()); userFound = false; @@ -2309,339 +2494,355 @@ public static boolean getAdminCheatStatus(String ApplicationRoot) throws SQLExce boolean adminCheatStatus = false; log.debug("*** Getter.getAdminCheatStatus ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Getting admin cheat setting"); - callstmt.setString(1, "adminCheatsEnabled"); + log.debug("Getting admin cheat setting"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet cheatResult = callstmt.executeQuery()) { - cheatResult.next(); - adminCheatStatus = cheatResult.getBoolean(1); - log.debug("Value found: " + adminCheatStatus); - } + callstmt.setString(1, "adminCheatsEnabled"); - log.debug("*** END getAdminCheatStatus ***"); - return adminCheatStatus; - } + ResultSet cheatResult = callstmt.executeQuery(); + + cheatResult.next(); + + adminCheatStatus = cheatResult.getBoolean(1); + + log.debug("Value found: " + adminCheatStatus); + + Database.closeConnection(conn); + log.debug("*** END getAdminCheatStatus ***"); + return adminCheatStatus; } public static boolean getPlayerCheatStatus(String ApplicationRoot) throws SQLException { boolean getPlayerCheatStatus = false; log.debug("*** Getter.getPlayerCheatStatus ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Getting player cheat setting"); - callstmt.setString(1, "playerCheatsEnabled"); + log.debug("Getting player cheat setting"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet cheatResult = callstmt.executeQuery()) { - cheatResult.next(); + callstmt.setString(1, "playerCheatsEnabled"); - getPlayerCheatStatus = cheatResult.getBoolean(1); + ResultSet cheatResult = callstmt.executeQuery(); - log.debug("Value found: " + getPlayerCheatStatus); + cheatResult.next(); - log.debug("*** END getPlayerCheatStatus ***"); - return getPlayerCheatStatus; - } - } + getPlayerCheatStatus = cheatResult.getBoolean(1); + + log.debug("Value found: " + getPlayerCheatStatus); + + Database.closeConnection(conn); + log.debug("*** END getPlayerCheatStatus ***"); + return getPlayerCheatStatus; } public static String getModuleLayout(String ApplicationRoot) throws SQLException { String theModuleLayout = ""; log.debug("*** Getter.getModuleLayout ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Getting module layout setting"); - callstmt.setString(1, "moduleLayout"); + log.debug("Getting module layout setting"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet layoutResult = callstmt.executeQuery()) { - layoutResult.next(); + callstmt.setString(1, "moduleLayout"); - theModuleLayout = layoutResult.getString(1); + ResultSet layoutResult = callstmt.executeQuery(); - log.debug("Value found: " + theModuleLayout); + layoutResult.next(); - log.debug("*** END getModuleLayout ***"); - return theModuleLayout; - } - } + theModuleLayout = layoutResult.getString(1); + + log.debug("Value found: " + theModuleLayout); + + Database.closeConnection(conn); + log.debug("*** END getModuleLayout ***"); + return theModuleLayout; } public static boolean getFeedbackStatus(String ApplicationRoot) throws SQLException { boolean theFeedbackStatus = false; log.debug("*** Getter.getFeedbackStatus ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Getting feedback status setting"); - callstmt.setString(1, "enableFeedback"); + log.debug("Getting feedback status setting"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet feedbackResult = callstmt.executeQuery()) { - feedbackResult.next(); + callstmt.setString(1, "enableFeedback"); - theFeedbackStatus = feedbackResult.getBoolean(1); + ResultSet feedbackResult = callstmt.executeQuery(); - log.debug("Value found: " + theFeedbackStatus); + feedbackResult.next(); - log.debug("*** END getFeedbackStatus ***"); - return theFeedbackStatus; - } - } + theFeedbackStatus = feedbackResult.getBoolean(1); + + log.debug("Value found: " + theFeedbackStatus); + + Database.closeConnection(conn); + log.debug("*** END getFeedbackStatus ***"); + return theFeedbackStatus; } public static boolean getRegistrationStatus(String ApplicationRoot) throws SQLException { boolean theRegistrationStatus = false; log.debug("*** Getter.getRegistrationStatus ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Getting registration status setting"); - callstmt.setString(1, "openRegistration"); + log.debug("Getting registration status setting"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet registrationResult = callstmt.executeQuery()) { - registrationResult.next(); + callstmt.setString(1, "openRegistration"); - theRegistrationStatus = registrationResult.getBoolean(1); + ResultSet registrationResult = callstmt.executeQuery(); - log.debug("Value found: " + theRegistrationStatus); + registrationResult.next(); - log.debug("*** END getRegistrationStatus ***"); - return theRegistrationStatus; - } - } + theRegistrationStatus = registrationResult.getBoolean(1); + + log.debug("Value found: " + theRegistrationStatus); + + Database.closeConnection(conn); + log.debug("*** END getRegistrationStatus ***"); + return theRegistrationStatus; } public static String getScoreboardStatus(String ApplicationRoot) throws SQLException { String theScoreboardStatus = ""; log.debug("*** Getter.getScoreboardStatus ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Setting scoreboard status setting"); - callstmt.setString(1, "scoreboardStatus"); + log.debug("Setting scoreboard status setting"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet scoreboardResult = callstmt.executeQuery()) { - scoreboardResult.next(); + callstmt.setString(1, "scoreboardStatus"); - theScoreboardStatus = scoreboardResult.getString(1); + ResultSet scoreboardResult = callstmt.executeQuery(); - log.debug("Value found: " + theScoreboardStatus); + scoreboardResult.next(); - log.debug("*** END getScoreboardStatus ***"); - return theScoreboardStatus; - } - } + theScoreboardStatus = scoreboardResult.getString(1); + + log.debug("Value found: " + theScoreboardStatus); + + Database.closeConnection(conn); + log.debug("*** END getScoreboardStatus ***"); + return theScoreboardStatus; } public static String getScoreboardClass(String ApplicationRoot) throws SQLException { String theScoreboardClass = ""; log.debug("*** Getter.getScoreboardClass ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Getting scoreboard class setting"); - callstmt.setString(1, "scoreboardClass"); + log.debug("Getting scoreboard class setting"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet scoreboardResult = callstmt.executeQuery()) { - scoreboardResult.next(); + callstmt.setString(1, "scoreboardClass"); - theScoreboardClass = scoreboardResult.getString(1); + ResultSet scoreboardResult = callstmt.executeQuery(); - log.debug("Value found: " + theScoreboardClass); + scoreboardResult.next(); - log.debug("*** END getScoreboardClass ***"); - return theScoreboardClass; - } - } + theScoreboardClass = scoreboardResult.getString(1); + + log.debug("Value found: " + theScoreboardClass); + + Database.closeConnection(conn); + log.debug("*** END getScoreboardClass ***"); + return theScoreboardClass; } public static Boolean getStartTimeStatus(String ApplicationRoot) throws SQLException { Boolean theStartTimeStatus = null; log.debug("*** Getter.getStartTimeStatus ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Getting start time setting"); - callstmt.setString(1, "hasStartTime"); + log.debug("Getting start time setting"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet timestampResult = callstmt.executeQuery()) { - timestampResult.next(); + callstmt.setString(1, "hasStartTime"); - theStartTimeStatus = timestampResult.getBoolean(1); + ResultSet timestampResult = callstmt.executeQuery(); - log.debug("Value found: " + theStartTimeStatus); + timestampResult.next(); - log.debug("*** END getStartTimeStatus ***"); - return theStartTimeStatus; - } - } + theStartTimeStatus = timestampResult.getBoolean(1); + + log.debug("Value found: " + theStartTimeStatus); + + Database.closeConnection(conn); + log.debug("*** END getStartTimeStatus ***"); + return theStartTimeStatus; } public static LocalDateTime getStartTime(String ApplicationRoot) throws SQLException { LocalDateTime theStartTimeStatus = null; log.debug("*** Getter.getStartTimeStatus ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Getting start time"); - callstmt.setString(1, "startTime"); + log.debug("Getting start time"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet timestampResult = callstmt.executeQuery()) { - timestampResult.next(); + callstmt.setString(1, "startTime"); - String dateTimeString = timestampResult.getString(1); + ResultSet timestampResult = callstmt.executeQuery(); - log.debug("Value found: " + dateTimeString); + timestampResult.next(); - theStartTimeStatus = LocalDateTime.parse(dateTimeString); + String dateTimeString = timestampResult.getString(1); - log.debug("*** END getStartTime ***"); - return theStartTimeStatus; - } - } + log.debug("Value found: " + dateTimeString); + + theStartTimeStatus = LocalDateTime.parse(dateTimeString); + + Database.closeConnection(conn); + log.debug("*** END getStartTime ***"); + return theStartTimeStatus; } public static Boolean getLockTimeStatus(String ApplicationRoot) throws SQLException { Boolean theLockTimeStatus = null; log.debug("*** Getter.getLockTimeStatus ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Getting lock time setting"); - callstmt.setString(1, "hasLockTime"); + log.debug("Getting lock time setting"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet timestampResult = callstmt.executeQuery()) { - timestampResult.next(); + callstmt.setString(1, "hasLockTime"); - theLockTimeStatus = timestampResult.getBoolean(1); + ResultSet timestampResult = callstmt.executeQuery(); - log.debug("Value found: " + theLockTimeStatus); + timestampResult.next(); - log.debug("*** END getLockTimeStatus ***"); - return theLockTimeStatus; - } - } + theLockTimeStatus = timestampResult.getBoolean(1); + + log.debug("Value found: " + theLockTimeStatus); + + Database.closeConnection(conn); + log.debug("*** END getLockTimeStatus ***"); + return theLockTimeStatus; } public static LocalDateTime getLockTime(String ApplicationRoot) throws SQLException { LocalDateTime theLockTimeStatus = null; log.debug("*** Getter.getLockTimeStatus ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Getting lock time"); - callstmt.setString(1, "lockTime"); + log.debug("Getting lock time"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet timestampResult = callstmt.executeQuery()) { - timestampResult.next(); + callstmt.setString(1, "lockTime"); - String dateTimeString = timestampResult.getString(1); + ResultSet timestampResult = callstmt.executeQuery(); - log.debug("Value found: " + dateTimeString); + timestampResult.next(); - theLockTimeStatus = LocalDateTime.parse(dateTimeString); + String dateTimeString = timestampResult.getString(1); - log.debug("*** END getLockTime ***"); - return theLockTimeStatus; - } - } + log.debug("Value found: " + dateTimeString); + + theLockTimeStatus = LocalDateTime.parse(dateTimeString); + + Database.closeConnection(conn); + log.debug("*** END getLockTime ***"); + return theLockTimeStatus; } public static Boolean getEndTimeStatus(String ApplicationRoot) throws SQLException { Boolean theEndTimeStatus = null; log.debug("*** Getter.getEndTimeStatus ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Getting end time setting"); - callstmt.setString(1, "hasEndTime"); + log.debug("Getting end time setting"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet timestampResult = callstmt.executeQuery()) { - timestampResult.next(); + callstmt.setString(1, "hasEndTime"); - theEndTimeStatus = timestampResult.getBoolean(1); + ResultSet timestampResult = callstmt.executeQuery(); - log.debug("Value found: " + theEndTimeStatus); + timestampResult.next(); - log.debug("*** END getEndTimeStatus ***"); - return theEndTimeStatus; - } - } + theEndTimeStatus = timestampResult.getBoolean(1); + + log.debug("Value found: " + theEndTimeStatus); + + Database.closeConnection(conn); + log.debug("*** END getEndTimeStatus ***"); + return theEndTimeStatus; } public static LocalDateTime getEndTime(String ApplicationRoot) throws SQLException { LocalDateTime theEndTimeStatus = null; log.debug("*** Getter.getEndTimeStatus ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Getting end time"); - callstmt.setString(1, "endTime"); + log.debug("Getting end time"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet timestampResult = callstmt.executeQuery()) { - timestampResult.next(); + callstmt.setString(1, "endTime"); - String dateTimeString = timestampResult.getString(1); + ResultSet timestampResult = callstmt.executeQuery(); - log.debug("Value found: " + dateTimeString); + timestampResult.next(); - theEndTimeStatus = LocalDateTime.parse(dateTimeString); + String dateTimeString = timestampResult.getString(1); - log.debug("*** END getEndTime ***"); - return theEndTimeStatus; - } - } + log.debug("Value found: " + dateTimeString); + + theEndTimeStatus = LocalDateTime.parse(dateTimeString); + + Database.closeConnection(conn); + log.debug("*** END getEndTime ***"); + return theEndTimeStatus; } public static String getDefaultClass(String ApplicationRoot) throws SQLException { String theDefaultClass = null; log.debug("*** Getter.getDefaultClass ***"); - try (Connection conn = Database.getCoreConnection(ApplicationRoot); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { + Connection conn = Database.getCoreConnection(ApplicationRoot); - log.debug("Getting default class"); - callstmt.setString(1, "defaultClass"); + log.debug("Getting default class"); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - try (ResultSet classResult = callstmt.executeQuery()) { - classResult.next(); + callstmt.setString(1, "defaultClass"); - theDefaultClass = classResult.getString(1); + ResultSet classResult = callstmt.executeQuery(); - log.debug("Value found: " + theDefaultClass); + classResult.next(); - log.debug("*** END getDefaultClass ***"); - return theDefaultClass; - } - } + theDefaultClass = classResult.getString(1); + + log.debug("Value found: " + theDefaultClass); + + Database.closeConnection(conn); + log.debug("*** END getDefaultClass ***"); + return theDefaultClass; } } diff --git a/src/main/java/utils/DbTime.java b/src/main/java/utils/DbTime.java index 1beb2f28b..3f9b36349 100644 --- a/src/main/java/utils/DbTime.java +++ b/src/main/java/utils/DbTime.java @@ -7,5 +7,6 @@ public class DbTime { private DbTime() {} - public static final Calendar UTC = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + public static final ThreadLocal UTC = + ThreadLocal.withInitial(() -> Calendar.getInstance(TimeZone.getTimeZone("UTC"))); } diff --git a/src/test/java/utils/DbTimeTest.java b/src/test/java/utils/DbTimeTest.java deleted file mode 100644 index 133165b60..000000000 --- a/src/test/java/utils/DbTimeTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package utils; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import java.sql.ResultSet; -import java.sql.Timestamp; -import java.time.Instant; -import java.util.TimeZone; - -import org.junit.jupiter.api.Test; - -public class DbTimeTest { - - @Test - void shouldReadTimestampCorrectlyInNonUtcJvm() throws Exception { - TimeZone original = TimeZone.getDefault(); - - try { - TimeZone.setDefault(TimeZone.getTimeZone("US/Pacific")); - - Instant expected = Instant.parse("2025-01-01T12:00:00Z"); - - ResultSet resultSet = mock(ResultSet.class); - - when(resultSet.getTimestamp(eq(7), eq(DbTime.UTC))) - .thenReturn(Timestamp.from(expected)); - - Timestamp suspendedUntil = - resultSet.getTimestamp(7, DbTime.UTC); - - assertEquals( - expected.toEpochMilli(), - suspendedUntil.toInstant().toEpochMilli()); - - } finally { - TimeZone.setDefault(original); - } - } -} \ No newline at end of file From b5db3b636168ab4848ac01adc76bc6ce2a14d50e Mon Sep 17 00:00:00 2001 From: Aman Gautam Date: Tue, 16 Jun 2026 11:54:08 +0530 Subject: [PATCH 6/8] fix: restore dev Getter.java, keep only UTC timestamp reads --- src/main/java/dbProcs/Getter.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/dbProcs/Getter.java b/src/main/java/dbProcs/Getter.java index a46e435bf..726edb7f1 100644 --- a/src/main/java/dbProcs/Getter.java +++ b/src/main/java/dbProcs/Getter.java @@ -369,7 +369,7 @@ public static String[] authUserSSO( log.debug("Getting suspension data"); try { - suspendedUntil = userResult.getTimestamp(7, DbTime.UTC.get()); + suspendedUntil = userResult.getTimestamp(7,DbTime.UTC.get()); } catch (SQLException e) { log.fatal( "Could not find suspension information from ssoName: " + ssoName + ": " + e.toString()); From fca681f5c8ffd89e9ad525a45562f09f3f199c4d Mon Sep 17 00:00:00 2001 From: DuggSe01 Date: Tue, 16 Jun 2026 10:26:05 +0100 Subject: [PATCH 7/8] fix: restore dev Getter.java, keep only UTC timestamp reads Getter.java had drifted to a pre-#816 version due to a bad merge, dropping the connection-pool refactor and CachedRowSet cap. This caused the integration-test connection-exhaustion failure. Restore Getter.java from upstream/dev and re-apply only the two UTC Calendar reads for suspendedUntil, as suggested in review. --- src/main/java/dbProcs/Getter.java | 2955 ++++++++++++++--------------- 1 file changed, 1377 insertions(+), 1578 deletions(-) diff --git a/src/main/java/dbProcs/Getter.java b/src/main/java/dbProcs/Getter.java index 726edb7f1..2650b1a5f 100644 --- a/src/main/java/dbProcs/Getter.java +++ b/src/main/java/dbProcs/Getter.java @@ -13,6 +13,8 @@ import java.util.ArrayList; import java.util.Locale; import java.util.ResourceBundle; +import javax.sql.rowset.CachedRowSet; +import javax.sql.rowset.RowSetProvider; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.json.JSONArray; @@ -62,6 +64,15 @@ public class Getter { private static final int admiralCap = 999; // everything above Major is Admiral + /** + * Safety cap on the number of rows materialized by {@link #getClassInfo}, {@link + * #getPlayersByClass}, and {@link #getAdmins}. These methods return a {@link + * javax.sql.rowset.CachedRowSet}, which holds every row in memory. Realistic workloads are well + * under this limit (tens to a few hundred per call); the cap exists to fail fast on a runaway + * query rather than OOM the JVM. Tracked for proper bounded-collection conversion in #839. + */ + private static final int MAX_ROWSET_ROWS = 10_000; + /** * This method hashes the user submitted password and sends it to the database. The database does * the rest of the work, including Brute Force prevention. @@ -72,167 +83,109 @@ public class Getter { * authentication process. */ public static String[] authUser(String ApplicationRoot, String userName, String password) { - String[] result = null; log.debug("$$$ Getter.authUser $$$"); - log.debug("userName = " + userName); - boolean userFound = false; - boolean userVerified = false; - - Connection conn; - try { - conn = Database.getCoreConnection(ApplicationRoot); + // Phase 1: Fetch user record (short DB hold, ~1-5ms) + String userId; + String dbUserName; + String dbHash; + String userRole; + int badLoginCount; + boolean tempPassword; + String classId; + Timestamp suspendedUntil; + String loginType; + boolean tempUsername; + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement prestmt = + conn.prepareStatement( + "SELECT userId, userName, userPass, userRole, badLoginCount, tempPassword, classId," + + " suspendedUntil, loginType, tempUsername FROM `users` WHERE userName = ?")) { + prestmt.setString(1, userName); + try (ResultSet userResult = prestmt.executeQuery()) { + if (userResult.next()) { + log.debug("User Found"); + userId = userResult.getString(1); + dbUserName = userResult.getString(2); + dbHash = userResult.getString(3); + userRole = userResult.getString(4); + badLoginCount = userResult.getInt(5); + tempPassword = userResult.getBoolean(6); + classId = userResult.getString(7); + suspendedUntil = userResult.getTimestamp(8, DbTime.utcCalendar()); + loginType = userResult.getString(9); + tempUsername = userResult.getBoolean(10); + } else { + log.debug("User did not exist"); + log.debug("$$$ End authUser $$$"); + return null; + } + } } catch (SQLException e) { - log.fatal("Could create get core connection: " + e.toString()); + log.fatal("authUser failed: " + e.toString()); throw new RuntimeException(e); } + // Connection released — all user data extracted into local variables - // See if user Exists - PreparedStatement prestmt; - CallableStatement callstmt; - try { - prestmt = - conn.prepareStatement( - "SELECT userId, userName, userPass, userRole, badLoginCount, tempPassword, classId," - + " suspendedUntil, loginType, tempUsername FROM `users` WHERE userName = ?"); - } catch (SQLException e) { - log.fatal("Could create call statement: " + e.toString()); - throw new RuntimeException(e); + // Fail-fast: reject suspended and SSO users before expensive Argon2 work + if (!"login".equals(loginType)) { + log.debug("User is SSO user, can't login with password!"); + return null; } - log.debug("Gathering results from query"); - ResultSet userResult; - try { - prestmt.setString(1, userName); - userResult = prestmt.executeQuery(); - } catch (SQLException e) { - log.fatal("Could not execute db query: " + e.toString()); - throw new RuntimeException(e); + Timestamp currentTime = new Timestamp(System.currentTimeMillis()); + if (suspendedUntil != null && suspendedUntil.after(currentTime)) { + return null; } - log.debug("Opening Result Set from query"); + // Phase 2: Verify password (CPU-bound Argon2, no DB connection held) + log.debug("Verifying hash"); + Argon2 argon2 = Argon2Factory.create(); + boolean userVerified = argon2.verify(dbHash, password.toCharArray()); - try { - if (userResult.next()) { - log.debug( - "User Found"); // User found if a row is in the database, this line will not work if the - // result - // set is empty - userFound = true; - } else { - log.debug("User did not exist"); - userFound = false; - } - } catch (SQLException e) { - log.debug("User did not exist"); - userFound = false; + if (!userVerified) { + log.debug("Hash did not match, authentication failed"); + log.debug("$$$ End authUser $$$"); + return null; } - if (userFound) { - // Authenticate User - Argon2 argon2 = Argon2Factory.create(); + // Phase 3: Post-verification DB updates (short DB hold if needed) + log.debug("Hash matches"); - log.debug("Getting password hash"); - String dbHash; - try { - dbHash = userResult.getString(3); - log.debug("Verifying hash"); + if (!dbUserName.equalsIgnoreCase(userName)) { + log.fatal( + "User Name used (" + + userName + + ") and User Name retrieved (" + + dbUserName + + ") were not the Same. Nulling Result"); + return null; + } - userVerified = argon2.verify(dbHash, password.toCharArray()); + log.debug("User '" + userName + "' has logged in"); + if (badLoginCount > 0) { + log.debug("Clearing Bad Login History"); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + CallableStatement callstmt = conn.prepareCall("call userBadLoginReset(?)")) { + callstmt.setString(1, userId); + callstmt.execute(); + log.debug("userBadLoginReset executed!"); } catch (SQLException e) { - log.fatal("Could not retrieve password hash from db: " + e.toString()); - result = null; - userVerified = false; + log.fatal("Could not reset bad login count: " + e.toString()); throw new RuntimeException(e); - // TODO: We should throw a checked exception here instead - } - - if (userVerified) { - // Hash matches - log.debug("Hash matches"); - - result = new String[6]; - - int badLoginCount; - String loginType = new String(); - - Timestamp suspendedUntil; - - try { - result[0] = userResult.getString(1); - result[1] = userResult.getString(2); // userName - result[2] = userResult.getString(4); // role - badLoginCount = userResult.getInt(5); - result[3] = Boolean.toString(userResult.getBoolean(6)); - result[4] = userResult.getString(7); // classId - suspendedUntil = userResult.getTimestamp(8, DbTime.UTC.get()); - loginType = userResult.getString(9); - result[5] = Boolean.toString(userResult.getBoolean(10)); - } catch (SQLException e) { - - log.fatal("Could not retrieve auth data from db: " + e.toString()); - throw new RuntimeException(e); - } - - if (!loginType.equals("login")) { - // Login type must be "login" and not "saml" if password login is to be allowed - log.debug("User is SSO user, can't login with password!"); - result = null; - return result; - } - - // Get current system time - Timestamp currentTime = new Timestamp(System.currentTimeMillis()); - - if (suspendedUntil.after(currentTime)) { - // User is suspended - result = null; - return result; - } - - if (!result[1].equalsIgnoreCase( - userName)) // If somehow this functionality has been compromised to sign - // in as - // other users, this will limit the expoitability. But the method is - // sql injection safe, so it should be ok - { - log.fatal( - "User Name used (" - + userName - + ") and User Name retrieved (" - + result[1] - + ") were not the Same. Nulling Result"); - result = null; - } else { - log.debug("User '" + userName + "' has logged in"); - // Before finishing, check if user had a badlogin history, if so, Clear it - if (badLoginCount > 0) { - log.debug("Clearing Bad Login History"); - try { - callstmt = conn.prepareCall("call userBadLoginReset(?)"); - callstmt.setString(1, result[0]); - callstmt.execute(); - } catch (SQLException e) { - log.fatal("Could not reset bad login count: " + e.toString()); - throw new RuntimeException(e); - } - - log.debug("userBadLoginReset executed!"); - } - } - // User has logged in, or a Authentication Bypass was detected... You never - // know! Better safe than sorry - // TODO: will this close the db connection if we return here? - return result; - } else { - // Hash did not match - log.debug("Hash did not match, authentication failed"); } } - Database.closeConnection(conn); + String[] result = new String[6]; + result[0] = userId; + result[1] = dbUserName; + result[2] = userRole; + result[3] = Boolean.toString(tempPassword); + result[4] = classId; + result[5] = Boolean.toString(tempUsername); + log.debug("$$$ End authUser $$$"); return result; } @@ -267,205 +220,143 @@ public static String[] authUserSSO( boolean isTempUsername = false; - Connection conn; try { - conn = Database.getCoreConnection(ApplicationRoot); - } catch (SQLException e) { - log.fatal("Could create get core connection: " + e.toString()); - throw new RuntimeException(e); - } - // See if user Exists - PreparedStatement prestmt; - try { - prestmt = - conn.prepareStatement( - "SELECT userId, userName, userPass, badLoginCount, tempPassword, classId," - + " suspendedUntil, loginType FROM `users` WHERE ssoName = ? AND" - + " loginType='saml'"); - } catch (SQLException e) { - log.fatal("Could create call statement: " + e.toString()); - throw new RuntimeException(e); - } - - log.debug("Gathering userFind ResultSet"); - ResultSet userResult; - try { - prestmt.setString(1, ssoName); - log.debug("Executing query"); - userResult = prestmt.executeQuery(); - } catch (SQLException e) { - log.fatal("Could not execute db query: " + e.toString()); - throw new RuntimeException(e); - } + // Phase 1: See if the user already exists, and capture suspension data if so. + // Each phase opens its own pooled connection in try-with-resources so the + // connection is never held across the Setter.userCreateSSO call (Phase 2). + Timestamp suspendedUntil = null; + + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement prestmt = + conn.prepareStatement( + "SELECT suspendedUntil FROM `users` WHERE ssoName = ? AND loginType='saml'")) { + prestmt.setString(1, ssoName); + log.debug("Gathering userFind ResultSet"); + try (ResultSet userResult = prestmt.executeQuery()) { + log.debug("Opening Result Set from userResult"); + if (userResult.next()) { + // User found if a row is in the database + userFound = true; + log.debug("User Found"); + suspendedUntil = userResult.getTimestamp(1, DbTime.utcCalendar()); + } else { + userFound = false; + } + } + } - log.debug("Opening Result Set from userResult"); + if (!userFound) { + // Phase 2: User wasn't found, enroll them in database. No pooled + // connection is held here; Setter.userCreateSSO borrows its own. - try { - if (userResult.next()) { - // User found if a row is in the database - userFound = true; - log.debug("User Found"); - } else { - userFound = false; - } + boolean userCreated = false; - } catch (SQLException e) { - log.debug("User did not exist"); - userFound = false; - } + log.debug("User did not exist, create it from SSO data"); - if (!userFound) { - // User wasn't found, enroll them in database + try { - boolean userCreated = false; + if (defaultClass.isEmpty()) { + log.debug("Adding player to database, with null classId"); + newUsername = Setter.userCreateSSO(ApplicationRoot, null, userName, ssoName, userRole); + } else // defaultClass is not empty, so It must be set to a class! + { + log.debug("Adding player to database, to class " + defaultClass); + newUsername = + Setter.userCreateSSO(ApplicationRoot, defaultClass, userName, ssoName, userRole); + } - log.debug("User did not exist, create it from SSO data"); + if (newUsername == null) { + userCreated = false; + } else { + userCreated = true; + } - try { + userName = newUsername; - if (defaultClass.isEmpty()) { - log.debug("Adding player to database, with null classId"); - newUsername = Setter.userCreateSSO(ApplicationRoot, null, userName, ssoName, userRole); - } else // defaultClass is not empty, so It must be set to a class! - { - log.debug("Adding player to database, to class " + defaultClass); - newUsername = - Setter.userCreateSSO(ApplicationRoot, defaultClass, userName, ssoName, userRole); + } catch (SQLException e) { + String message = + "Could not create user " + + userName + + " with ssoName " + + ssoName + + " via SSO: " + + e.toString(); + log.fatal(message); + throw new RuntimeException(message); } - if (newUsername == null) { - userCreated = false; - } else { - userCreated = true; + if (!userCreated) { + String message = + "Could not create user " + userName + " with ssoName " + ssoName + " via SSO"; + log.fatal(message); + throw new RuntimeException(message); } - userName = newUsername; + log.debug("User created"); - } catch (SQLException e) { - String message = - "Could not create user " - + userName - + " with ssoName " - + ssoName - + " via SSO: " - + e.toString(); - log.fatal(message); - throw new RuntimeException(message); - } - - if (!userCreated) { - String message = - "Could not create user " + userName + " with ssoName " + ssoName + " via SSO"; - log.fatal(message); - throw new RuntimeException(message); - } - - log.debug("User created"); + } else { - } else { + log.debug("Getting suspension data"); - Timestamp suspendedUntil; + // Get current system time + Timestamp currentTime = new Timestamp(System.currentTimeMillis()); - log.debug("Getting suspension data"); + if (suspendedUntil.after(currentTime)) { + // User is suspended + log.debug("User is suspended"); - try { - suspendedUntil = userResult.getTimestamp(7,DbTime.UTC.get()); - } catch (SQLException e) { - log.fatal( - "Could not find suspension information from ssoName: " + ssoName + ": " + e.toString()); - throw new RuntimeException(e); + result = null; + return result; + } } - // Get current system time - Timestamp currentTime = new Timestamp(System.currentTimeMillis()); + // Phase 3: Find the generated userID and username by asking the database. + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement prestmt = + conn.prepareStatement( + "SELECT userId, userName, classID, tempUsername FROM `users` WHERE ssoName = ?" + + " AND loginType='saml'")) { + prestmt.setString(1, ssoName); + log.debug("Gathering userResult ResultSet"); + try (ResultSet userResult = prestmt.executeQuery()) { + log.debug("Opening user list result set"); + if (userResult.next()) { + userFound = true; + log.debug("User Found"); + } else { + userFound = false; + } - if (suspendedUntil.after(currentTime)) { - // User is suspended - log.debug("User is suspended"); + if (!userFound) { + // If user wasn't found at this stage something is quite wrong, so exit + // forcefully + String message = "User wasn't found after being added!"; + log.fatal(message); + throw new RuntimeException(message); + } - result = null; - return result; + userID = userResult.getString(1); + userName = userResult.getString(2); + classId = userResult.getString(3); // classId + isTempUsername = userResult.getBoolean(4); + } } - } - // Find the generated userID and username by asking the database - try { - prestmt = - conn.prepareStatement( - "SELECT userId, userName, classID, tempUsername FROM `users` WHERE ssoName = ? AND" - + " loginType='saml'"); + log.debug("User '" + userName + "' has logged in via SSO" + " with role " + userRole); - } catch (SQLException e) { - log.fatal("Could create call statement: " + e.toString()); - throw new RuntimeException(e); - } + result[0] = userID; + result[1] = userName; // userName + result[2] = userRole; // role + result[5] = "false"; // sso logins can't change password + result[4] = classId; // classId + result[5] = Boolean.toString(isTempUsername); - log.debug("Gathering userResult ResultSet"); - - try { - prestmt.setString(1, ssoName); - log.debug("Executing query"); - userResult = prestmt.executeQuery(); + log.debug("$$$ End authUser $$$"); + return result; } catch (SQLException e) { - log.fatal("Could not execute db query: " + e.toString()); + log.fatal("authUserSSO failed: " + e.toString()); throw new RuntimeException(e); } - - log.debug("Opening user list result set"); - - try { - if (userResult.next()) { - userFound = true; - log.debug( - "User Found"); // User found if a row is in the database, this line will not work if the - // result - // set is empty - } else { - userFound = false; - } - - } catch (SQLException e) { - log.debug("User did not exist"); - userFound = false; - } - - if (!userFound) { - // If user wasn't found at this stage something is quite wrong, so exit - // forefully - String message = "User wasn't found after being added!"; - log.fatal(message); - throw new RuntimeException(message); - } - - try { - userID = userResult.getString(1); - userName = userResult.getString(2); - classId = userResult.getString(3); // classId - isTempUsername = userResult.getBoolean(4); - } catch (SQLException e) { - String message = - "Could find userID for userName " - + userName - + " with ssoName " - + ssoName - + " via SSO: " - + e.toString(); - log.fatal(message); - throw new RuntimeException(message); - } - - log.debug("User '" + userName + "' has logged in via SSO" + " with role " + userRole); - - result[0] = userID; - result[1] = userName; // userName - result[2] = userRole; // role - result[5] = "false"; // sso logins can't change password - result[4] = classId; // classId - result[5] = Boolean.toString(isTempUsername); - - Database.closeConnection(conn); - log.debug("$$$ End authUser $$$"); - return result; } /** @@ -481,19 +372,17 @@ public static String checkPlayerResult(String ApplicationRoot, String moduleId, log.debug("*** Getter.checkPlayerResult ***"); String result = null; - try { - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + CallableStatement callstmnt = conn.prepareCall("call userCheckResult(?, ?)")) { log.debug("Preparing userCheckResult call"); - CallableStatement callstmnt = conn.prepareCall("call userCheckResult(?, ?)"); callstmnt.setString(1, moduleId); callstmnt.setString(2, userId); log.debug("Executing userCheckResult"); - ResultSet resultSet = callstmnt.executeQuery(); - resultSet.next(); - result = resultSet.getString(1); - Database.closeConnection(conn); - + try (ResultSet resultSet = callstmnt.executeQuery()) { + resultSet.next(); + result = resultSet.getString(1); + } } catch (SQLException e) { log.debug("userCheckResult Failure: " + e.toString()); result = null; @@ -512,21 +401,19 @@ public static boolean findPlayerById(String ApplicationRoot, String userId) { log.debug("*** Getter.findPlayerById ***"); boolean userFound = false; // Get connection - try { - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + CallableStatement callstmt = conn.prepareCall("call playerFindById(?)")) { - CallableStatement callstmt = conn.prepareCall("call playerFindById(?)"); log.debug("Gathering playerFindById ResultSet"); callstmt.setString(1, userId); - ResultSet userFind = callstmt.executeQuery(); - log.debug("Opening Result Set from playerFindById"); - userFind.next(); // This will throw an exception if player not found - log.debug( - "Player Found: " - + userFind.getString(1)); // This line will not execute if player not found - userFound = true; - Database.closeConnection(conn); - + try (ResultSet userFind = callstmt.executeQuery()) { + log.debug("Opening Result Set from playerFindById"); + userFind.next(); // This will throw an exception if player not found + log.debug( + "Player Found: " + + userFind.getString(1)); // This line will not execute if player not found + userFound = true; + } } catch (SQLException e) { log.error("Player did not exist: " + e.toString()); userFound = false; @@ -547,26 +434,24 @@ public static ArrayList getAllModuleInfo(String ApplicationRoot) { log.debug("*** Getter.getAllModuleInfo ***"); ArrayList modules = new ArrayList(); - try { - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + CallableStatement callstmt = conn.prepareCall("call moduleGetAll()")) { - CallableStatement callstmt = conn.prepareCall("call moduleGetAll()"); log.debug("Gathering moduleGetAll ResultSet"); - ResultSet resultSet = callstmt.executeQuery(); - log.debug("Opening Result Set from moduleGetAll"); - int i = 0; - while (resultSet.next()) { - String[] result = new String[4]; - i++; - result[0] = resultSet.getString(1); // moduleId - result[1] = resultSet.getString(2); // moduleName - result[2] = resultSet.getString(3); // moduleType - result[3] = resultSet.getString(4); // mdouleCategory - modules.add(result); + try (ResultSet resultSet = callstmt.executeQuery()) { + log.debug("Opening Result Set from moduleGetAll"); + int i = 0; + while (resultSet.next()) { + String[] result = new String[4]; + i++; + result[0] = resultSet.getString(1); // moduleId + result[1] = resultSet.getString(2); // moduleName + result[2] = resultSet.getString(3); // moduleType + result[3] = resultSet.getString(4); // mdouleCategory + modules.add(result); + } + log.debug("Returning Array list with " + i + " entries."); } - log.debug("Returning Array list with " + i + " entries."); - Database.closeConnection(conn); - } catch (SQLException e) { log.error("Could not execute query: " + e.toString()); } @@ -591,63 +476,64 @@ public static String getChallenges(String ApplicationRoot, String userId, Locale // Getting Translated Level Names ResourceBundle bundle = ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", lang); // Encoder to prevent XSS - Connection conn = Database.getCoreConnection(ApplicationRoot); - - CallableStatement callstmt = conn.prepareCall("call moduleAllInfo(?, ?)"); - callstmt.setString(1, "challenge"); - callstmt.setString(2, userId); - log.debug("Gathering moduleAllInfo ResultSet"); - ResultSet challenges = callstmt.executeQuery(); - log.debug("Opening Result Set from moduleAllInfo"); - String challengeCategory = new String(); - int rowNumber = 0; // Identifies the first row, ie the start of the list. This is slightly - // different output to every other row - while (challenges.next()) { - if (!challengeCategory.equalsIgnoreCase(challenges.getString(2))) { - challengeCategory = challenges.getString(2); - // log.debug("New Category Detected: " + challengeCategory); - if (rowNumber > 0) // output prepared for Every row after row 1 - { - output += - "
                        • " - + Encode.forHtml(bundle.getString("category." + challengeCategory)) - + "
                        • " + + Encode.forHtml(bundle.getString("category." + challengeCategory)) + + "\n"; + try (ResultSet levels = callstmt.executeQuery()) { + log.debug("Opening Result Set from moduleTournamentOpenInfo"); + int currentSection = + 0; // Used to identify the first row, as it is slightly different to all other rows + // for output + while (levels.next()) { + // Create Row Entry First + // log.debug("Adding " + lessons.getString(1)); + listEntry = "
                        • "; + // Markers for completion + if (levels.getString(4) != null) { + listEntry += ""; + } else { + listEntry += ""; } - // Update the current section to the one we have just added to the list - currentSection = getTounnamentSectionFromRankNumber(levels.getInt(5)); - // Which to Add? - switch (currentSection) { - case 1: // fieldTraining - // log.debug("Starting Field Training List"); - levelMasterList += - "
                          " - + bundle.getString("getter.tournamentRank.1") - + "
                            \n"; - break; - case 2: // private - // log.debug("Starting Private List"); - levelMasterList += - "
                            " - + bundle.getString("getter.tournamentRank.2") - + "
                            " - + "
                              \n"; - break; - case 3: // corporal - // log.debug("Starting Corporal List"); - levelMasterList += - "
                              " - + bundle.getString("getter.tournamentRank.3") - + "
                              " - + "
                                \n"; - break; - case 4: // sergeant - // log.debug("Starting Sergeant List"); - levelMasterList += - "
                                " - + bundle.getString("getter.tournamentRank.4") - + "
                                " - + "
                                  \n"; - break; - case 5: // Lieutenant - // log.debug("Starting Lieutenant List"); - levelMasterList += - "
                                  " - + bundle.getString("getter.tournamentRank.5") - + "
                                    \n"; - break; - case 6: // major - // log.debug("Starting Major List"); - levelMasterList += - "
                                    " - + bundle.getString("getter.tournamentRank.6") - + "
                                    " - + "
                                      \n"; - break; - case 7: // admiral - // log.debug("Starting Admiral List"); - levelMasterList += - "
                                      " - + bundle.getString("getter.tournamentRank.7") - + "
                                      " - + "
                                        \n"; - break; + // Prepare entry output + listEntry += + "" + + Encode.forHtml(levelNames.getString(levels.getString(1))) + + "\n"; + listEntry += ""; + // What section does this belong in? Current or Next? + if (getTounnamentSectionFromRankNumber(levels.getInt(5)) > currentSection) { + // This level is not in the same level band as the previous level. So a new + // Level Band Header is required on the master list before we add the entry. + // Do we need to close a previous list? + if (currentSection + != 0) // If a Section Select hasn't been made before, we don't need to close any + // previous sections + { + // We've had a section before, so need to close the previous one before we make + // this new one + levelMasterList += "
                                      \n"; + } + // Update the current section to the one we have just added to the list + currentSection = getTounnamentSectionFromRankNumber(levels.getInt(5)); + // Which to Add? + switch (currentSection) { + case 1: // fieldTraining + // log.debug("Starting Field Training List"); + levelMasterList += + "
                                      " + + bundle.getString("getter.tournamentRank.1") + + "
                                        \n"; + break; + case 2: // private + // log.debug("Starting Private List"); + levelMasterList += + "
                                        " + + bundle.getString("getter.tournamentRank.2") + + "
                                        " + + "
                                          \n"; + break; + case 3: // corporal + // log.debug("Starting Corporal List"); + levelMasterList += + "
                                          " + + bundle.getString("getter.tournamentRank.3") + + "
                                          " + + "
                                            \n"; + break; + case 4: // sergeant + // log.debug("Starting Sergeant List"); + levelMasterList += + "
                                            " + + bundle.getString("getter.tournamentRank.4") + + "
                                            " + + "
                                              \n"; + break; + case 5: // Lieutenant + // log.debug("Starting Lieutenant List"); + levelMasterList += + "
                                              " + + bundle.getString("getter.tournamentRank.5") + + "
                                                \n"; + break; + case 6: // major + // log.debug("Starting Major List"); + levelMasterList += + "
                                                " + + bundle.getString("getter.tournamentRank.6") + + "
                                                " + + "
                                                  \n"; + break; + case 7: // admiral + // log.debug("Starting Admiral List"); + levelMasterList += + "
                                                  " + + bundle.getString("getter.tournamentRank.7") + + "
                                                  " + + "
                                                    \n"; + break; + } } + // Now we can add the entry to the level master List and start again + levelMasterList += listEntry; + // log.debug("Put level in category: " + currentSection); + } + // If no output has been found, return an error message + if (levelMasterList.isEmpty()) { + levelMasterList = + ""; + } else { + // List is complete, but we need to close the last list we made, which deinfetly + // exists as the levelmasterList is not empty + levelMasterList += "
                                                  "; + log.debug("Tournament List returned"); } - // Now we can add the entry to the level master List and start again - levelMasterList += listEntry; - // log.debug("Put level in category: " + currentSection); - } - // If no output has been found, return an error message - if (levelMasterList.isEmpty()) { - levelMasterList = - ""; - } else { - // List is complete, but we need to close the last list we made, which deinfetly - // exists as the levelmasterList is not empty - levelMasterList += "
                                                "; - log.debug("Tournament List returned"); } - Database.closeConnection(conn); - } catch (Exception e) { log.error("Tournament List Retrieval: " + e.toString()); } @@ -2209,73 +2036,75 @@ public static JSONArray getModulesJson(String userId, String floor, Locale local log.debug("*** Getter.getModulesJson ***"); JSONArray jsonOutput = new JSONArray(); new String(); - Connection conn; - try { - conn = Database.getCoreConnection(); - } catch (SQLException | IOException e) { - log.error("Could not connect to core database: " + e.toString()); - throw new RuntimeException(e); - } - ResourceBundle.getBundle("i18n.text", locale); - ResourceBundle levelNames = ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", locale); - try { - JSONObject jsonSection = new JSONObject(); - JSONArray jsonSectionModules = new JSONArray(); - JSONObject jsonObject = new JSONObject(); - jsonSection.put("levelMode", floor); - jsonOutput.put(jsonSection); - jsonSection = new JSONObject(); - - // Get the modules - CallableStatement callstmt = conn.prepareCall("call getMyModules(?)"); - callstmt.setString(1, userId); - log.debug("Gathering getMyModules ResultSet for user " + userId); - ResultSet levels = callstmt.executeQuery(); - boolean thisModuleIsOpen = - true; // If Incremental Mode is enabled, after all the modules that have been - // completed have been added to the JSON Array the next level will be - // labeled as open and the rest as closed - while (levels.next()) { - jsonObject = new JSONObject(); - boolean moduleCompleted = levels.getString(4) != null; - jsonObject.put("moduleCompleted", moduleCompleted); - jsonObject.put("moduleId", levels.getString(3)); - jsonObject.put("moduleType", levels.getString(5)); - jsonObject.put("moduleName", levelNames.getString(levels.getString(1))); - jsonObject.put("moduleCategory", levelNames.getString("category." + levels.getString(2))); - jsonObject.put("difficultyCategory", getTounnamentSectionFromRankNumber(levels.getInt(7))); - jsonObject.put("moduleScore", levels.getString(6)); - jsonObject.put("moduleRank", levels.getInt(7)); - jsonObject.put("scoredPoints", levels.getString(8)); // Could be null - jsonObject.put("medalEarned", levels.getString(9)); // Could be null - if (ModulePlan.isIncrementalFloor()) { - boolean moduleOpen; - if (moduleCompleted - || (!moduleCompleted && thisModuleIsOpen)) // If its completed or if this is the - // first not completed - { - moduleOpen = true; - if (!moduleCompleted && thisModuleIsOpen) { - log.debug( - levelNames.getString(levels.getString(1)) - + " is the Next Module for user " - + userId); - thisModuleIsOpen = false; // Stop this from being set again + try (Connection conn = Database.getCoreConnection()) { + ResourceBundle.getBundle("i18n.text", locale); + ResourceBundle levelNames = + ResourceBundle.getBundle("i18n.moduleGenerics.moduleNames", locale); + try { + JSONObject jsonSection = new JSONObject(); + JSONArray jsonSectionModules = new JSONArray(); + JSONObject jsonObject = new JSONObject(); + jsonSection.put("levelMode", floor); + jsonOutput.put(jsonSection); + jsonSection = new JSONObject(); + + // Get the modules + try (CallableStatement callstmt = conn.prepareCall("call getMyModules(?)")) { + callstmt.setString(1, userId); + log.debug("Gathering getMyModules ResultSet for user " + userId); + try (ResultSet levels = callstmt.executeQuery()) { + boolean thisModuleIsOpen = + true; // If Incremental Mode is enabled, after all the modules that have been + // completed have been added to the JSON Array the next level will be + // labeled as open and the rest as closed + while (levels.next()) { + jsonObject = new JSONObject(); + boolean moduleCompleted = levels.getString(4) != null; + jsonObject.put("moduleCompleted", moduleCompleted); + jsonObject.put("moduleId", levels.getString(3)); + jsonObject.put("moduleType", levels.getString(5)); + jsonObject.put("moduleName", levelNames.getString(levels.getString(1))); + jsonObject.put( + "moduleCategory", levelNames.getString("category." + levels.getString(2))); + jsonObject.put( + "difficultyCategory", getTounnamentSectionFromRankNumber(levels.getInt(7))); + jsonObject.put("moduleScore", levels.getString(6)); + jsonObject.put("moduleRank", levels.getInt(7)); + jsonObject.put("scoredPoints", levels.getString(8)); // Could be null + jsonObject.put("medalEarned", levels.getString(9)); // Could be null + if (ModulePlan.isIncrementalFloor()) { + boolean moduleOpen; + if (moduleCompleted + || (!moduleCompleted && thisModuleIsOpen)) // If its completed or if this is the + // first not completed + { + moduleOpen = true; + if (!moduleCompleted && thisModuleIsOpen) { + log.debug( + levelNames.getString(levels.getString(1)) + + " is the Next Module for user " + + userId); + thisModuleIsOpen = false; // Stop this from being set again + } + } else { + moduleOpen = false; + } + jsonObject.put("moduleOpen", moduleOpen); + } + jsonSectionModules.put(jsonObject); } - } else { - moduleOpen = false; + jsonSection.put("modules", jsonSectionModules); + jsonOutput.put(jsonSection); } - jsonObject.put("moduleOpen", moduleOpen); } - jsonSectionModules.put(jsonObject); + } catch (Exception e) { + log.error("Module List Retrieval: " + e.toString()); } - jsonSection.put("modules", jsonSectionModules); - jsonOutput.put(jsonSection); - } catch (Exception e) { - log.error("Module List Retrieval: " + e.toString()); + return jsonOutput; + } catch (SQLException | IOException e) { + log.error("Could not connect to core database: " + e.toString()); + throw new RuntimeException(e); } - Database.closeConnection(conn); - return jsonOutput; } /** @@ -2287,19 +2116,16 @@ public static String getUserClassFromName(String ApplicationRoot, String userNam log.debug("*** Getter.getUserClass ***"); String result = new String(); userName = userName.toLowerCase(); - try { - Connection conn = Database.getCoreConnection(ApplicationRoot); - - CallableStatement callstmt = conn.prepareCall("call userClassId(?)"); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + CallableStatement callstmt = conn.prepareCall("call userClassId(?)")) { log.debug("Gathering userClassId ResultSet"); callstmt.setString(1, userName); - ResultSet resultSet = callstmt.executeQuery(); - log.debug("Opening Result Set from userClassId"); - resultSet.next(); - result = resultSet.getString(1); - log.debug("Found " + result); - Database.closeConnection(conn); - + try (ResultSet resultSet = callstmt.executeQuery()) { + log.debug("Opening Result Set from userClassId"); + resultSet.next(); + result = resultSet.getString(1); + log.debug("Found " + result); + } } catch (SQLException e) { log.error("Could not execute userClassId: " + e.toString()); result = new String(); @@ -2319,18 +2145,15 @@ public static String getUserIdFromName(String ApplicationRoot, String userName) userName = userName.toLowerCase(); - try { - Connection conn = Database.getCoreConnection(ApplicationRoot); - - CallableStatement callstmt = conn.prepareCall("call userGetIdByName(?)"); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + CallableStatement callstmt = conn.prepareCall("call userGetIdByName(?)")) { log.debug("Gathering userGetIdByName ResultSet"); callstmt.setString(1, userName); - ResultSet resultSet = callstmt.executeQuery(); - log.debug("Opening Result Set from userGetIdByName"); - resultSet.next(); - result = resultSet.getString(1); - Database.closeConnection(conn); - + try (ResultSet resultSet = callstmt.executeQuery()) { + log.debug("Opening Result Set from userGetIdByName"); + resultSet.next(); + result = resultSet.getString(1); + } } catch (SQLException e) { log.error("Could not execute query: " + e.toString()); result = null; @@ -2347,18 +2170,15 @@ public static String getUserIdFromName(String ApplicationRoot, String userName) public static String getUserName(String ApplicationRoot, String userId) { log.debug("*** Getter.getUserName ***"); String result = new String(); - try { - Connection conn = Database.getCoreConnection(ApplicationRoot); - - CallableStatement callstmt = conn.prepareCall("call userGetNameById(?)"); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + CallableStatement callstmt = conn.prepareCall("call userGetNameById(?)")) { log.debug("Gathering userGetNameById ResultSet"); callstmt.setString(1, userId); - ResultSet resultSet = callstmt.executeQuery(); - log.debug("Opening Result Set from userGetNameById"); - resultSet.next(); - result = resultSet.getString(1); - Database.closeConnection(conn); - + try (ResultSet resultSet = callstmt.executeQuery()) { + log.debug("Opening Result Set from userGetNameById"); + resultSet.next(); + result = resultSet.getString(1); + } } catch (SQLException e) { log.error("Could not execute query: " + e.toString()); result = null; @@ -2383,24 +2203,21 @@ public static boolean isCsrfLevelComplete( boolean result = false; - try { - Connection conn = Database.getCoreConnection(applicationRoot); - - log.debug("Preparing csrfLevelComplete call"); - PreparedStatement callstmnt = conn.prepareCall("call csrfLevelComplete(?, ?)"); + log.debug("Preparing csrfLevelComplete call"); + try (Connection conn = Database.getCoreConnection(applicationRoot); + PreparedStatement callstmnt = conn.prepareCall("call csrfLevelComplete(?, ?)")) { callstmnt.setString(1, moduleId); callstmnt.setString(2, userId); log.debug("moduleId: " + moduleId); log.debug("userId: " + userId); log.debug("Executing csrfLevelComplete"); - ResultSet resultSet = callstmnt.executeQuery(); - resultSet.next(); - result = resultSet.getInt(1) > 0; // If Result is > 0, then the CSRF level is complete - if (result) { - log.debug("CSRF Level is complete"); + try (ResultSet resultSet = callstmnt.executeQuery()) { + resultSet.next(); + result = resultSet.getInt(1) > 0; // If Result is > 0, then the CSRF level is complete + if (result) { + log.debug("CSRF Level is complete"); + } } - Database.closeConnection(conn); - } catch (SQLException e) { log.error("csrfLevelComplete Failure: " + e.toString()); result = false; @@ -2412,22 +2229,18 @@ public static boolean isCsrfLevelComplete( public static boolean isModuleOpen(String ApplicationRoot, String moduleId) { log.debug("*** Getter.isModuleOpen ***"); boolean result = false; - try { - Connection conn = Database.getCoreConnection(ApplicationRoot); - - // Get the modules - PreparedStatement prepStmt = - conn.prepareStatement("SELECT moduleStatus FROM modules WHERE moduleId = ?"); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + // Get the modules + PreparedStatement prepStmt = + conn.prepareStatement("SELECT moduleStatus FROM modules WHERE moduleId = ?")) { prepStmt.setString(1, moduleId); - ResultSet rs = prepStmt.executeQuery(); - if (rs.next()) { - if (rs.getString(1).equalsIgnoreCase("open")) { - result = true; + try (ResultSet rs = prepStmt.executeQuery()) { + if (rs.next()) { + if (rs.getString(1).equalsIgnoreCase("open")) { + result = true; + } } } - rs.close(); - Database.closeConnection(conn); - } catch (Exception e) { log.error("isModuleOpen Error: " + e.toString()); } @@ -2441,12 +2254,16 @@ public static boolean isModuleOpen(String ApplicationRoot, String moduleId) { public static ResultSet getAdmins(String ApplicationRoot) { ResultSet result = null; log.debug("*** Getter.adminGetAll () ***"); - try { - Connection conn = Database.getCoreConnection(ApplicationRoot); - - CallableStatement callstmt = conn.prepareCall("call adminGetAll()"); - log.debug("Gathering adminGetAll ResultSet"); - result = callstmt.executeQuery(); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + CallableStatement callstmt = conn.prepareCall("call adminGetAll()")) { + callstmt.setMaxRows(MAX_ROWSET_ROWS); + try (ResultSet resultSet = callstmt.executeQuery()) { + log.debug("Gathering adminGetAll ResultSet"); + CachedRowSet rowSet = RowSetProvider.newFactory().createCachedRowSet(); + rowSet.populate(resultSet); + rowSet.beforeFirst(); // populate() leaves the cursor after the last row + result = rowSet; + } log.debug("Returning Result Set from adminGetAll"); } catch (SQLException e) { @@ -2468,20 +2285,18 @@ public static boolean findAdminById(String ApplicationRoot, String userId) { log.debug("*** Getter.findAdminById ***"); boolean userFound = false; // Get connection - try { - Connection conn = Database.getCoreConnection(ApplicationRoot); - - CallableStatement callstmt = conn.prepareCall("call adminFindById(?)"); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + CallableStatement callstmt = conn.prepareCall("call adminFindById(?)")) { log.debug("Gathering adminFindById ResultSet"); callstmt.setString(1, userId); - ResultSet userFind = callstmt.executeQuery(); - log.debug("Opening Result Set from adminFindById"); - userFind.next(); // This will throw an exception if player not found - log.debug( - "Admin Found: " + userFind.getString(1)); // This line will not execute if admin not found - userFound = true; - Database.closeConnection(conn); - + try (ResultSet userFind = callstmt.executeQuery()) { + log.debug("Opening Result Set from adminFindById"); + userFind.next(); // This will throw an exception if player not found + log.debug( + "Admin Found: " + + userFind.getString(1)); // This line will not execute if admin not found + userFound = true; + } } catch (Exception e) { log.error("Admin does not exist: " + e.toString()); userFound = false; @@ -2494,355 +2309,339 @@ public static boolean getAdminCheatStatus(String ApplicationRoot) throws SQLExce boolean adminCheatStatus = false; log.debug("*** Getter.getAdminCheatStatus ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); - - log.debug("Getting admin cheat setting"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); - - callstmt.setString(1, "adminCheatsEnabled"); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - ResultSet cheatResult = callstmt.executeQuery(); + log.debug("Getting admin cheat setting"); + callstmt.setString(1, "adminCheatsEnabled"); - cheatResult.next(); - - adminCheatStatus = cheatResult.getBoolean(1); - - log.debug("Value found: " + adminCheatStatus); + try (ResultSet cheatResult = callstmt.executeQuery()) { + cheatResult.next(); + adminCheatStatus = cheatResult.getBoolean(1); + log.debug("Value found: " + adminCheatStatus); + } - Database.closeConnection(conn); - log.debug("*** END getAdminCheatStatus ***"); - return adminCheatStatus; + log.debug("*** END getAdminCheatStatus ***"); + return adminCheatStatus; + } } public static boolean getPlayerCheatStatus(String ApplicationRoot) throws SQLException { boolean getPlayerCheatStatus = false; log.debug("*** Getter.getPlayerCheatStatus ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - log.debug("Getting player cheat setting"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); + log.debug("Getting player cheat setting"); + callstmt.setString(1, "playerCheatsEnabled"); - callstmt.setString(1, "playerCheatsEnabled"); + try (ResultSet cheatResult = callstmt.executeQuery()) { + cheatResult.next(); - ResultSet cheatResult = callstmt.executeQuery(); + getPlayerCheatStatus = cheatResult.getBoolean(1); - cheatResult.next(); + log.debug("Value found: " + getPlayerCheatStatus); - getPlayerCheatStatus = cheatResult.getBoolean(1); - - log.debug("Value found: " + getPlayerCheatStatus); - - Database.closeConnection(conn); - log.debug("*** END getPlayerCheatStatus ***"); - return getPlayerCheatStatus; + log.debug("*** END getPlayerCheatStatus ***"); + return getPlayerCheatStatus; + } + } } public static String getModuleLayout(String ApplicationRoot) throws SQLException { String theModuleLayout = ""; log.debug("*** Getter.getModuleLayout ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - log.debug("Getting module layout setting"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); + log.debug("Getting module layout setting"); + callstmt.setString(1, "moduleLayout"); - callstmt.setString(1, "moduleLayout"); + try (ResultSet layoutResult = callstmt.executeQuery()) { + layoutResult.next(); - ResultSet layoutResult = callstmt.executeQuery(); + theModuleLayout = layoutResult.getString(1); - layoutResult.next(); + log.debug("Value found: " + theModuleLayout); - theModuleLayout = layoutResult.getString(1); - - log.debug("Value found: " + theModuleLayout); - - Database.closeConnection(conn); - log.debug("*** END getModuleLayout ***"); - return theModuleLayout; + log.debug("*** END getModuleLayout ***"); + return theModuleLayout; + } + } } public static boolean getFeedbackStatus(String ApplicationRoot) throws SQLException { boolean theFeedbackStatus = false; log.debug("*** Getter.getFeedbackStatus ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - log.debug("Getting feedback status setting"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); + log.debug("Getting feedback status setting"); + callstmt.setString(1, "enableFeedback"); - callstmt.setString(1, "enableFeedback"); + try (ResultSet feedbackResult = callstmt.executeQuery()) { + feedbackResult.next(); - ResultSet feedbackResult = callstmt.executeQuery(); + theFeedbackStatus = feedbackResult.getBoolean(1); - feedbackResult.next(); + log.debug("Value found: " + theFeedbackStatus); - theFeedbackStatus = feedbackResult.getBoolean(1); - - log.debug("Value found: " + theFeedbackStatus); - - Database.closeConnection(conn); - log.debug("*** END getFeedbackStatus ***"); - return theFeedbackStatus; + log.debug("*** END getFeedbackStatus ***"); + return theFeedbackStatus; + } + } } public static boolean getRegistrationStatus(String ApplicationRoot) throws SQLException { boolean theRegistrationStatus = false; log.debug("*** Getter.getRegistrationStatus ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - log.debug("Getting registration status setting"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); + log.debug("Getting registration status setting"); + callstmt.setString(1, "openRegistration"); - callstmt.setString(1, "openRegistration"); + try (ResultSet registrationResult = callstmt.executeQuery()) { + registrationResult.next(); - ResultSet registrationResult = callstmt.executeQuery(); + theRegistrationStatus = registrationResult.getBoolean(1); - registrationResult.next(); + log.debug("Value found: " + theRegistrationStatus); - theRegistrationStatus = registrationResult.getBoolean(1); - - log.debug("Value found: " + theRegistrationStatus); - - Database.closeConnection(conn); - log.debug("*** END getRegistrationStatus ***"); - return theRegistrationStatus; + log.debug("*** END getRegistrationStatus ***"); + return theRegistrationStatus; + } + } } public static String getScoreboardStatus(String ApplicationRoot) throws SQLException { String theScoreboardStatus = ""; log.debug("*** Getter.getScoreboardStatus ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - log.debug("Setting scoreboard status setting"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); + log.debug("Setting scoreboard status setting"); + callstmt.setString(1, "scoreboardStatus"); - callstmt.setString(1, "scoreboardStatus"); + try (ResultSet scoreboardResult = callstmt.executeQuery()) { + scoreboardResult.next(); - ResultSet scoreboardResult = callstmt.executeQuery(); + theScoreboardStatus = scoreboardResult.getString(1); - scoreboardResult.next(); + log.debug("Value found: " + theScoreboardStatus); - theScoreboardStatus = scoreboardResult.getString(1); - - log.debug("Value found: " + theScoreboardStatus); - - Database.closeConnection(conn); - log.debug("*** END getScoreboardStatus ***"); - return theScoreboardStatus; + log.debug("*** END getScoreboardStatus ***"); + return theScoreboardStatus; + } + } } public static String getScoreboardClass(String ApplicationRoot) throws SQLException { String theScoreboardClass = ""; log.debug("*** Getter.getScoreboardClass ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - log.debug("Getting scoreboard class setting"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); + log.debug("Getting scoreboard class setting"); + callstmt.setString(1, "scoreboardClass"); - callstmt.setString(1, "scoreboardClass"); + try (ResultSet scoreboardResult = callstmt.executeQuery()) { + scoreboardResult.next(); - ResultSet scoreboardResult = callstmt.executeQuery(); + theScoreboardClass = scoreboardResult.getString(1); - scoreboardResult.next(); + log.debug("Value found: " + theScoreboardClass); - theScoreboardClass = scoreboardResult.getString(1); - - log.debug("Value found: " + theScoreboardClass); - - Database.closeConnection(conn); - log.debug("*** END getScoreboardClass ***"); - return theScoreboardClass; + log.debug("*** END getScoreboardClass ***"); + return theScoreboardClass; + } + } } public static Boolean getStartTimeStatus(String ApplicationRoot) throws SQLException { Boolean theStartTimeStatus = null; log.debug("*** Getter.getStartTimeStatus ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - log.debug("Getting start time setting"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); + log.debug("Getting start time setting"); + callstmt.setString(1, "hasStartTime"); - callstmt.setString(1, "hasStartTime"); + try (ResultSet timestampResult = callstmt.executeQuery()) { + timestampResult.next(); - ResultSet timestampResult = callstmt.executeQuery(); + theStartTimeStatus = timestampResult.getBoolean(1); - timestampResult.next(); + log.debug("Value found: " + theStartTimeStatus); - theStartTimeStatus = timestampResult.getBoolean(1); - - log.debug("Value found: " + theStartTimeStatus); - - Database.closeConnection(conn); - log.debug("*** END getStartTimeStatus ***"); - return theStartTimeStatus; + log.debug("*** END getStartTimeStatus ***"); + return theStartTimeStatus; + } + } } public static LocalDateTime getStartTime(String ApplicationRoot) throws SQLException { LocalDateTime theStartTimeStatus = null; log.debug("*** Getter.getStartTimeStatus ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - log.debug("Getting start time"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); + log.debug("Getting start time"); + callstmt.setString(1, "startTime"); - callstmt.setString(1, "startTime"); + try (ResultSet timestampResult = callstmt.executeQuery()) { + timestampResult.next(); - ResultSet timestampResult = callstmt.executeQuery(); + String dateTimeString = timestampResult.getString(1); - timestampResult.next(); + log.debug("Value found: " + dateTimeString); - String dateTimeString = timestampResult.getString(1); + theStartTimeStatus = LocalDateTime.parse(dateTimeString); - log.debug("Value found: " + dateTimeString); - - theStartTimeStatus = LocalDateTime.parse(dateTimeString); - - Database.closeConnection(conn); - log.debug("*** END getStartTime ***"); - return theStartTimeStatus; + log.debug("*** END getStartTime ***"); + return theStartTimeStatus; + } + } } public static Boolean getLockTimeStatus(String ApplicationRoot) throws SQLException { Boolean theLockTimeStatus = null; log.debug("*** Getter.getLockTimeStatus ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - log.debug("Getting lock time setting"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); + log.debug("Getting lock time setting"); + callstmt.setString(1, "hasLockTime"); - callstmt.setString(1, "hasLockTime"); + try (ResultSet timestampResult = callstmt.executeQuery()) { + timestampResult.next(); - ResultSet timestampResult = callstmt.executeQuery(); + theLockTimeStatus = timestampResult.getBoolean(1); - timestampResult.next(); + log.debug("Value found: " + theLockTimeStatus); - theLockTimeStatus = timestampResult.getBoolean(1); - - log.debug("Value found: " + theLockTimeStatus); - - Database.closeConnection(conn); - log.debug("*** END getLockTimeStatus ***"); - return theLockTimeStatus; + log.debug("*** END getLockTimeStatus ***"); + return theLockTimeStatus; + } + } } public static LocalDateTime getLockTime(String ApplicationRoot) throws SQLException { LocalDateTime theLockTimeStatus = null; log.debug("*** Getter.getLockTimeStatus ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - log.debug("Getting lock time"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); + log.debug("Getting lock time"); + callstmt.setString(1, "lockTime"); - callstmt.setString(1, "lockTime"); + try (ResultSet timestampResult = callstmt.executeQuery()) { + timestampResult.next(); - ResultSet timestampResult = callstmt.executeQuery(); + String dateTimeString = timestampResult.getString(1); - timestampResult.next(); + log.debug("Value found: " + dateTimeString); - String dateTimeString = timestampResult.getString(1); + theLockTimeStatus = LocalDateTime.parse(dateTimeString); - log.debug("Value found: " + dateTimeString); - - theLockTimeStatus = LocalDateTime.parse(dateTimeString); - - Database.closeConnection(conn); - log.debug("*** END getLockTime ***"); - return theLockTimeStatus; + log.debug("*** END getLockTime ***"); + return theLockTimeStatus; + } + } } public static Boolean getEndTimeStatus(String ApplicationRoot) throws SQLException { Boolean theEndTimeStatus = null; log.debug("*** Getter.getEndTimeStatus ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - log.debug("Getting end time setting"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); + log.debug("Getting end time setting"); + callstmt.setString(1, "hasEndTime"); - callstmt.setString(1, "hasEndTime"); + try (ResultSet timestampResult = callstmt.executeQuery()) { + timestampResult.next(); - ResultSet timestampResult = callstmt.executeQuery(); + theEndTimeStatus = timestampResult.getBoolean(1); - timestampResult.next(); + log.debug("Value found: " + theEndTimeStatus); - theEndTimeStatus = timestampResult.getBoolean(1); - - log.debug("Value found: " + theEndTimeStatus); - - Database.closeConnection(conn); - log.debug("*** END getEndTimeStatus ***"); - return theEndTimeStatus; + log.debug("*** END getEndTimeStatus ***"); + return theEndTimeStatus; + } + } } public static LocalDateTime getEndTime(String ApplicationRoot) throws SQLException { LocalDateTime theEndTimeStatus = null; log.debug("*** Getter.getEndTimeStatus ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - log.debug("Getting end time"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); + log.debug("Getting end time"); + callstmt.setString(1, "endTime"); - callstmt.setString(1, "endTime"); + try (ResultSet timestampResult = callstmt.executeQuery()) { + timestampResult.next(); - ResultSet timestampResult = callstmt.executeQuery(); + String dateTimeString = timestampResult.getString(1); - timestampResult.next(); + log.debug("Value found: " + dateTimeString); - String dateTimeString = timestampResult.getString(1); + theEndTimeStatus = LocalDateTime.parse(dateTimeString); - log.debug("Value found: " + dateTimeString); - - theEndTimeStatus = LocalDateTime.parse(dateTimeString); - - Database.closeConnection(conn); - log.debug("*** END getEndTime ***"); - return theEndTimeStatus; + log.debug("*** END getEndTime ***"); + return theEndTimeStatus; + } + } } public static String getDefaultClass(String ApplicationRoot) throws SQLException { String theDefaultClass = null; log.debug("*** Getter.getDefaultClass ***"); - Connection conn = Database.getCoreConnection(ApplicationRoot); + try (Connection conn = Database.getCoreConnection(ApplicationRoot); + PreparedStatement callstmt = + conn.prepareStatement("SELECT value FROM settings WHERE setting= ?")) { - log.debug("Getting default class"); - PreparedStatement callstmt = - conn.prepareStatement("SELECT value FROM settings WHERE setting= ?"); + log.debug("Getting default class"); + callstmt.setString(1, "defaultClass"); - callstmt.setString(1, "defaultClass"); + try (ResultSet classResult = callstmt.executeQuery()) { + classResult.next(); - ResultSet classResult = callstmt.executeQuery(); + theDefaultClass = classResult.getString(1); - classResult.next(); + log.debug("Value found: " + theDefaultClass); - theDefaultClass = classResult.getString(1); - - log.debug("Value found: " + theDefaultClass); - - Database.closeConnection(conn); - log.debug("*** END getDefaultClass ***"); - return theDefaultClass; + log.debug("*** END getDefaultClass ***"); + return theDefaultClass; + } + } } } From 60545af7d5d2f025c2f2411298d4754f3d05c4e7 Mon Sep 17 00:00:00 2001 From: DuggSe01 Date: Tue, 16 Jun 2026 10:38:26 +0100 Subject: [PATCH 8/8] fix: use DbTime.UTC.get() to match ThreadLocal API in DbTime.java --- src/main/java/dbProcs/Getter.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/dbProcs/Getter.java b/src/main/java/dbProcs/Getter.java index 2650b1a5f..f6b094199 100644 --- a/src/main/java/dbProcs/Getter.java +++ b/src/main/java/dbProcs/Getter.java @@ -113,7 +113,7 @@ public static String[] authUser(String ApplicationRoot, String userName, String badLoginCount = userResult.getInt(5); tempPassword = userResult.getBoolean(6); classId = userResult.getString(7); - suspendedUntil = userResult.getTimestamp(8, DbTime.utcCalendar()); + suspendedUntil = userResult.getTimestamp(8, DbTime.UTC.get()); loginType = userResult.getString(9); tempUsername = userResult.getBoolean(10); } else { @@ -238,7 +238,7 @@ public static String[] authUserSSO( // User found if a row is in the database userFound = true; log.debug("User Found"); - suspendedUntil = userResult.getTimestamp(1, DbTime.utcCalendar()); + suspendedUntil = userResult.getTimestamp(1, DbTime.UTC.get()); } else { userFound = false; }